commit16
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapArea,
|
||||
type InvestmentMapFeature,
|
||||
type InvestmentMapKind,
|
||||
} from './interactive-investment-map';
|
||||
import { TerritoryGeometryDetails } from './territory-geometry-preview';
|
||||
import { useTerritoryGeometry } from './use-territory-geometry';
|
||||
const noAreas: InvestmentMapArea[] = [];
|
||||
|
||||
export default function CatalogueInvestmentMap({
|
||||
points,
|
||||
areas = noAreas,
|
||||
territoryId,
|
||||
mapKind,
|
||||
}: {
|
||||
points: InvestmentMapFeature[] | null;
|
||||
areas?: InvestmentMapArea[];
|
||||
territoryId?: string;
|
||||
mapKind?: InvestmentMapKind;
|
||||
}) {
|
||||
const { context, error } = useTerritoryGeometry(territoryId);
|
||||
return (
|
||||
<InteractiveInvestmentMap
|
||||
points={points}
|
||||
areas={areas}
|
||||
administrativeAreas={context?.areas}
|
||||
layerControls
|
||||
mapKind={mapKind}
|
||||
administrativeInfo={
|
||||
territoryId ? (
|
||||
<TerritoryGeometryDetails
|
||||
context={context}
|
||||
error={error}
|
||||
showSources={false}
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
notice={
|
||||
territoryId ? (
|
||||
<>
|
||||
{error && (
|
||||
<p role="alert">
|
||||
{error} Os restantes dados do mapa continuam
|
||||
disponíveis.
|
||||
</p>
|
||||
)}
|
||||
{!context && !error && (
|
||||
<p role="status">
|
||||
A carregar limites administrativos…
|
||||
</p>
|
||||
)}
|
||||
{context && !context.selected_geometry_available && (
|
||||
<p role="note">
|
||||
Sem limite administrativo acessível para o
|
||||
território seleccionado.
|
||||
{context.areas.length > 0
|
||||
? ' Os limites de níveis superiores são apenas contexto e não representam a selecção.'
|
||||
: ''}
|
||||
</p>
|
||||
)}
|
||||
{context?.truncated && (
|
||||
<p role="alert">
|
||||
Cobertura administrativa incompleta: são
|
||||
apresentados até 100 limites.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -94,9 +94,6 @@ export default function CountrySelect({
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{matches.length === 0 && (
|
||||
<p role="status">Nenhum país corresponde à pesquisa.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
import type { Definition, Field } from '@/pages/desk/service-editor';
|
||||
|
||||
type Version = {
|
||||
id: string;
|
||||
version: number;
|
||||
status: string;
|
||||
author_id: number | null;
|
||||
published_by: number | null;
|
||||
published_at: string | null;
|
||||
definition: Definition;
|
||||
source: { identifier?: string; edition?: string; sha256?: string };
|
||||
reason: string | null;
|
||||
};
|
||||
type History = { page: number; pages: number; total: number; data: Version[] };
|
||||
const publishedDate = (value: string | null) => {
|
||||
if (!value) return 'Não indicada';
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? 'Não indicada'
|
||||
: date.toLocaleString('pt-MZ');
|
||||
};
|
||||
|
||||
export default function DeskServiceHistory({
|
||||
code,
|
||||
formatField,
|
||||
}: {
|
||||
code: string;
|
||||
formatField: (field: Field) => string;
|
||||
}) {
|
||||
const [page, setPage] = useState(1);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const key = JSON.stringify([code, page, attempt]);
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
history: History | null;
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void portalRequest<History>(
|
||||
`/management/balcao/servicos/${encodeURIComponent(code)}/versoes?page=${page}`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((history) => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (
|
||||
!history ||
|
||||
!Array.isArray(history.data) ||
|
||||
!Number.isSafeInteger(history.page) ||
|
||||
!Number.isSafeInteger(history.pages) ||
|
||||
!Number.isSafeInteger(history.total) ||
|
||||
history.page < 1 ||
|
||||
history.pages < history.page ||
|
||||
history.total < 0 ||
|
||||
history.data.some(
|
||||
(row) =>
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
!Number.isSafeInteger(row.version) ||
|
||||
!row.definition ||
|
||||
typeof row.definition.title !== 'string' ||
|
||||
!row.definition.fields ||
|
||||
typeof row.definition.fields !== 'object' ||
|
||||
Array.isArray(row.definition.fields) ||
|
||||
Object.values(row.definition.fields).some(
|
||||
(field) =>
|
||||
!field ||
|
||||
typeof field.label !== 'string' ||
|
||||
typeof field.type !== 'string',
|
||||
),
|
||||
)
|
||||
)
|
||||
throw new Error('Invalid version history');
|
||||
setResult({ key, history });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, history: null });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [code, page, attempt, key]);
|
||||
const current = result?.key === key ? result : null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-4 rounded-xl border bg-white p-5 [overflow-wrap:anywhere]"
|
||||
aria-label="Histórico dos formulários"
|
||||
aria-busy={!current}
|
||||
>
|
||||
<h2 className="text-xl font-bold">Versões anteriores e autoria</h2>
|
||||
<p>
|
||||
Consulta das definições guardadas. Esta área não altera versões
|
||||
nem apresenta respostas dos requerentes.
|
||||
</p>
|
||||
{!current ? (
|
||||
<p role="status">A recuperar versões…</p>
|
||||
) : !current.history ? (
|
||||
<div role="alert">
|
||||
<p>Não foi possível recuperar o histórico.</p>
|
||||
<button
|
||||
className="underline"
|
||||
type="button"
|
||||
onClick={() => setAttempt((value) => value + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{current.history.total} versões · página{' '}
|
||||
{current.history.page} de {current.history.pages}
|
||||
</p>
|
||||
{current.history.data.length === 0 && (
|
||||
<p>
|
||||
Ainda não existem versões guardadas para este
|
||||
serviço.
|
||||
</p>
|
||||
)}
|
||||
{current.history.data.map((version) => (
|
||||
<details
|
||||
key={version.id}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<summary>
|
||||
Versão {version.version} —{' '}
|
||||
{version.definition.title} ·{' '}
|
||||
{version.status === 'published'
|
||||
? 'Publicada'
|
||||
: 'Preparada'}
|
||||
</summary>
|
||||
<dl className="mt-3 space-y-2">
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Autor / publicador (identificadores)
|
||||
</dt>
|
||||
<dd>
|
||||
{version.author_id ?? 'Não indicado'} /{' '}
|
||||
{version.published_by ?? 'Não indicado'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Publicação
|
||||
</dt>
|
||||
<dd>
|
||||
{publishedDate(version.published_at)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Motivo registado
|
||||
</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{version.reason ||
|
||||
'Não disponível nesta versão.'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Fonte da definição
|
||||
</dt>
|
||||
<dd>
|
||||
{version.source?.identifier ||
|
||||
'Não indicada'}
|
||||
{version.source?.edition
|
||||
? ` · ${version.source.edition}`
|
||||
: ''}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<h3 className="mt-3 font-semibold">
|
||||
Identificação e percurso
|
||||
</h3>
|
||||
<p>
|
||||
{version.definition.theme} ·{' '}
|
||||
{version.definition.profile} ·{' '}
|
||||
{version.definition.entity} · etapa{' '}
|
||||
{version.definition.stage}
|
||||
</p>
|
||||
<p>{version.definition.result}</p>
|
||||
<h3 className="mt-3 font-semibold">
|
||||
Perguntas e regras desta versão
|
||||
</h3>
|
||||
<dl className="space-y-2">
|
||||
{Object.entries(version.definition.fields).map(
|
||||
([id, field]) => (
|
||||
<div key={id}>
|
||||
<dt className="font-semibold">
|
||||
{id}
|
||||
</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{formatField(field)}
|
||||
</dd>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</dl>
|
||||
</details>
|
||||
))}
|
||||
<nav
|
||||
className="flex gap-4"
|
||||
aria-label="Páginas do histórico"
|
||||
>
|
||||
<button
|
||||
className="underline disabled:opacity-50"
|
||||
type="button"
|
||||
disabled={current.history.page <= 1}
|
||||
onClick={() => setPage(current.history!.page - 1)}
|
||||
>
|
||||
Anterior
|
||||
</button>
|
||||
<button
|
||||
className="underline disabled:opacity-50"
|
||||
type="button"
|
||||
disabled={
|
||||
current.history.page >= current.history.pages
|
||||
}
|
||||
onClick={() => setPage(current.history!.page + 1)}
|
||||
>
|
||||
Seguinte
|
||||
</button>
|
||||
</nav>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -485,7 +485,7 @@ export function DossierPrefill(props: Props) {
|
||||
setReviewed(false);
|
||||
props.onReview?.(view.context.revision, false);
|
||||
setMessage(
|
||||
'Valores selecionados aplicados ao formulário. Os outros valores e os snapshots anteriores foram preservados.',
|
||||
'Dados seleccionados aplicados. Os restantes campos e as versões anteriores foram conservados.',
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Map as LeafletMap, Marker } from 'leaflet';
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import type {
|
||||
Map as LeafletMap,
|
||||
Marker,
|
||||
LayerGroup,
|
||||
LayersControlEvent,
|
||||
} from 'leaflet';
|
||||
import type { GeoJsonObject } from 'geojson';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
|
||||
@@ -29,24 +34,87 @@ export type InvestmentMapArea = {
|
||||
url: string;
|
||||
};
|
||||
const noAreas: InvestmentMapArea[] = [];
|
||||
export type InvestmentMapKind =
|
||||
| 'investments'
|
||||
| 'administrative'
|
||||
| 'documented_locations'
|
||||
| 'declared_parcel';
|
||||
|
||||
export default function InteractiveInvestmentMap({
|
||||
points,
|
||||
areas = noAreas,
|
||||
contextOnly = false,
|
||||
mapKind = contextOnly ? 'administrative' : 'investments',
|
||||
administrativeAreas = noAreas,
|
||||
layerControls = false,
|
||||
administrativeInfo,
|
||||
notice,
|
||||
}: {
|
||||
points: InvestmentMapFeature[] | null;
|
||||
areas?: InvestmentMapArea[];
|
||||
contextOnly?: boolean;
|
||||
mapKind?: InvestmentMapKind;
|
||||
administrativeAreas?: InvestmentMapArea[];
|
||||
layerControls?: boolean;
|
||||
administrativeInfo?: ReactNode;
|
||||
notice?: ReactNode;
|
||||
}) {
|
||||
const title = {
|
||||
investments: 'Mapa dos investimentos',
|
||||
administrative: 'Contexto administrativo',
|
||||
documented_locations: 'Mapa dos locais documentados',
|
||||
declared_parcel: 'Perímetro declarado pelo Promotor',
|
||||
}[mapKind];
|
||||
const areaDescription = (area: InvestmentMapArea) =>
|
||||
area.purpose === 'administrative_boundary'
|
||||
? 'Limite administrativo da edição indicada; não representa um local de investimento'
|
||||
: area.purpose === 'declared_parcel'
|
||||
? 'Perímetro declarado pelo Promotor; não é limite administrativo nem comprova disponibilidade legal'
|
||||
: mapKind === 'documented_locations'
|
||||
? 'Área documentada na fonte; não confirma implantação de investimento'
|
||||
: 'Polígono cadastrado; comparação com limite administrativo pendente';
|
||||
const allAreas = useMemo(() => {
|
||||
const unique = new Map<string, InvestmentMapArea>();
|
||||
for (const area of [
|
||||
...areas,
|
||||
...administrativeAreas.map((area) => ({
|
||||
...area,
|
||||
purpose: 'administrative_boundary',
|
||||
})),
|
||||
]) {
|
||||
const key = JSON.stringify([
|
||||
area.geometry,
|
||||
area.purpose,
|
||||
area.title,
|
||||
area.source_reference,
|
||||
area.source_date,
|
||||
]);
|
||||
const previous = unique.get(key);
|
||||
unique.set(key, {
|
||||
...area,
|
||||
selected_territory: Boolean(
|
||||
previous?.selected_territory || area.selected_territory,
|
||||
),
|
||||
});
|
||||
}
|
||||
return [...unique.values()];
|
||||
}, [areas, administrativeAreas]);
|
||||
const element = useRef<HTMLDivElement>(null);
|
||||
const map = useRef<LeafletMap | null>(null);
|
||||
const markers = useRef(new Map<number, Marker>());
|
||||
const pointLayer = useRef<LayerGroup | null>(null);
|
||||
const visibility = useRef({
|
||||
points: true,
|
||||
investments: true,
|
||||
administrative: true,
|
||||
});
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let observer: ResizeObserver | undefined;
|
||||
setError('');
|
||||
setSelected(null);
|
||||
void import('leaflet')
|
||||
.then((L) => {
|
||||
if (cancelled || !element.current) return;
|
||||
@@ -75,8 +143,64 @@ export default function InteractiveInvestmentMap({
|
||||
})
|
||||
.addTo(instance);
|
||||
L.control.scale({ imperial: false }).addTo(instance);
|
||||
const groups = {
|
||||
points: L.layerGroup(),
|
||||
investments: L.layerGroup(),
|
||||
administrative: L.layerGroup(),
|
||||
};
|
||||
pointLayer.current = groups.points;
|
||||
for (const key of Object.keys(
|
||||
groups,
|
||||
) as (keyof typeof groups)[]) {
|
||||
if (!layerControls || visibility.current[key])
|
||||
groups[key].addTo(instance);
|
||||
}
|
||||
if (layerControls) {
|
||||
const overlays: Record<string, LayerGroup> = {};
|
||||
if (points === null || points.length)
|
||||
overlays[
|
||||
mapKind === 'investments'
|
||||
? 'Oportunidades com coordenadas'
|
||||
: 'Locais documentados com coordenadas'
|
||||
] = groups.points;
|
||||
if (
|
||||
allAreas.some(
|
||||
(area) =>
|
||||
area.purpose !== 'administrative_boundary',
|
||||
)
|
||||
)
|
||||
overlays[
|
||||
mapKind === 'investments'
|
||||
? 'Áreas de investimento cadastradas'
|
||||
: 'Áreas documentadas'
|
||||
] = groups.investments;
|
||||
if (
|
||||
allAreas.some(
|
||||
(area) =>
|
||||
area.purpose === 'administrative_boundary',
|
||||
)
|
||||
)
|
||||
overlays['Limites administrativos'] =
|
||||
groups.administrative;
|
||||
L.control
|
||||
.layers(undefined, overlays, { collapsed: false })
|
||||
.addTo(instance);
|
||||
instance.on('overlayadd overlayremove', (event) => {
|
||||
const changed = event as LayersControlEvent;
|
||||
for (const key of Object.keys(
|
||||
groups,
|
||||
) as (keyof typeof groups)[]) {
|
||||
if (changed.layer === groups[key])
|
||||
visibility.current[key] =
|
||||
event.type === 'overlayadd';
|
||||
}
|
||||
});
|
||||
}
|
||||
const bounds: [number, number][] = [];
|
||||
const hasSelectedBoundary = areas.some(
|
||||
const selectedBounds: [number, number][] = [];
|
||||
const opportunityBounds: [number, number][] = [];
|
||||
const contextBounds: [number, number][] = [];
|
||||
const hasSelectedBoundary = allAreas.some(
|
||||
(area) => area.selected_territory,
|
||||
);
|
||||
const administrativeLevel: Record<string, number> = {
|
||||
@@ -85,20 +209,27 @@ export default function InteractiveInvestmentMap({
|
||||
admin_post: 3,
|
||||
locality: 4,
|
||||
};
|
||||
const closestContextLevel = contextOnly
|
||||
? Math.max(
|
||||
0,
|
||||
...areas.map(
|
||||
(area) =>
|
||||
administrativeLevel[
|
||||
area.location_type ?? ''
|
||||
] ?? 0,
|
||||
),
|
||||
)
|
||||
: 0;
|
||||
for (const area of areas) {
|
||||
const closestContextLevel =
|
||||
contextOnly || layerControls
|
||||
? Math.max(
|
||||
0,
|
||||
...allAreas
|
||||
.filter(
|
||||
(area) =>
|
||||
area.purpose ===
|
||||
'administrative_boundary',
|
||||
)
|
||||
.map(
|
||||
(area) =>
|
||||
administrativeLevel[
|
||||
area.location_type ?? ''
|
||||
] ?? 0,
|
||||
),
|
||||
)
|
||||
: 0;
|
||||
for (const area of allAreas) {
|
||||
const label = document.createElement('p');
|
||||
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'}`;
|
||||
label.textContent = `${area.title} · ${areaDescription(area)} · Fonte: ${area.source_reference ?? 'Não indicada'} · Data: ${area.source_date ?? 'Não documentada'}`;
|
||||
const layer = L.geoJSON(
|
||||
area.geometry,
|
||||
area.purpose === 'administrative_boundary'
|
||||
@@ -109,10 +240,21 @@ export default function InteractiveInvestmentMap({
|
||||
fillOpacity: 0.06,
|
||||
},
|
||||
}
|
||||
: {},
|
||||
: layerControls
|
||||
? {
|
||||
style: {
|
||||
color: '#b45309',
|
||||
fillOpacity: 0.16,
|
||||
},
|
||||
}
|
||||
: {},
|
||||
)
|
||||
.bindPopup(label)
|
||||
.addTo(instance);
|
||||
.addTo(
|
||||
area.purpose === 'administrative_boundary'
|
||||
? groups.administrative
|
||||
: groups.investments,
|
||||
);
|
||||
const extent = layer.getBounds();
|
||||
const focusBoundary = hasSelectedBoundary
|
||||
? area.selected_territory
|
||||
@@ -124,6 +266,19 @@ export default function InteractiveInvestmentMap({
|
||||
[extent.getSouth(), extent.getWest()],
|
||||
[extent.getNorth(), extent.getEast()],
|
||||
);
|
||||
if (extent.isValid()) {
|
||||
const corners: [number, number][] = [
|
||||
[extent.getSouth(), extent.getWest()],
|
||||
[extent.getNorth(), extent.getEast()],
|
||||
];
|
||||
if (area.purpose !== 'administrative_boundary')
|
||||
opportunityBounds.push(...corners);
|
||||
else {
|
||||
if (area.selected_territory)
|
||||
selectedBounds.push(...corners);
|
||||
if (focusBoundary) contextBounds.push(...corners);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [index, point] of (points ?? []).entries()) {
|
||||
const [longitude, latitude] = point.geometry.coordinates;
|
||||
@@ -171,12 +326,20 @@ export default function InteractiveInvestmentMap({
|
||||
})
|
||||
.bindPopup(popup, { autoPan: false })
|
||||
.on('click', () => setSelected(index))
|
||||
.addTo(instance);
|
||||
.addTo(groups.points);
|
||||
markers.current.set(index, marker);
|
||||
bounds.push([latitude, longitude]);
|
||||
opportunityBounds.push([latitude, longitude]);
|
||||
}
|
||||
if (bounds.length)
|
||||
instance.fitBounds(bounds, {
|
||||
const focusBounds = layerControls
|
||||
? selectedBounds.length
|
||||
? selectedBounds
|
||||
: opportunityBounds.length
|
||||
? opportunityBounds
|
||||
: contextBounds
|
||||
: bounds;
|
||||
if (focusBounds.length)
|
||||
instance.fitBounds(focusBounds, {
|
||||
padding: [40, 40],
|
||||
maxZoom: 14,
|
||||
animate: false,
|
||||
@@ -196,29 +359,57 @@ export default function InteractiveInvestmentMap({
|
||||
map.current?.remove();
|
||||
map.current = null;
|
||||
markers.current.clear();
|
||||
pointLayer.current = null;
|
||||
};
|
||||
}, [points, areas]);
|
||||
}, [points, allAreas, contextOnly, layerControls, mapKind]);
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
|
||||
aria-label={
|
||||
contextOnly
|
||||
? 'Mapa dos limites administrativos'
|
||||
: 'Mapa interactivo dos investimentos'
|
||||
}
|
||||
aria-label={title}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{contextOnly
|
||||
? 'Contexto administrativo'
|
||||
: 'Mapa dos investimentos'}
|
||||
</h2>
|
||||
<h2 className="text-xl font-bold">{title}</h2>
|
||||
<p>
|
||||
Arraste para navegar; use +/− para ampliar. Pode seleccionar um
|
||||
{contextOnly
|
||||
? 'limite cadastrado para consultar a sua edição.'
|
||||
: 'investimento na lista para o localizar.'}
|
||||
Arraste para navegar; use +/− para ampliar.{' '}
|
||||
{mapKind === 'declared_parcel'
|
||||
? 'Esta pré-visualização representa a declaração do Promotor, não o limite administrativo.'
|
||||
: mapKind === 'administrative'
|
||||
? 'Seleccione um limite cadastrado para consultar a sua edição.'
|
||||
: 'Seleccione um local na lista para o localizar.'}
|
||||
</p>
|
||||
{error && <p role="status">{error}</p>}
|
||||
{notice}
|
||||
{layerControls && (
|
||||
<div
|
||||
aria-label="Legenda das camadas"
|
||||
className="flex flex-wrap gap-4 text-sm"
|
||||
>
|
||||
<span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="mr-2 inline-block h-3 w-3 rounded-full bg-emerald-800"
|
||||
/>
|
||||
{mapKind === 'investments'
|
||||
? 'Oportunidade com coordenadas confirmadas'
|
||||
: 'Local documentado com coordenadas'}
|
||||
</span>
|
||||
<span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="mr-2 inline-block h-3 w-4 border-2 border-amber-700 bg-amber-100"
|
||||
/>
|
||||
{mapKind === 'investments'
|
||||
? 'Área de investimento cadastrada'
|
||||
: 'Área documentada'}
|
||||
</span>
|
||||
<span>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="mr-2 inline-block h-3 w-4 border-2 border-dashed border-blue-600"
|
||||
/>
|
||||
Limite administrativo — não indica terreno disponível
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={element}
|
||||
className="relative z-0 h-[460px] w-full min-w-0 overflow-hidden rounded"
|
||||
@@ -229,9 +420,11 @@ export default function InteractiveInvestmentMap({
|
||||
<p role="status">A carregar localizações…</p>
|
||||
) : (
|
||||
<p role="status">
|
||||
{contextOnly
|
||||
? `${areas.length} limites administrativos disponíveis.`
|
||||
: `${points.length} locais com coordenadas disponíveis.`}
|
||||
{mapKind === 'declared_parcel'
|
||||
? `${allAreas.length} perímetro declarado em pré-visualização.`
|
||||
: mapKind === 'administrative'
|
||||
? `${areas.length} limites administrativos disponíveis.`
|
||||
: `${points.length} locais com coordenadas disponíveis.`}
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-2 md:grid-cols-2">
|
||||
@@ -251,6 +444,11 @@ export default function InteractiveInvestmentMap({
|
||||
onClick={() => {
|
||||
const marker = markers.current.get(index);
|
||||
if (marker) {
|
||||
visibility.current.points = true;
|
||||
if (pointLayer.current)
|
||||
map.current?.addLayer(
|
||||
pointLayer.current,
|
||||
);
|
||||
map.current?.setView(
|
||||
marker.getLatLng(),
|
||||
14,
|
||||
@@ -278,19 +476,42 @@ export default function InteractiveInvestmentMap({
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{areas.map((area, index) => (
|
||||
<p key={index}>
|
||||
<a className="underline" href={area.url}>
|
||||
{area.title}
|
||||
</a>{' '}
|
||||
·{' '}
|
||||
{area.purpose === 'administrative_boundary'
|
||||
? 'Limite administrativo da edição indicada; não representa um local de investimento'
|
||||
: 'Polígono cadastrado; comparação com limite administrativo pendente'}{' '}
|
||||
· Fonte: {area.source_reference ?? 'Não indicada'} · Data:{' '}
|
||||
{area.source_date ?? 'Não documentada'}
|
||||
</p>
|
||||
))}
|
||||
{layerControls && (
|
||||
<details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
Fontes e contexto do mapa
|
||||
</summary>
|
||||
<div className="mt-3 space-y-2">
|
||||
{administrativeInfo}
|
||||
{allAreas.map((area, index) => (
|
||||
<p key={index}>
|
||||
{area.url.startsWith('/') &&
|
||||
!area.url.startsWith('//') ? (
|
||||
<a className="underline" href={area.url}>
|
||||
{area.title}
|
||||
</a>
|
||||
) : (
|
||||
area.title
|
||||
)}{' '}
|
||||
· {areaDescription(area)} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
{!layerControls &&
|
||||
allAreas.map((area, index) => (
|
||||
<p key={index}>
|
||||
<a className="underline" href={area.url}>
|
||||
{area.title}
|
||||
</a>{' '}
|
||||
· {areaDescription(area)} · Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} · Data:{' '}
|
||||
{area.source_date ?? 'Não documentada'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,8 +36,10 @@ export default function InvestmentMapCoverage({
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<caption className="text-left">
|
||||
Registos recebidos para os filtros actuais, incluindo
|
||||
camadas ocultas.
|
||||
Registos da pesquisa de investimentos para os filtros
|
||||
actuais, incluindo camadas ocultas. A cobertura dos
|
||||
limites administrativos adicionais é apresentada em
|
||||
«Fontes e contexto do mapa».
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import SearchState from '@/components/search-state';
|
||||
import { useEffect, useState } from 'react';
|
||||
import TerritoryGeometryPreview from './territory-geometry-preview';
|
||||
import TerritorialMap from './catalogue-investment-map';
|
||||
import InvestmentMapCoverage from './investment-map-coverage';
|
||||
import InteractiveInvestmentMap, {
|
||||
import {
|
||||
type InvestmentMapFeature,
|
||||
type InvestmentMapArea,
|
||||
} from './interactive-investment-map';
|
||||
@@ -23,9 +23,9 @@ export default function InvestmentMapPanel({
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [areas, setAreas] = useState<InvestmentMapArea[]>([]);
|
||||
const [truncated, setTruncated] = useState(false);
|
||||
const [showPoints, setShowPoints] = useState(true);
|
||||
const [showAreas, setShowAreas] = useState(true);
|
||||
const [matched, setMatched] = useState(0);
|
||||
const [responseKey, setResponseKey] = useState('');
|
||||
const current = responseKey === key;
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const params = new URLSearchParams(JSON.parse(key));
|
||||
@@ -46,6 +46,7 @@ export default function InvestmentMapPanel({
|
||||
.then((data) => {
|
||||
if (controller.signal.aborted) return;
|
||||
setPoints(data.features);
|
||||
setResponseKey(key);
|
||||
setAreas(data.areas ?? []);
|
||||
setMissing(data.unlocated ?? []);
|
||||
setTruncated(Boolean(data.truncated));
|
||||
@@ -59,8 +60,10 @@ export default function InvestmentMapPanel({
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
if (!controller.signal.aborted) {
|
||||
setResponseKey(key);
|
||||
setError('Não foi possível concluir a pesquisa.');
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [key, retry]);
|
||||
@@ -69,53 +72,14 @@ export default function InvestmentMapPanel({
|
||||
<SearchState
|
||||
scope="Registos consultados pelo mapa"
|
||||
countLabel="investimentos, incluindo os que não têm coordenadas"
|
||||
loading={points === null && !error}
|
||||
error={error}
|
||||
total={matched}
|
||||
loading={!current || (points === null && !error)}
|
||||
error={current ? error : ''}
|
||||
total={current ? matched : 0}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<fieldset className="flex flex-wrap gap-4 rounded border p-3">
|
||||
<legend className="font-semibold">
|
||||
Camadas desta consulta
|
||||
</legend>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showPoints}
|
||||
onChange={(event) =>
|
||||
setShowPoints(event.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Investimentos com ponto
|
||||
</label>
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showAreas}
|
||||
onChange={(event) => setShowAreas(event.target.checked)}
|
||||
/>{' '}
|
||||
Áreas e limites
|
||||
</label>
|
||||
</fieldset>
|
||||
{!showPoints && !showAreas && (
|
||||
<p role="status">
|
||||
Camadas ocultas. Active uma camada para voltar a consultar
|
||||
os registos no mapa.
|
||||
</p>
|
||||
)}
|
||||
<InteractiveInvestmentMap
|
||||
points={points === null ? null : showPoints ? points : []}
|
||||
areas={showAreas ? areas : []}
|
||||
/>
|
||||
{points !== null && (
|
||||
<InvestmentMapCoverage
|
||||
points={points}
|
||||
areas={areas}
|
||||
unlocated={missing.length}
|
||||
truncated={truncated}
|
||||
/>
|
||||
)}
|
||||
<TerritoryGeometryPreview
|
||||
<TerritorialMap
|
||||
points={current ? (error ? [] : points) : null}
|
||||
areas={current ? areas : []}
|
||||
territoryId={
|
||||
territoryId ||
|
||||
String(
|
||||
@@ -123,12 +87,20 @@ export default function InvestmentMapPanel({
|
||||
filters.admin_post_id ||
|
||||
filters.district_id ||
|
||||
filters.province_id ||
|
||||
filters.geo_location_id ||
|
||||
'',
|
||||
)
|
||||
) ||
|
||||
undefined
|
||||
}
|
||||
/>
|
||||
{missing.length > 0 && (
|
||||
{current && points !== null && (
|
||||
<InvestmentMapCoverage
|
||||
points={points}
|
||||
areas={areas}
|
||||
unlocated={missing.length}
|
||||
truncated={truncated}
|
||||
/>
|
||||
)}
|
||||
{current && missing.length > 0 && (
|
||||
<div>
|
||||
<p>
|
||||
{missing.length} investimentos sem ponto público
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
|
||||
export type AlertPreferences = {
|
||||
version: number;
|
||||
enabled: boolean;
|
||||
frequency: string;
|
||||
channel: string;
|
||||
next_run_at: string | null;
|
||||
criteria_available?: boolean;
|
||||
sources?: string[];
|
||||
criteria: {
|
||||
sector?: string;
|
||||
province_id?: string;
|
||||
category?: string;
|
||||
tender_regime?: string;
|
||||
funding_certainty?: string;
|
||||
funding_state?: string;
|
||||
};
|
||||
};
|
||||
export type AlertOptions = {
|
||||
frequencies: Record<string, string>;
|
||||
sectors: { slug: string; name: string }[];
|
||||
provinces: { id: string; name: string }[];
|
||||
categories: string[];
|
||||
tendersAvailable?: boolean;
|
||||
fundingAvailable?: boolean;
|
||||
tenderRegimes?: Record<string, string>;
|
||||
tenderActs?: Record<string, string>;
|
||||
};
|
||||
|
||||
export default function OpportunityAlertPreferences({
|
||||
preferences,
|
||||
options,
|
||||
}: {
|
||||
preferences: AlertPreferences;
|
||||
options: AlertOptions;
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: preferences.version,
|
||||
enabled: true,
|
||||
frequency: preferences.frequency,
|
||||
channel: 'in_app',
|
||||
sources: preferences.sources ?? ['opportunities'],
|
||||
criteria: {
|
||||
sector: preferences.criteria.sector ?? '',
|
||||
province_id: preferences.criteria.province_id ?? '',
|
||||
category: preferences.criteria.category ?? '',
|
||||
tender_regime: preferences.criteria.tender_regime ?? '',
|
||||
funding_certainty:
|
||||
preferences.criteria.funding_certainty ?? 'documented',
|
||||
funding_state: preferences.criteria.funding_state ?? '',
|
||||
},
|
||||
consent: false,
|
||||
});
|
||||
const send = (enabled: boolean) => {
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
enabled,
|
||||
consent: enabled && data.consent,
|
||||
}));
|
||||
form.put('/investidor/alert-preferences', { preserveScroll: true });
|
||||
};
|
||||
return (
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Preferências de alertas"
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Novidades dos catálogos públicos
|
||||
</h2>
|
||||
<p role="status">
|
||||
{preferences.enabled
|
||||
? 'Acompanhamento activo.'
|
||||
: 'Acompanhamento desactivado.'}
|
||||
</p>
|
||||
{preferences.enabled &&
|
||||
preferences.criteria_available === false && (
|
||||
<p role="alert">
|
||||
Uma selecção anterior deixou de estar disponível no
|
||||
catálogo. O acompanhamento das selecções indisponíveis
|
||||
fica suspenso; os restantes catálogos seleccionados
|
||||
continuam a ser verificados. Pode escolher outra opção
|
||||
ou cancelar os alertas a qualquer momento.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Escolha os catálogos, critérios e frequência. As novas
|
||||
disponibilizações compatíveis aparecem nesta área. Não são
|
||||
enviados emails ou SMS. O acompanhamento de concursos considera
|
||||
anúncios e actos publicados no catálogo do portal. Fundos e
|
||||
apoios consideram novas versões do catálogo do portal; não há
|
||||
recolha automática de fontes externas.
|
||||
</p>
|
||||
<p>
|
||||
Ao activar, reactivar ou alterar os critérios ou catálogos, os
|
||||
registos já disponíveis estabelecem o ponto de partida e não
|
||||
geram alertas retroactivos. Uma oportunidade ou versão de acto
|
||||
não gera alertas repetidos.
|
||||
</p>
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
send(true);
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={form.processing} className="space-y-3">
|
||||
<legend className="font-semibold">
|
||||
O que pretende acompanhar
|
||||
</legend>
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="font-semibold">Catálogos</legend>
|
||||
{(['opportunities', 'tenders', 'funding'] as const).map(
|
||||
(source) => (
|
||||
<label
|
||||
key={source}
|
||||
className="flex items-start gap-2"
|
||||
>
|
||||
<input
|
||||
name={`source-${source}`}
|
||||
type="checkbox"
|
||||
checked={form.data.sources.includes(
|
||||
source,
|
||||
)}
|
||||
disabled={
|
||||
((source === 'tenders' &&
|
||||
!options.tendersAvailable) ||
|
||||
(source === 'funding' &&
|
||||
!options.fundingAvailable)) &&
|
||||
!form.data.sources.includes(source)
|
||||
}
|
||||
onChange={(event) => {
|
||||
form.setData(
|
||||
'sources',
|
||||
event.target.checked
|
||||
? [
|
||||
...form.data.sources,
|
||||
source,
|
||||
]
|
||||
: form.data.sources.filter(
|
||||
(value) =>
|
||||
value !== source,
|
||||
),
|
||||
);
|
||||
form.setData('consent', false);
|
||||
}}
|
||||
/>
|
||||
{source === 'opportunities'
|
||||
? 'Oportunidades de investimento'
|
||||
: source === 'tenders'
|
||||
? 'Concursos e actos publicados'
|
||||
: 'Fundos, programas e incentivos publicados'}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
{!options.tendersAvailable && (
|
||||
<p className="text-sm">
|
||||
O catálogo de concursos não está disponível
|
||||
neste momento.
|
||||
</p>
|
||||
)}
|
||||
{!options.fundingAvailable && (
|
||||
<p className="text-sm">
|
||||
O catálogo de fundos não está disponível neste
|
||||
momento.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
<label className="block">
|
||||
Sector
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.sector}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
sector: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Todos os sectores</option>
|
||||
{form.data.criteria.sector &&
|
||||
!options.sectors.some(
|
||||
(sector) =>
|
||||
sector.slug ===
|
||||
form.data.criteria.sector,
|
||||
) && (
|
||||
<option value={form.data.criteria.sector}>
|
||||
Sector anterior indisponível
|
||||
</option>
|
||||
)}
|
||||
{options.sectors.map((sector) => (
|
||||
<option key={sector.slug} value={sector.slug}>
|
||||
{sector.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Província
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.province_id}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
province_id: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Todo o território</option>
|
||||
{form.data.criteria.province_id &&
|
||||
!options.provinces.some(
|
||||
(province) =>
|
||||
province.id ===
|
||||
form.data.criteria.province_id,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.criteria.province_id}
|
||||
>
|
||||
Província anterior indisponível
|
||||
</option>
|
||||
)}
|
||||
{options.provinces.map((province) => (
|
||||
<option key={province.id} value={province.id}>
|
||||
{province.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
A selecção provincial usa o mesmo âmbito territorial do
|
||||
catálogo, incluindo locais dos níveis inferiores.
|
||||
</p>
|
||||
{form.data.sources.includes('opportunities') && (
|
||||
<label className="block">
|
||||
Modalidade
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.category}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
category: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Todas as modalidades</option>
|
||||
{form.data.criteria.category &&
|
||||
!options.categories.includes(
|
||||
form.data.criteria.category,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.criteria.category}
|
||||
>
|
||||
Modalidade anterior indisponível
|
||||
</option>
|
||||
)}
|
||||
{options.categories.map((category) => (
|
||||
<option key={category} value={category}>
|
||||
{modalityLabels[category] ?? category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{form.data.sources.includes('tenders') && (
|
||||
<label className="block">
|
||||
Regime do concurso
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.tender_regime}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
tender_regime: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Todos os regimes</option>
|
||||
{form.data.criteria.tender_regime &&
|
||||
!Object.hasOwn(
|
||||
options.tenderRegimes ?? {},
|
||||
form.data.criteria.tender_regime,
|
||||
) && (
|
||||
<option
|
||||
value={
|
||||
form.data.criteria.tender_regime
|
||||
}
|
||||
>
|
||||
Regime anterior indisponível
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(
|
||||
options.tenderRegimes ?? {},
|
||||
).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{form.data.sources.includes('funding') && (
|
||||
<fieldset className="space-y-3">
|
||||
<legend>Condições para fundos e apoios</legend>
|
||||
<label className="block">
|
||||
Âmbitos por confirmar
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.funding_certainty}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
funding_certainty:
|
||||
event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="documented">
|
||||
Só âmbito documentado para o sector e
|
||||
província escolhidos
|
||||
</option>
|
||||
<option value="include_unknown">
|
||||
Incluir e assinalar informação por
|
||||
confirmar
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Estado de uma janela
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.criteria.funding_state}
|
||||
onChange={(event) =>
|
||||
form.setData('criteria', {
|
||||
...form.data.criteria,
|
||||
funding_state: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Qualquer estado</option>
|
||||
<option value="open">
|
||||
Aberta segundo as datas documentadas
|
||||
</option>
|
||||
<option value="upcoming">
|
||||
Abertura futura
|
||||
</option>
|
||||
<option value="closed">Encerrada</option>
|
||||
<option value="unknown">
|
||||
Por confirmar
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Sector e província referem-se ao programa. Uma
|
||||
chamada pode ter cobertura mais restrita. O
|
||||
aviso acompanha novas versões publicadas; uma
|
||||
mudança de data sem nova publicação não gera
|
||||
outro aviso.
|
||||
</p>
|
||||
</fieldset>
|
||||
)}
|
||||
<label className="block">
|
||||
Frequência
|
||||
<select
|
||||
className={input}
|
||||
value={form.data.frequency}
|
||||
onChange={(event) =>
|
||||
form.setData('frequency', event.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries(options.frequencies).map(
|
||||
([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<p>
|
||||
Canal: notificações no portal. «Na próxima verificação»
|
||||
depende da execução periódica do acompanhamento.
|
||||
</p>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="alert-consent"
|
||||
checked={form.data.consent}
|
||||
onChange={(event) =>
|
||||
form.setData('consent', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Quero receber estes alertas no portal e confirmo os
|
||||
critérios escolhidos.
|
||||
</label>
|
||||
{Object.entries(form.errors).map(([key, error]) => (
|
||||
<p key={key} role="alert">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button type="submit" className={button}>
|
||||
{preferences.enabled
|
||||
? 'Guardar preferências'
|
||||
: 'Activar alertas'}
|
||||
</button>
|
||||
{preferences.enabled && (
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => send(false)}
|
||||
>
|
||||
Cancelar estes alertas
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
<p className="text-sm">
|
||||
O cancelamento conserva as notificações anteriores e não altera
|
||||
o acompanhamento das manifestações já apresentadas.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -90,10 +90,9 @@ export default function OpportunityContactForm({
|
||||
<details className="rounded border p-3">
|
||||
<summary>Cadastrar contacto do promotor</summary>
|
||||
<p>
|
||||
Reutiliza o cadastro de contactos. Indique dados reais e
|
||||
autorizados do promotor desta oportunidade. O operador do portal
|
||||
não substitui o promotor real. A gravação não publica o
|
||||
contacto.
|
||||
Indique os dados de contacto autorizados pelo promotor desta
|
||||
oportunidade. O contacto fica guardado para reutilização e não é
|
||||
publicado.
|
||||
</p>
|
||||
<fieldset disabled={disabled || busy} className="space-y-3">
|
||||
<legend>Dados do contacto</legend>
|
||||
@@ -142,7 +141,7 @@ export default function OpportunityContactForm({
|
||||
{organization && investors.length > 1 && (
|
||||
<div>
|
||||
<label htmlFor="contact-investor_id">
|
||||
Cadastro mestre do promotor
|
||||
Promotor associado ao contacto
|
||||
</label>
|
||||
<select
|
||||
id="contact-investor_id"
|
||||
|
||||
@@ -204,6 +204,7 @@ export default function OpportunityParcelGeometry({
|
||||
<InteractiveInvestmentMap
|
||||
points={[]}
|
||||
contextOnly
|
||||
mapKind="declared_parcel"
|
||||
areas={[
|
||||
{
|
||||
purpose: 'declared_parcel',
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
|
||||
export type RelatedOpportunitySearch = {
|
||||
query: string;
|
||||
subject: string;
|
||||
href: string;
|
||||
items: {
|
||||
id: number;
|
||||
slug: string;
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export default function OpportunityRelatedResults({
|
||||
related,
|
||||
loading,
|
||||
error,
|
||||
total,
|
||||
}: {
|
||||
related: RelatedOpportunitySearch | null;
|
||||
loading: boolean;
|
||||
error: string;
|
||||
total: number;
|
||||
}) {
|
||||
if (loading || error || total !== 0 || !related?.items.length) return null;
|
||||
const context = new URL(related.href, 'https://portal.invalid');
|
||||
context.searchParams.set('q', related.query);
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-xl border border-slate-300 bg-white p-5"
|
||||
aria-label="Fichas relacionadas, sem correspondência completa"
|
||||
>
|
||||
<h3 className="text-xl font-bold">
|
||||
Fichas relacionadas com «{related.subject}»
|
||||
</h3>
|
||||
<p>
|
||||
Não encontrámos fichas que correspondam a todos os termos de «
|
||||
{related.query}». As fichas abaixo são de actividades
|
||||
relacionadas e podem corresponder a outras etapas da cadeia.
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{related.items.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={`/oportunidades/${encodeURIComponent(item.slug)}${context.search}`}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
{item.summary && <p>{item.summary}</p>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Link className="underline" href={related.href}>
|
||||
Ver a pesquisa relacionada «{related.subject}»
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { Link, router, usePage } from '@inertiajs/react';
|
||||
import {
|
||||
ChevronDown,
|
||||
ArrowUpRight,
|
||||
LayoutDashboard,
|
||||
LogOut,
|
||||
Menu,
|
||||
UserRound,
|
||||
@@ -13,11 +12,8 @@ import {
|
||||
import { Fragment, useEffect, useId, useRef, useState } from 'react';
|
||||
import { useIsMobile } from '@/hooks/use-mobile';
|
||||
import { useNavigationContext } from '@/components/navigation-context';
|
||||
import { tempoSocialLinks, useTempoUi } from '@/components/tempo-brand';
|
||||
import {
|
||||
TempoLanguageSelector,
|
||||
TempoWeather,
|
||||
} from '@/components/tempo-header-tools';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
import { TempoLanguageSelector } from '@/components/tempo-header-tools';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -51,6 +47,7 @@ export function PortalGroupedMenu() {
|
||||
businessReviewUrl?: string | null;
|
||||
educationEnabled?: boolean;
|
||||
procurementEnabled?: boolean;
|
||||
fundingEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
legacyContentEnabled?: boolean;
|
||||
profileAccess?: ProfileAccess | null;
|
||||
@@ -61,7 +58,7 @@ export function PortalGroupedMenu() {
|
||||
opportunities?: { index: string; create?: string | null };
|
||||
};
|
||||
}>();
|
||||
const { t, language, requestCount } = useTempoUi();
|
||||
const { t, language } = useTempoUi();
|
||||
const mobile = useIsMobile();
|
||||
const navigation = useNavigationContext();
|
||||
const groups = portalNavigation({
|
||||
@@ -74,6 +71,7 @@ export function PortalGroupedMenu() {
|
||||
businessReviewUrl: props.businessReviewUrl,
|
||||
education: props.educationEnabled,
|
||||
procurement: props.procurementEnabled,
|
||||
funding: props.fundingEnabled,
|
||||
ai: props.aiEnabled,
|
||||
legacyContent: props.legacyContentEnabled,
|
||||
opportunityManagement: props.opportunityManagement,
|
||||
@@ -137,7 +135,6 @@ export function PortalGroupedMenu() {
|
||||
group.id,
|
||||
),
|
||||
);
|
||||
const panelLabel = `${t('O meu painel')} — ${requestCount} ${t(requestCount === 1 ? 'pedido recebido' : 'pedidos recebidos')}`;
|
||||
const institutionalCurrent = url.split('?')[0] === '/contacto';
|
||||
return (
|
||||
<header
|
||||
@@ -307,36 +304,6 @@ export function PortalGroupedMenu() {
|
||||
</DropdownMenuItem>
|
||||
),
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuLabel className="text-xs text-slate-500">
|
||||
Revista Tempo
|
||||
</DropdownMenuLabel>
|
||||
{tempoSocialLinks.map(
|
||||
({ name, href, icon: Icon }) => (
|
||||
<DropdownMenuItem
|
||||
key={name}
|
||||
asChild
|
||||
className="tempo-menu-item"
|
||||
>
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={`Revista Tempo — ${name}`}
|
||||
>
|
||||
<Icon
|
||||
size={16}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{name}
|
||||
<ArrowUpRight
|
||||
size={12}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
),
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</li>
|
||||
@@ -345,31 +312,11 @@ export function PortalGroupedMenu() {
|
||||
<div id={toolsId} className="tempo-header-extras">
|
||||
<div className="tempo-header-utilities">
|
||||
<div className="flex items-center gap-1">
|
||||
<TempoWeather />
|
||||
<TempoLanguageSelector />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="tempo-header-actions">
|
||||
<Link
|
||||
href="/investidor/manifestacoes"
|
||||
className="tempo-panel-summary"
|
||||
aria-label={panelLabel}
|
||||
title={panelLabel}
|
||||
>
|
||||
<LayoutDashboard size={19} aria-hidden="true" />
|
||||
<span className="tempo-panel-count" aria-hidden="true">
|
||||
{requestCount}
|
||||
</span>
|
||||
</Link>
|
||||
<span
|
||||
className="sr-only"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{panelLabel}
|
||||
</span>
|
||||
{props.auth?.user ? (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger className="tempo-login-button">
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { ArrowRight, Search } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { FormEvent } from 'react';
|
||||
import type { HomeResponse } from '@/lib/portal-api';
|
||||
|
||||
const slides = [
|
||||
@@ -127,7 +126,6 @@ function HeroAnimatedCopy({
|
||||
type PortalHeroProps = {
|
||||
query: string;
|
||||
setQuery: (value: string) => void;
|
||||
onSearch: (event: FormEvent<HTMLFormElement>) => void;
|
||||
stats?: HomeResponse['data']['stats'];
|
||||
};
|
||||
|
||||
@@ -135,7 +133,6 @@ type PortalHeroProps = {
|
||||
export default function PortalHero({
|
||||
query,
|
||||
setQuery,
|
||||
onSearch,
|
||||
stats,
|
||||
}: PortalHeroProps) {
|
||||
const [currentSlide, setCurrentSlide] = useState(0);
|
||||
@@ -229,7 +226,20 @@ export default function PortalHero({
|
||||
</p>
|
||||
|
||||
<form
|
||||
onSubmit={onSearch}
|
||||
action="/oportunidades"
|
||||
method="get"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const value = new FormData(event.currentTarget).get(
|
||||
'q',
|
||||
);
|
||||
router.get('/oportunidades', {
|
||||
q:
|
||||
typeof value === 'string'
|
||||
? value.trim()
|
||||
: query.trim(),
|
||||
});
|
||||
}}
|
||||
role="search"
|
||||
aria-label="Pesquisar oportunidades"
|
||||
className="mt-7 w-full max-w-4xl"
|
||||
@@ -245,6 +255,8 @@ export default function PortalHero({
|
||||
id="portal-opportunity-search"
|
||||
type="search"
|
||||
name="q"
|
||||
maxLength={120}
|
||||
aria-describedby="portal-opportunity-search-help"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Ex.: agronegócio, Nampula, energia..."
|
||||
@@ -258,6 +270,13 @@ export default function PortalHero({
|
||||
Pesquisar
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
id="portal-opportunity-search-help"
|
||||
className="mt-2 text-left text-sm text-white/90"
|
||||
>
|
||||
Combine palavras-chave, sector e localização. Ex.:
|
||||
plantio de algodão ou agronegócio Nampula.
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center justify-center gap-2">
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
|
||||
type Match = {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
published_at?: string | null;
|
||||
};
|
||||
function publicationDate(value?: string | null): string | null {
|
||||
if (typeof value !== 'string' || !value.trim()) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? null
|
||||
: date.toLocaleDateString('pt-MZ');
|
||||
}
|
||||
type Classification = {
|
||||
target_type: string;
|
||||
target_id: string;
|
||||
label: string;
|
||||
purpose?: string;
|
||||
purpose_label?: string;
|
||||
source_reference?: string | null;
|
||||
};
|
||||
const classificationKey = (row: Classification) =>
|
||||
`${row.target_type}:${row.target_id}:${row.purpose ?? ''}`;
|
||||
type Props = {
|
||||
currentId: string;
|
||||
catalogueUrl: string;
|
||||
criteria: string[];
|
||||
classifications?: Classification[];
|
||||
};
|
||||
|
||||
export default function SimilarBusinesses({
|
||||
currentId,
|
||||
catalogueUrl,
|
||||
criteria,
|
||||
classifications = [],
|
||||
}: Props) {
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [selection, setSelection] = useState({
|
||||
recordId: currentId,
|
||||
value: '',
|
||||
});
|
||||
const selected =
|
||||
selection.recordId === currentId
|
||||
? classifications.find(
|
||||
(row) => classificationKey(row) === selection.value,
|
||||
)
|
||||
: undefined;
|
||||
const query = new URL(catalogueUrl, 'https://portal.invalid');
|
||||
if (selected) {
|
||||
query.searchParams.set('association_type', selected.target_type);
|
||||
query.searchParams.set('association_target', selected.target_id);
|
||||
if (selected.purpose)
|
||||
query.searchParams.set('association_purpose', selected.purpose);
|
||||
}
|
||||
const effectiveCatalogueUrl = query.pathname + query.search;
|
||||
const key = JSON.stringify([currentId, effectiveCatalogueUrl, attempt]);
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
rows: Match[];
|
||||
error: boolean;
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const params = new URL(effectiveCatalogueUrl, 'https://portal.invalid')
|
||||
.searchParams;
|
||||
params.set('per_page', '7');
|
||||
params.set('page', '1');
|
||||
void portalRequest<{ data: Match[] }>(
|
||||
`/api/v1/business-opportunities?${params}`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
.then((response) => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (!Array.isArray(response.data))
|
||||
throw new Error('Invalid catalogue response');
|
||||
const seen = new Set([currentId]);
|
||||
if (
|
||||
response.data.some(
|
||||
(row) =>
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
!row.id.trim() ||
|
||||
typeof row.slug !== 'string' ||
|
||||
!row.slug.trim() ||
|
||||
typeof row.title !== 'string' ||
|
||||
!row.title.trim(),
|
||||
)
|
||||
) {
|
||||
throw new Error('Invalid catalogue record');
|
||||
}
|
||||
const rows = response.data
|
||||
.filter((row) => {
|
||||
if (
|
||||
!row ||
|
||||
typeof row.id !== 'string' ||
|
||||
typeof row.slug !== 'string' ||
|
||||
typeof row.title !== 'string' ||
|
||||
seen.has(row.id)
|
||||
)
|
||||
return false;
|
||||
seen.add(row.id);
|
||||
return true;
|
||||
})
|
||||
.slice(0, 6);
|
||||
setResult({ key, rows, error: false });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, rows: [], error: true });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [currentId, effectiveCatalogueUrl, key]);
|
||||
const current = result?.key === key ? result : null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded-xl border bg-white p-5"
|
||||
aria-label="Negócios com critérios semelhantes"
|
||||
aria-busy={!current}
|
||||
>
|
||||
<h2 className="text-xl font-bold">Explorar negócios semelhantes</h2>
|
||||
<p>
|
||||
Critérios:{' '}
|
||||
{[...criteria, ...(selected ? [selected.label] : [])].join(
|
||||
' · ',
|
||||
)}
|
||||
. A consulta compara os dados publicados; não avalia
|
||||
rentabilidade nem proximidade geográfica.
|
||||
</p>
|
||||
{!current ? (
|
||||
<p role="status">A consultar o catálogo…</p>
|
||||
) : current.error ? (
|
||||
<div role="alert">
|
||||
<p>Não foi possível consultar os negócios semelhantes.</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setAttempt((value) => value + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</div>
|
||||
) : current.rows.length ? (
|
||||
<ul className="space-y-2">
|
||||
{current.rows.map((row) => (
|
||||
<li key={row.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/negocios/${encodeURIComponent(row.slug)}${new URL(effectiveCatalogueUrl, 'https://portal.invalid').search}`}
|
||||
>
|
||||
{row.title}
|
||||
</Link>
|
||||
<p className="text-sm text-slate-600">
|
||||
Fonte: catálogo público do InvesteMoz.{' '}
|
||||
{publicationDate(row.published_at) ? (
|
||||
<>
|
||||
Publicado em{' '}
|
||||
<time
|
||||
dateTime={
|
||||
row.published_at ?? undefined
|
||||
}
|
||||
>
|
||||
{publicationDate(row.published_at)}
|
||||
</time>
|
||||
.
|
||||
</>
|
||||
) : (
|
||||
'Data de publicação não indicada.'
|
||||
)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>
|
||||
Não foram encontrados outros negócios públicos com estes
|
||||
critérios. Isto não demonstra ausência de negócios no
|
||||
mercado.
|
||||
</p>
|
||||
)}
|
||||
{classifications.length > 0 && (
|
||||
<label className="block space-y-1">
|
||||
Comparar também por uma classificação divulgada
|
||||
<select
|
||||
className="block w-full rounded border p-2"
|
||||
value={selected ? classificationKey(selected) : ''}
|
||||
onChange={(event) =>
|
||||
setSelection({
|
||||
recordId: currentId,
|
||||
value: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Sem classificação adicional</option>
|
||||
{classifications
|
||||
.filter(
|
||||
(row, index, all) =>
|
||||
all.findIndex(
|
||||
(other) =>
|
||||
classificationKey(other) ===
|
||||
classificationKey(row),
|
||||
) === index,
|
||||
)
|
||||
.map((row) => (
|
||||
<option
|
||||
key={classificationKey(row)}
|
||||
value={classificationKey(row)}
|
||||
>
|
||||
{row.label}
|
||||
{row.purpose_label
|
||||
? ` — ${row.purpose_label}`
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{selected && (
|
||||
<p className="text-sm">
|
||||
Fonte da classificação na ficha de origem:{' '}
|
||||
{selected.source_reference || 'não indicada'}. A relação
|
||||
documental não comprova implantação, propriedade ou
|
||||
capacidade.
|
||||
</p>
|
||||
)}
|
||||
<Link href={effectiveCatalogueUrl} className="underline">
|
||||
Consultar o catálogo com estes critérios
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
São apresentados até seis resultados. Pode ajustar os filtros no
|
||||
catálogo. A data de publicação não indica a data dos dados de
|
||||
origem.
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -209,6 +209,8 @@ export default function StructureGeographyPanel({
|
||||
</p>
|
||||
)}
|
||||
<InteractiveInvestmentMap
|
||||
mapKind="documented_locations"
|
||||
layerControls
|
||||
points={points}
|
||||
areas={[
|
||||
...items.flatMap((item) =>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { TempoSocialLinks, useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
const navigation = [
|
||||
['/', 'Início'],
|
||||
['/apoio', 'Contacto'],
|
||||
['/apoio', 'Apoio ao investidor'],
|
||||
];
|
||||
|
||||
export function TempoFooter() {
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import InteractiveInvestmentMap, {
|
||||
type InvestmentMapArea,
|
||||
} from './interactive-investment-map';
|
||||
import InteractiveInvestmentMap from './interactive-investment-map';
|
||||
import {
|
||||
useTerritoryGeometry,
|
||||
type TerritoryGeometryContext,
|
||||
} from './use-territory-geometry';
|
||||
|
||||
const noPoints: [] = [];
|
||||
type Context = {
|
||||
selected_geometry_available: boolean;
|
||||
context_geometry_count: number;
|
||||
areas: InvestmentMapArea[];
|
||||
truncated: boolean;
|
||||
};
|
||||
export default function TerritoryGeometryPreview({
|
||||
territoryId,
|
||||
management = false,
|
||||
@@ -21,44 +16,37 @@ export default function TerritoryGeometryPreview({
|
||||
endpoint?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const [context, setContext] = useState<Context | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
setContext(null);
|
||||
setError('');
|
||||
if (!territoryId) return;
|
||||
const controller = new AbortController();
|
||||
const endpoint =
|
||||
suppliedEndpoint ??
|
||||
const { context, error } = useTerritoryGeometry(
|
||||
territoryId,
|
||||
suppliedEndpoint ??
|
||||
(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, suppliedEndpoint]);
|
||||
: '/api/v1/investment/territory-geometries'),
|
||||
);
|
||||
if (!territoryId) return null;
|
||||
return (
|
||||
<TerritoryGeometryDetails
|
||||
context={context}
|
||||
error={error}
|
||||
label={label}
|
||||
renderMap
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function TerritoryGeometryDetails({
|
||||
context,
|
||||
error,
|
||||
label = 'Cobertura cartográfica da selecção',
|
||||
renderMap = false,
|
||||
showSources = true,
|
||||
}: {
|
||||
context: TerritoryGeometryContext | null;
|
||||
error: string;
|
||||
label?: string;
|
||||
renderMap?: boolean;
|
||||
showSources?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-2 md:col-span-full" aria-label={label}>
|
||||
<p>Território selecionado no cadastro.</p>
|
||||
@@ -91,26 +79,28 @@ export default function TerritoryGeometryPreview({
|
||||
incompleta.
|
||||
</p>
|
||||
)}
|
||||
{context.areas.length > 0 && (
|
||||
{renderMap && context.areas.length > 0 && (
|
||||
<InteractiveInvestmentMap
|
||||
points={noPoints}
|
||||
areas={context.areas}
|
||||
contextOnly
|
||||
/>
|
||||
)}
|
||||
<ul>
|
||||
{context.areas.map((area, index) => (
|
||||
<li key={index}>
|
||||
{area.title} ·{' '}
|
||||
{area.selected_territory
|
||||
? 'Território seleccionado'
|
||||
: 'Contexto de nível superior'}{' '}
|
||||
· Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{showSources && (
|
||||
<ul>
|
||||
{context.areas.map((area, index) => (
|
||||
<li key={index}>
|
||||
{area.title} ·{' '}
|
||||
{area.selected_territory
|
||||
? 'Território seleccionado'
|
||||
: 'Contexto de nível superior'}{' '}
|
||||
· Fonte:{' '}
|
||||
{area.source_reference ?? 'Não indicada'} ·
|
||||
Edição: {area.source_date ?? 'Não indicada'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { InvestmentMapArea } from './interactive-investment-map';
|
||||
|
||||
export type TerritoryGeometryContext = {
|
||||
selected_geometry_available: boolean;
|
||||
context_geometry_count: number;
|
||||
areas: InvestmentMapArea[];
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
export function useTerritoryGeometry(
|
||||
territoryId?: string,
|
||||
endpoint = '/api/v1/investment/territory-geometries',
|
||||
) {
|
||||
const key = JSON.stringify([territoryId, endpoint]);
|
||||
const [result, setResult] = useState<{
|
||||
key: string;
|
||||
context: TerritoryGeometryContext | null;
|
||||
error: string;
|
||||
}>({ key, context: null, error: '' });
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setResult({ key, context: null, error: '' });
|
||||
if (!territoryId) return () => controller.abort();
|
||||
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<TerritoryGeometryContext>;
|
||||
})
|
||||
.then((context) => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, context, error: '' });
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({
|
||||
key,
|
||||
context: null,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Erro de ligação.',
|
||||
});
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [key, territoryId, endpoint]);
|
||||
return result.key === key ? result : { key, context: null, error: '' };
|
||||
}
|
||||
Reference in New Issue
Block a user