oportunidades 4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-10 07:03:59 +02:00
parent e662230df7
commit 6ddafc95ba
179 changed files with 22750 additions and 933 deletions
+7 -1
View File
@@ -179,11 +179,17 @@ export function AppHeader({ breadcrumbs = [] }: Props) {
<div className="ml-auto flex items-center space-x-2">
<div className="relative flex items-center space-x-1">
<Button
asChild
variant="ghost"
size="icon"
className="group h-9 w-9 cursor-pointer"
>
<Search className="!size-5 opacity-80 group-hover:opacity-100" />
<Link
href="/oportunidades"
aria-label="Pesquisar oportunidades"
>
<Search className="!size-5 opacity-80 group-hover:opacity-100" />
</Link>
</Button>
<div className="ml-1 hidden gap-1 lg:flex">
{rightNavItems.map((item) => (
+73 -14
View File
@@ -1,20 +1,79 @@
import { useState } from 'react';
import { useId, useState } from 'react';
export type Country = { code: string; name: string; name_en: string };
export default function CountrySelect({ countries, value, onChange, id, disabled = false }: {
countries: Country[]; value: string; onChange: (value: string) => void; id: string; disabled?: boolean;
export default function CountrySelect({
countries,
value,
onChange,
id,
disabled = false,
label = 'País',
required = false,
allowLegacyValue = false,
}: {
countries: Country[];
value: string;
onChange: (value: string) => void;
id?: string;
disabled?: boolean;
label?: string;
required?: boolean;
allowLegacyValue?: boolean;
}) {
const generatedId = useId();
const [search, setSearch] = useState('');
const matches = countries.filter((country) => country.code === value ||
`${country.name} ${country.name_en} ${country.code}`.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase()
.includes(search.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase()));
return <div className="space-y-2">
<input disabled={disabled} className="w-full rounded border p-2" aria-label="Pesquisar país" value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Pesquisar nome ou código do país" />
<select disabled={disabled} id={id} className="w-full rounded border p-2" value={value} onChange={(event) => onChange(event.target.value)}>
<option value="">Não informado</option>
{matches.map((country) => <option key={country.code} value={country.code}>{country.name} ({country.code})</option>)}
</select>
{matches.length === 0 && <p role="status">Nenhum país corresponde à pesquisa.</p>}
</div>;
const matches = countries.filter(
(country) =>
country.code === value ||
`${country.name} ${country.name_en} ${country.code}`
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase()
.includes(
search
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase(),
),
);
return (
<div className="space-y-2">
<input
disabled={disabled}
className="w-full rounded border p-2"
aria-label={`Pesquisar ${label.toLowerCase()}`}
maxLength={100}
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Pesquisar nome ou código do país"
/>
<select
disabled={disabled}
id={id ?? generatedId}
aria-label={label}
required={required}
className="w-full rounded border p-2"
value={value}
onChange={(event) => onChange(event.target.value)}
>
<option value="">Não informado</option>
{allowLegacyValue &&
value &&
!countries.some((country) => country.code === value) && (
<option value={value}>
{value} (valor anterior conservado)
</option>
)}
{matches.map((country) => (
<option key={country.code} value={country.code}>
{country.name} ({country.code})
</option>
))}
</select>
{matches.length === 0 && (
<p role="status">Nenhum país corresponde à pesquisa.</p>
)}
</div>
);
}
@@ -19,6 +19,7 @@ export type InvestmentMapFeature = {
};
};
export type InvestmentMapArea = {
purpose?: string;
geometry: GeoJsonObject;
title: string;
source_reference?: string | null;
@@ -30,9 +31,11 @@ const noAreas: InvestmentMapArea[] = [];
export default function InteractiveInvestmentMap({
points,
areas = noAreas,
contextOnly = false,
}: {
points: InvestmentMapFeature[] | null;
areas?: InvestmentMapArea[];
contextOnly?: boolean;
}) {
const element = useRef<HTMLDivElement>(null);
const map = useRef<LeafletMap | null>(null);
@@ -73,8 +76,19 @@ export default function InteractiveInvestmentMap({
const bounds: [number, number][] = [];
for (const area of areas) {
const label = document.createElement('p');
label.textContent = `${area.title} · Polígono cadastrado, limites oficiais por verificar · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
const layer = L.geoJSON(area.geometry)
label.textContent = `${area.title} · ${area.purpose === 'administrative_boundary' ? 'Limite administrativo da edição indicada; não representa um local de investimento' : 'Polígono cadastrado, limites oficiais por verificar'} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
const layer = L.geoJSON(
area.geometry,
area.purpose === 'administrative_boundary'
? {
style: {
color: '#2563eb',
dashArray: '5 5',
fillOpacity: 0.06,
},
}
: {},
)
.bindPopup(label)
.addTo(instance);
const extent = layer.getBounds();
@@ -160,12 +174,22 @@ export default function InteractiveInvestmentMap({
return (
<section
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
aria-label="Mapa interactivo dos investimentos"
aria-label={
contextOnly
? 'Mapa dos limites administrativos'
: 'Mapa interactivo dos investimentos'
}
>
<h2 className="text-xl font-bold">Mapa dos investimentos</h2>
<h2 className="text-xl font-bold">
{contextOnly
? 'Contexto administrativo'
: 'Mapa dos investimentos'}
</h2>
<p>
Arraste para navegar; use +/− para ampliar. Pode seleccionar um
investimento na lista para o localizar.
{contextOnly
? 'limite cadastrado para consultar a sua edição.'
: 'investimento na lista para o localizar.'}
</p>
{error && <p role="status">{error}</p>}
<div
@@ -177,7 +201,9 @@ export default function InteractiveInvestmentMap({
<p role="status">A carregar localizações…</p>
) : (
<p role="status">
{points.length} locais com coordenadas disponíveis.
{contextOnly
? `${areas.length} limites administrativos disponíveis.`
: `${points.length} locais com coordenadas disponíveis.`}
</p>
)}
<ul className="grid gap-2 md:grid-cols-2">
@@ -1,20 +1,23 @@
import { useEffect, useState } from 'react';
import { useEffect, useState } from "react";
import TerritoryGeometryPreview from "./territory-geometry-preview";
import InteractiveInvestmentMap, {
type InvestmentMapFeature,
type InvestmentMapArea,
} from './interactive-investment-map';
} from "./interactive-investment-map";
export default function InvestmentMapPanel({
filters,
territoryId,
}: {
filters: Record<string, string | number>;
territoryId?: string;
}) {
const key = JSON.stringify(filters);
const [points, setPoints] = useState<InvestmentMapFeature[] | null>(null);
const [missing, setMissing] = useState<
{ id: number; title: string; url: string }[]
>([]);
const [error, setError] = useState('');
const [error, setError] = useState("");
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
useEffect(() => {
const controller = new AbortController();
@@ -23,10 +26,10 @@ export default function InvestmentMapPanel({
setAreas([]);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
headers: { Accept: 'application/json' },
headers: { Accept: "application/json" },
})
.then(async (response) => {
if (!response.ok) throw new Error('Mapa indisponível.');
if (!response.ok) throw new Error("Mapa indisponível.");
return response.json();
})
.then((data) => {
@@ -36,8 +39,8 @@ export default function InvestmentMapPanel({
setMissing(data.unlocated ?? []);
setError(
data.truncated
? 'Cobertura limitada: refine os filtros.'
: '',
? "Cobertura limitada: refine os filtros."
: "",
);
})
.catch((e) => {
@@ -49,6 +52,19 @@ export default function InvestmentMapPanel({
<section className="space-y-3">
{error && <p role="alert">{error}</p>}
<InteractiveInvestmentMap points={points} areas={areas} />
<TerritoryGeometryPreview
territoryId={
territoryId ||
String(
filters.locality_id ||
filters.admin_post_id ||
filters.district_id ||
filters.province_id ||
filters.geo_location_id ||
"",
)
}
/>
{missing.length > 0 && (
<div>
<p>
@@ -1,6 +1,7 @@
import { useEffect, useId, useState } from 'react';
import { api } from '@/pages/investment/shared';
import { replaceTerritoryPath } from '@/lib/territory-path.js';
import TerritoryGeometryPreview from './territory-geometry-preview';
export type TerritoryOption = {
id: string;
@@ -38,51 +39,77 @@ export function ProvinceSelect({
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [retry, setRetry] = useState(0);
const [search, setSearch] = useState('');
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError('');
fetch(`${endpoint}?type=province&page=1`, {
signal: controller.signal,
headers: { Accept: 'application/json' },
})
.then(async (response) => {
if (!response.ok)
throw new Error('Não foi possível carregar as províncias.');
return response.json();
})
.then((data) => setOptions(data.data))
.catch((cause) => {
if (!controller.signal.aborted)
setError(
cause instanceof Error
? cause.message
: 'Erro de ligação.',
);
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [endpoint, retry]);
const timer = setTimeout(
() =>
fetch(
`${endpoint}?${new URLSearchParams({ type: 'province', page: '1', q: search })}`,
{
signal: controller.signal,
headers: { Accept: 'application/json' },
},
)
.then(async (response) => {
if (!response.ok)
throw new Error(
'Não foi possível carregar as províncias.',
);
return response.json();
})
.then((data) => {
if (!controller.signal.aborted) setOptions(data.data);
})
.catch((cause) => {
if (!controller.signal.aborted)
setError(
cause instanceof Error
? cause.message
: 'Erro de ligação.',
);
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
}),
250,
);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [endpoint, retry, search]);
return (
<>
<input
className={className}
aria-label={`Pesquisar ${label}`}
maxLength={100}
placeholder="Pesquisar nome ou código"
value={search}
onChange={(event) => setSearch(event.target.value)}
/>
<select
id={id}
aria-label={label}
className={className}
required={required}
value={
options.some((option) => option.name === value) ? value : ''
}
value={value}
disabled={loading || Boolean(error)}
onChange={(event) => onChange(event.target.value)}
>
<option value="">
{loading ? 'A carregar províncias…' : placeholder}
</option>
{value && !options.some((option) => option.name === value) && (
<option value={value}>
{value} (seleção guardada; conferir cadastro)
</option>
)}
{options.map((option) => (
<option key={option.id} value={option.name}>
{option.name}
@@ -108,10 +135,12 @@ export function TerritoryFields({
initial = emptyTerritoryPath,
onChange,
endpoint = '/api/v1/investment/territory-options',
disabled = false,
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
endpoint?: string;
disabled?: boolean;
}) {
const [path, setPath] = useState(initial);
useEffect(() => setPath(initial), [initial]);
@@ -132,6 +161,7 @@ export function TerritoryFields({
value={path[index]?.id ?? ''}
/>
<TerritoryLevel
disabled={disabled}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
@@ -148,6 +178,10 @@ export function TerritoryFields({
/>
</div>
))}
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management={endpoint.startsWith('/management/')}
/>
</div>
);
}
@@ -159,6 +193,7 @@ export function TerritoryLevel({
onChange,
endpoint = '/management/territory-options',
fieldError,
disabled = false,
}: {
index: number;
parent: string;
@@ -166,6 +201,7 @@ export function TerritoryLevel({
onChange: (value?: Option) => void;
endpoint?: string;
fieldError?: string;
disabled?: boolean;
}) {
const id = useId();
const [page, setPage] = useState(1);
@@ -175,8 +211,11 @@ export function TerritoryLevel({
const [loading, setLoading] = useState(false);
const [retry, setRetry] = useState(0);
const [search, setSearch] = useState('');
const enabled = index === 0 || Boolean(parent);
useEffect(() => { setPage(1); setSearch(''); }, [parent, index]);
const enabled = !disabled && (index === 0 || Boolean(parent));
useEffect(() => {
setPage(1);
setSearch('');
}, [parent, index]);
useEffect(() => {
setOptions([]);
setMore(false);
@@ -224,7 +263,18 @@ export function TerritoryLevel({
<label htmlFor={id} className="font-medium">
{labels[index]}
</label>
<input className={control} aria-label={`Pesquisar ${labels[index]}`} disabled={!enabled} maxLength={100} value={search} onChange={(event) => { setSearch(event.target.value); setPage(1); }} placeholder={`Pesquisar ${labels[index].toLowerCase()}`} />
<input
className={control}
aria-label={`Pesquisar ${labels[index]}`}
disabled={!enabled}
maxLength={100}
value={search}
onChange={(event) => {
setSearch(event.target.value);
setPage(1);
}}
placeholder={`Pesquisar ${labels[index].toLowerCase()}`}
/>
<select
id={id}
aria-invalid={Boolean(fieldError)}
@@ -345,6 +395,10 @@ export default function InvestmentTerritory({
/>
))}
</div>
<TerritoryGeometryPreview
territoryId={path.at(-1)?.id}
management
/>
<button
type="button"
className="bg-primary text-primary-foreground rounded px-4 py-2 disabled:opacity-50"
+47 -7
View File
@@ -4,10 +4,15 @@ import type { Guidance } from './investor-guidance';
/** Carries only an account-scoped case identifier between modules; never a contact/document payload. */
export function JourneyCompanion() {
const { props, url } = usePage<{ auth: { user: { id: number } | null } }>();
const { props, url } = usePage<{
auth: { user: { id: number } | null };
investorPathEnabled?: boolean;
}>();
const actor = props.auth?.user?.id;
const [open, setOpen] = useState(false);
const [cases, setCases] = useState<{ id: string; title: string }[]>([]);
const [cases, setCases] = useState<
{ id: string; title: string; path_supported?: boolean }[]
>([]);
const [active, setActive] = useState('');
const [guidance, setGuidance] = useState<Guidance | null>(null);
const [message, setMessage] = useState('');
@@ -19,15 +24,27 @@ export function JourneyCompanion() {
if (!actor) return;
try {
const key = `investmoz-guidance-case:${actor}`;
const routeId = url.match(
/^\/balcao-virtual\/dossiers\/([a-f0-9-]{36})/i,
)?.[1];
const context = new URL(
url,
'https://investmoz.invalid',
).searchParams.get('context');
const pathId = props.investorPathEnabled
? url.match(/^\/investimentos\/([a-f0-9-]{36})/i)?.[1]
: null;
const routeId =
pathId ??
(props.investorPathEnabled &&
context &&
/^[a-f0-9-]{36}$/i.test(context)
? context
: null) ??
url.match(/^\/balcao-virtual\/dossiers\/([a-f0-9-]{36})/i)?.[1];
if (routeId) sessionStorage.setItem(key, routeId);
setActive(routeId ?? sessionStorage.getItem(key) ?? '');
} catch {
setMessage('Selecção de contexto disponível apenas nesta página.');
}
}, [actor, url]);
}, [actor, url, props.investorPathEnabled]);
useEffect(() => {
if (!open || !actor) return;
const controller = new AbortController();
@@ -42,7 +59,11 @@ export function JourneyCompanion() {
'Acompanhamento em preparação; os pedidos anteriores continuam no Balcão Virtual.',
);
return r.json() as Promise<{
cases: { id: string; title: string }[];
cases: {
id: string;
title: string;
path_supported?: boolean;
}[];
}>;
})
.then((data) => setCases(data.cases))
@@ -110,6 +131,25 @@ export function JourneyCompanion() {
</p>
) : (
<>
{props.investorPathEnabled && (
<Link
className="block underline"
href="/investimentos"
>
Os meus investimentos e próxima acção
</Link>
)}
{cases.some(
(item) =>
item.id === active && item.path_supported,
) && (
<Link
className="block font-semibold underline"
href={`/investimentos/${active}`}
>
Voltar ao percurso deste investimento
</Link>
)}
<label className="block">
Contexto do projecto
<select
+191 -23
View File
@@ -63,10 +63,10 @@ import {
} from '@/lib/simulation-api';
type Choice = { id: string; label: string };
const draftKey = 'investmoz-simulation-draft-v1';
const idempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
const draftCreateKey = 'investmoz-simulation-draft-create-key-v1';
const draftIdKey = 'investmoz-simulation-draft-id-v1';
const legacyDraftKey = 'investmoz-simulation-draft-v1';
const legacyIdempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
const legacyDraftCreateKey = 'investmoz-simulation-draft-create-key-v1';
const legacyDraftIdKey = 'investmoz-simulation-draft-id-v1';
const idempotencyKey = () => crypto.randomUUID();
function csrfToken(): string {
@@ -397,6 +397,26 @@ function useChoices(
let url: URL;
if (source === 'sector') {
url = new URL('/api/v1/sectors', window.location.origin);
} else if (source === 'country') {
url = new URL(
'/api/v1/catalogs/countries',
window.location.origin,
);
url.searchParams.set('q', query);
url.searchParams.set('per_page', '100');
} else if (
['province', 'district', 'admin_post', 'locality'].includes(
source,
)
) {
url = new URL(
'/api/v1/investment/territory-options',
window.location.origin,
);
url.searchParams.set('type', source);
url.searchParams.set('q', query);
if (source !== 'province')
url.searchParams.set('parent_id', parent);
} else {
url = new URL(
'/api/v1/catalogs/' +
@@ -427,6 +447,7 @@ function useChoices(
'Não foi possível carregar as opções. Tente novamente.',
);
const payload = await readSimulationApiJson(response);
if (controller.signal.aborted) return;
setChoices(simulationCatalogChoices(payload));
} catch (cause) {
if (!controller.signal.aborted)
@@ -489,12 +510,15 @@ function SearchChoice({
retry,
} = useChoices(source, query, parent, !disabled && open);
const chosen = Array.isArray(value) ? value : value ? [value] : [];
const searchText = (text: string) =>
text
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLocaleLowerCase();
const filtered = choices.filter(
(option) =>
option.label
.toLocaleLowerCase()
.includes(query.toLocaleLowerCase()) ||
option.id.toLocaleLowerCase().includes(query.toLocaleLowerCase()),
searchText(option.label).includes(searchText(query)) ||
searchText(option.id).includes(searchText(query)),
);
useEffect(() => {
if (open) activeOptionRef.current?.scrollIntoView({ block: 'nearest' });
@@ -746,6 +770,28 @@ export function SimulationForm() {
const { auth } = usePage<{
auth: { user: { email_verified_at?: string | null } | null };
}>().props;
const pageUrl = usePage().url;
const draftContext = useMemo(() => {
const params = new URL(pageUrl, 'https://investmoz.invalid')
.searchParams;
return {
context: params.get('context'),
requestedDraft: params.get('draft'),
};
}, [pageUrl]);
const contextId = draftContext.context;
const storageScope = contextId
? `:case:${contextId}`
: draftContext.requestedDraft
? `:draft:${draftContext.requestedDraft}`
: '';
const draftKey = legacyDraftKey + storageScope;
const draftCreateKey = legacyDraftCreateKey + storageScope;
const draftIdKey = legacyDraftIdKey + storageScope;
const idempotencyStorageKey = legacyIdempotencyStorageKey + storageScope;
const currentDraftUrl = contextId
? `/api/v1/simulation-drafts/current?context=${encodeURIComponent(contextId)}`
: '/api/v1/simulation-drafts/current';
const canSavePersonalData = Boolean(auth?.user);
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
const [draft, setDraft] = useState<SimulationDraft>({});
@@ -1123,9 +1169,9 @@ export function SimulationForm() {
}
try {
const response = await fetch(
requestedDraftId
requestedDraftId && !contextId
? `/api/v1/simulation-drafts/${encodeURIComponent(requestedDraftId)}`
: '/api/v1/simulation-drafts/current',
: currentDraftUrl,
{
credentials: 'same-origin',
headers: {
@@ -1140,7 +1186,7 @@ export function SimulationForm() {
throw new Error(
'O servidor devolveu um rascunho com formato inválido.',
);
if (canSavePersonalData) {
if (canSavePersonalData && !contextId) {
const [listResponse, previewResponse] =
await Promise.all([
fetch('/api/v1/simulation-drafts', {
@@ -1222,9 +1268,19 @@ export function SimulationForm() {
if (storedId) sessionStorage.removeItem(draftIdKey);
setDraft(local);
}
} else if (contextId || requestedDraftId) {
saveConflictRef.current = true;
setHasSaveConflict(true);
setSaveStatus(
'Dossier indisponível para esta conta. Nenhum outro rascunho foi aberto.',
);
} else if (!canSavePersonalData && Object.keys(local).length)
setDraft(local);
} catch {
if (contextId || requestedDraftId) {
saveConflictRef.current = true;
setHasSaveConflict(true);
}
if (!canSavePersonalData && Object.keys(local).length)
setDraft(local);
setSaveStatus(
@@ -1236,7 +1292,7 @@ export function SimulationForm() {
return () => {
cancelled = true;
};
}, [canSavePersonalData]);
}, [canSavePersonalData, contextId, currentDraftUrl, draftIdKey, draftKey]);
useEffect(() => {
if (!ready || !draft.purpose) return;
const timer = window.setTimeout(() => {
@@ -1268,15 +1324,12 @@ export function SimulationForm() {
'X-XSRF-TOKEN': csrfToken(),
};
if (!draftIdRef.current) {
const currentResponse = await fetch(
'/api/v1/simulation-drafts/current',
{
credentials: 'same-origin',
headers: {
Accept: 'application/json',
},
const currentResponse = await fetch(currentDraftUrl, {
credentials: 'same-origin',
headers: {
Accept: 'application/json',
},
);
});
const currentPayload: unknown = currentResponse.ok
? await readSimulationApiJson(currentResponse)
: { data: null };
@@ -1313,7 +1366,12 @@ export function SimulationForm() {
...headers,
'If-Match': draftEtagRef.current,
},
body: JSON.stringify(snapshots),
body: JSON.stringify({
...snapshots,
...(contextId
? { context: contextId }
: {}),
}),
},
);
} else {
@@ -1326,7 +1384,10 @@ export function SimulationForm() {
method: 'POST',
credentials: 'same-origin',
headers: { ...headers, 'Idempotency-Key': key },
body: JSON.stringify(snapshots),
body: JSON.stringify({
...snapshots,
...(contextId ? { context: contextId } : {}),
}),
});
}
if (response.status === 412 || response.status === 428) {
@@ -1401,7 +1462,87 @@ export function SimulationForm() {
});
}, 450);
return () => window.clearTimeout(timer);
}, [draft, ready, canSavePersonalData, accountDrafts]);
}, [
draft,
ready,
canSavePersonalData,
accountDrafts,
contextId,
currentDraftUrl,
draftCreateKey,
draftIdKey,
draftKey,
]);
async function returnToInvestment() {
if (!contextId || !draftIdRef.current) return;
setContinuityError('');
try {
await saveQueueRef.current;
const current = await fetch(
`/api/v1/simulation-drafts/${draftIdRef.current}`,
{
headers: { Accept: 'application/json' },
credentials: 'same-origin',
},
);
const saved: unknown = await readSimulationApiJson(current);
if (
!current.ok ||
!isApiSimulationDraftReadResponseV1(saved) ||
!saved.data
)
throw new Error(
'Não foi possível recuperar o rascunho guardado.',
);
if (
saved.data.economic_snapshot.financial_tools_snapshot !==
draft.financial_tools_snapshot
)
throw new Error(
'Aguarde a gravação das entradas da ferramenta e tente novamente.',
);
const dossier = await fetch(`/investimentos/${contextId}`, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!dossier.ok)
throw new Error('Dossier indisponível para esta conta.');
const view = (await dossier.json()) as {
case: { version: number };
};
const response = await fetch(
`/investimentos/${contextId}/resultados`,
{
method: 'POST',
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken(),
},
body: JSON.stringify({
version: view.case.version,
draft_id: saved.data.id,
draft_version: saved.data.version_no,
}),
},
);
if (!response.ok)
throw new Error(
response.status === 409
? 'O dossier mudou. Recupere a versão actual antes de devolver o resultado.'
: 'Não foi possível devolver as entradas financeiras guardadas ao dossier.',
);
window.location.assign(`/investimentos/${contextId}`);
} catch (cause) {
setContinuityError(
cause instanceof Error
? cause.message
: 'Erro ao devolver o resultado.',
);
}
}
async function openOwnedDraft(id: string) {
setContinuityError('');
@@ -2264,6 +2405,32 @@ export function SimulationForm() {
id={draftIdRef.current}
/>
)}
{contextId && (
<section
className="rounded-lg border p-4"
aria-label="Contexto do investimento"
>
<p>
Ferramenta ligada ao dossier actual. As entradas são
guardadas no rascunho deste investimento.
</p>
<button
type="button"
className="mt-2 rounded border px-3 py-2"
disabled={!ready || hasSaveConflict || !draftVersionNo}
onClick={() => void returnToInvestment()}
>
Guardar resultado financeiro e voltar ao dossier
</button>
{continuityError && <p role="alert">{continuityError}</p>}
<a
className="ml-3 underline"
href={`/investimentos/${contextId}`}
>
Ver dossier
</a>
</section>
)}
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2
@@ -2465,6 +2632,7 @@ export function SimulationForm() {
</section>
)}
{canSavePersonalData &&
!contextId &&
!showDraftChoice &&
accountDrafts.length > 0 && (
<section
@@ -0,0 +1,103 @@
import { useEffect, useState } from 'react';
import InteractiveInvestmentMap, {
type InvestmentMapArea,
} from './interactive-investment-map';
const noPoints: [] = [];
type Context = {
selected_geometry_available: boolean;
context_geometry_count: number;
areas: InvestmentMapArea[];
truncated: boolean;
};
export default function TerritoryGeometryPreview({
territoryId,
management = false,
}: {
territoryId?: string;
management?: boolean;
}) {
const [context, setContext] = useState<Context | null>(null);
const [error, setError] = useState('');
useEffect(() => {
setContext(null);
setError('');
if (!territoryId) return;
const controller = new AbortController();
const endpoint = management
? '/management/territory-geometries'
: '/api/v1/investment/territory-geometries';
void fetch(
`${endpoint}?${new URLSearchParams({ territory_id: territoryId })}`,
{
signal: controller.signal,
headers: { Accept: 'application/json' },
},
)
.then(async (response) => {
if (!response.ok)
throw new Error(
'Não foi possível consultar os limites administrativos.',
);
return response.json() as Promise<Context>;
})
.then((data) => {
if (!controller.signal.aborted) setContext(data);
})
.catch((e: unknown) => {
if (!controller.signal.aborted)
setError(
e instanceof Error ? e.message : 'Erro de ligação.',
);
});
return () => controller.abort();
}, [territoryId, management]);
if (!territoryId) return null;
return (
<section
className="space-y-2 md:col-span-full"
aria-label="Cobertura cartográfica da seleção"
>
<p>Território selecionado no cadastro.</p>
{error && <p role="alert">{error}</p>}
{!context && !error && <p role="status">A consultar geometria…</p>}
{context && (
<>
<p role="status">
{context.selected_geometry_available
? 'Limite administrativo disponível para este território.'
: 'Sem limite administrativo disponível para este território.'}
</p>
<p>
{context.context_geometry_count} limites disponíveis na
hierarquia selecionada. São contexto administrativo, não
perímetro nem disponibilidade de investimento. A edição
e a atualidade jurídica são informações distintas.
</p>
{context.truncated && (
<p role="alert">
Exibidos os primeiros 100 limites; cobertura
incompleta.
</p>
)}
{context.areas.length > 0 && (
<InteractiveInvestmentMap
points={noPoints}
areas={context.areas}
contextOnly
/>
)}
<ul>
{context.areas.map((area, index) => (
<li key={index}>
{area.title} · Fonte:{' '}
{area.source_reference ?? 'Não indicada'} ·
Edição: {area.source_date ?? 'Não indicada'}
</li>
))}
</ul>
</>
)}
</section>
);
}