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>
);
}
+26 -1
View File
@@ -1,6 +1,7 @@
import { Link, router, useForm, usePage } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import Map from '@/components/interactive-investment-map';
import type { InvestmentMapArea } from '@/components/interactive-investment-map';
import {
TerritoryLevel,
type TerritoryOption,
@@ -57,6 +58,7 @@ export default function Catalogue({
q: String(filters.q ?? ''),
dimension: String(filters.dimension ?? ''),
view: String(filters.view ?? 'grid'),
territory_basis: String(filters.territory_basis ?? 'all'),
sector: String(filters.sector ?? ''),
province: String(filters.province ?? ''),
district: String(filters.district ?? ''),
@@ -91,6 +93,7 @@ export default function Catalogue({
const [selected, setSelected] = useState<number[]>([]);
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
const [points, setPoints] = useState<Feature[] | null>(null);
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
const [unlocated, setUnlocated] = useState<
{ id: number; title: string; location: string; url: string }[]
>([]);
@@ -147,6 +150,7 @@ export default function Catalogue({
);
}
setPoints(null);
setAreas([]);
setUnlocated([]);
setTruncated(false);
setError('');
@@ -154,6 +158,7 @@ export default function Catalogue({
.then((data) => {
if (active) {
setPoints(data.features);
setAreas(data.areas ?? []);
setUnlocated(data.unlocated ?? []);
setTruncated(Boolean(data.truncated));
}
@@ -551,6 +556,26 @@ export default function Catalogue({
/>
</Field>
</section>
<Field label="Base da relação territorial">
<select
className={input}
value={form.data.territory_basis}
onChange={(e) =>
form.setData('territory_basis', e.target.value)
}
>
<option value="all">
Implantação e contexto associado
</option>
<option value="direct">
Implantação declarada da oportunidade
</option>
<option value="context">
Apenas contexto associado; implantação por
documentar
</option>
</select>
</Field>
<label className="flex gap-2">
<input
type="checkbox"
@@ -1060,7 +1085,7 @@ export default function Catalogue({
</Link>
</div>
{error && <p role="alert">{error}</p>}
{!error && <Map points={points} />}
{!error && <Map points={points} areas={areas} />}
{truncated && (
<p role="alert">
O mapa atingiu o limite de 1.000 registos; refine os
+25 -2
View File
@@ -1,8 +1,11 @@
import { Link, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import InvestmentMapPanel from '@/components/investment-map-panel';
import StructureGeographyPanel from '@/components/structure-geography';
import StructureGeographyPanel, {
LocationList,
} from '@/components/structure-geography';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import TerritorialSources from '@/components/territorial-source-evidence';
import { Frame, card, button, money, groupLabels } from './shared';
import type { Opportunity, Context } from './shared';
export default function Detail({
@@ -48,11 +51,31 @@ export default function Detail({
</p>
)}
<p className="text-xl">{r.summary}</p>
<TerritorialSources sources={c.source_evidence} />
<section className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
Implantação declarada da oportunidade
</h2>
<p>
As relações cadastradas não confirmam disponibilidade ou
capacidade. Locais dos projetos associados, áreas de impacto
e abrangência dos clusters são apresentados separadamente.
</p>
<LocationList locations={c.opportunity_locations ?? []} />
{!c.opportunity_locations?.length && (
<p>
Implantação estruturada não documentada. O contexto
associado abaixo não confirma onde a oportunidade será
implantada.
</p>
)}
</section>
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
{c.primary_territory_path &&
c.primary_territory_path.length > 0 && (
<p>
Localização:{' '}
Território principal cadastrado (implantação por
confirmar):{' '}
{c.primary_territory_path
.map((node) => node.name)
.join(' → ')}
+7 -1
View File
@@ -1,7 +1,11 @@
import { Head, Link, usePage } from '@inertiajs/react';
import type { ReactNode } from 'react';
import { PortalMenu } from '@/layouts/portal-navigation';
import type { StructureGeography } from '@/components/structure-geography';
import type { TerritorialSourceEvidence } from '@/components/territorial-source-evidence';
import type {
StructureGeography,
DocumentedLocation,
} from '@/components/structure-geography';
export type Option = {
id: number;
@@ -47,6 +51,8 @@ export type Opportunity = {
last_validated_at?: string | null;
};
export type Context = {
source_evidence?: TerritorialSourceEvidence[];
opportunity_locations?: DocumentedLocation[];
primary_territory_path?: {
id: string;
name: string;
+6
View File
@@ -8,6 +8,9 @@ import {
import { useState } from 'react';
import { Frame, Field, input, button, card, api } from './shared';
import PartnershipSourceLinks from '@/components/partnership-source-links';
import TerritorialSources, {
type TerritorialSourceEvidence,
} from '@/components/territorial-source-evidence';
import ZoneRelations from './zone-relations';
import ZoneMap from './zone-map';
import ZoneAttachments from './zone-attachments';
@@ -124,6 +127,7 @@ type Props = {
validation_status: string;
}[];
record: Zone;
territorialSources?: TerritorialSourceEvidence[];
management: boolean;
zoneExtensionsAvailable?: boolean;
source: Source | null;
@@ -186,6 +190,7 @@ function Editor({
relations,
geometries,
record: z,
territorialSources,
management,
zoneExtensionsAvailable = false,
source,
@@ -268,6 +273,7 @@ function Editor({
}
return (
<Frame title={z.name}>
<TerritorialSources sources={territorialSources} />
{!management && <PartnershipSourceLinks type="zone" id={z.id} />}
<p>
{z.code} · {z.category.toUpperCase()} · {z.validation_status} ·{' '}
@@ -1,5 +1,8 @@
import { Link, useForm } from '@inertiajs/react';
import { Management } from './shared';
import TerritorialTraceabilityPlan, {
type TraceabilityPlan,
} from '@/components/territorial-traceability-plan';
type Plan = {
target: { database: string; port: number };
@@ -149,16 +152,21 @@ export default function RelationshipRepair({
territorial,
history,
unproposed,
traceability,
}: {
hash: string;
plan: Plan;
territorial: Territory[];
history: History[];
unproposed: Unproposed[];
traceability?: TraceabilityPlan | null;
}) {
const form = useForm({ hash });
return (
<Management title="Associações documentadas de projectos âncora e clusters">
{traceability && (
<TerritorialTraceabilityPlan preview={traceability} />
)}
<p>
Pré-visualização para {plan.target.database}:{plan.target.port}.
A execução verifica o backup e o restauro, a versão dos dossiers