function csrfToken(): string { return decodeURIComponent( document.cookie .split('; ') .find((c) => c.startsWith('XSRF-TOKEN=')) ?.slice('XSRF-TOKEN='.length) ?? '', ); } export type ContextReference = { key: string; kind: string; id: string; title: string; href: string; version: number | string | null; sha256: string; fields: Record; }; export type DossierContext = { revision: number; selection: Partial< Record< 'opportunity' | 'sector' | 'territory' | 'park', ContextReference > >; fields: Record; provenance: Record< string, { kind?: string; title?: string; id?: string; version?: number | string; } >; updated_at?: string; dependency_hash?: string; }; export type ContextView = { simulator_context_revision?: number | null; case: { id: string; title: string; version: number }; context: DossierContext; can_write: boolean; next: { code: string; title: string } | null; steps: { code: string; title: string; state: string }[]; results: { id: string; engine: string; context_state?: string }[]; requests: { id: string; status: string; protocol: string | null; context_state?: string; }[]; prefill: Record>; notice: string; }; export type ContextPlan = { preview_hash: string; version: number; revision: number; fields: Record; selection: DossierContext['selection']; updated: { field: string; before: string | null; after: string }[]; maintained: { field: string; value: string; proposed: string }[]; dependent_results: { id: string; engine: string }[]; requests: { id: string; status: string; protocol: string | null; version: number; }[]; review_steps: string[]; documents_preserved: number; notice: string; }; export async function contextApi( url: string, body?: unknown, method = 'POST', ): Promise { const response = await fetch(url, { method: body === undefined ? 'GET' : method, credentials: 'same-origin', headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': csrfToken(), }), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), }); const data = await response.json().catch(() => null); if (!response.ok) throw new Error( data?.message || `Não foi possível recuperar ou guardar o contexto (HTTP ${response.status}).`, ); return data as T; } export const contextFieldNames: Record = { title: 'Título do investimento', territory_id: 'Localização documentada', location_source: 'Origem da localização', description: 'Descrição', project_title: 'Título do investimento', project_summary: 'Descrição do investimento', sector_id: 'Sector (identificador)', sector: 'Sector', province_id: 'Província (identificador)', district_id: 'Distrito (identificador)', admin_post_id: 'Posto administrativo', locality_id: 'Localidade', province: 'Província', district: 'Distrito', location: 'Localização', };