varias alteracoes

This commit is contained in:
2026-09-29 08:41:57 +02:00
parent b77714b156
commit 2e0217b486
51 changed files with 2605 additions and 270 deletions
@@ -0,0 +1,179 @@
import { useEffect, useRef, useState } from "react";
import type { Map as LeafletMap, Marker } from "leaflet";
import "leaflet/dist/leaflet.css";
export type InvestmentMapFeature = {
geometry: { coordinates: [number, number] };
properties: {
id: number;
title: string;
location: string;
url: string;
category?: string;
clusters?: string[];
corridors?: string[];
projects?: string[];
};
};
export default function InteractiveInvestmentMap({
points,
}: {
points: InvestmentMapFeature[] | null;
}) {
const element = useRef<HTMLDivElement>(null);
const map = useRef<LeafletMap | null>(null);
const markers = useRef(new Map<number, Marker>());
const [selected, setSelected] = useState<number | null>(null);
const [error, setError] = useState("");
useEffect(() => {
let cancelled = false;
let observer: ResizeObserver | undefined;
void import("leaflet")
.then((L) => {
if (cancelled || !element.current) return;
const instance = L.map(element.current, {
scrollWheelZoom: false,
keyboard: true,
}).setView([-18.5, 35], 5);
map.current = instance;
L.tileLayer(
import.meta.env.VITE_MAP_TILE_URL ||
"https://tile.openstreetmap.org/{z}/{x}/{y}.png",
{
maxZoom: 19,
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
},
)
.on("tileerror", () => {
if (!cancelled)
setError(
"Mapa base indisponível. Os marcadores e a lista continuam acessíveis.",
);
})
.addTo(instance);
L.control.scale({ imperial: false }).addTo(instance);
const bounds: [number, number][] = [];
for (const [index, point] of (points ?? []).entries()) {
const [longitude, latitude] = point.geometry.coordinates;
if (
!Number.isFinite(latitude) ||
!Number.isFinite(longitude) ||
Math.abs(latitude) > 90 ||
Math.abs(longitude) > 180
)
continue;
const { properties: p } = point;
const popup = document.createElement("div");
const heading = document.createElement("strong");
heading.textContent = p.title;
popup.append(heading);
for (const text of [
p.category,
p.location,
`Corredor: ${p.corridors?.join(", ") || "Não associado"}`,
`Cluster: ${p.clusters?.join(", ") || "Não associado"}`,
`Projecto âncora: ${p.projects?.join(", ") || "Não associado"}`,
]) {
const line = document.createElement("p");
line.textContent = text ?? "";
popup.append(line);
}
if (p.url.startsWith("/") && !p.url.startsWith("//")) {
const link = document.createElement("a");
link.href = p.url;
link.textContent = "Abrir ficha detalhada";
popup.append(link);
}
const icon = L.divIcon({
className: "",
html: `<span style="display:grid;place-items:center;width:32px;height:32px;border-radius:50%;background:#065f46;color:white;border:2px solid white;font-weight:bold">${index + 1}</span>`,
iconSize: [32, 32],
iconAnchor: [16, 16],
});
const marker = L.marker([latitude, longitude], {
icon,
title: p.title,
alt: p.title,
keyboard: true,
})
.bindPopup(popup)
.on("click", () => setSelected(p.id))
.addTo(instance);
markers.current.set(p.id, marker);
bounds.push([latitude, longitude]);
}
if (bounds.length) instance.fitBounds(bounds, { padding: [40, 40], maxZoom: 14 });
observer = new ResizeObserver(() => instance.invalidateSize());
observer.observe(element.current);
})
.catch(() => {
if (!cancelled) setError("Não foi possível iniciar o mapa.");
});
return () => {
cancelled = true;
observer?.disconnect();
map.current?.remove();
map.current = null;
markers.current.clear();
};
}, [points]);
return (
<section
className="space-y-3 rounded-xl border bg-white p-4 text-slate-900"
aria-label="Mapa interactivo dos investimentos"
>
<h2 className="text-xl font-bold">Mapa dos investimentos</h2>
<p>
Arraste para navegar; use +/− para ampliar. Pode seleccionar um investimento na
lista para o localizar.
</p>
{error && <p role="status">{error}</p>}
<div
ref={element}
className="relative z-0 h-[460px] w-full rounded"
aria-label="Mapa; navegação por setas e teclas mais e menos"
/>
{points === null ? (
<p role="status">A carregar localizações…</p>
) : (
<p role="status">{points.length} investimentos com coordenadas disponíveis.</p>
)}
<ul className="grid gap-2 md:grid-cols-2">
{(points ?? []).map((p) => (
<li
key={p.properties.id}
className={
selected === p.properties.id
? "rounded border-2 border-emerald-700 p-3"
: "rounded border p-3"
}
>
<button
type="button"
className="text-left font-bold underline"
aria-pressed={selected === p.properties.id}
onClick={() => {
const marker = markers.current.get(p.properties.id);
if (marker) {
map.current?.setView(marker.getLatLng(), 14);
marker.openPopup();
setSelected(p.properties.id);
}
}}
>
{p.properties.title}
</button>
<p>
{p.properties.category} · {p.properties.location}
</p>
<a className="underline" href={p.properties.url}>
Abrir ficha
</a>
</li>
))}
</ul>
</section>
);
}
@@ -0,0 +1,106 @@
import { useEffect, useState } from "react";
import { api } from "@/pages/investment/shared";
export default function InvestmentCoordinates({ id }: { id: number | string }) {
const [data, setData] = useState({
version: 0,
latitude: "",
longitude: "",
source_reference: "",
});
const [ready, setReady] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
useEffect(() => {
let active = true;
api(`/management/opportunities/${id}/coordinates`)
.then((result) => {
if (active) {
setData({
...result,
latitude: String(result.latitude ?? ""),
longitude: String(result.longitude ?? ""),
});
setReady(true);
}
})
.catch((e) => {
if (active) setMessage(e.message);
});
return () => {
active = false;
};
}, [id]);
return (
<form
className="my-6 space-y-3 rounded border p-4"
onSubmit={async (event) => {
event.preventDefault();
setBusy(true);
try {
const result = await api(`/management/opportunities/${id}/coordinates`, {
...data,
confirmed_site: confirmed,
});
setData((previous) => ({ ...previous, version: result.version }));
setMessage(
"Coordenadas guardadas. O marcador acompanha a publicação da oportunidade.",
);
} catch (e) {
setMessage(e instanceof Error ? e.message : "Falha ao guardar.");
} finally {
setBusy(false);
}
}}
>
<h2 className="text-lg font-bold">Posição do investimento no mapa</h2>
<p>Registe a posição do local em WGS84 e a referência que a confirma.</p>
<div className="grid gap-3 md:grid-cols-2">
{(["latitude", "longitude"] as const).map((field) => (
<label key={field}>
{field === "latitude" ? "Latitude" : "Longitude"}
<input
className="w-full rounded border p-2"
type="number"
step="any"
min={field === "latitude" ? -90 : -180}
max={field === "latitude" ? 90 : 180}
required
value={data[field]}
onChange={(e) => setData({ ...data, [field]: e.target.value })}
/>
</label>
))}
</div>
<label className="block">
Fonte das coordenadas
<input
className="w-full rounded border p-2"
required
minLength={10}
maxLength={2000}
value={data.source_reference}
onChange={(e) => setData({ ...data, source_reference: e.target.value })}
/>
</label>
<label className="flex gap-2">
<input
type="checkbox"
required
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
/>
Confirmo que esta posição corresponde ao local do investimento e pode ser divulgada
quando a ficha estiver publicada.
</label>
<button
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
disabled={!ready || busy}
>
Guardar coordenadas
</button>
{message && <p role="status">{message}</p>}
</form>
);
}
@@ -0,0 +1,56 @@
import { useEffect, useState } from "react";
import InteractiveInvestmentMap, { type InvestmentMapFeature } from "./interactive-investment-map";
export default function InvestmentMapPanel({
filters,
}: {
filters: Record<string, string | number>;
}) {
const key = JSON.stringify(filters);
const [points, setPoints] = useState<InvestmentMapFeature[] | null>(null);
const [missing, setMissing] = useState<{ id: number; title: string; url: string }[]>([]);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
const params = new URLSearchParams(JSON.parse(key));
setPoints(null);
fetch(`/api/v1/investment/map?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
})
.then(async (response) => {
if (!response.ok) throw new Error("Mapa indisponível.");
return response.json();
})
.then((data) => {
if (controller.signal.aborted) return;
setPoints(data.features);
setMissing(data.unlocated ?? []);
setError(data.truncated ? "Cobertura limitada: refine os filtros." : "");
})
.catch((e) => {
if (!controller.signal.aborted) setError(e.message);
});
return () => controller.abort();
}, [key]);
return (
<section className="space-y-3">
{error && <p role="alert">{error}</p>}
<InteractiveInvestmentMap points={points} />
{missing.length > 0 && (
<div>
<p>{missing.length} investimentos aguardam coordenadas do local:</p>
<ul>
{missing.map((record) => (
<li key={record.id}>
<a href={record.url} className="underline">
{record.title}
</a>
</li>
))}
</ul>
</div>
)}
</section>
);
}
@@ -0,0 +1,230 @@
import { useEffect, useId, useState } from "react";
import { api } from "@/pages/investment/shared";
export type TerritoryOption = {
id: string;
name: string;
parent_id: string | null;
location_type: string;
deleted_at?: string | null;
};
type Option = TerritoryOption;
const levels = ["province", "district", "admin_post", "locality"];
const labels = ["Província", "Distrito", "Posto administrativo", "Localidade"];
const control = "w-full rounded border bg-background p-2 text-foreground";
export function TerritoryFields({
initial = [],
onChange,
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
}) {
const [path, setPath] = useState(initial);
return (
<div className="grid gap-4 md:col-span-full md:grid-cols-2">
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
(field, index) => (
<div key={`${field}-${path[index - 1]?.id ?? ""}`}>
<input type="hidden" name={field} value={path[index]?.id ?? ""} />
<TerritoryLevel
index={index}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
endpoint="/api/v1/investment/territory-options"
onChange={(value) => {
const next = [...path.slice(0, index), ...(value ? [value] : [])];
setPath(next);
onChange?.(next);
}}
/>
</div>
),
)}
</div>
);
}
export function TerritoryLevel({
index,
parent,
selected,
onChange,
endpoint = "/management/territory-options",
}: {
index: number;
parent: string;
selected?: Option;
onChange: (value?: Option) => void;
endpoint?: string;
}) {
const id = useId();
const [q, setQ] = useState("");
const [page, setPage] = useState(1);
const [options, setOptions] = useState<Option[]>([]);
const [more, setMore] = useState(false);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const enabled = index === 0 || Boolean(parent);
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
const timer = setTimeout(async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams({
type: levels[index],
parent_id: parent,
q,
page: String(page),
});
const response = await fetch(`${endpoint}?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
});
if (!response.ok) throw new Error("Não foi possível carregar as localizações.");
const data = await response.json();
setOptions(data.data);
setMore(Boolean(data.next_page_url));
} catch (e) {
if (!controller.signal.aborted)
setError(e instanceof Error ? e.message : "Erro de ligação.");
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}, 250);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [index, parent, q, page, enabled, endpoint]);
return (
<div className="space-y-2">
<label htmlFor={id} className="font-medium">
{labels[index]}
</label>
<input
className={control}
aria-label={`Pesquisar ${labels[index]}`}
disabled={!enabled}
value={q}
onChange={(e) => {
setQ(e.target.value);
setPage(1);
}}
placeholder="Pesquisar por nome"
/>
<select
id={id}
className={control}
disabled={!enabled || loading}
value={selected?.id ?? ""}
onChange={(e) => onChange(options.find((o) => o.id === e.target.value))}
>
<option value="">{enabled ? "Seleccione" : "Seleccione o nível anterior"}</option>
{selected && !options.some((o) => o.id === selected.id) && (
<option value={selected.id}>
{selected.name}
{selected.deleted_at ? " (arquivada)" : " (selecção actual)"}
</option>
)}
{options.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
{loading && <p role="status">A carregar…</p>}
{error && <p role="alert">{error}</p>}
{enabled && !loading && !error && options.length === 0 && (
<p className="text-sm">Sem opções para esta pesquisa.</p>
)}
<div className="flex gap-3 text-sm">
{page > 1 && (
<button type="button" onClick={() => setPage(page - 1)}>
Anterior
</button>
)}
{more && (
<button type="button" onClick={() => setPage(page + 1)}>
Mais opções
</button>
)}
</div>
</div>
);
}
export default function InvestmentTerritory({ kind, id }: { kind: string; id: string | number }) {
const [path, setPath] = useState<Option[]>([]);
const [version, setVersion] = useState<number | null>(null);
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
api(`/management/territories/${kind}/${id}`)
.then((data) => {
if (!active) return;
setPath(
levels.flatMap((level) =>
data.path.filter((o: Option) => o.location_type === level),
),
);
setVersion(data.version);
})
.catch((e) => {
if (active) setMessage(e.message);
});
return () => {
active = false;
};
}, [kind, id]);
return (
<section
className="my-6 space-y-4 rounded border p-4"
aria-label="Localização do investimento"
>
<h2 className="text-lg font-semibold">Localização do investimento</h2>
<p>Seleccione até ao nível conhecido. Alterar um nível limpa as selecções seguintes.</p>
<div className="grid gap-4 md:grid-cols-2">
{levels.map((level, index) => (
<TerritoryLevel
key={`${level}-${path[index - 1]?.id ?? ""}`}
index={index}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
onChange={(value) => {
setPath([...path.slice(0, index), ...(value ? [value] : [])]);
setMessage("");
}}
/>
))}
</div>
<button
type="button"
className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50"
disabled={version === null || busy}
onClick={async () => {
setBusy(true);
setMessage("");
try {
const data = await api(`/management/territories/${kind}/${id}`, {
version,
path: path.map((o) => o.id),
});
setVersion(data.version);
setMessage("Localização associada e guardada.");
} catch (e) {
setMessage(e instanceof Error ? e.message : "Erro ao guardar.");
} finally {
setBusy(false);
}
}}
>
Guardar localização
</button>
{message && <p role="status">{message}</p>}
</section>
);
}