Deliver additive INE demography and authenticated homologation installation
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
import { useState } from 'react';
|
||||
import DemographicEvidence, {
|
||||
type DemographicAnalysis,
|
||||
} from './demographic-evidence';
|
||||
|
||||
export default function DemographicContext({
|
||||
territoryId,
|
||||
}: {
|
||||
territoryId?: string | null;
|
||||
}) {
|
||||
const [evidence, setEvidence] = useState<DemographicAnalysis | null>(null);
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
if (!territoryId) return null;
|
||||
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('');
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/v1/investment/demography?territories[]=${encodeURIComponent(territoryId)}`,
|
||||
{ headers: { Accept: 'application/json' } },
|
||||
);
|
||||
if (!response.ok)
|
||||
throw new Error('Consulta indisponível.');
|
||||
setEvidence(await response.json());
|
||||
} catch {
|
||||
setMessage(
|
||||
'Não foi possível consultar a evidência demográfica.',
|
||||
);
|
||||
} finally {
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
export type DemographicAnalysis = {
|
||||
state: string;
|
||||
start_year: number;
|
||||
end_year: number;
|
||||
limitations: string[];
|
||||
comparisons: {
|
||||
year: number;
|
||||
left: string;
|
||||
right: string;
|
||||
left_value: string;
|
||||
right_value: string;
|
||||
left_import: string;
|
||||
right_import: string;
|
||||
difference: string | null;
|
||||
explanation: string;
|
||||
}[];
|
||||
differences: {
|
||||
territory_id: string;
|
||||
dimension: string;
|
||||
state: string;
|
||||
values: { import_id: string; value: string; data_kind: string }[];
|
||||
}[];
|
||||
territories: {
|
||||
id: string;
|
||||
name: string;
|
||||
level: string;
|
||||
factors_to_assess: string[];
|
||||
series: {
|
||||
import_id: string;
|
||||
source: string;
|
||||
version: string;
|
||||
sha256: string;
|
||||
file_name: string;
|
||||
missing_years: number[];
|
||||
issue_counts: Record<string, number>;
|
||||
values: {
|
||||
year: number;
|
||||
indicator: string;
|
||||
age_group: string;
|
||||
residence: string;
|
||||
value: string;
|
||||
original_value: string;
|
||||
unit: string;
|
||||
data_kind: string;
|
||||
sheet: string;
|
||||
cell: string;
|
||||
validation_status: string;
|
||||
}[];
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
|
||||
const indicators: Record<string, string> = {
|
||||
population: 'População',
|
||||
life_expectancy: 'Esperança de vida',
|
||||
infant_mortality: 'Mortalidade infantil',
|
||||
crude_death_rate: 'Mortalidade bruta',
|
||||
crude_birth_rate: 'Natalidade bruta',
|
||||
fertility_rate: 'Fecundidade',
|
||||
population_growth_rate: 'Crescimento populacional',
|
||||
};
|
||||
export default function DemographicEvidence({
|
||||
evidence,
|
||||
}: {
|
||||
evidence: DemographicAnalysis;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-4" aria-label="Evidência demográfica">
|
||||
{evidence.state !== 'available' && (
|
||||
<p>Sem séries demográficas aprovadas para esta selecção.</p>
|
||||
)}
|
||||
{evidence.territories.map((t) => (
|
||||
<article
|
||||
key={t.id}
|
||||
className="space-y-3 rounded border bg-white p-4 text-slate-900"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{t.name} —{' '}
|
||||
{t.level === 'district' ? 'Distrito' : 'Província'}
|
||||
</h2>
|
||||
{t.factors_to_assess.map((f) => (
|
||||
<p key={f}>{f}</p>
|
||||
))}
|
||||
{t.series.length === 0 && (
|
||||
<p>Sem dados no período escolhido.</p>
|
||||
)}
|
||||
{t.series.map((s) => (
|
||||
<details key={s.import_id} open={t.series.length === 1}>
|
||||
<summary>
|
||||
{s.source} · {s.version} · {s.file_name}
|
||||
</summary>
|
||||
<p className="text-xs break-all">
|
||||
SHA256: {s.sha256}
|
||||
</p>
|
||||
{s.missing_years.length > 0 && (
|
||||
<p>
|
||||
Anos sem dados: {s.missing_years.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
{Object.keys(s.issue_counts).length > 0 && (
|
||||
<details>
|
||||
<summary>Advertências da série</summary>
|
||||
<pre className="overflow-auto text-xs">
|
||||
{JSON.stringify(
|
||||
s.issue_counts,
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
<div className="max-h-96 overflow-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="text-left">
|
||||
Valores originais por ano e dimensão —
|
||||
versões apresentadas separadamente
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
{[
|
||||
'Ano',
|
||||
'Indicador',
|
||||
'Idade',
|
||||
'Residência',
|
||||
'Valor',
|
||||
'Unidade',
|
||||
'Tipo',
|
||||
'Referência',
|
||||
].map((h) => (
|
||||
<th className="p-2" key={h}>
|
||||
{h}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{s.values.map((v) => (
|
||||
<tr
|
||||
key={`${v.sheet}:${v.cell}`}
|
||||
className="border-t"
|
||||
>
|
||||
<td className="p-2">
|
||||
{v.year}
|
||||
</td>
|
||||
<td>
|
||||
{indicators[v.indicator] ??
|
||||
v.indicator}
|
||||
</td>
|
||||
<td>
|
||||
{v.age_group === 'all'
|
||||
? 'Todas'
|
||||
: v.age_group}
|
||||
</td>
|
||||
<td>
|
||||
{
|
||||
{
|
||||
all: 'Total',
|
||||
urban: 'Urbana',
|
||||
rural: 'Rural',
|
||||
}[v.residence]
|
||||
}
|
||||
</td>
|
||||
<td>{v.original_value}</td>
|
||||
<td>
|
||||
{v.unit === 'unspecified'
|
||||
? 'Não indicada na fonte'
|
||||
: v.unit}
|
||||
</td>
|
||||
<td>
|
||||
{v.data_kind === 'projected'
|
||||
? 'Projecção'
|
||||
: 'Não especificado'}
|
||||
</td>
|
||||
<td>
|
||||
{v.sheet}!{v.cell}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
</article>
|
||||
))}
|
||||
{evidence.comparisons.length > 0 && (
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Diferenças entre localizações
|
||||
</h2>
|
||||
{evidence.comparisons.map((c) => (
|
||||
<p
|
||||
key={`${c.year}:${c.left_import}:${c.right_import}:${c.left}:${c.right}`}
|
||||
>
|
||||
{c.year}: {c.left} ({c.left_value}) / {c.right} (
|
||||
{c.right_value}). Diferença:{' '}
|
||||
{c.difference ?? 'não comparável'}. {c.explanation}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{evidence.differences.length > 0 && (
|
||||
<details>
|
||||
<summary>
|
||||
Reconciliação entre exemplares:{' '}
|
||||
{evidence.differences.length} dimensões comuns
|
||||
</summary>
|
||||
<ul>
|
||||
{evidence.differences.map((d) => (
|
||||
<li key={`${d.territory_id}:${d.dimension}`}>
|
||||
{d.dimension}:{' '}
|
||||
{d.state === 'matching_values'
|
||||
? 'valores coincidentes; conservar ambas as fontes'
|
||||
: 'valores divergentes'}{' '}
|
||||
—{' '}
|
||||
{d.values
|
||||
.map((v) => `${v.value} (${v.data_kind})`)
|
||||
.join(' / ')}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
<ul className="list-disc pl-5 text-sm">
|
||||
{evidence.limitations.map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual';
|
||||
import DemographicContext from '@/components/demographic-context';
|
||||
import { SimulationIrpcNormal } from '@/components/simulation-irpc-normal';
|
||||
import { SimulationIrpcWithholdings } from '@/components/simulation-irpc-withholdings';
|
||||
import { SimulationIspcResiduals } from '@/components/simulation-ispc-residuals';
|
||||
@@ -3077,6 +3078,10 @@ export function SimulationForm() {
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
<DemographicContext
|
||||
key={String(draft.district_id ?? draft.province_id ?? '')}
|
||||
territoryId={String(draft.district_id || draft.province_id || '')}
|
||||
/>
|
||||
<progress
|
||||
className="h-2 w-full accent-emerald-800"
|
||||
aria-label="Progresso do formulário"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import DemographicContext from './demographic-context';
|
||||
import TerritorialSources, {
|
||||
type TerritorialSourceEvidence,
|
||||
} from './territorial-source-evidence';
|
||||
@@ -95,6 +96,12 @@ export function LocationList({
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<DemographicContext
|
||||
key={location.id}
|
||||
territoryId={location.path
|
||||
.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id}
|
||||
/>
|
||||
{location.coordinates.map((point) => (
|
||||
<p key={point.geometry_id}>
|
||||
Coordenadas documentadas (
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
persistOpportunitySelection,
|
||||
} from '@/lib/opportunity-selection';
|
||||
import CatalogueGuideLinks from '@/components/catalogue-guide-links';
|
||||
import DemographicContext from '@/components/demographic-context';
|
||||
import OpportunityCorridorGroups, {
|
||||
type CorridorGroup,
|
||||
} from '@/components/opportunity-corridor-groups';
|
||||
@@ -22,7 +23,7 @@ import type { QuantitativeMapContext } from '@/components/investment-map-indicat
|
||||
import type { InvestmentMapArea } from '@/components/interactive-investment-map';
|
||||
import { type TerritoryOption } from '@/components/investment-territory';
|
||||
import { Frame, button, card, money, api } from './shared';
|
||||
import type { Opportunity, References } from './shared';
|
||||
import type { Opportunity, References, Context } from './shared';
|
||||
import {
|
||||
ArrowUpRight,
|
||||
Bookmark,
|
||||
@@ -171,7 +172,9 @@ export default function Catalogue({
|
||||
const [territoryPath, setTerritoryPath] = useState(territorySelection);
|
||||
const [saved, setSaved] = useState(favourites);
|
||||
const [selected, setSelected] = useState<number[]>([]);
|
||||
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
|
||||
const [comparison, setComparison] = useState<
|
||||
{ record: Opportunity; context?: Context }[]
|
||||
>([]);
|
||||
const comparisonRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (view === 'corridors' && comparison.length)
|
||||
@@ -406,6 +409,21 @@ export default function Catalogue({
|
||||
: 'Catálogo de investimento'
|
||||
}
|
||||
>
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
'/localizacoes/demografia' +
|
||||
(territoryPath
|
||||
.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id
|
||||
? '?territories[]=' + territoryPath
|
||||
.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id
|
||||
: '')
|
||||
}
|
||||
>
|
||||
Comparar demografia e evolução das localizações
|
||||
</Link>
|
||||
{!!territoryPath.length && (
|
||||
<Link
|
||||
className={button}
|
||||
@@ -1074,6 +1092,19 @@ export default function Catalogue({
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<th className="border p-3">Demografia INE</th>
|
||||
{comparison.map(({ record: r, context: c }) => (
|
||||
<td className="border p-3" key={r.id}>
|
||||
<DemographicContext
|
||||
key={r.id}
|
||||
territoryId={c?.primary_territory_path
|
||||
?.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id}
|
||||
/>
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import DemographicEvidence, {
|
||||
type DemographicAnalysis,
|
||||
} from '@/components/demographic-evidence';
|
||||
import { Frame, button } from './shared';
|
||||
|
||||
export default function Demography({
|
||||
evidence,
|
||||
filters,
|
||||
territories,
|
||||
sectors,
|
||||
}: {
|
||||
evidence: DemographicAnalysis;
|
||||
filters: {
|
||||
territories?: string[];
|
||||
start_year?: number;
|
||||
end_year?: number;
|
||||
sector?: string;
|
||||
};
|
||||
territories: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
parent_id: string | null;
|
||||
}[];
|
||||
sectors: Record<string, string>;
|
||||
}) {
|
||||
const [selected, setSelected] = useState(filters.territories ?? []);
|
||||
const [start, setStart] = useState(
|
||||
filters.start_year ?? new Date().getFullYear(),
|
||||
);
|
||||
const [end, setEnd] = useState(filters.end_year ?? start);
|
||||
const [sector, setSector] = useState(filters.sector ?? 'general');
|
||||
return (
|
||||
<Frame title="Demografia e viabilidade territorial">
|
||||
<p>
|
||||
Compare até quatro localizações no mesmo sector e período. Use
|
||||
esta evidência em conjunto com as condições económicas, fiscais
|
||||
e territoriais do investimento.
|
||||
</p>
|
||||
<form
|
||||
className="grid gap-4 rounded border bg-white p-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
router.get(
|
||||
'/localizacoes/demografia',
|
||||
{
|
||||
territories: selected,
|
||||
start_year: start,
|
||||
end_year: end,
|
||||
sector,
|
||||
},
|
||||
{ preserveState: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Províncias ou distritos (até quatro)
|
||||
<select
|
||||
multiple
|
||||
className="block h-48 w-full rounded border p-2"
|
||||
value={selected}
|
||||
onChange={(e) =>
|
||||
setSelected(
|
||||
Array.from(
|
||||
e.target.selectedOptions,
|
||||
(o) => o.value,
|
||||
).slice(0, 4),
|
||||
)
|
||||
}
|
||||
>
|
||||
{territories.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name} —{' '}
|
||||
{t.location_type === 'province'
|
||||
? 'Província'
|
||||
: `Distrito (${territories.find((p) => p.id === t.parent_id)?.name ?? ''})`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="space-y-3">
|
||||
<label className="block">
|
||||
Sector
|
||||
<select
|
||||
className="block w-full rounded border p-2"
|
||||
value={sector}
|
||||
onChange={(e) => setSector(e.target.value)}
|
||||
>
|
||||
{Object.entries(sectors).map(([key, label]) => (
|
||||
<option value={key} key={key}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Ano inicial
|
||||
<input
|
||||
className="block rounded border p-2"
|
||||
type="number"
|
||||
min="1900"
|
||||
max="2100"
|
||||
value={start}
|
||||
onChange={(e) => setStart(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Ano final
|
||||
<input
|
||||
className="block rounded border p-2"
|
||||
type="number"
|
||||
min={start}
|
||||
max={Math.min(2100, start + 50)}
|
||||
value={end}
|
||||
onChange={(e) => setEnd(Number(e.target.value))}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={selected.length === 0}>
|
||||
Consultar e comparar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<DemographicEvidence evidence={evidence} />
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ProactiveSummary } from '@/components/proactive-investment';
|
||||
import DemographicContext from '@/components/demographic-context';
|
||||
import EducationalGuides from '@/components/educational-guides';
|
||||
import InvestmentComplements, {
|
||||
type ComplementOption,
|
||||
@@ -183,6 +184,12 @@ export default function Detail({
|
||||
filters={{ opportunity_id: r.id }}
|
||||
territoryId={c.primary_territory_path?.at(-1)?.id}
|
||||
/>
|
||||
<DemographicContext
|
||||
key={c.primary_territory_path?.at(-1)?.id}
|
||||
territoryId={c.primary_territory_path
|
||||
?.filter((t) => ['province', 'district'].includes(t.location_type))
|
||||
.at(-1)?.id}
|
||||
/>
|
||||
{c.primary_territory_path &&
|
||||
c.primary_territory_path.length > 0 && (
|
||||
<p>
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Plan = {
|
||||
mode: 'initial' | 'remaining' | 'zambezia';
|
||||
pending_count: number;
|
||||
aliases: Record<string,string>;
|
||||
alias_sources: string[];
|
||||
missing_province_source: string | null;
|
||||
hash: string;
|
||||
ready: boolean;
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
backup_verified: boolean;
|
||||
mfa_confirmed: boolean;
|
||||
target: { database: string; port: number };
|
||||
migration: string;
|
||||
code_sha256: string;
|
||||
files: Record<string, { sha256: string; records: number; issues?: Record<string,number> }>;
|
||||
new_districts: string[];
|
||||
notice: string;
|
||||
};
|
||||
|
||||
export default function DemographyInstallation({ plan }: { plan: Plan }) {
|
||||
const [reason, setReason] = useState(
|
||||
'Disponibilização autorizada pela Tempo em 13/11/2026, preservando valores, advertências e histórico.',
|
||||
);
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [operation] = useState(createOperationKey);
|
||||
async function apply() {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const cookie =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join('=') ?? '';
|
||||
const response = await fetch('/management/demography/install', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(cookie),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
hash: plan.hash,
|
||||
mode: plan.mode,
|
||||
confirm: confirmed,
|
||||
operation_key: operation,
|
||||
reason,
|
||||
}),
|
||||
});
|
||||
const body = await response.text();
|
||||
if (!body.trim() || !response.headers.get('content-type')?.includes('application/json')) {
|
||||
throw new Error(`O servidor não devolveu um recibo JSON (HTTP ${response.status}). Consulte o estado antes de repetir a operação.`);
|
||||
}
|
||||
const result = JSON.parse(body);
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
result.message ??
|
||||
'Não foi possível disponibilizar os dados.',
|
||||
);
|
||||
router.visit('/management/demography');
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Falha de comunicação. Consulte o estado antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management title="Disponibilizar dados demográficos INE">
|
||||
<p>
|
||||
Destino:{' '}
|
||||
<strong>
|
||||
{plan.target.database}:{plan.target.port}
|
||||
</strong>
|
||||
. {plan.mode !== 'initial' ? 'Disponibiliza os ficheiros pendentes deste conjunto e acrescenta apenas os distritos autorizados, preservando todos os lotes já aprovados.' : 'Instala as tabelas demográficas e disponibiliza os três exemplares homologados.'} Mantém os dados existentes, as versões e os valores originais.
|
||||
</p>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
<dt>Backup e restauro da entrega</dt>
|
||||
<dd>
|
||||
{plan.backup_verified
|
||||
? 'Conferidos'
|
||||
: 'Pendentes ou desactualizados'}
|
||||
</dd>
|
||||
<dt>Estrutura</dt>
|
||||
<dd>
|
||||
{plan.consistent
|
||||
? plan.installed
|
||||
? 'Instalada'
|
||||
: 'Preparada'
|
||||
: 'Divergente — reconciliar'}
|
||||
</dd>
|
||||
<dt>MFA da sessão</dt>
|
||||
<dd>
|
||||
{plan.mfa_confirmed
|
||||
? 'Confirmado'
|
||||
: 'Conclua o MFA da sua conta antes de executar'}
|
||||
</dd>
|
||||
</dl>
|
||||
<table className="w-full text-left">
|
||||
<caption className="text-left font-semibold">
|
||||
Pré-visualização aprovada para disponibilização
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Exemplar</th>
|
||||
<th>Observações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{Object.entries(plan.files).map(([name, file]) => (
|
||||
<tr key={name}>
|
||||
<td>{name}</td>
|
||||
<td>{file.records.toLocaleString('pt-MZ')}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
Distritos a acrescentar quando ausentes:{' '}
|
||||
{plan.new_districts.join(' e ')}. Não são criados limites
|
||||
geográficos, licenças ou direitos territoriais.
|
||||
</p>
|
||||
<p>{plan.notice}</p>
|
||||
{plan.mode !== 'initial' && <details><summary>Conferir advertências por ficheiro</summary><p>Nas células com fórmulas, são conservados apenas os valores numéricos guardados no original. O portal não executa nem recalcula fórmulas. Valores ausentes não se tornam zero.</p><ul>{Object.entries(plan.files).map(([name,file])=><li key={name}><strong>{name}</strong><ul>{Object.entries(file.issues ?? {}).map(([code,count])=><li key={code}>{({cached_formula_value:'Valores guardados em células com fórmula',missing_value:'Valores em falta',age_total_mismatch:'Divergências na soma de idades',sex_total_mismatch:'Divergências na soma por sexo',residence_total_mismatch:'Divergências entre urbano/rural',district_total_mismatch:'Divergências na soma de distritos'} as Record<string,string>)[code] ?? code}: {count.toLocaleString('pt-MZ')}</li>)}</ul></li>)}</ul></details>}
|
||||
{plan.mode !== 'initial' && <p>{plan.pending_count} ficheiros ainda por disponibilizar. {plan.missing_province_source && <>{plan.missing_province_source}: ficheiro provincial não fornecido; não se presume cobertura anual.</>}</p>}
|
||||
{Object.keys(plan.aliases).length > 0 && <details><summary>Conferir correspondências com o cadastro existente</summary><ul>{Object.entries(plan.aliases).map(([key,name])=><li key={key}>{key.split('|').slice(0,2).join(' — ')} → {name}</li>)}</ul><p>Designações originais preservadas; os identificadores do cadastro não são renomeados ou fundidos.</p><ul>{plan.alias_sources.map(url=><li key={url}><a href={url} target="_blank" rel="noopener noreferrer">Consultar fundamento da correspondência</a></li>)}</ul></details>}
|
||||
{plan.pending_count === 0 && <p role="status">Todos os ficheiros deste conjunto já estão aprovados. Não é necessário repetir a operação.</p>}
|
||||
<label className="block">
|
||||
Motivo
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>
|
||||
Confirmo o destino, os {Object.keys(plan.files).length} exemplares, as correspondências territoriais e a preservação das advertências apresentadas.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
!plan.ready ||
|
||||
!plan.mfa_confirmed ||
|
||||
!confirmed ||
|
||||
reason.length < 20 ||
|
||||
busy
|
||||
}
|
||||
onClick={() => void apply()}
|
||||
>
|
||||
{busy ? 'A importar e conferir…' : plan.mode === 'zambezia' ? 'Disponibilizar Zambézia' : plan.mode !== 'initial' ? 'Disponibilizar restantes províncias' : 'Instalar e disponibilizar'}
|
||||
</button>
|
||||
{message && <p role="alert">{message}</p>}
|
||||
<p>
|
||||
<a className="underline" href="/localizacoes/demografia">
|
||||
Consultar os dados disponíveis
|
||||
</a>
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Preview = {
|
||||
id: string;
|
||||
file_name: string;
|
||||
sha256: string;
|
||||
publication_version: string;
|
||||
status: string;
|
||||
report: {
|
||||
record_count: number;
|
||||
issue_counts: Record<string, number>;
|
||||
issues: { code: string; sheet: string; cell: string; delta?: string }[];
|
||||
};
|
||||
matches: {
|
||||
key: string;
|
||||
province: string;
|
||||
territory: string;
|
||||
level: string;
|
||||
geo_location_id: string | null;
|
||||
state: string;
|
||||
}[];
|
||||
territory_options: {
|
||||
id: string;
|
||||
name: string;
|
||||
location_type: string;
|
||||
parent_id: string | null;
|
||||
}[];
|
||||
events: {
|
||||
id: number;
|
||||
action: string;
|
||||
reason: string;
|
||||
created_at: string;
|
||||
}[];
|
||||
};
|
||||
export default function DemographyManagement({
|
||||
batches,
|
||||
preview,
|
||||
qa = true,
|
||||
}: {
|
||||
qa?: boolean;
|
||||
batches: {
|
||||
id: string;
|
||||
file_name: string;
|
||||
publication_version: string;
|
||||
status: string;
|
||||
}[];
|
||||
preview: Preview | null;
|
||||
}) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [version, setVersion] = useState('');
|
||||
const [year, setYear] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [mapping, setMapping] = useState<Record<string, string>>({});
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function execute(path: string, body: FormData | object) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const token =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join('=') ?? '';
|
||||
const response = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token),
|
||||
...(body instanceof FormData
|
||||
? {}
|
||||
: { 'Content-Type': 'application/json' }),
|
||||
},
|
||||
body: body instanceof FormData ? body : JSON.stringify(body),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
data.message ?? 'Não foi possível executar a operação.',
|
||||
);
|
||||
setMapping({});
|
||||
router.get('/management/demography', { batch: data.id });
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error ? error.message : 'Erro de comunicação.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management
|
||||
title={
|
||||
qa ? 'Dados demográficos INE — QA' : 'Dados demográficos INE'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
Preparar não grava observações. Confirmar importa para consulta
|
||||
administrativa. Aprovar disponibiliza a série nas análises deste
|
||||
ambiente; desactivar conserva dados e histórico.
|
||||
</p>
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (!file) return;
|
||||
const body = new FormData();
|
||||
body.append('file', file);
|
||||
body.append('publication_version', version);
|
||||
if (year) body.append('baseline_year', year);
|
||||
void execute('/management/demography/prepare', body);
|
||||
}}
|
||||
>
|
||||
<label className="block">
|
||||
Excel original
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx"
|
||||
required
|
||||
className={control}
|
||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Publicação / identificação do exemplar
|
||||
<input
|
||||
required
|
||||
maxLength={255}
|
||||
className={control}
|
||||
value={version}
|
||||
onChange={(e) => setVersion(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Ano de referência, apenas para folha sem ano
|
||||
<input
|
||||
type="number"
|
||||
min="1900"
|
||||
max="2100"
|
||||
className={control}
|
||||
value={year}
|
||||
onChange={(e) => setYear(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={busy}>
|
||||
Preparar e verificar
|
||||
</button>
|
||||
</form>
|
||||
{message && <p role="alert">{message}</p>}
|
||||
<h2 className="text-xl font-semibold">Importações anteriores</h2>
|
||||
<ul>
|
||||
{batches.map((b) => (
|
||||
<li key={b.id}>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/management/demography?batch=${b.id}`}
|
||||
>
|
||||
{b.file_name} · {b.publication_version} · {b.status}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{preview && (
|
||||
<section key={preview.id} className="space-y-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
{preview.file_name} — {preview.status}
|
||||
</h2>
|
||||
<p>
|
||||
{preview.report.record_count} observações extraídas.
|
||||
SHA256: {preview.sha256}
|
||||
</p>
|
||||
<details>
|
||||
<summary>Erros e advertências</summary>
|
||||
<pre>
|
||||
{JSON.stringify(
|
||||
preview.report.issue_counts,
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
</pre>
|
||||
<div className="max-h-72 overflow-auto">
|
||||
<ul>
|
||||
{preview.report.issues.map((i, n) => (
|
||||
<li key={n}>
|
||||
{i.sheet}!{i.cell}: {i.code}{' '}
|
||||
{i.delta ?? ''}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
<h3 className="font-semibold">
|
||||
Correspondências territoriais
|
||||
</h3>
|
||||
{preview.matches.map((m) => (
|
||||
<label className="block" key={m.key}>
|
||||
{m.province} / {m.territory} ({m.level}) — {m.state}
|
||||
<select
|
||||
className={control}
|
||||
disabled={preview.status !== 'prepared'}
|
||||
value={
|
||||
mapping[m.key] ?? m.geo_location_id ?? ''
|
||||
}
|
||||
onChange={(e) =>
|
||||
setMapping({
|
||||
...mapping,
|
||||
[m.key]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Por resolver</option>
|
||||
{preview.territory_options
|
||||
.filter((t) => t.location_type === m.level)
|
||||
.map((t) => (
|
||||
<option value={t.id} key={t.id}>
|
||||
{t.name} (
|
||||
{preview.territory_options.find(
|
||||
(p) => p.id === t.parent_id,
|
||||
)?.name ?? 'Província'}
|
||||
)
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
<label className="block">
|
||||
Motivo e tratamento das advertências
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={10}
|
||||
maxLength={2000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{preview.status === 'prepared' ? (
|
||||
<button
|
||||
disabled={busy || reason.length < 10}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
`/management/demography/${preview.id}/confirm`,
|
||||
{
|
||||
sha256: preview.sha256,
|
||||
mapping,
|
||||
reason,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Confirmar importação
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
{preview.status !== 'approved' && (
|
||||
<button
|
||||
disabled={busy || reason.length < 10}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
`/management/demography/${preview.id}/transition`,
|
||||
{ action: 'approved', reason },
|
||||
)
|
||||
}
|
||||
>
|
||||
{qa
|
||||
? 'Aprovar utilização em QA'
|
||||
: 'Aprovar utilização'}
|
||||
</button>
|
||||
)}
|
||||
{preview.status !== 'disabled' && (
|
||||
<button
|
||||
disabled={busy || reason.length < 10}
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
`/management/demography/${preview.id}/transition`,
|
||||
{ action: 'disabled', reason },
|
||||
)
|
||||
}
|
||||
>
|
||||
Desactivar série
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<details>
|
||||
<summary>Histórico</summary>
|
||||
<ul>
|
||||
{preview.events.map((e) => (
|
||||
<li key={e.id}>
|
||||
{e.created_at}: {e.action} — {e.reason}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
)}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -78,6 +78,7 @@ export function Management({
|
||||
Revisão da origem das oportunidades
|
||||
</Link>
|
||||
<Link href="/management/history">Histórico</Link>
|
||||
<Link href="/management/demography">Demografia INE</Link>
|
||||
<Link href="/management/crm/leads">CRM</Link>
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
|
||||
Reference in New Issue
Block a user