Consolida rastreabilidade territorial e plano autenticado V2

This commit is contained in:
2026-10-09 02:05:44 +02:00
parent 30acdc9934
commit 6a71aa47e3
33 changed files with 2555 additions and 49 deletions
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import type { Map as LeafletMap, Marker } from 'leaflet';
import type { GeoJsonObject } from 'geojson';
import 'leaflet/dist/leaflet.css';
export type InvestmentMapFeature = {
@@ -13,13 +14,25 @@ export type InvestmentMapFeature = {
clusters?: string[];
corridors?: string[];
projects?: string[];
source_reference?: string | null;
source_date?: string | null;
};
};
export type InvestmentMapArea = {
geometry: GeoJsonObject;
title: string;
source_reference?: string | null;
source_date?: string | null;
url: string;
};
const noAreas: InvestmentMapArea[] = [];
export default function InteractiveInvestmentMap({
points,
areas = noAreas,
}: {
points: InvestmentMapFeature[] | null;
areas?: InvestmentMapArea[];
}) {
const element = useRef<HTMLDivElement>(null);
const map = useRef<LeafletMap | null>(null);
@@ -35,6 +48,9 @@ export default function InteractiveInvestmentMap({
const instance = L.map(element.current, {
scrollWheelZoom: false,
keyboard: true,
zoomAnimation: false,
fadeAnimation: false,
markerZoomAnimation: false,
}).setView([-18.5, 35], 5);
map.current = instance;
L.tileLayer(
@@ -55,6 +71,19 @@ export default function InteractiveInvestmentMap({
.addTo(instance);
L.control.scale({ imperial: false }).addTo(instance);
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)
.bindPopup(label)
.addTo(instance);
const extent = layer.getBounds();
if (extent.isValid())
bounds.push(
[extent.getSouth(), extent.getWest()],
[extent.getNorth(), extent.getEast()],
);
}
for (const [index, point] of (points ?? []).entries()) {
const [longitude, latitude] = point.geometry.coordinates;
if (
@@ -72,6 +101,7 @@ export default function InteractiveInvestmentMap({
for (const text of [
p.category,
p.location,
`Fonte: ${p.source_reference ?? 'Não indicada'} · Data: ${p.source_date ?? 'Não documentada'}`,
`Corredor: ${p.corridors?.join(', ') || 'Não associado'}`,
`Cluster: ${p.clusters?.join(', ') || 'Não associado'}`,
`Projecto âncora: ${p.projects?.join(', ') || 'Não associado'}`,
@@ -98,18 +128,22 @@ export default function InteractiveInvestmentMap({
alt: p.title,
keyboard: true,
})
.bindPopup(popup)
.on('click', () => setSelected(p.id))
.bindPopup(popup, { autoPan: false })
.on('click', () => setSelected(index))
.addTo(instance);
markers.current.set(p.id, marker);
markers.current.set(index, marker);
bounds.push([latitude, longitude]);
}
if (bounds.length)
instance.fitBounds(bounds, {
padding: [40, 40],
maxZoom: 14,
animate: false,
});
observer = new ResizeObserver(() => instance.invalidateSize());
observer = new ResizeObserver(() => {
if (!cancelled)
instance.invalidateSize({ animate: false, pan: false });
});
observer.observe(element.current);
})
.catch(() => {
@@ -122,7 +156,7 @@ export default function InteractiveInvestmentMap({
map.current = null;
markers.current.clear();
};
}, [points]);
}, [points, areas]);
return (
<section
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
@@ -143,15 +177,15 @@ export default function InteractiveInvestmentMap({
<p role="status">A carregar localizações…</p>
) : (
<p role="status">
{points.length} investimentos com coordenadas disponíveis.
{points.length} locais com coordenadas disponíveis.
</p>
)}
<ul className="grid gap-2 md:grid-cols-2">
{(points ?? []).map((p) => (
{(points ?? []).map((p, index) => (
<li
key={p.properties.id}
key={index}
className={
selected === p.properties.id
selected === index
? 'rounded border-2 border-emerald-700 p-3'
: 'rounded border p-3'
}
@@ -159,18 +193,17 @@ export default function InteractiveInvestmentMap({
<button
type="button"
className="text-left font-bold underline"
aria-pressed={selected === p.properties.id}
aria-pressed={selected === index}
onClick={() => {
const marker = markers.current.get(
p.properties.id,
);
const marker = markers.current.get(index);
if (marker) {
map.current?.setView(
marker.getLatLng(),
14,
{ animate: false },
);
marker.openPopup();
setSelected(p.properties.id);
setSelected(index);
}
}}
>
@@ -179,12 +212,28 @@ export default function InteractiveInvestmentMap({
<p>
{p.properties.category} · {p.properties.location}
</p>
<p>
Fonte:{' '}
{p.properties.source_reference ?? 'Não indicada'} ·
Data:{' '}
{p.properties.source_date ?? 'Não documentada'}
</p>
<a className="underline" href={p.properties.url}>
Abrir ficha
</a>
</li>
))}
</ul>
{areas.map((area, index) => (
<p key={index}>
<a className="underline" href={area.url}>
{area.title}
</a>{' '}
· Polígono cadastrado, limites oficiais por verificar ·
Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
{area.source_date ?? 'Não documentada'}
</p>
))}
</section>
);
}
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import InteractiveInvestmentMap, {
type InvestmentMapFeature,
type InvestmentMapArea,
} from './interactive-investment-map';
export default function InvestmentMapPanel({
@@ -14,10 +15,12 @@ export default function InvestmentMapPanel({
{ id: number; title: string; url: string }[]
>([]);
const [error, setError] = useState('');
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
setPoints(null);
setAreas([]);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
headers: { Accept: 'application/json' },
@@ -29,6 +32,7 @@ export default function InvestmentMapPanel({
.then((data) => {
if (controller.signal.aborted) return;
setPoints(data.features);
setAreas(data.areas ?? []);
setMissing(data.unlocated ?? []);
setError(
data.truncated
@@ -44,12 +48,13 @@ export default function InvestmentMapPanel({
return (
<section className="space-y-3">
{error && <p role="alert">{error}</p>}
<InteractiveInvestmentMap points={points} />
<InteractiveInvestmentMap points={points} areas={areas} />
{missing.length > 0 && (
<div>
<p>
{missing.length} investimentos aguardam coordenadas do
local:
{missing.length} investimentos sem ponto público
utilizável. Consulte as fichas para localizações
documentadas sem coordenadas:
</p>
<ul>
{missing.map((record) => (
@@ -1,4 +1,8 @@
import { Link } from '@inertiajs/react';
import TerritorialSources, {
type TerritorialSourceEvidence,
} from './territorial-source-evidence';
import type { GeoJsonObject } from 'geojson';
import InteractiveInvestmentMap from './interactive-investment-map';
export type DocumentedLocation = {
@@ -6,15 +10,24 @@ export type DocumentedLocation = {
name: string;
role: string;
source_reference?: string;
source_date?: string | null;
boundaries?: {
geometry_id: string;
source_reference: string | null;
source_date: string | null;
geometry: GeoJsonObject;
}[];
location_type: string;
path: { id: string; name: string; location_type: string }[];
coordinates: {
geometry_id: string;
source_reference: string;
source_reference: string | null;
source_date?: string | null;
geometry: { coordinates: [number, number] };
}[];
};
export type StructureGeography = {
source_evidence?: TerritorialSourceEvidence[];
locations: DocumentedLocation[];
members: {
id: string;
@@ -44,6 +57,7 @@ export type StructureGeography = {
};
const roles: Record<string, string> = {
opportunity: 'Implantação cadastrada da oportunidade',
primary: 'Localização principal',
secondary: 'Localização secundária',
impact: 'Área de impacto',
@@ -85,11 +99,13 @@ export function LocationList({
<p key={point.geometry_id}>
Coordenadas documentadas (
{location.location_type === 'site'
? 'local do projecto'
? 'local cadastrado; não confirma a implantação da oportunidade'
: 'referência territorial; não representa a implantação'}
): {point.geometry.coordinates[1]},{' '}
{point.geometry.coordinates[0]} · Fonte:{' '}
{point.source_reference}
{point.source_reference ?? 'Não indicada'}
{' · Data da fonte: '}
{point.source_date ?? 'Não documentada'}
</p>
))}
{!location.coordinates.length && (
@@ -98,7 +114,20 @@ export function LocationList({
<p className="text-sm">
Fonte da relação:{' '}
{location.source_reference ?? 'Não indicada'}
{' · Data da fonte: '}
{location.source_date ?? 'Não documentada'}
</p>
{location.boundaries?.map((boundary) => (
<p key={boundary.geometry_id}>
Polígono cadastrado · Fonte:{' '}
{boundary.source_reference ?? 'Não indicada'} ·
Data: {boundary.source_date ?? 'Não documentada'}. O
cadastro não certifica limites oficiais.
</p>
))}
{!location.boundaries?.length && (
<p>Polígono não documentado.</p>
)}
<Link
className="underline"
href={`/oportunidades?geo_location_id=${location.id}`}
@@ -165,6 +194,7 @@ export default function StructureGeographyPanel({
: 'Localização documentada do projecto'}
</h2>
<LocationList locations={geography.locations} />
<TerritorialSources sources={geography.source_evidence} />
{!geography.locations.length && (
<p>
{cluster
@@ -178,7 +208,27 @@ export default function StructureGeographyPanel({
um ponto único atribuído ao cluster.
</p>
)}
<InteractiveInvestmentMap points={points} />
<InteractiveInvestmentMap
points={points}
areas={[
...items.flatMap((item) =>
(item.location.boundaries ?? []).map((area) => ({
...area,
title: `${roles[item.location.role] ?? item.location.role} · ${item.title}`,
url: item.url,
})),
),
...(cluster
? geography.locations.flatMap((location) =>
(location.boundaries ?? []).map((area) => ({
...area,
title: `Abrangência do cluster · ${location.name}`,
url: `/carteira/${dossierId}`,
})),
)
: []),
]}
/>
{!points.length && (
<p>
Sem coordenadas documentadas dos locais. Nenhum ponto foi
@@ -0,0 +1,52 @@
export type TerritorialSourceEvidence = {
association: string;
role: string;
source_reference: string | null;
source_quote: string | null;
supports: string;
traceability: string;
official_source_accepted: boolean;
existing_validation: string | null;
};
export default function TerritorialSources({
sources,
}: {
sources?: TerritorialSourceEvidence[];
}) {
if (!sources?.length) return null;
return (
<section className="space-y-3 rounded border p-4">
<h2 className="text-xl font-bold">
Fundamento documental das associações
</h2>
<p>
Fontes oficiais identificadas são aceites; recuperar uma
referência não retira a aceitação existente. O fundamento
aplica-se à informação indicada, sem deduzir implantação,
disponibilidade ou capacidade.
</p>
{sources.map((source, i) => (
<article className="border-t pt-3" key={i}>
<h3 className="font-semibold">
{source.role} — {source.association}
</h3>
<p>
Fonte:{' '}
{source.source_reference ??
'ligação ao exemplar por recuperar'}
</p>
<p>{source.source_quote ?? source.supports}</p>
<p>
{source.official_source_accepted
? 'Fonte oficial identificada e aceite.'
: 'Aceitação existente preservada; ponte ao exemplar oficial por recuperar. Esta referência não recebe outra classificação de proveniência.'}{' '}
Rastreabilidade: {source.traceability}. Estado
registado:{' '}
{source.existing_validation ?? 'sem campo específico'};
preservado.
</p>
</article>
))}
</section>
);
}
@@ -0,0 +1,155 @@
import { useForm } from '@inertiajs/react';
export type TraceabilityPlan = {
hash: string;
code_matches: boolean;
backup_ready: boolean;
applied: boolean;
plan: {
target: { database: string; port: number };
rows: {
key: string;
reference: string;
association: string;
role: string;
source_reference: string | null;
source_quote: string | null;
supports: string;
traceability: string;
existing_validation: string | null;
effect: string;
}[];
updates: {
id: string;
reference: string;
current: {
source_reference: string | null;
evidence_reference: string | null;
};
values: { source_reference: string; evidence_reference: string };
source_quote: string;
effect: string;
}[];
pending: { reference: string; reason: string }[];
};
};
export default function TerritorialTraceabilityPlan({
preview,
}: {
preview: TraceabilityPlan;
}) {
const form = useForm({
hash: preview.hash,
operation: 'traceability',
reverse: false,
});
return (
<section className="space-y-4 rounded border p-5">
<h2 className="text-xl font-bold">
V2 — aplicar rastreabilidade territorial
</h2>
<p>
Destino: {preview.plan.target.database}:
{preview.plan.target.port}. Fontes oficiais identificadas são
aceites; não se repete validação da proveniência. Estados
existentes são preservados.
</p>
<p>
{preview.plan.rows.length} associações/fontes;{' '}
{preview.plan.updates.length} atualizações de referências.
Nenhuma nova implantação ou relação por proximidade.
</p>
<p role="status">
Backup/restauro/reversão:{' '}
{preview.backup_ready
? 'verificados (validade 24 horas)'
: 'pendentes ou expirados'}{' '}
· Código:{' '}
{preview.code_matches
? 'corresponde ao plano'
: 'plano deve ser atualizado'}{' '}
· Aplicação: {preview.applied ? 'aplicada' : 'não aplicada'}
</p>
<form
onSubmit={(e) => {
e.preventDefault();
form.transform(() => ({
hash: preview.hash,
operation: 'traceability',
reverse: preview.applied,
}));
form.post('/management/relationship-repair', {
preserveScroll: true,
});
}}
>
<button
disabled={
form.processing ||
!preview.backup_ready ||
!preview.code_matches
}
className="rounded bg-emerald-800 px-4 py-3 text-white disabled:opacity-50"
>
{preview.applied
? 'Reverter este incremento de rastreabilidade'
: 'Aplicar rastreabilidade territorial V2'}
</button>
{Object.values(form.errors).map((error) => (
<p role="alert" key={error}>
{error}
</p>
))}
</form>
<h3 className="font-bold">Alterações aos campos existentes</h3>
{preview.plan.updates.map((update) => (
<article className="border-t py-3" key={update.id}>
<h4 className="font-bold">{update.reference}</h4>
<p>
Referência atual:{' '}
{update.current.source_reference ?? 'não preenchida'};
evidência atual:{' '}
{update.current.evidence_reference ?? 'não preenchida'}.
</p>
<p>
Proposta: {update.values.source_reference}; dossier{' '}
{update.values.evidence_reference}.
</p>
<p>Fundamento: {update.source_quote}</p>
<p>{update.effect}</p>
</article>
))}
<h3 className="font-bold">Fundamento por associação</h3>
{preview.plan.rows.map((row) => (
<article className="border-t py-3" key={row.key}>
<h3 className="font-bold">
{row.reference} — {row.association} ({row.role})
</h3>
<p>
Atual:{' '}
{row.existing_validation ??
'sem campo de validação nesta associação'}
; estado preservado.
</p>
<p>
Proposta: ligar a referência e o fundamento. Fonte:{' '}
{row.source_reference ?? 'por recuperar no acervo'}
</p>
<p>Citação/âmbito: {row.source_quote ?? row.supports}</p>
<p>
Rastreabilidade: {row.traceability} · Efeito:{' '}
{row.effect}
</p>
</article>
))}
<h3 className="font-bold">
Pendências de rastreabilidade (não invalidam dados)
</h3>
{preview.plan.pending.map((row, i) => (
<p key={i}>
{row.reference}: {row.reason}
</p>
))}
</section>
);
}