81 lines
3.4 KiB
TypeScript
81 lines
3.4 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import DemographicEvidence, {
|
|
type DemographicAnalysis,
|
|
} from './demographic-evidence';
|
|
|
|
export default function DemographicContext({
|
|
territoryId,
|
|
}: {
|
|
territoryId?: string | null;
|
|
}) {
|
|
if (!territoryId) return null;
|
|
// A change of territory resets this consultation, never the investor's dossier.
|
|
return <TerritoryDemography key={territoryId} territoryId={territoryId} />;
|
|
}
|
|
|
|
function TerritoryDemography({ territoryId }: { territoryId: string }) {
|
|
const [evidence, setEvidence] = useState<DemographicAnalysis | null>(null);
|
|
const [message, setMessage] = useState('');
|
|
const [busy, setBusy] = useState(false);
|
|
const pending = useRef<AbortController | null>(null);
|
|
useEffect(() => () => pending.current?.abort(), []);
|
|
return (
|
|
<details className="rounded border p-4">
|
|
<summary>Demografia na análise de viabilidade</summary>
|
|
<p>
|
|
Consulte a população e a estrutura etária da localização
|
|
escolhida, com fontes, anos e limitações.
|
|
</p>
|
|
<button
|
|
type="button"
|
|
className="my-2 underline"
|
|
disabled={busy}
|
|
onClick={async () => {
|
|
setBusy(true);
|
|
setMessage('');
|
|
setEvidence(null);
|
|
pending.current?.abort();
|
|
const controller = new AbortController();
|
|
pending.current = controller;
|
|
try {
|
|
const response = await fetch(
|
|
`/api/v1/investment/demography?investment_context=1&territories[]=${encodeURIComponent(territoryId)}`,
|
|
{
|
|
headers: { Accept: 'application/json' },
|
|
signal: controller.signal,
|
|
},
|
|
);
|
|
if (!response.ok)
|
|
throw new Error('Consulta indisponível.');
|
|
const result = await response.json();
|
|
if (!controller.signal.aborted) {
|
|
setEvidence(result);
|
|
if (result.broader_context)
|
|
setMessage(
|
|
'Contexto administrativo mais amplo. Estes indicadores não representam a população da localidade escolhida.',
|
|
);
|
|
}
|
|
} catch {
|
|
if (controller.signal.aborted) return;
|
|
setMessage(
|
|
'Não foi possível consultar a evidência demográfica.',
|
|
);
|
|
} finally {
|
|
if (!controller.signal.aborted) setBusy(false);
|
|
}
|
|
}}
|
|
>
|
|
Consultar indicadores do ano actual
|
|
</button>
|
|
{message && <p role="alert">{message}</p>}
|
|
{evidence && <DemographicEvidence evidence={evidence} />}
|
|
<a
|
|
className="block underline"
|
|
href={`/localizacoes/demografia?territories[]=${encodeURIComponent(territoryId)}`}
|
|
>
|
|
Escolher período, sector e comparar localizações
|
|
</a>
|
|
</details>
|
|
);
|
|
}
|