varias alteracoes
This commit is contained in:
@@ -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:
|
||||
'© <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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Estados de preparação usados pelo cadastro de oportunidades (níveis 1–6). */
|
||||
export const MATURITY_LEVELS = [
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
] as const;
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createContext, useContext, useRef, useState } from "react";
|
||||
import { router } from "@inertiajs/react";
|
||||
import { PortalMenu } from "@/layouts/portal-navigation";
|
||||
import { MATURITY_LEVELS } from "@/lib/investment-maturity";
|
||||
import type { Dispatch, FormEvent, ReactNode, SetStateAction } from "react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import { usePortalQuery } from "@/hooks/use-portal-query";
|
||||
@@ -94,14 +95,6 @@ const PROVINCES = [
|
||||
"Niassa",
|
||||
];
|
||||
|
||||
const MATURITY_LEVELS = [
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Componentes */
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Link, router, useForm, usePage } from "@inertiajs/react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Map from "@/components/interactive-investment-map";
|
||||
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { MATURITY_LEVELS } from "@/lib/investment-maturity";
|
||||
import { Frame, Field, input, button, card, money, api, groupLabels } from "./shared";
|
||||
import type { Opportunity, References } from "./shared";
|
||||
|
||||
@@ -13,6 +16,7 @@ export default function Catalogue({
|
||||
results,
|
||||
favourites,
|
||||
territorial,
|
||||
territorySelection,
|
||||
}: {
|
||||
filters: Record<string, string | string[] | boolean>;
|
||||
references: References;
|
||||
@@ -23,6 +27,7 @@ export default function Catalogue({
|
||||
next_page_url: string | null;
|
||||
};
|
||||
favourites: number[];
|
||||
territorySelection: TerritoryOption[];
|
||||
territorial: {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -40,6 +45,10 @@ export default function Catalogue({
|
||||
sector: String(filters.sector ?? ""),
|
||||
province: String(filters.province ?? ""),
|
||||
district: String(filters.district ?? ""),
|
||||
province_id: String(filters.province_id ?? ""),
|
||||
district_id: String(filters.district_id ?? ""),
|
||||
admin_post_id: String(filters.admin_post_id ?? ""),
|
||||
locality_id: String(filters.locality_id ?? ""),
|
||||
cluster_id: String(filters.cluster_id ?? ""),
|
||||
zee_id: String(filters.zee_id ?? ""),
|
||||
zfi_id: String(filters.zfi_id ?? ""),
|
||||
@@ -53,19 +62,49 @@ export default function Catalogue({
|
||||
currency: String(filters.currency ?? ""),
|
||||
maturity_level: String(filters.maturity_level ?? ""),
|
||||
before: String(filters.before ?? ""),
|
||||
sort: String(filters.sort ?? "recent"),
|
||||
sort: typeof filters.sort === "string" ? filters.sort : "recent",
|
||||
facets: (Array.isArray(filters.facets) ? filters.facets : []).map(Number),
|
||||
});
|
||||
const view = String(filters.view ?? "grid");
|
||||
const [territoryPath, setTerritoryPath] = useState(territorySelection);
|
||||
const [saved, setSaved] = useState(favourites);
|
||||
const [selected, setSelected] = useState<number[]>([]);
|
||||
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
|
||||
const [points, setPoints] = useState<Feature[] | null>(null);
|
||||
const [unlocated, setUnlocated] = useState<
|
||||
{ id: number; title: string; location: string; url: string }[]
|
||||
>([]);
|
||||
const [truncated, setTruncated] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [suggestions, setSuggestions] = useState<{ title: string; slug: string }[]>([]);
|
||||
const filterKey = JSON.stringify(filters);
|
||||
const draftFilterKey = JSON.stringify(form.data);
|
||||
const lastRequest = useRef(draftFilterKey);
|
||||
useEffect(() => {
|
||||
if (draftFilterKey === lastRequest.current) return;
|
||||
let cancel: (() => void) | undefined;
|
||||
const timer = setTimeout(() => {
|
||||
const data = JSON.parse(draftFilterKey);
|
||||
lastRequest.current = draftFilterKey;
|
||||
router.get(
|
||||
"/oportunidades",
|
||||
{ ...data, education: data.education ? 1 : 0 },
|
||||
{
|
||||
preserveState: true,
|
||||
preserveScroll: true,
|
||||
replace: true,
|
||||
onCancelToken: (token) => {
|
||||
cancel = () => token.cancel();
|
||||
},
|
||||
},
|
||||
);
|
||||
}, 350);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
cancel?.();
|
||||
};
|
||||
}, [draftFilterKey]);
|
||||
useEffect(() => {
|
||||
if (view !== "map" && view !== "combined") return;
|
||||
let active = true;
|
||||
const values = JSON.parse(filterKey) as Record<string, string | string[] | boolean>;
|
||||
const params = new URLSearchParams();
|
||||
@@ -75,10 +114,16 @@ export default function Catalogue({
|
||||
params.set(key, String(value === true ? 1 : value === false ? 0 : value));
|
||||
}
|
||||
setPoints(null);
|
||||
setUnlocated([]);
|
||||
setTruncated(false);
|
||||
setError("");
|
||||
api(`/api/v1/investment/map?${params}`)
|
||||
.then((data) => {
|
||||
if (active) setPoints(data.features);
|
||||
if (active) {
|
||||
setPoints(data.features);
|
||||
setUnlocated(data.unlocated ?? []);
|
||||
setTruncated(Boolean(data.truncated));
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active)
|
||||
@@ -166,6 +211,7 @@ export default function Catalogue({
|
||||
setPoints(null);
|
||||
setComparison([]);
|
||||
setSelected([]);
|
||||
form.transform((data) => ({ ...data, education: data.education ? 1 : 0 }));
|
||||
form.get("/oportunidades", { preserveState: true });
|
||||
}}
|
||||
>
|
||||
@@ -218,39 +264,30 @@ export default function Catalogue({
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
{(["clusters", "corridors", "projects", "locations"] as const).map(
|
||||
(group, i) => {
|
||||
const key = (
|
||||
[
|
||||
"cluster_id",
|
||||
"corridor_id",
|
||||
"project_id",
|
||||
"geo_location_id",
|
||||
] as const
|
||||
)[i];
|
||||
return (
|
||||
<Field
|
||||
key={group}
|
||||
label={
|
||||
["Cluster", "Corredor", "Projecto âncora", "Localização"][i]
|
||||
}
|
||||
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
|
||||
const key = (
|
||||
["cluster_id", "corridor_id", "project_id", "geo_location_id"] as const
|
||||
)[i];
|
||||
return (
|
||||
<Field
|
||||
key={group}
|
||||
label={["Cluster", "Corredor", "Projecto âncora", "Localização"][i]}
|
||||
>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
>
|
||||
<select
|
||||
className={input}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{references[group].map((r) => (
|
||||
<option value={r.id} key={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
},
|
||||
)}
|
||||
<option value="">Todos</option>
|
||||
{references[group].map((r) => (
|
||||
<option value={r.id} key={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
<Field label="Sector">
|
||||
<select
|
||||
className={input}
|
||||
@@ -265,16 +302,34 @@ export default function Catalogue({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{(["province", "district"] as const).map((key) => (
|
||||
<Field key={key} label={key === "province" ? "Província" : "Distrito"}>
|
||||
<input
|
||||
className={input}
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
maxLength={100}
|
||||
{(["province_id", "district_id", "admin_post_id", "locality_id"] as const).map(
|
||||
(key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${territoryPath[index - 1]?.id ?? ""}`}
|
||||
index={index}
|
||||
parent={territoryPath[index - 1]?.id ?? ""}
|
||||
selected={territoryPath[index]}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(value) => {
|
||||
const path = [
|
||||
...territoryPath.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setTerritoryPath(path);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
province: "",
|
||||
district: "",
|
||||
geo_location_id: "",
|
||||
province_id: path[0]?.id ?? "",
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
<Field label="Estado de preparação">
|
||||
<select
|
||||
className={input}
|
||||
@@ -282,9 +337,9 @@ export default function Catalogue({
|
||||
onChange={(e) => form.setData("maturity_level", e.target.value)}
|
||||
>
|
||||
<option value="">Todos os níveis</option>
|
||||
{[1, 2, 3, 4, 5, 6].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
Maturidade {n}
|
||||
{MATURITY_LEVELS.map((label, index) => (
|
||||
<option key={index + 1} value={index + 1}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -434,7 +489,34 @@ export default function Catalogue({
|
||||
</Link>
|
||||
</div>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{(view === "map" || view === "combined") && !error && <Map points={points} />}
|
||||
{!error && <Map points={points} />}
|
||||
{truncated && (
|
||||
<p role="alert">
|
||||
O mapa atingiu o limite de 1.000 registos; refine os filtros. A cobertura não
|
||||
está completa.
|
||||
</p>
|
||||
)}
|
||||
{unlocated.length > 0 && (
|
||||
<section className={card} aria-label="Investimentos a georreferenciar">
|
||||
<h2 className="text-xl font-bold">
|
||||
{unlocated.length} investimentos sem coordenadas de local confirmadas
|
||||
</h2>
|
||||
<p>
|
||||
Continuam nos resultados. Seleccionar uma província não determina a posição
|
||||
exacta do investimento.
|
||||
</p>
|
||||
<ul>
|
||||
{unlocated.map((record) => (
|
||||
<li key={record.id}>
|
||||
<Link href={record.url} className="underline">
|
||||
{record.title}
|
||||
</Link>{" "}
|
||||
— {record.location || "Localização por completar"}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{(view !== "map" || error || points?.length === 0) && (
|
||||
<div
|
||||
className={
|
||||
@@ -583,63 +665,3 @@ export default function Catalogue({
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
function Map({ points }: { points: Feature[] | null }) {
|
||||
if (points === null) return <p role="status">A carregar localizações…</p>;
|
||||
if (!points.length)
|
||||
return (
|
||||
<p className={card}>
|
||||
Sem coordenadas públicas associadas aos resultados. Não são atribuídas localizações
|
||||
aproximadas.
|
||||
</p>
|
||||
);
|
||||
const xs = points.map((p) => p.geometry.coordinates[0]),
|
||||
ys = points.map((p) => p.geometry.coordinates[1]);
|
||||
const minX = Math.min(...xs) - 0.1,
|
||||
maxX = Math.max(...xs) + 0.1,
|
||||
minY = Math.min(...ys) - 0.1,
|
||||
maxY = Math.max(...ys) + 0.1;
|
||||
return (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Localizações georreferenciadas</h2>
|
||||
<p>
|
||||
Coordenadas WGS84 publicadas, sem mapa base externo. Até 1.000 pontos; a lista
|
||||
acessível apresenta os mesmos dados.
|
||||
</p>
|
||||
<svg
|
||||
viewBox="0 0 900 400"
|
||||
role="img"
|
||||
aria-label="Distribuição das localizações por longitude e latitude"
|
||||
className="my-4 w-full rounded bg-sky-50"
|
||||
>
|
||||
<path d="M30 10 V370 H880" fill="none" stroke="#475569" />
|
||||
{points.map((p, i) => (
|
||||
<a
|
||||
key={`${p.properties.id}-${i}`}
|
||||
href={p.properties.url}
|
||||
aria-label={`${p.properties.title}, ${p.properties.location}`}
|
||||
>
|
||||
<circle
|
||||
cx={45 + ((p.geometry.coordinates[0] - minX) / (maxX - minX)) * 810}
|
||||
cy={350 - ((p.geometry.coordinates[1] - minY) / (maxY - minY)) * 310}
|
||||
r="8"
|
||||
fill="#065f46"
|
||||
>
|
||||
<title>{p.properties.title}</title>
|
||||
</circle>
|
||||
</a>
|
||||
))}
|
||||
</svg>
|
||||
<ul className="space-y-2">
|
||||
{points.map((p, i) => (
|
||||
<li key={i}>
|
||||
<Link className="underline" href={p.properties.url}>
|
||||
{p.properties.title}
|
||||
</Link>{" "}
|
||||
— {p.properties.location}; longitude {p.geometry.coordinates[0]}, latitude{" "}
|
||||
{p.geometry.coordinates[1]}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link, router, usePage } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { Frame, card, button, money, groupLabels } from "./shared";
|
||||
import type { Opportunity, Context } from "./shared";
|
||||
export default function Detail({
|
||||
@@ -19,6 +20,10 @@ export default function Detail({
|
||||
{r.reference} · {r.sector?.name} · {r.province} {r.district}
|
||||
</p>
|
||||
<p className="text-xl">{r.summary}</p>
|
||||
<InvestmentMapPanel filters={{ opportunity_id: r.id }} />
|
||||
{c.primary_territory_path && c.primary_territory_path.length > 0 && (
|
||||
<p>Localização: {c.primary_territory_path.map((node) => node.name).join(" → ")}</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-4">
|
||||
{auth.user ? (
|
||||
<button
|
||||
|
||||
@@ -40,6 +40,7 @@ export type Opportunity = {
|
||||
status: string;
|
||||
};
|
||||
export type Context = {
|
||||
primary_territory_path?: { id: string; name: string; location_type: string }[];
|
||||
zones?: {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Link, router, useForm } from "@inertiajs/react";
|
||||
import InvestmentTerritory from "@/components/investment-territory";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { useState } from "react";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
import ZoneRelations from "./zone-relations";
|
||||
@@ -91,8 +93,6 @@ function Editor({
|
||||
name_en: z.name_en ?? "",
|
||||
description: z.description ?? "",
|
||||
description_en: z.description_en ?? "",
|
||||
province: z.province ?? "",
|
||||
district: z.district ?? "",
|
||||
operator_id: z.operator_id ?? "",
|
||||
legal_source_id: z.legal_source_id ?? "",
|
||||
});
|
||||
@@ -153,8 +153,6 @@ function Editor({
|
||||
["code", "Código"],
|
||||
["name", "Nome PT"],
|
||||
["name_en", "Nome EN"],
|
||||
["province", "Província"],
|
||||
["district", "Distrito"],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<Field key={key} label={label}>
|
||||
@@ -484,6 +482,18 @@ function Editor({
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
{management && <InvestmentTerritory kind="zones" id={z.id} />}
|
||||
{!management && ["zee", "zfi", "industrial_park"].includes(z.category) && (
|
||||
<InvestmentMapPanel
|
||||
filters={{
|
||||
[z.category === "zee"
|
||||
? "zee_id"
|
||||
: z.category === "zfi"
|
||||
? "zfi_id"
|
||||
: "park_id"]: z.id,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState } from "react";
|
||||
import { TerritoryFields, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { Frame, Field, input, button, card, api } from "./shared";
|
||||
|
||||
type Zone = {
|
||||
@@ -17,6 +18,7 @@ export default function Zones({
|
||||
records,
|
||||
filters,
|
||||
management,
|
||||
territorySelection = [],
|
||||
}: {
|
||||
records: {
|
||||
data: Zone[];
|
||||
@@ -26,6 +28,7 @@ export default function Zones({
|
||||
};
|
||||
filters: { q?: string; category?: string };
|
||||
management: boolean;
|
||||
territorySelection?: TerritoryOption[];
|
||||
}) {
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -56,6 +59,7 @@ export default function Zones({
|
||||
<option value="industrial_park">Parque industrial</option>
|
||||
</select>
|
||||
</Field>
|
||||
<TerritoryFields initial={territorySelection} />
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
<p role="status">{records.total} registos disponíveis</p>
|
||||
@@ -115,6 +119,7 @@ export default function Zones({
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">Criar rascunho</h2>
|
||||
<TerritoryFields />
|
||||
<Field label="Código">
|
||||
<input name="code" className={input} required maxLength={80} />
|
||||
</Field>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import InvestmentTerritory from "@/components/investment-territory";
|
||||
import InvestmentCoordinates from "@/components/investment-coordinates";
|
||||
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
|
||||
import { useState } from "react";
|
||||
import { Management, Field, button, control, states } from "./shared";
|
||||
|
||||
type Values = Record<string, string | boolean>;
|
||||
@@ -9,8 +13,6 @@ const opportunityFields = {
|
||||
slug: "Slug (endereço)",
|
||||
summary: "Resumo",
|
||||
description: "Descrição",
|
||||
province: "Província",
|
||||
district: "Distrito",
|
||||
promoter_name: "Promotor",
|
||||
promoter_type: "Tipo de promotor",
|
||||
estimated_investment_amount: "Investimento estimado",
|
||||
@@ -66,6 +68,7 @@ export default function Editor({
|
||||
initial.is_featured = Boolean(record?.is_featured ?? false);
|
||||
}
|
||||
const form = useForm<Values>(initial);
|
||||
const [creationPath, setCreationPath] = useState<TerritoryOption[]>([]);
|
||||
return (
|
||||
<Management
|
||||
title={`${record ? "Editar" : "Criar"} ${isSector ? "sector" : "oportunidade"}`}
|
||||
@@ -84,6 +87,40 @@ export default function Editor({
|
||||
}}
|
||||
>
|
||||
<fieldset disabled={form.processing} className="space-y-5">
|
||||
{!isSector && !record && (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${creationPath[index - 1]?.id ?? ""}`}
|
||||
index={index}
|
||||
parent={creationPath[index - 1]?.id ?? ""}
|
||||
selected={creationPath[index]}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(value) => {
|
||||
const path = [
|
||||
...creationPath.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setCreationPath(path);
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
province_id: path[0]?.id ?? "",
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={form.errors[key]}>
|
||||
{[
|
||||
@@ -177,6 +214,8 @@ export default function Editor({
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{!isSector && record && <InvestmentTerritory kind="opportunities" id={record.id} />}
|
||||
{!isSector && record && <InvestmentCoordinates id={record.id} />}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ export function Management({ title, children }: { title: string; children: React
|
||||
<Link href="/management/crm/investors">Investidores</Link>
|
||||
<Link href="/management/projects">Projectos</Link>
|
||||
<Link href="/management/clusters">Clusters</Link>
|
||||
<Link href="/management/territory-associations">
|
||||
Localizações dos investimentos
|
||||
</Link>
|
||||
<Link href="/management/investment/zones">ZEE, ZFI e parques</Link>
|
||||
{educationEnabled && (
|
||||
<Link href="/management/education">Competências e formação</Link>
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import InvestmentTerritory from "@/components/investment-territory";
|
||||
import { Management, Field, control } from "./shared";
|
||||
|
||||
export default function TerritoryAssociations() {
|
||||
const [kind, setKind] = useState("projects");
|
||||
const [id, setId] = useState("");
|
||||
const [q, setQ] = useState("");
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<{ id: string; name: string }[]>([]);
|
||||
const [more, setMore] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ kind, q, page: String(page) });
|
||||
const response = await fetch(`/management/territory-subjects?${params}`, {
|
||||
signal: controller.signal,
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) throw new Error("Não foi possível carregar os investimentos.");
|
||||
const data = await response.json();
|
||||
setRows(data.data);
|
||||
setMore(Boolean(data.next_page_url));
|
||||
setError("");
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setError(e instanceof Error ? e.message : "Erro de ligação.");
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [kind, q, page]);
|
||||
return (
|
||||
<Management title="Localizações dos investimentos">
|
||||
<Field label="Tipo de investimento">
|
||||
<select
|
||||
className={control}
|
||||
value={kind}
|
||||
onChange={(e) => {
|
||||
setKind(e.target.value);
|
||||
setId("");
|
||||
setRows([]);
|
||||
setQ("");
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<option value="projects">Projectos / projectos âncora</option>
|
||||
<option value="clusters">Clusters</option>
|
||||
<option value="corridors">Corredores</option>
|
||||
<option value="zones">ZEE / ZFI / parques industriais</option>
|
||||
<option value="opportunities">Oportunidades</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Pesquisar investimento">
|
||||
<input
|
||||
className={control}
|
||||
value={q}
|
||||
onChange={(e) => {
|
||||
setQ(e.target.value);
|
||||
setPage(1);
|
||||
setId("");
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Investimento">
|
||||
<select className={control} value={id} onChange={(e) => setId(e.target.value)}>
|
||||
<option value="">Seleccione</option>
|
||||
{rows.map((row) => (
|
||||
<option value={row.id} key={row.id}>
|
||||
{row.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{!error && rows.length === 0 && <p>Sem registos para esta pesquisa.</p>}
|
||||
<div className="flex gap-4">
|
||||
{page > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setId("");
|
||||
setPage(page - 1);
|
||||
}}
|
||||
>
|
||||
Anterior
|
||||
</button>
|
||||
)}
|
||||
{more && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setId("");
|
||||
setPage(page + 1);
|
||||
}}
|
||||
>
|
||||
Mais investimentos
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{id && <InvestmentTerritory key={`${kind}-${id}`} kind={kind} id={id} />}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link, useForm, router } from "@inertiajs/react";
|
||||
import InvestmentMapPanel from "@/components/investment-map-panel";
|
||||
import { Management } from "../management/shared";
|
||||
import { Layout, Field, control, button, labels, kind } from "./shared";
|
||||
import type { Dossier } from "./shared";
|
||||
@@ -47,6 +48,17 @@ function Editor({
|
||||
{kind(record)} · {record.content.code}
|
||||
</p>
|
||||
<p className="text-sm">Fonte: {record.source}</p>
|
||||
{!management && (record.cluster_id || record.corridor_id || record.project_id) && (
|
||||
<InvestmentMapPanel
|
||||
filters={
|
||||
record.cluster_id
|
||||
? { cluster_id: record.cluster_id }
|
||||
: record.corridor_id
|
||||
? { corridor_id: record.corridor_id }
|
||||
: { project_id: record.project_id! }
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{zones.length > 0 && (
|
||||
<section>
|
||||
<h2 className="text-xl font-bold">ZEE, ZFI e parques relacionados</h2>
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Management, Field, button, control } from '../management/shared';
|
||||
import { titles, statuses, stages, roles } from './types';
|
||||
import type { Structure, StructureRecord, Chain } from './types';
|
||||
import ValueNetwork from './value-network';
|
||||
import type { ChainLink, Gap } from './value-network';
|
||||
import { Link, useForm } from "@inertiajs/react";
|
||||
import InvestmentTerritory, { TerritoryFields } from "@/components/investment-territory";
|
||||
import { Management, Field, button, control } from "../management/shared";
|
||||
import { titles, statuses, stages, roles } from "./types";
|
||||
import type { Structure, StructureRecord, Chain } from "./types";
|
||||
import ValueNetwork from "./value-network";
|
||||
import type { ChainLink, Gap } from "./value-network";
|
||||
|
||||
function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
|
||||
const form = useForm({
|
||||
code: chain?.code ?? '',
|
||||
name: chain?.name ?? '',
|
||||
stage: chain?.stage ?? 'input',
|
||||
code: chain?.code ?? "",
|
||||
name: chain?.name ?? "",
|
||||
stage: chain?.stage ?? "input",
|
||||
});
|
||||
return (
|
||||
<form
|
||||
@@ -17,8 +18,7 @@ function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const url = `/management/clusters/${clusterId}/chains`;
|
||||
if (chain)
|
||||
form.put(`${url}/${chain.id}`, { preserveScroll: true });
|
||||
if (chain) form.put(`${url}/${chain.id}`, { preserveScroll: true });
|
||||
else
|
||||
form.post(url, {
|
||||
preserveScroll: true,
|
||||
@@ -26,28 +26,26 @@ function ChainForm({ clusterId, chain }: { clusterId: string; chain?: Chain }) {
|
||||
});
|
||||
}}
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
{chain ? chain.name : 'Nova etapa'}
|
||||
</h3>
|
||||
<h3 className="font-semibold">{chain ? chain.name : "Nova etapa"}</h3>
|
||||
<Field label="Código da etapa" error={form.errors.code}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.code}
|
||||
onChange={(e) => form.setData('code', e.target.value)}
|
||||
onChange={(e) => form.setData("code", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nome da etapa" error={form.errors.name}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.name}
|
||||
onChange={(e) => form.setData('name', e.target.value)}
|
||||
onChange={(e) => form.setData("name", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fase da cadeia" error={form.errors.stage}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.stage}
|
||||
onChange={(e) => form.setData('stage', e.target.value)}
|
||||
onChange={(e) => form.setData("stage", e.target.value)}
|
||||
>
|
||||
{Object.entries(stages).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
@@ -85,36 +83,47 @@ export default function Editor({
|
||||
role: string;
|
||||
}[];
|
||||
}) {
|
||||
const isProject = structure === 'projects';
|
||||
const isProject = structure === "projects";
|
||||
const form = useForm({
|
||||
code: record?.code ?? '',
|
||||
name: record?.name ?? '',
|
||||
status: record?.status ?? (isProject ? 'draft' : 'planned'),
|
||||
sector: record?.sector ?? '',
|
||||
description: record?.description ?? '',
|
||||
budget_amount: record?.budget_amount ?? '',
|
||||
budget_currency: record?.budget_currency ?? '',
|
||||
start_date: record?.start_date?.slice(0, 10) ?? '',
|
||||
end_date: record?.end_date?.slice(0, 10) ?? '',
|
||||
code: record?.code ?? "",
|
||||
name: record?.name ?? "",
|
||||
status: record?.status ?? (isProject ? "draft" : "planned"),
|
||||
sector: record?.sector ?? "",
|
||||
description: record?.description ?? "",
|
||||
budget_amount: record?.budget_amount ?? "",
|
||||
budget_currency: record?.budget_currency ?? "",
|
||||
start_date: record?.start_date?.slice(0, 10) ?? "",
|
||||
end_date: record?.end_date?.slice(0, 10) ?? "",
|
||||
province_id: "",
|
||||
district_id: "",
|
||||
admin_post_id: "",
|
||||
locality_id: "",
|
||||
});
|
||||
const association = useForm({ project_id: '', role: 'complementary' });
|
||||
const association = useForm({ project_id: "", role: "complementary" });
|
||||
return (
|
||||
<Management
|
||||
title={`${record ? 'Editar' : 'Criar'} ${isProject ? 'projecto' : 'cluster'}`}
|
||||
>
|
||||
<Management title={`${record ? "Editar" : "Criar"} ${isProject ? "projecto" : "cluster"}`}>
|
||||
<Link className="underline" href={`/management/${structure}`}>
|
||||
Voltar a {titles[structure].toLowerCase()}
|
||||
</Link>
|
||||
<p>
|
||||
Registo interno de gestão. O estado activo não publica este
|
||||
conteúdo no portal.
|
||||
</p>
|
||||
<p>Registo interno de gestão. O estado activo não publica este conteúdo no portal.</p>
|
||||
{!record && (
|
||||
<TerritoryFields
|
||||
onChange={(path) =>
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
province_id: path[0]?.id ?? "",
|
||||
district_id: path[1]?.id ?? "",
|
||||
admin_post_id: path[2]?.id ?? "",
|
||||
locality_id: path[3]?.id ?? "",
|
||||
}))
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<form
|
||||
className="max-w-3xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (record)
|
||||
form.put(`/management/${structure}/${record.id}`);
|
||||
if (record) form.put(`/management/${structure}/${record.id}`);
|
||||
else form.post(`/management/${structure}`);
|
||||
}}
|
||||
>
|
||||
@@ -122,29 +131,27 @@ export default function Editor({
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.code}
|
||||
onChange={(e) => form.setData('code', e.target.value)}
|
||||
onChange={(e) => form.setData("code", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nome" error={form.errors.name}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.name}
|
||||
onChange={(e) => form.setData('name', e.target.value)}
|
||||
onChange={(e) => form.setData("name", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado" error={form.errors.status}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
onChange={(e) => form.setData("status", e.target.value)}
|
||||
>
|
||||
{Object.entries(statuses[structure]).map(
|
||||
([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{Object.entries(statuses[structure]).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{!isProject && (
|
||||
@@ -152,25 +159,18 @@ export default function Editor({
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.sector}
|
||||
onChange={(e) =>
|
||||
form.setData('sector', e.target.value)
|
||||
}
|
||||
onChange={(e) => form.setData("sector", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{isProject && (
|
||||
<>
|
||||
<Field
|
||||
label="Descrição"
|
||||
error={form.errors.description}
|
||||
>
|
||||
<Field label="Descrição" error={form.errors.description}>
|
||||
<textarea
|
||||
className={control}
|
||||
rows={5}
|
||||
value={form.data.description}
|
||||
onChange={(e) =>
|
||||
form.setData('description', e.target.value)
|
||||
}
|
||||
onChange={(e) => form.setData("description", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
@@ -181,12 +181,7 @@ export default function Editor({
|
||||
inputMode="decimal"
|
||||
className={control}
|
||||
value={form.data.budget_amount}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'budget_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
onChange={(e) => form.setData("budget_amount", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
@@ -198,37 +193,24 @@ export default function Editor({
|
||||
className={control}
|
||||
value={form.data.budget_currency}
|
||||
onChange={(e) =>
|
||||
form.setData(
|
||||
'budget_currency',
|
||||
e.target.value.toUpperCase(),
|
||||
)
|
||||
form.setData("budget_currency", e.target.value.toUpperCase())
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Data de início"
|
||||
error={form.errors.start_date}
|
||||
>
|
||||
<Field label="Data de início" error={form.errors.start_date}>
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.data.start_date}
|
||||
onChange={(e) =>
|
||||
form.setData('start_date', e.target.value)
|
||||
}
|
||||
onChange={(e) => form.setData("start_date", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Data de conclusão"
|
||||
error={form.errors.end_date}
|
||||
>
|
||||
<Field label="Data de conclusão" error={form.errors.end_date}>
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.data.end_date}
|
||||
onChange={(e) =>
|
||||
form.setData('end_date', e.target.value)
|
||||
}
|
||||
onChange={(e) => form.setData("end_date", e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
</>
|
||||
@@ -240,9 +222,7 @@ export default function Editor({
|
||||
{!isProject && record && (
|
||||
<>
|
||||
<section className="max-w-3xl space-y-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Projectos associados
|
||||
</h2>
|
||||
<h2 className="text-xl font-semibold">Projectos associados</h2>
|
||||
{memberships.map((member) => (
|
||||
<p key={member.id}>
|
||||
<Link
|
||||
@@ -250,93 +230,61 @@ export default function Editor({
|
||||
href={`/management/projects/${member.project_id}/edit`}
|
||||
>
|
||||
{member.name}
|
||||
</Link>{' '}
|
||||
</Link>{" "}
|
||||
· {roles[member.role]}
|
||||
</p>
|
||||
))}
|
||||
{!memberships.length && (
|
||||
<p>Ainda não existem projectos associados.</p>
|
||||
)}
|
||||
{!memberships.length && <p>Ainda não existem projectos associados.</p>}
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
association.post(
|
||||
`/management/clusters/${record.id}/projects`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
association.post(`/management/clusters/${record.id}/projects`, {
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field
|
||||
label="Projecto"
|
||||
error={association.errors.project_id}
|
||||
>
|
||||
<Field label="Projecto" error={association.errors.project_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={association.data.project_id}
|
||||
onChange={(e) =>
|
||||
association.setData(
|
||||
'project_id',
|
||||
e.target.value,
|
||||
)
|
||||
association.setData("project_id", e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{projects.map((project) => (
|
||||
<option
|
||||
key={project.id}
|
||||
value={project.id}
|
||||
>
|
||||
<option key={project.id} value={project.id}>
|
||||
{project.code} — {project.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Papel no cluster"
|
||||
error={association.errors.role}
|
||||
>
|
||||
<Field label="Papel no cluster" error={association.errors.role}>
|
||||
<select
|
||||
className={control}
|
||||
value={association.data.role}
|
||||
onChange={(e) =>
|
||||
association.setData(
|
||||
'role',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
onChange={(e) => association.setData("role", e.target.value)}
|
||||
>
|
||||
{Object.entries(roles).map(
|
||||
([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
{Object.entries(roles).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={association.processing}
|
||||
>
|
||||
<button className={button} disabled={association.processing}>
|
||||
Guardar associação
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Seleccionar um projecto já associado permite
|
||||
actualizar o seu papel.
|
||||
Seleccionar um projecto já associado permite actualizar o seu papel.
|
||||
</p>
|
||||
</form>
|
||||
</section>
|
||||
<section className="max-w-3xl space-y-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Etapas da cadeia de valor
|
||||
</h2>
|
||||
<h2 className="text-xl font-semibold">Etapas da cadeia de valor</h2>
|
||||
{chains.map((chain) => (
|
||||
<ChainForm
|
||||
key={chain.id}
|
||||
clusterId={record.id}
|
||||
chain={chain}
|
||||
/>
|
||||
<ChainForm key={chain.id} clusterId={record.id} chain={chain} />
|
||||
))}
|
||||
<ChainForm clusterId={record.id} />
|
||||
</section>
|
||||
@@ -348,6 +296,7 @@ export default function Editor({
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{record && <InvestmentTerritory kind={structure} id={record.id} />}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user