first commit
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-09-28 10:01:09 +02:00
commit 250ac35fd1
481 changed files with 92144 additions and 0 deletions
+645
View File
@@ -0,0 +1,645 @@
import { Link, router, useForm, usePage } from "@inertiajs/react";
import { useEffect, useState } from "react";
import { Frame, Field, input, button, card, money, api, groupLabels } from "./shared";
import type { Opportunity, References } from "./shared";
type Feature = {
geometry: { coordinates: [number, number] };
properties: { id: number; title: string; location: string; url: string };
};
export default function Catalogue({
filters,
references,
results,
favourites,
territorial,
}: {
filters: Record<string, string | string[] | boolean>;
references: References;
results: {
data: Opportunity[];
total: number;
prev_page_url: string | null;
next_page_url: string | null;
};
favourites: number[];
territorial: {
id: string;
title: string;
content: { code: string };
project_id: string | null;
cluster_id: string | null;
corridor_id: string | null;
}[];
}) {
const { auth } = usePage<{ auth: { user: unknown } }>().props;
const form = useForm({
q: String(filters.q ?? ""),
dimension: String(filters.dimension ?? ""),
view: String(filters.view ?? "grid"),
sector: String(filters.sector ?? ""),
province: String(filters.province ?? ""),
district: String(filters.district ?? ""),
cluster_id: String(filters.cluster_id ?? ""),
zee_id: String(filters.zee_id ?? ""),
zfi_id: String(filters.zfi_id ?? ""),
park_id: String(filters.park_id ?? ""),
corridor_id: String(filters.corridor_id ?? ""),
project_id: String(filters.project_id ?? ""),
geo_location_id: String(filters.geo_location_id ?? ""),
education: Boolean(filters.education && filters.education !== "0"),
min_amount: String(filters.min_amount ?? ""),
max_amount: String(filters.max_amount ?? ""),
currency: String(filters.currency ?? ""),
maturity_level: String(filters.maturity_level ?? ""),
before: String(filters.before ?? ""),
sort: String(filters.sort ?? "recent"),
facets: (Array.isArray(filters.facets) ? filters.facets : []).map(Number),
});
const view = String(filters.view ?? "grid");
const [saved, setSaved] = useState(favourites);
const [selected, setSelected] = useState<number[]>([]);
const [comparison, setComparison] = useState<{ record: Opportunity }[]>([]);
const [points, setPoints] = useState<Feature[] | null>(null);
const [error, setError] = useState("");
const [suggestions, setSuggestions] = useState<{ title: string; slug: string }[]>([]);
const filterKey = JSON.stringify(filters);
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();
for (const [key, value] of Object.entries(values)) {
if (Array.isArray(value)) value.forEach((v) => params.append(`${key}[]`, v));
else if (value !== "" && value !== null)
params.set(key, String(value === true ? 1 : value === false ? 0 : value));
}
setPoints(null);
setError("");
api(`/api/v1/investment/map?${params}`)
.then((data) => {
if (active) setPoints(data.features);
})
.catch(() => {
if (active)
setError("Mapa indisponível. A lista e os filtros continuam disponíveis.");
});
return () => {
active = false;
};
}, [view, filterKey]);
useEffect(() => {
if (form.data.q.length < 2) {
setSuggestions([]);
return;
}
let active = true;
const timer = setTimeout(() => {
api(`/api/v1/investment/suggest?q=${encodeURIComponent(form.data.q)}`)
.then((data) => {
if (active) setSuggestions(data.opportunities);
})
.catch(() => {
if (active) setSuggestions([]);
});
}, 300);
return () => {
active = false;
clearTimeout(timer);
};
}, [form.data.q]);
const query = () => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(filters)) {
if (Array.isArray(value)) value.forEach((v) => params.append(`${key}[]`, String(v)));
else if (value !== "" && value !== null)
params.set(key, String(value === true ? 1 : value === false ? 0 : value));
}
return params.toString();
};
const toggle = async (id: number) => {
if (!auth.user) {
window.location.href = "/login";
return;
}
try {
const data = await api(`/api/v1/investment/favourites/${id}`, {
saved: !saved.includes(id),
});
setSaved(data.saved ? [...saved, id] : saved.filter((n) => n !== id));
} catch (e) {
setError((e as Error).message);
}
};
const dimensionUrl = (dimension: string) => {
const params = new URLSearchParams(query());
params.set("dimension", dimension);
params.delete("page");
return `/oportunidades?${params}`;
};
return (
<Frame
title={form.data.education ? "Oportunidades na Educação" : "Catálogo de investimento"}
>
<nav aria-label="Dimensões do catálogo" className="grid gap-3 sm:grid-cols-4">
<Link className={card} href={dimensionUrl("cluster")}>
Por Cluster
</Link>
<Link className={card} href={dimensionUrl("corridor")}>
Por Corredor
</Link>
<Link className={card} href={dimensionUrl("zee")}>
Por ZEE
</Link>
<Link className={card} href={dimensionUrl("zfi")}>
Por ZFI
</Link>
</nav>
<p>
Combine contexto territorial, dimensão e necessidades. As fichas documentais e as
oportunidades mantêm a sua origem e natureza.
</p>
<form
className={card + " space-y-4"}
onSubmit={(e) => {
e.preventDefault();
setPoints(null);
setComparison([]);
setSelected([]);
form.get("/oportunidades", { preserveState: true });
}}
>
<Field label="Pesquisar oportunidades">
<input
className={input}
value={form.data.q}
onChange={(e) => form.setData("q", e.target.value)}
autoComplete="off"
aria-describedby="search-suggestions"
/>
</Field>
{suggestions.length > 0 && (
<ul
id="search-suggestions"
aria-label="Sugestões de pesquisa"
className="space-y-2"
>
{suggestions.map((s) => (
<li key={s.slug}>
<Link href={`/oportunidades/${s.slug}`} className="underline">
{s.title}
</Link>
</li>
))}
</ul>
)}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{(
[
["zee_id", "zee", "ZEE"],
["zfi_id", "zfi", "ZFI"],
["park_id", "industrial_park", "Parque industrial"],
] as const
).map(([field, category, label]) => (
<Field key={field} label={label}>
<select
className={input}
value={form.data[field]}
onChange={(e) => form.setData(field, e.target.value)}
>
<option value="">Todos</option>
{(references.zones ?? [])
.filter((z) => z.category === category)
.map((z) => (
<option key={z.id} value={z.id}>
{z.name}
</option>
))}
</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]
}
>
<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>
);
},
)}
<Field label="Sector">
<select
className={input}
value={form.data.sector}
onChange={(e) => form.setData("sector", e.target.value)}
>
<option value="">Todos</option>
{references.sectors.map((s) => (
<option key={s.id} value={s.slug}>
{s.name}
</option>
))}
</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}
/>
</Field>
))}
<Field label="Estado de preparação">
<select
className={input}
value={form.data.maturity_level}
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}
</option>
))}
</select>
</Field>
{(["min_amount", "max_amount"] as const).map((key) => (
<Field
key={key}
label={
key === "min_amount" ? "Investimento mínimo" : "Investimento máximo"
}
>
<input
type="number"
min="0"
step="0.01"
className={input}
value={form.data[key]}
onChange={(e) => {
form.setData(key, e.target.value);
if (!form.data.currency) form.setData("currency", "MZN");
}}
/>
</Field>
))}
<Field label="Moeda">
<select
className={input}
value={form.data.currency}
required={!!form.data.min_amount || !!form.data.max_amount}
onChange={(e) => form.setData("currency", e.target.value)}
>
<option value="">Todas, sem comparação cambial</option>
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</Field>
<Field label="Data-alvo até">
<input
type="date"
className={input}
value={form.data.before}
onChange={(e) => form.setData("before", e.target.value)}
/>
</Field>
</div>
<label className="flex gap-2">
<input
type="checkbox"
checked={form.data.education}
onChange={(e) => form.setData("education", e.target.checked)}
/>
Apenas oportunidades na educação
</label>
<details>
<summary className="cursor-pointer font-semibold">
Subsector, educação, infraestruturas, competências e apoios
</summary>
<div className="mt-4 grid gap-4 md:grid-cols-3">
{[
"subsector",
"education",
"infrastructure",
"labour",
"qualification",
"support",
"impact",
"partnership",
].map((group) => (
<fieldset
key={group}
className="max-h-52 space-y-2 overflow-auto rounded border p-3"
>
<legend className="font-semibold">{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group)
.map((o) => (
<label key={o.id} className="flex gap-2">
<input
type="checkbox"
checked={form.data.facets.includes(o.id)}
onChange={(e) =>
form.setData(
"facets",
e.target.checked
? [...form.data.facets, o.id]
: form.data.facets.filter(
(id) => id !== o.id,
),
)
}
/>
{o.label}
</label>
))}
</fieldset>
))}
</div>
</details>
<div className="flex flex-wrap items-end gap-4">
<Field label="Ordenar">
<select
className={input}
value={form.data.sort}
onChange={(e) => form.setData("sort", e.target.value)}
>
<option value="recent">Mais recentes</option>
<option value="title">Título</option>
<option value="amount_asc">Montante crescente, por moeda</option>
<option value="amount_desc">Montante decrescente, por moeda</option>
</select>
</Field>
<button className={button} disabled={form.processing}>
Aplicar filtros
</button>
<Link href="/oportunidades" className="underline">
Limpar filtros
</Link>
</div>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key}>
{value}
</p>
))}
</form>
<div className="flex flex-wrap items-center gap-4">
<p role="status">{results.total} oportunidades publicadas</p>
{["grid", "list", "map", "combined"].map((value, i) => (
<button
key={value}
aria-pressed={view === value}
className="rounded border px-4 py-2"
onClick={() => {
const params = new URLSearchParams(query());
params.set("view", value);
router.get(`/oportunidades?${params}`, {}, { preserveScroll: true });
}}
>
{["Grelha", "Lista", "Mapa", "Lista e mapa"][i]}
</button>
))}
<a className="underline" href={"/api/v1/investment/export?" + query()}>
Exportar CSV (até 1.000)
</a>
<Link className="underline" href="/investidor/manifestacoes">
Favoritos e pedidos
</Link>
</div>
{error && <p role="alert">{error}</p>}
{(view === "map" || view === "combined") && !error && <Map points={points} />}
{(view !== "map" || error || points?.length === 0) && (
<div
className={
view === "grid" ? "grid gap-5 md:grid-cols-2 xl:grid-cols-3" : "space-y-4"
}
>
{results.data.map((r) => (
<article key={r.id} className={card + " space-y-3"}>
<p className="text-sm">
{r.sector?.name} · {r.province || "Localização não indicada"}
</p>
<h2 className="text-xl font-bold">
<Link href={`/oportunidades/${r.slug}`}>{r.title}</Link>
</h2>
<p>{r.summary}</p>
<p className="font-semibold">{money(r)}</p>
<p>{r.maturity_label}</p>
<div className="flex flex-wrap gap-4">
<Link className="underline" href={`/oportunidades/${r.slug}`}>
Ver ficha
</Link>
<button
aria-pressed={saved.includes(r.id)}
className="underline"
onClick={() => toggle(r.id)}
>
{saved.includes(r.id) ? "Retirar favorito" : "Guardar favorito"}
</button>
<label className="flex gap-2">
<input
type="checkbox"
checked={selected.includes(r.id)}
disabled={!selected.includes(r.id) && selected.length >= 4}
onChange={(e) =>
setSelected(
e.target.checked
? [...selected, r.id]
: selected.filter((id) => id !== r.id),
)
}
/>
Comparar
</label>
</div>
</article>
))}
</div>
)}
{!results.total && (
<p className={card}>
Sem oportunidades com estes filtros. Explore as fichas territoriais ou{" "}
<Link href="/apoio" className="underline">
peça apoio
</Link>
.
</p>
)}
<nav aria-label="Paginação" className="flex gap-6">
{results.prev_page_url && <Link href={results.prev_page_url}>Anterior</Link>}
{results.next_page_url && <Link href={results.next_page_url}>Seguinte</Link>}
</nav>
{selected.length > 0 && (
<button
className={button}
onClick={() =>
api(
"/api/v1/investment/compare?" +
selected.map((id) => "ids[]=" + id).join("&"),
)
.then((data) => setComparison(data.records))
.catch((e) => setError(e.message))
}
>
Comparar {selected.length} oportunidades
</button>
)}
{comparison.length > 0 && (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-left">
<caption className="p-3 text-left font-bold">
Comparação — montantes nas moedas de origem
</caption>
<thead>
<tr>
<th className="border p-3">Campo</th>
{comparison.map(({ record: r }) => (
<th key={r.id} className="border p-3">
{r.title}
</th>
))}
</tr>
</thead>
<tbody>
{[
"Sector",
"Província",
"Investimento",
"Maturidade",
"Parceria",
"Impacto",
].map((field, i) => (
<tr key={field}>
<th className="border p-3">{field}</th>
{comparison.map(({ record: r }) => (
<td className="border p-3" key={r.id}>
{[
r.sector?.name,
r.province,
money(r),
r.maturity_label,
r.financing_modality,
r.expected_impact,
][i] || "Não indicado"}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
)}
{territorial.length > 0 && (
<section className="space-y-4">
<h2 className="text-2xl font-bold">Contexto territorial e projectos âncora</h2>
<p>
Fichas do documento de referência; montantes e metas conservam a natureza
declarada na fonte.
</p>
<div className="grid gap-4 md:grid-cols-3">
{territorial.map((d) => (
<Link href={`/carteira/${d.id}`} key={d.id} className={card}>
<span className="text-sm">
{d.content.code} ·{" "}
{d.cluster_id
? "Cluster"
: d.corridor_id
? "Corredor"
: "Projecto âncora"}
</span>
<h3 className="mt-2 font-semibold">{d.title}</h3>
</Link>
))}
</div>
</section>
)}
</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>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { Link, useForm } from "@inertiajs/react";
import { Management } from "../management/shared";
import { Field, input, button, card, groupLabels } from "./shared";
import type { Opportunity, Context, References } from "./shared";
export default function EditContext({
record,
context,
references,
}: {
record: Opportunity;
context: Context;
references: References;
}) {
const form = useForm({
version: context.profile?.version ?? 0,
is_education: context.profile?.is_education ?? false,
business_model: context.profile?.business_model ?? "",
requirements: context.profile?.requirements ?? "",
risks: context.profile?.risks ?? "",
target_date: context.profile?.target_date ?? "",
source_reference: context.profile?.source_reference ?? "",
clusters: context.clusters.map((r) => r.id),
corridors: context.corridors.map((r) => r.id),
projects: context.projects.map((r) => r.id),
locations: context.locations.map((r) => r.id),
facets: context.facets.map((r) => r.id),
});
return (
<Management title={"Contexto: " + record.title}>
<p>
As relações e características são parte da ficha publicada. Guardar devolve-a a
rascunho para revisão.
</p>
<Link href={`/management/opportunities/${record.id}/edit`} className="underline">
Editar e publicar a ficha principal
</Link>
<form
className="space-y-6"
onSubmit={(e) => {
e.preventDefault();
form.put(`/management/opportunities/${record.id}/context`, {
onSuccess: () => form.setData("version", form.data.version + 1),
});
}}
>
<label className="flex gap-2">
<input
type="checkbox"
checked={form.data.is_education}
onChange={(e) => form.setData("is_education", e.target.checked)}
/>
Oportunidade na educação
</label>
<div className="grid gap-4 md:grid-cols-2">
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
<fieldset className={card + " max-h-72 space-y-2 overflow-auto"} key={key}>
<legend className="font-bold">
{["Clusters", "Corredores", "Projectos âncora", "Localizações"][i]}
</legend>
{references[key].map((r) => (
<label key={r.id} className="flex gap-2">
<input
type="checkbox"
checked={form.data[key].includes(r.id)}
onChange={(e) =>
form.setData(
key,
e.target.checked
? [...form.data[key], r.id]
: form.data[key].filter((id) => id !== r.id),
)
}
/>
{r.name}
</label>
))}
</fieldset>
))}
</div>
<div className="grid gap-4 md:grid-cols-3">
{[
"subsector",
"education",
"infrastructure",
"labour",
"qualification",
"support",
"impact",
"partnership",
].map((group) => (
<fieldset
key={group}
className={card + " max-h-64 space-y-2 overflow-auto"}
>
<legend>{groupLabels[group]}</legend>
{references.options
.filter((o) => o.group === group && o.active)
.map((o) => (
<label key={o.id} className="flex gap-2">
<input
type="checkbox"
checked={form.data.facets.includes(o.id)}
onChange={(e) =>
form.setData(
"facets",
e.target.checked
? [...form.data.facets, o.id]
: form.data.facets.filter(
(id) => id !== o.id,
),
)
}
/>
{o.label}
</label>
))}
</fieldset>
))}
</div>
{(["business_model", "requirements", "risks", "source_reference"] as const).map(
(key) => (
<Field
key={key}
label={
{
business_model: "Modelo de negócio",
requirements: "Requisitos e necessidades",
risks: "Riscos",
source_reference: "Fonte e referência de autorização",
}[key]
}
>
<textarea
className={input}
required={key === "source_reference"}
rows={3}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
/>
</Field>
),
)}
<Field label="Data-alvo">
<input
type="date"
className={input}
value={form.data.target_date}
onChange={(e) => form.setData("target_date", e.target.value)}
/>
</Field>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key}>
{value}
</p>
))}
<button className={button} disabled={form.processing}>
Guardar contexto em rascunho
</button>
</form>
</Management>
);
}
@@ -0,0 +1,134 @@
import { useForm } from "@inertiajs/react";
import { useState } from "react";
import { newSubmissionKey } from "@/lib/portal-api";
import { Field, card, input, button, api } from "./shared";
export type Message = { id: string; sender_role: string; body: string; created_at: string };
export function Conversation({
id,
messages,
submitted,
revisions,
}: {
id: string;
messages: Message[];
submitted: boolean;
revisions: { version: number; created_at: string }[];
}) {
const form = useForm({ client_key: newSubmissionKey(), body: "" });
const [revision, setRevision] = useState<{
version: number;
snapshot: {
payload: {
full_name?: string;
organisation?: string;
objective?: string;
horizon?: string;
};
needs: { details: { description: string } }[];
attachment_ids: string[];
};
} | null>(null);
const [error, setError] = useState("");
return (
<>
<section className={card + " space-y-4"}>
<h2 className="text-xl font-bold">Versões guardadas</h2>
<Field label="Consultar versão">
<select
className={input}
defaultValue=""
onChange={(e) => {
setError("");
if (!e.target.value) {
setRevision(null);
return;
}
api(`/api/v1/investment/submissions/${id}/revisions/${e.target.value}`)
.then(setRevision)
.catch(() => setError("Não foi possível consultar esta versão."));
}}
>
<option value="">Seleccionar versão</option>
{revisions.map((r) => (
<option value={r.version} key={r.version}>
Versão {r.version} —{" "}
{new Date(r.created_at).toLocaleString("pt-MZ")}
</option>
))}
</select>
</Field>
{error && <p role="alert">{error}</p>}
{revision && (
<div className="space-y-2">
<h3 className="font-bold">Versão {revision.version}</h3>
<p>Investidor: {revision.snapshot.payload.full_name}</p>
<p>Empresa: {revision.snapshot.payload.organisation || "Não indicada"}</p>
<p className="whitespace-pre-line">
Objectivo: {revision.snapshot.payload.objective || "Não indicado"}
</p>
<p>Prazo: {revision.snapshot.payload.horizon || "Não indicado"}</p>
<ul>
{revision.snapshot.needs.map((n, i) => (
<li key={i}>{n.details.description}</li>
))}
</ul>
<p>
{revision.snapshot.attachment_ids.length} anexos associados nessa
versão.
</p>
</div>
)}
</section>
{submitted && (
<section className={card + " space-y-4"}>
<h2 className="text-xl font-bold">Conversa com o apoio</h2>
<p>
As mensagens ficam registadas neste pedido e são visíveis ao investidor e à
equipa autorizada.
</p>
{messages.map((m) => (
<article key={m.id} className="rounded-lg border p-4">
<p className="font-semibold">
{m.sender_role === "support" ? "Apoio ao Investidor" : "Investidor"}{" "}
· {new Date(m.created_at).toLocaleString("pt-MZ")}
</p>
<p className="mt-2 whitespace-pre-line">{m.body}</p>
</article>
))}
{!messages.length && <p>Ainda não existem mensagens neste pedido.</p>}
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
form.post(`/investidor/manifestacoes/${id}/messages`, {
preserveScroll: true,
onSuccess: () =>
form.setData({ client_key: newSubmissionKey(), body: "" }),
});
}}
>
<Field label="Mensagem para acompanhamento">
<textarea
className={input}
rows={4}
required
minLength={3}
maxLength={5000}
value={form.data.body}
onChange={(e) => form.setData("body", e.target.value)}
/>
</Field>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key}>
{value}
</p>
))}
<button className={button} disabled={form.processing}>
Enviar mensagem
</button>
</form>
</section>
)}
</>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { Link, router, usePage } from "@inertiajs/react";
import { useState } from "react";
import { Frame, card, button, money, groupLabels } from "./shared";
import type { Opportunity, Context } from "./shared";
export default function Detail({
record: r,
context: c,
zone_origin,
}: {
record: Opportunity;
context: Context;
zone_origin?: { id: string; name: string } | null;
}) {
const { auth } = usePage<{ auth: { user: unknown } }>().props;
const [sharing, setSharing] = useState("");
return (
<Frame title={r.title}>
<p>
{r.reference} · {r.sector?.name} · {r.province} {r.district}
</p>
<p className="text-xl">{r.summary}</p>
<div className="flex flex-wrap gap-4">
{auth.user ? (
<button
className={button}
onClick={() =>
router.post("/investidor/manifestacoes", {
opportunity_id: r.id,
...(zone_origin
? { zone_id: zone_origin.id, intent: "interest" }
: {}),
})
}
>
Preparar manifestação de interesse
</button>
) : (
<Link className={button} href="/login">
Entrar para preparar manifestação
</Link>
)}
<Link className="underline" href={`/manifestar-interesse/${r.slug}`}>
Contacto rápido sem rascunho
</Link>
<button
className="underline"
onClick={() => {
if (!navigator.clipboard) {
setSharing("Copie a ligação na barra de endereço do navegador.");
return;
}
navigator.clipboard
.writeText(window.location.href)
.then(() => setSharing("Ligação copiada."))
.catch(() =>
setSharing("Copie a ligação na barra de endereço do navegador."),
);
}}
>
Copiar ligação
</button>
</div>
{sharing && <p role="status">{sharing}</p>}
{!!c.zones?.length && (
<section className={card}>
<h2 className="text-xl font-bold">ZEE, ZFI e parques associados</h2>
{c.zones.map((z) => (
<p key={z.id}>
<Link
className="underline"
href={`/zonas?category=${z.category}&q=${encodeURIComponent(z.name)}`}
>
{z.name}
</Link>{" "}
·{" "}
{z.association_type === "official"
? "Associação documental validada"
: "Relação " + z.association_type}{" "}
· Fonte: {z.source_reference}
</p>
))}
<p>A associação não atribui automaticamente benefícios ou licenças.</p>
</section>
)}
<div className="grid gap-6 lg:grid-cols-3">
<section className={card + " whitespace-pre-line lg:col-span-2"}>
<h2 className="mb-3 text-xl font-bold">O investimento</h2>
{r.description || "Descrição por completar."}
</section>
<dl className={card + " space-y-4"}>
{[
["Promotor", r.promoter_name],
["Investimento", money(r)],
["Maturidade", r.maturity_label],
["Parceria", r.financing_modality],
["Impacto", r.expected_impact],
["Calendário", c.profile?.target_date],
].map(([key, value]) => (
<div key={key}>
<dt className="font-bold">{key}</dt>
<dd>{value || "Não indicado"}</dd>
</div>
))}
</dl>
</div>
{c.profile && (
<section className={card + " space-y-4"}>
<h2 className="text-xl font-bold">Viabilidade e preparação</h2>
{[
["Modelo de negócio", c.profile.business_model],
["Requisitos", c.profile.requirements],
["Riscos", c.profile.risks],
["Fonte", c.profile.source_reference],
].map(([label, text]) => (
<div key={label}>
<h3 className="font-bold">{label}</h3>
<p className="whitespace-pre-line">{text || "Não indicado"}</p>
</div>
))}
{c.profile.is_education && (
<Link href="/educacao" className="underline">
Explorar oportunidades na educação
</Link>
)}
</section>
)}
<section className="grid gap-4 md:grid-cols-4">
{(["clusters", "corridors", "projects", "locations"] as const).map((key, i) => (
<div className={card} key={key}>
<h2 className="font-bold">
{["Clusters", "Corredores", "Projectos âncora", "Territórios"][i]}
</h2>
{c[key].map((entity) => (
<p key={entity.id}>
<Link
className="underline"
href={
"/oportunidades?" +
[
"cluster_id",
"corridor_id",
"project_id",
"geo_location_id",
][i] +
"=" +
entity.id
}
>
{entity.name}
</Link>
</p>
))}
{!c[key].length && <p>Sem relação publicada.</p>}
</div>
))}
</section>
<section className={card}>
<h2 className="text-xl font-bold">
Infraestruturas, competências, educação e apoios
</h2>
{c.facets.map((f) => (
<p key={f.id}>
{groupLabels[f.group] ?? f.group}: {f.label}
</p>
))}
{!c.facets.length && (
<p>
Sem características estruturadas publicadas. Pode declarar as suas
necessidades na manifestação de interesse.
</p>
)}
</section>
</Frame>
);
}
@@ -0,0 +1,84 @@
import { Link, router } from "@inertiajs/react";
import { Frame, card, button } from "./shared";
export default function Notifications({
unread,
notifications,
}: {
unread: number;
notifications: {
data: {
id: string;
submission_id: string;
kind: string;
payload: { status?: string; reference?: string };
read_at: string | null;
created_at: string;
}[];
prev_page_url: string | null;
next_page_url: string | null;
};
}) {
const states: Record<string, string> = {
received: "Recebido",
in_review: "Em análise",
contacted: "Contactado",
closed: "Encerrado",
};
return (
<Frame title="Notificações e acompanhamento">
<Link href="/investidor/manifestacoes" className="underline">
Área do investidor
</Link>
<p role="status">{unread} notificações por ler</p>
{notifications.data.map((n) => (
<article key={n.id} className={card + " space-y-3"}>
<h2 className="text-xl font-bold">
{n.kind === "received"
? "Manifestação recebida"
: n.kind === "status"
? "Estado actualizado"
: "Nova mensagem na conversa"}
</h2>
<p>
{n.payload.reference ??
(n.payload.status
? (states[n.payload.status] ?? n.payload.status)
: "Consulte o pedido para ler a mensagem.")}
</p>
<p className="text-sm">{new Date(n.created_at).toLocaleString("pt-MZ")}</p>
<div className="flex flex-wrap gap-4">
<Link
href={"/investidor/manifestacoes/" + n.submission_id}
className="underline"
>
Abrir manifestação
</Link>
{!n.read_at && (
<button
className={button}
onClick={() =>
router.post(
"/investidor/notifications/" + n.id + "/read",
{},
{ preserveScroll: true },
)
}
>
Marcar como lida
</button>
)}
</div>
</article>
))}
{!notifications.data.length && <p>Ainda não existem notificações.</p>}
<nav aria-label="Paginação" className="flex gap-4">
{notifications.prev_page_url && (
<Link href={notifications.prev_page_url}>Anterior</Link>
)}
{notifications.next_page_url && (
<Link href={notifications.next_page_url}>Seguinte</Link>
)}
</nav>
</Frame>
);
}
+156
View File
@@ -0,0 +1,156 @@
import { Link, router, useForm } from "@inertiajs/react";
import { Frame, Field, input, button, card } from "./shared";
type RecordData = { version: number; payload: Record<string, string> };
type Company = RecordData & { id: string };
const labels: Record<string, string> = {
phone: "Telefone",
country: "País",
sector: "Sector de interesse",
experience: "Experiência relevante",
investment_capacity: "Capacidade de investimento declarada",
name: "Nome da empresa",
registration: "Referência de registo / NUIT",
role: "Função ou relação com a empresa",
description: "Actividade e observações",
};
export default function Profile({
account,
companies,
}: {
account: RecordData;
companies: Company[];
}) {
return (
<Frame title="Perfil de investimento e empresas">
<Link href="/investidor/manifestacoes" className="underline">
Voltar à área do investidor
</Link>
<p>
Estes dados são privados e servem para preencher novas manifestações. Nome e email
são mantidos nas{" "}
<Link className="underline" href="/settings/profile">
definições da conta
</Link>
.
</p>
<Editor
key={"account-" + account.version}
record={account}
fields={["phone", "country", "sector", "experience", "investment_capacity"]}
/>
<h2 className="text-2xl font-bold">Empresas declaradas</h2>
<p>
Declarar uma empresa não comprova representação legal nem concede acesso aos
registos de outras pessoas. A equipa pode pedir evidência durante o atendimento.
</p>
{companies.map((company) => (
<section key={company.id} className={card}>
<h3 className="text-xl font-bold">{company.payload.name}</h3>
<Editor
key={company.version}
record={company}
fields={[
"name",
"country",
"registration",
"sector",
"role",
"description",
]}
/>
<button
className={button + " mt-4"}
onClick={() =>
router.post("/investidor/manifestacoes", { company_id: company.id })
}
>
Preparar manifestação desta empresa
</button>
</section>
))}
{companies.length < 20 && (
<section className={card}>
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
<Editor
key={"new-" + companies.length}
record={{ version: 0, payload: {} }}
company
fields={[
"name",
"country",
"registration",
"sector",
"role",
"description",
]}
/>
</section>
)}
</Frame>
);
}
function Editor({
record,
fields,
company = false,
}: {
record: RecordData & { id?: string };
fields: string[];
company?: boolean;
}) {
const isCompany = company || !!record.id;
const form = useForm({
version: record.version,
payload: Object.fromEntries(fields.map((key) => [key, record.payload[key] ?? ""])),
});
return (
<form
className="mt-4 space-y-4"
onSubmit={(e) => {
e.preventDefault();
const options = { preserveScroll: true };
if (isCompany)
form.post(
"/investidor/companies" + (record.id ? "/" + record.id : ""),
options,
);
else form.put("/investidor/profile", options);
}}
>
<div className="grid gap-4 md:grid-cols-2">
{fields.map((key) => (
<Field key={key} label={labels[key]}>
<input
className={input}
value={form.data.payload[key]}
required={isCompany && ["name", "country", "role"].includes(key)}
maxLength={
key === "description" || key === "experience"
? 2000
: key === "investment_capacity"
? 1000
: 200
}
onChange={(e) =>
form.setData("payload", {
...form.data.payload,
[key]: e.target.value,
})
}
/>
</Field>
))}
</div>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key} className="text-red-700">
{value}
</p>
))}
<button className={button} disabled={form.processing}>
{isCompany ? "Guardar declaração da empresa" : "Guardar perfil de investimento"}
</button>
</form>
);
}
@@ -0,0 +1,122 @@
import { useForm } from "@inertiajs/react";
import { Management } from "../management/shared";
import { Field, input, button, card, groupLabels } from "./shared";
import type { Option } from "./shared";
export default function References({ options }: { options: Option[] }) {
const groups = [...new Set(options.map((o) => o.group))];
return (
<Management title="Opções dos formulários e filtros">
<p>
Os códigos são estáveis; pode corrigir etiquetas ou desactivar opções sem eliminar
referências históricas. Cada grupo conserva Outro — especificar.
</p>
<OptionForm groups={groups} />
<div className="space-y-4">
{groups.map((group) => (
<details key={group} className={card}>
<summary className="cursor-pointer font-bold">
{groupLabels[group] ?? group}
</summary>
<div className="mt-4 space-y-5">
{options
.filter((o) => o.group === group)
.map((o) => (
<OptionForm key={o.id} option={o} groups={groups} />
))}
</div>
</details>
))}
</div>
</Management>
);
}
function OptionForm({ option, groups }: { option?: Option; groups: string[] }) {
const form = useForm({
group: option?.group ?? groups[0],
code: option?.code ?? "",
label: option?.label ?? "",
active: option?.active ?? true,
requires_description: option?.requires_description ?? false,
sort_order: option?.sort_order ?? 0,
});
return (
<form
className="space-y-3 rounded border p-4"
onSubmit={(e) => {
e.preventDefault();
form.post("/management/investment/references" + (option ? "/" + option.id : ""), {
preserveScroll: true,
});
}}
>
<h2 className="font-semibold">{option ? "Editar opção" : "Criar opção"}</h2>
<div className="grid gap-3 md:grid-cols-3">
<Field label="Grupo">
<select
disabled={!!option}
className={input}
value={form.data.group}
onChange={(e) => form.setData("group", e.target.value)}
>
{groups.map((g) => (
<option key={g} value={g}>
{groupLabels[g] ?? g}
</option>
))}
</select>
</Field>
<Field label="Código">
<input
className={input}
required
readOnly={!!option}
value={form.data.code}
onChange={(e) => form.setData("code", e.target.value)}
/>
</Field>
<Field label="Etiqueta">
<input
className={input}
required
value={form.data.label}
onChange={(e) => form.setData("label", e.target.value)}
/>
</Field>
</div>
<label className="mr-4 inline-flex gap-2">
<input
type="checkbox"
checked={form.data.active}
onChange={(e) => form.setData("active", e.target.checked)}
/>
Activa
</label>
<label className="inline-flex gap-2">
<input
type="checkbox"
checked={form.data.requires_description}
onChange={(e) => form.setData("requires_description", e.target.checked)}
/>
Exige especificação
</label>
<Field label="Ordem">
<input
type="number"
min="0"
max="10000"
className={input}
value={form.data.sort_order}
onChange={(e) => form.setData("sort_order", Number(e.target.value))}
/>
</Field>
{Object.entries(form.errors).map(([key, value]) => (
<p role="alert" key={key}>
{value}
</p>
))}
<button disabled={form.processing} className={button}>
Guardar opção
</button>
</form>
);
}
+149
View File
@@ -0,0 +1,149 @@
import { Head, Link, usePage } from "@inertiajs/react";
import type { ReactNode } from "react";
import { PortalMenu } from "@/layouts/portal-navigation";
export type Option = {
id: number;
group: string;
code: string;
label: string;
active: boolean;
requires_description: boolean;
sort_order: number;
};
export type Entity = { id: string; name: string };
export type References = {
zones?: { id: string; name: string; category: string }[];
options: Option[];
clusters: Entity[];
corridors: Entity[];
projects: Entity[];
locations: Entity[];
sectors: { id: number; name: string; slug: string }[];
};
export type Opportunity = {
id: number;
title: string;
slug: string;
reference: string;
summary: string | null;
description: string | null;
province: string | null;
district: string | null;
sector?: { name: string; slug: string };
estimated_investment_amount: string | null;
estimated_investment_currency: string;
maturity_label: string | null;
promoter_name: string | null;
expected_impact: string | null;
financing_modality: string | null;
status: string;
};
export type Context = {
zones?: {
id: string;
name: string;
category: string;
association_type: string;
source_reference: string;
}[];
profile: {
version: number;
is_education: boolean;
business_model: string | null;
requirements: string | null;
risks: string | null;
target_date: string | null;
source_reference: string | null;
} | null;
facets: { id: number; group: string; label: string }[];
clusters: Entity[];
corridors: Entity[];
projects: Entity[];
locations: Entity[];
};
export const input =
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
export const button =
"inline-flex items-center justify-center rounded-lg bg-emerald-800 px-4 py-2 font-semibold text-white disabled:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700";
export const card = "rounded-xl border border-slate-200 bg-white p-5 shadow-sm";
export function Frame({ title, children }: { title: string; children: ReactNode }) {
const { flash } = usePage<{ flash?: { success?: string } }>().props;
return (
<div className="min-h-screen bg-slate-50 text-slate-900">
<Head title={title} />
<PortalMenu />
<main className="mx-auto max-w-7xl space-y-6 px-5 py-9">
<h1 className="text-3xl font-bold">{title}</h1>
{flash?.success && (
<p
role="status"
className="rounded border border-emerald-700 bg-emerald-50 p-4"
>
{flash.success}
</p>
)}
{children}
</main>
<footer className="border-t p-6 text-center">
<Link href="/apoio" className="underline">
Apoio ao Investidor
</Link>{" "}
·{" "}
<Link href="/documentos" className="underline">
Documentos
</Link>
</footer>
</div>
);
}
export function Field({ label, children }: { label: string; children: ReactNode }) {
return (
<label className="block space-y-1 text-sm font-medium">
<span>{label}</span>
{children}
</label>
);
}
export function money(r: Opportunity) {
return r.estimated_investment_amount === null
? "Montante não indicado"
: `${new Intl.NumberFormat("pt-MZ", { maximumFractionDigits: 2 }).format(Number(r.estimated_investment_amount))} ${r.estimated_investment_currency}`;
}
export async function api(url: string, body?: unknown) {
const token = decodeURIComponent(
document.cookie
.split("; ")
.find((c) => c.startsWith("XSRF-TOKEN="))
?.slice(11) ?? "",
);
const response = await fetch(url, {
method: body === undefined ? "GET" : "POST",
credentials: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-XSRF-TOKEN": token,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.message ?? "Não foi possível concluir a operação.");
return data;
}
export const groupLabels: Record<string, string> = {
education: "Educação",
infrastructure: "Infraestruturas",
labour: "Mão de obra",
qualification: "Qualificações",
support: "Apoios",
impact: "Impacto",
partnership: "Modelo de parceria",
subsector: "Subsector",
need_category: "Categoria da necessidade",
priority: "Prioridade",
unit: "Unidade",
participation: "Participação",
investor_profile: "Perfil do investidor",
need_status: "Estado da necessidade",
};
@@ -0,0 +1,767 @@
import { Link, useForm } from "@inertiajs/react";
import { useState } from "react";
import { Frame, Field, input, button, card } from "./shared";
import type { References } from "./shared";
import { Conversation } from "./conversation";
import type { Message } from "./conversation";
type Payload = {
full_name: string;
email: string;
phone: string;
country: string;
organisation: string;
representative_role: string;
experience: string;
investment_capacity: string;
other_details: string;
profile_id: string;
sector: string;
objective: string;
participation_id: string;
partnership_id: string;
estimated_amount: string;
currency: string;
horizon: string;
location: string;
cluster_ids: string[];
corridor_ids: string[];
project_ids: string[];
contact_consent: boolean;
};
type Need = {
category_id: string;
option_id: string;
unit_id: string;
priority_id: string;
quantity: string;
deadline: string;
details: {
description: string;
location: string;
observations: string;
qualification: string;
specialty: string;
experience: string;
certifications: string;
availability: string;
institution: string;
training_mode: string;
duration: string;
status: string;
};
};
type Props = {
zone_origin?: {
zone_id: string;
zone_version: number;
intent: "interest" | "dossier" | "meeting";
} | null;
submission: { id: string; version: number; payload: Partial<Payload>; status: string };
references: References;
needs: Need[];
attachments: { id: string; file_name: string }[];
events: { action: string; version: number; created_at: string }[];
receipt: { reference: string; status: string } | null;
target: string | null;
management: boolean;
messages: Message[];
revisions: { version: number; created_at: string }[];
};
const emptyNeed = (): Need => ({
category_id: "",
option_id: "",
unit_id: "",
priority_id: "",
quantity: "",
deadline: "",
details: {
description: "",
location: "",
observations: "",
qualification: "",
specialty: "",
experience: "",
certifications: "",
availability: "",
institution: "",
training_mode: "",
duration: "",
status: "",
},
});
export default function Submission(props: Props) {
const [step, setStep] = useState(0);
return <Editor key={props.submission.version} {...props} step={step} setStep={setStep} />;
}
function Editor({
zone_origin,
submission: s,
references: r,
needs,
attachments,
events,
receipt,
target,
management,
messages,
revisions,
step,
setStep,
}: Props & { step: number; setStep: (step: number) => void }) {
const initial: Payload = {
full_name: "",
email: "",
phone: "",
country: "",
organisation: "",
representative_role: "",
experience: "",
investment_capacity: "",
other_details: "",
profile_id: "",
sector: "",
objective: "",
participation_id: "",
partnership_id: "",
estimated_amount: "",
currency: "",
horizon: "",
location: "",
cluster_ids: [],
corridor_ids: [],
project_ids: [],
contact_consent: false,
...s.payload,
};
const form = useForm({
version: s.version,
payload: initial,
needs: needs.map((n) => ({
...emptyNeed(),
...Object.fromEntries(
Object.entries(n).filter(([k]) =>
[
"category_id",
"option_id",
"unit_id",
"priority_id",
"quantity",
"deadline",
"details",
].includes(k),
),
),
details: { ...emptyNeed().details, ...n.details },
})) as Need[],
});
const upload = useForm<{ version: number; file: File | null }>({
version: s.version,
file: null,
});
const [note, setNote] = useState("");
const readonly = s.status !== "draft" || management;
const base = "/investidor/manifestacoes/" + s.id;
const update = <K extends keyof Payload>(key: K, value: Payload[K]) =>
form.setData("payload", { ...form.data.payload, [key]: value });
const text = (key: keyof Payload, label: string, required = false, type = "text") => (
<Field label={label}>
<input
className={input}
type={type}
required={required}
disabled={readonly}
name={key}
min={type === "number" ? 0 : undefined}
minLength={key === "objective" ? 20 : key === "full_name" ? 3 : undefined}
onBlur={(e) => {
if (!e.target.validity.valid)
setNote(`Verifique o campo ${label}: ${e.target.validationMessage}`);
else setNote("");
}}
value={String(form.data.payload[key] ?? "")}
onChange={(e) => update(key, e.target.value as never)}
maxLength={key === "objective" ? 5000 : 2000}
/>
</Field>
);
const option = (
key: "profile_id" | "participation_id" | "partnership_id",
group: string,
label: string,
) => (
<Field label={label}>
<select
className={input}
disabled={readonly}
value={form.data.payload[key] ?? ""}
onChange={(e) => update(key, e.target.value)}
>
<option value="">Seleccionar</option>
{r.options
.filter(
(o) =>
o.group === group &&
(o.active || String(o.id) === String(form.data.payload[key])),
)
.map((o) => (
<option value={o.id} key={o.id} disabled={!o.active}>
{o.label}
{!o.active ? " (inactiva)" : ""}
</option>
))}
</select>
</Field>
);
const updateNeed = (index: number, value: Need) =>
form.setData(
"needs",
form.data.needs.map((n, i) => (i === index ? value : n)),
);
const errorStep = (key: string) =>
key.startsWith("needs.")
? 2
: /payload\.(full_name|email|phone|country|profile_id|organisation|representative_role|sector|experience|investment_capacity)/.test(
key,
)
? 0
: key === "payload.contact_consent"
? 4
: 1;
return (
<Frame
title={
receipt ? "Manifestação " + receipt.reference : "Preparar manifestação de interesse"
}
>
<p>
{target ??
(zone_origin
? "Pedido relativo a zona de investimento"
: "Interesse geral")}{" "}
· Versão {s.version} · {s.status === "draft" ? "Rascunho privado" : "Submetido"}
</p>
{zone_origin && (
<p className={card}>
<Link className="underline" href={`/zonas/${zone_origin.zone_id}`}>
Consultar zona de origem
</Link>{" "}
· Versão da ficha {zone_origin.zone_version} ·{" "}
{
{
interest: "Manifestação de interesse",
dossier: "Pedido de dossier",
meeting: "Pedido de reunião",
}[zone_origin.intent]
}
. Atendimento assistido, sem decisão administrativa automática.
</p>
)}
{receipt && (
<p role="status" className={card}>
Protocolo: <strong>{receipt.reference}</strong> · Estado:{" "}
{(
{
received: "Recebido",
in_review: "Em análise",
contacted: "Contactado",
closed: "Encerrado",
} as Record<string, string>
)[receipt.status] ?? receipt.status}
</p>
)}
<nav aria-label="Etapas da manifestação" className="flex flex-wrap gap-2">
{["Identificação", "Investimento", "Necessidades", "Anexos", "Rever e enviar"].map(
(label, i) => (
<button
key={label}
type="button"
aria-current={step === i ? "step" : undefined}
className={step === i ? button : "rounded border px-4 py-2"}
onClick={() => setStep(i)}
>
{i + 1}. {label}
</button>
),
)}
</nav>
<p className="text-sm">
Etapa {step + 1} de 5. Guarde antes de sair. A informação declarada não é publicada.
</p>
<form
className={card + " space-y-5"}
onSubmit={(e) => {
e.preventDefault();
form.put(base, { preserveScroll: true });
}}
>
{step === 0 && (
<div className="grid gap-4 md:grid-cols-2">
{text("full_name", "Nome completo", true)}
{text("email", "Email", true, "email")}
{text("phone", "Telefone")}
{text("country", "País", true)}
{option("profile_id", "investor_profile", "Perfil do investidor")}
{text("organisation", "Organização / empresa")}
{text("representative_role", "Função do representante")}
{text("sector", "Sector de interesse", true)}
{text("experience", "Experiência relevante")}
{text(
"investment_capacity",
"Capacidade de investimento / especificação do perfil",
)}
</div>
)}
{step === 1 && (
<div className="space-y-5">
{text(
"objective",
"Objectivo do investimento (mínimo 20 caracteres)",
true,
)}
<div className="grid gap-4 md:grid-cols-2">
{option(
"participation_id",
"participation",
"Modalidade de participação",
)}
{option("partnership_id", "partnership", "Modelo de parceria")}
{text("estimated_amount", "Investimento estimado", false, "number")}
{text("currency", "Moeda (código de três letras)")}
{text("horizon", "Prazo / horizonte", true)}
{text("location", "Localização pretendida")}
</div>
<div className="grid gap-4 md:grid-cols-3">
{(["clusters", "corridors", "projects"] as const).map((group, i) => {
const key = (
["cluster_ids", "corridor_ids", "project_ids"] as const
)[i];
return (
<fieldset
className="max-h-64 space-y-2 overflow-auto rounded border p-3"
key={group}
>
<legend>
{["Clusters", "Corredores", "Projectos âncora"][i]}
</legend>
{r[group].map((entity) => (
<label key={entity.id} className="flex gap-2">
<input
type="checkbox"
disabled={readonly}
checked={(
form.data.payload[key] ?? []
).includes(entity.id)}
onChange={(e) =>
update(
key,
e.target.checked
? [
...(form.data.payload[key] ??
[]),
entity.id,
]
: form.data.payload[key].filter(
(id) => id !== entity.id,
),
)
}
/>
{entity.name}
</label>
))}
</fieldset>
);
})}
</div>
</div>
)}
{step === 2 && (
<section className="space-y-5">
<h2 className="text-xl font-bold">
Mão de obra, infraestruturas, formação e apoios
</h2>
<p>
Acrescente o que existe no local e o que necessita. As opções são
mantidas pela gestão; use Outro para especificar casos adicionais.
</p>
{form.data.needs.map((need, index) => {
const category =
r.options.find((o) => String(o.id) === String(need.category_id))
?.code ?? "";
const group = category.startsWith("labour")
? "labour"
: category.startsWith("infrastructure")
? "infrastructure"
: category === "education"
? "education"
: "support";
const needSelect = (
field: "category_id" | "option_id" | "unit_id" | "priority_id",
optionGroup: string,
label: string,
) => (
<Field label={label}>
<select
className={input}
disabled={readonly}
value={need[field] ?? ""}
onChange={(e) =>
updateNeed(index, {
...need,
[field]: e.target.value,
...(field === "category_id"
? { option_id: "" }
: {}),
})
}
>
<option value="">Seleccionar</option>
{r.options
.filter(
(o) =>
o.group === optionGroup &&
(o.active ||
String(o.id) === String(need[field])),
)
.map((o) => (
<option value={o.id} key={o.id}>
{o.label}
</option>
))}
</select>
</Field>
);
return (
<fieldset key={index} className="space-y-4 rounded-lg border p-4">
<legend className="font-bold">Necessidade {index + 1}</legend>
<div className="grid gap-4 md:grid-cols-2">
{needSelect("category_id", "need_category", "Categoria")}
{needSelect("option_id", group, "Tipo")}
{needSelect("unit_id", "unit", "Unidade")}
{needSelect("priority_id", "priority", "Prioridade")}
<Field label="Quantidade">
<input
className={input}
type="number"
min="0"
step="0.01"
disabled={readonly}
value={need.quantity ?? ""}
onChange={(e) =>
updateNeed(index, {
...need,
quantity: e.target.value,
})
}
/>
</Field>
<Field label="Prazo">
<input
className={input}
type="date"
disabled={readonly}
value={need.deadline ?? ""}
onChange={(e) =>
updateNeed(index, {
...need,
deadline: e.target.value,
})
}
/>
</Field>
</div>
{(
[
"description",
"location",
"observations",
...(group === "labour"
? [
"qualification",
"specialty",
"experience",
"certifications",
"availability",
"institution",
]
: []),
...(group === "education"
? [
"qualification",
"institution",
"training_mode",
"duration",
"certifications",
]
: []),
] as (keyof Need["details"])[]
).map((field) => (
<Field
key={field}
label={
{
description: "Descrição / especificação",
location: "Localização",
observations:
"Observações e referência dos anexos de suporte",
qualification: "Nível de qualificação",
specialty: "Profissão / especialidade",
experience: "Experiência",
certifications: "Certificações",
availability: "Disponibilidade",
institution:
"Instituições ou centros de formação",
training_mode: "Modalidade de formação",
duration: "Duração",
status: "Estado",
}[field]
}
>
<textarea
className={input}
rows={2}
disabled={readonly}
value={need.details[field] ?? ""}
onChange={(e) =>
updateNeed(index, {
...need,
details: {
...need.details,
[field]: e.target.value,
},
})
}
/>
</Field>
))}
{!readonly && (
<button
type="button"
className="underline"
onClick={() =>
form.setData(
"needs",
form.data.needs.filter((_, i) => i !== index),
)
}
>
Retirar esta necessidade
</button>
)}
</fieldset>
);
})}
{!readonly && (
<button
type="button"
className={button}
disabled={form.data.needs.length >= 40}
onClick={() =>
form.setData("needs", [...form.data.needs, emptyNeed()])
}
>
Acrescentar necessidade
</button>
)}
</section>
)}
{step === 3 && (
<p>
Guarde primeiro o rascunho e carregue os anexos no formulário abaixo.
Identifique o nome do ficheiro nas observações da necessidade a que
corresponde.
</p>
)}
{step === 4 && (
<section className="space-y-5">
<h2 className="text-xl font-bold">Rever antes de enviar</h2>
<dl className="space-y-3">
{[
["Investidor", form.data.payload.full_name],
["Email", form.data.payload.email],
["Organização", form.data.payload.organisation],
["Objectivo", form.data.payload.objective],
["Prazo", form.data.payload.horizon],
["Necessidades", String(form.data.needs.length)],
["Anexos", String(attachments.length)],
].map(([label, value]) => (
<div key={label}>
<dt className="font-semibold">{label}</dt>
<dd className="whitespace-pre-line">
{value || "Não indicado"}
</dd>
</div>
))}
</dl>
<label className="flex gap-3">
<input
type="checkbox"
disabled={readonly}
checked={form.data.payload.contact_consent}
onChange={(e) => update("contact_consent", e.target.checked)}
/>
Autorizo o tratamento destes dados e o contacto pela equipa para
analisar e acompanhar esta manifestação. Os anexos são privados. Não
constitui consentimento para utilização em IA.
</label>
</section>
)}
{r.options.some(
(o) =>
o.requires_description &&
[
form.data.payload.profile_id,
form.data.payload.participation_id,
form.data.payload.partnership_id,
]
.map(String)
.includes(String(o.id)),
) &&
text(
"other_details",
"Outro — especifique o perfil, participação ou parceria seleccionados",
true,
)}
{Object.entries(form.errors).map(([key, value]) => (
<p key={key} role="alert" className="text-red-700">
<button
type="button"
className="underline"
onClick={() => setStep(errorStep(key))}
>
Corrigir na etapa {errorStep(key) + 1}
</button>
: {value}
</p>
))}
{note && <p role="status">{note}</p>}
<div className="flex flex-wrap gap-4">
{step > 0 && (
<button
type="button"
className="underline"
onClick={() => setStep(step - 1)}
>
Anterior
</button>
)}
{step < 4 && (
<button
type="button"
className={button}
onClick={() => {
setNote("");
setStep(step + 1);
}}
>
Continuar
</button>
)}
{!readonly && (
<button
formNoValidate
className="rounded border px-4 py-2"
disabled={form.processing}
>
Guardar rascunho
</button>
)}
{step === 4 && !readonly && (
<button
type="button"
className={button}
disabled={form.processing || !form.data.payload.contact_consent}
onClick={() =>
form.post(base + "/submit", {
preserveScroll: true,
onError: (errors) =>
setStep(errorStep(Object.keys(errors)[0] ?? "")),
})
}
>
Submeter manifestação
</button>
)}
</div>
</form>
{step === 3 && (
<section className={card + " space-y-4"}>
<h2 className="text-xl font-bold">Anexos privados</h2>
<p>
PDF ou TXT, até 10 MiB cada, máximo de dez anexos. Guardar um anexo
actualiza a versão do rascunho.
</p>
{attachments.map((a) => (
<p key={a.id}>
<a className="underline" href={base + "/attachments/" + a.id}>
{a.file_name}
</a>
</p>
))}
{!readonly && (
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
if (form.isDirty) {
setNote(
"Guarde as alterações do formulário antes de carregar o anexo.",
);
return;
}
upload.post(base + "/attachments", {
forceFormData: true,
preserveScroll: true,
});
}}
>
<Field label="Documento de suporte">
<input
type="file"
accept="application/pdf,text/plain"
required
onChange={(e) =>
upload.setData("file", e.target.files?.[0] ?? null)
}
/>
</Field>
{Object.entries(upload.errors).map(([key, value]) => (
<p role="alert" key={key}>
{value}
</p>
))}
<button className={button} disabled={upload.processing}>
Carregar anexo
</button>
</form>
)}
</section>
)}
<details className={card}>
<summary className="cursor-pointer font-bold">Histórico do pedido</summary>
<ol className="mt-3 space-y-2">
{events.map((e, i) => (
<li key={i}>
{new Date(e.created_at).toLocaleString("pt-MZ")} —{" "}
{(
{
draft_created: "Rascunho criado",
draft_saved: "Rascunho guardado",
attachment_added: "Anexo acrescentado",
submitted: "Submetido",
} as Record<string, string>
)[e.action] ?? e.action}{" "}
· versão {e.version}
</li>
))}
</ol>
</details>
<Conversation
id={s.id}
messages={messages}
revisions={revisions}
submitted={s.status === "submitted"}
/>
</Frame>
);
}
@@ -0,0 +1,86 @@
import { Link, router } from "@inertiajs/react";
import { Frame, card, button } from "./shared";
export default function Workspace({
submissions,
favourites,
}: {
submissions: {
data: {
id: string;
status: string;
reference: string | null;
request_status: string | null;
created_at: string;
}[];
prev_page_url: string | null;
next_page_url: string | null;
};
favourites: { id: number; title: string; slug: string }[];
}) {
const states: Record<string, string> = {
received: "Recebido",
in_review: "Em análise",
contacted: "Contactado",
closed: "Encerrado",
};
return (
<Frame title="Área do investidor">
<nav className="flex flex-wrap gap-4">
<Link href="/investidor/profile" className="underline">
Perfil e empresas
</Link>
<Link href="/investidor/notifications" className="underline">
Notificações
</Link>
<Link href="/investidor" className="underline">
Fichas territoriais guardadas
</Link>
<Link href="/balcao-virtual" className="underline">
Apoio e parcerias
</Link>
</nav>
<button className={button} onClick={() => router.post("/investidor/manifestacoes")}>
Preparar nova manifestação
</button>
<section className="space-y-4">
<h2 className="text-2xl font-bold">Rascunhos e manifestações</h2>
{submissions.data.map((s) => (
<article className={card} key={s.id}>
<Link
href={`/investidor/manifestacoes/${s.id}`}
className="font-semibold underline"
>
{s.reference ?? "Continuar rascunho"}
</Link>
<p>
{s.status === "draft"
? "Rascunho privado"
: (states[s.request_status ?? ""] ?? s.request_status)}
</p>
<p>{new Date(s.created_at).toLocaleDateString("pt-MZ")}</p>
</article>
))}
{!submissions.data.length && <p>Ainda não existem manifestações neste percurso.</p>}
<nav aria-label="Paginação" className="flex gap-4">
{submissions.prev_page_url && (
<Link href={submissions.prev_page_url}>Anterior</Link>
)}
{submissions.next_page_url && (
<Link href={submissions.next_page_url}>Seguinte</Link>
)}
</nav>
</section>
<section className="space-y-4">
<h2 className="text-2xl font-bold">Oportunidades favoritas</h2>
{favourites.map((f) => (
<Link href={`/oportunidades/${f.slug}`} className={card + " block"} key={f.id}>
{f.title}
</Link>
))}
{!favourites.length && (
<p>Explore o catálogo e guarde as oportunidades que pretende acompanhar.</p>
)}
</section>
</Frame>
);
}
+109
View File
@@ -0,0 +1,109 @@
import { useState } from "react";
import { api, button, card } from "./shared";
type Feature = {
id: string;
geometry: { type: string; coordinates: unknown[] };
properties: { purpose: string; source: string; observed_at: string };
};
function rings(value: unknown): number[][][] {
if (!Array.isArray(value) || !value.length) return [];
if (typeof value[0] === "number") return [[value as number[]]];
if (Array.isArray(value[0]) && typeof value[0][0] === "number") return [value as number[][]];
return value.flatMap(rings);
}
export default function ZoneMap({ id }: { id: string }) {
const [features, setFeatures] = useState<Feature[] | null>(null);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const points = (features ?? []).flatMap((f) => rings(f.geometry.coordinates).flat());
const xs = points.map((p) => p[0]),
ys = points.map((p) => p[1]);
const west = xs.length ? Math.min(...xs) : 0,
south = ys.length ? Math.min(...ys) : 0;
const dx = xs.length ? Math.max(...xs) - west : 1,
dy = ys.length ? Math.max(...ys) - south : 1;
const project = (p: number[]) => [
20 + ((p[0] - west) / (dx || 1)) * 600,
300 - ((p[1] - south) / (dy || 1)) * 280,
];
return (
<section className={card}>
<h2 className="text-xl font-bold">Localização e geometrias autorizadas</h2>
<button
className={button}
disabled={busy}
onClick={async () => {
setBusy(true);
setError("");
try {
const data = await api(`/api/v2/investment/zone-map?zone_id=${id}`);
setFeatures(data.features);
if (data.truncated) setError("Exibidas as primeiras 100 geometrias.");
} catch {
setError(
"Mapa indisponível. A ficha, a localização textual e as acções de apoio continuam disponíveis.",
);
} finally {
setBusy(false);
}
}}
>
{busy ? "A carregar…" : "Consultar mapa"}
</button>
{error && <p role="status">{error}</p>}
{features?.length === 0 && (
<p>Não existe geometria autorizada para divulgação nesta ficha.</p>
)}
{!!features?.length && (
<>
<p>
Esquema das geometrias cadastradas, sem mapa-base. Não serve para demarcação
ou atribuição de estatuto.
</p>
<svg
viewBox="0 0 640 320"
className="w-full rounded border bg-slate-50"
role="img"
aria-label="Esquema das geometrias autorizadas da zona"
>
{features.map((f) => (
<g key={f.id}>
<title>
{f.properties.purpose} · {f.properties.source}
</title>
{rings(f.geometry.coordinates).map((ring, i) =>
ring.length === 1 ? (
<circle
key={i}
cx={project(ring[0])[0]}
cy={project(ring[0])[1]}
r="5"
fill="#065f46"
/>
) : (
<polyline
key={i}
points={ring.map((p) => project(p).join(",")).join(" ")}
fill="none"
stroke="#065f46"
strokeWidth="2"
/>
),
)}
</g>
))}
</svg>
<ul>
{features.map((f) => (
<li key={f.id}>
{f.properties.purpose} · Fonte: {f.properties.source} · Data:{" "}
{f.properties.observed_at}
</li>
))}
</ul>
</>
)}
</section>
);
}
@@ -0,0 +1,244 @@
import { Field, input, button, card } from "./shared";
export type ZoneTargets = {
opportunities: { id: number; title: string }[];
dossiers: {
id: string;
title: string;
project_id: string | null;
cluster_id: string | null;
corridor_id: string | null;
}[];
};
type Review = {
id: string;
version_no: number;
validation_status: string;
association_type?: string;
purpose?: string;
};
type Props = {
id: string;
targets: ZoneTargets;
sources: { id: string; title: string }[];
relations: Review[];
geometries: Review[];
busy: boolean;
action: (url: string, data: unknown) => Promise<void>;
};
export default function ZoneRelations({
id,
targets,
sources,
relations,
geometries,
busy,
action,
}: Props) {
return (
<>
<form
className={card + " grid gap-4 md:grid-cols-2"}
onSubmit={(e) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
if (typeof data.target !== "string") return;
const [kind, target] = data.target.split(":");
delete data.target;
void action(
`/api/v2/investment/admin/zones/${id}/${kind === "opportunity_id" ? "links" : "relations"}`,
{ ...data, [kind]: target },
);
}}
>
<h2 className="text-xl font-bold md:col-span-2">
Associar investimento ou território
</h2>
<Field label="Registo existente">
<select className={input} name="target" required>
<option value="">Seleccionar</option>
{targets.opportunities.map((o) => (
<option key={o.id} value={`opportunity_id:${o.id}`}>
{o.title} · oportunidade
</option>
))}
{targets.dossiers.map((d) => {
const field = d.project_id
? "project_id"
: d.cluster_id
? "cluster_id"
: "corridor_id";
return (
<option key={d.id} value={`${field}:${d[field]}`}>
{d.title} · ficha territorial
</option>
);
})}
</select>
</Field>
<Field label="Tipo de associação">
<select className={input} name="association_type">
<option value="potential">Potencial</option>
<option value="official">Oficial, com título próprio</option>
<option value="influence">Área de influência</option>
<option value="proximity">Proximidade geográfica</option>
<option value="historical">Histórica</option>
</select>
</Field>
<Field label="Papel">
<select className={input} name="role">
<option value="related">Relacionada</option>
<option value="primary">Principal</option>
<option value="beneficiary">Beneficiária</option>
<option value="served">Servida</option>
<option value="enabled">Habilitada</option>
<option value="dependent">Dependente</option>
<option value="potential">Potencial</option>
<option value="historical">Histórica</option>
</select>
</Field>
<Field label="Fonte jurídica, obrigatória para associação oficial">
<select name="legal_source_id" className={input}>
<option value="">Não aplicável à relação proposta</option>
{sources.map((s) => (
<option key={s.id} value={s.id}>
{s.title}
</option>
))}
</select>
</Field>
<Field label="Fonte da relação">
<input
name="source_reference"
className={input}
required
minLength={10}
maxLength={2000}
/>
</Field>
<Field label="Justificação">
<textarea
name="justification"
className={input}
required
minLength={10}
maxLength={3000}
/>
</Field>
<Field label="Válida desde">
<input name="valid_from" type="date" className={input} required />
</Field>
<Field label="Válida até">
<input name="valid_until" type="date" className={input} />
</Field>
<button disabled={busy} className={button}>
Submeter associação para revisão
</button>
</form>
<section className={card}>
<h2 className="text-xl font-bold">Relações territoriais</h2>
{relations.map((r) => (
<p key={r.id}>
{r.association_type} · {r.validation_status}{" "}
<button
disabled={busy || r.validation_status === "revoked"}
className={button}
onClick={() =>
action(
`/api/v2/investment/admin/zone-relations/${r.id}/${r.validation_status === "pending" ? "validate" : "revoke"}`,
{ version_no: r.version_no },
)
}
>
{r.validation_status === "pending" ? "Validar" : "Revogar"}
</button>
</p>
))}
</section>
<form
className={card + " grid gap-4 md:grid-cols-2"}
onSubmit={(e) => {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
if (typeof data.geometry !== "string") return;
const raw = data.geometry;
try {
data.geometry = JSON.parse(raw);
void action(`/api/v2/investment/admin/zones/${id}/geometries`, data);
} catch {
const field = e.currentTarget.elements.namedItem(
"geometry",
) as HTMLTextAreaElement;
field.setCustomValidity("Introduza GeoJSON válido.");
field.reportValidity();
}
}}
>
<h2 className="text-xl font-bold md:col-span-2">Geometria para revisão GIS</h2>
<p>
GeoJSON no SRID 4326, até 200 KB. Não desenhe um perímetro sem fonte autorizada.
</p>
<Field label="GeoJSON">
<textarea
name="geometry"
className={input}
required
onChange={(e) => e.currentTarget.setCustomValidity("")}
/>
</Field>
<Field label="Finalidade">
<select name="purpose" className={input}>
<option value="site">Localização</option>
<option value="influence">Área de influência</option>
<option value="alternative">Alternativa</option>
<option value="official_perimeter">Perímetro oficial</option>
</select>
</Field>
<Field label="Fonte jurídica do perímetro">
<select name="legal_source_id" className={input}>
<option value="">Por confirmar</option>
{sources.map((s) => (
<option key={s.id} value={s.id}>
{s.title}
</option>
))}
</select>
</Field>
<Field label="Proveniência da geometria">
<input className={input} name="source_reference" required minLength={10} />
</Field>
<Field label="Entidade indicada para validação">
<input className={input} name="validating_entity" required />
</Field>
<Field label="Data da observação">
<input className={input} type="date" name="observed_at" required />
</Field>
<button disabled={busy} className={button}>
Submeter geometria
</button>
</form>
<section className={card}>
<h2 className="text-xl font-bold">Revisão GIS</h2>
{geometries.map((g) => (
<p key={g.id}>
{g.purpose} · {g.validation_status}{" "}
<button
className={button}
disabled={busy || g.validation_status === "revoked"}
onClick={() =>
action(
`/api/v2/investment/admin/zone-geometries/${g.id}/${g.validation_status === "pending" ? "validate" : "revoke"}`,
{ version_no: g.version_no },
)
}
>
{g.validation_status === "pending"
? "Validar e autorizar divulgação"
: "Retirar geometria"}
</button>
</p>
))}
</section>
</>
);
}
+489
View File
@@ -0,0 +1,489 @@
import { Link, router, useForm } from "@inertiajs/react";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
import ZoneRelations from "./zone-relations";
import ZoneMap from "./zone-map";
import type { ZoneTargets } from "./zone-relations";
type Zone = {
id: string;
version_no: number;
code: string;
category: string;
name: string;
name_en: string | null;
description: string | null;
description_en: string | null;
province: string | null;
district: string | null;
operator_id?: string;
legal_source_id?: string;
publication_status?: string;
validation_status: string;
};
type Source = {
id: string;
title: string;
url: string;
diploma: string;
article: string;
competent_entity: string;
valid_from: string;
valid_until: string | null;
version_no: number;
validation_status: string;
};
type Props = {
targets: ZoneTargets | null;
related: { id: string; title: string }[];
relations: {
id: string;
version_no: number;
association_type: string;
validation_status: string;
}[];
geometries: { id: string; version_no: number; purpose: string; validation_status: string }[];
record: Zone;
management: boolean;
source: Source | null;
operator: string | null;
operators: { id: string; name: string }[];
legalSources: Source[];
links: {
id: string;
item_id: string;
association_type: string;
validation_status: string;
version_no: number;
}[];
revisions: { version_no: number; action: string; created_at: string }[];
opportunities: {
data: { id: number; title: string; slug: string }[];
next_page_url: string | null;
prev_page_url: string | null;
} | null;
};
export default function ZonePage(props: Props) {
return <Editor key={`${props.record.id}:${props.record.version_no}`} {...props} />;
}
function Editor({
targets,
related,
relations,
geometries,
record: z,
management,
source,
operator,
operators,
legalSources,
links,
revisions,
opportunities,
}: Props) {
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
const form = useForm({
version_no: z.version_no,
code: z.code,
category: z.category,
name: z.name,
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 ?? "",
});
async function action(url: string, data: unknown) {
setBusy(true);
setMessage("");
try {
await api(url, data);
router.reload();
} catch (e) {
setMessage(e instanceof Error ? e.message : "Falha na operação.");
} finally {
setBusy(false);
}
}
return (
<Frame title={z.name}>
<p>
{z.code} · {z.category.toUpperCase()} · {z.validation_status} · {z.province}{" "}
{z.district}
</p>
<p>
A ficha é informativa. A associação territorial não atribui benefícios, licenças ou
autorização aduaneira.
</p>
{message && (
<p role="alert" className={card}>
{message}
</p>
)}
{management ? (
<>
<form
className={card + " grid gap-4 md:grid-cols-2"}
onSubmit={async (e) => {
e.preventDefault();
setBusy(true);
setMessage("");
try {
await api(`/api/v2/investment/admin/zones/${z.id}`, {
...form.data,
_method: "PUT",
});
router.reload();
} catch (failure) {
setMessage(
failure instanceof Error
? failure.message
: "Falha ao guardar.",
);
} finally {
setBusy(false);
}
}}
>
{(
[
["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}>
<input
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
/>
</Field>
))}
<Field label="Categoria">
<select
className={input}
value={form.data.category}
onChange={(e) => form.setData("category", e.target.value)}
>
<option value="pending">Pendente</option>
<option value="zee">ZEE</option>
<option value="zfi">ZFI</option>
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
{(
[
["description", "Descrição PT"],
["description_en", "Descrição EN"],
] as const
).map(([key, label]) => (
<Field key={key} label={label}>
<textarea
className={input}
value={form.data[key]}
onChange={(e) => form.setData(key, e.target.value)}
/>
</Field>
))}
<Field label="Operador cadastrado">
<select
className={input}
value={form.data.operator_id}
onChange={(e) => form.setData("operator_id", e.target.value)}
>
<option value="">Por confirmar</option>
{operators.map((o) => (
<option key={o.id} value={o.id}>
{o.name}
</option>
))}
</select>
</Field>
<Field label="Fonte jurídica">
<select
className={input}
value={form.data.legal_source_id}
onChange={(e) => form.setData("legal_source_id", e.target.value)}
>
<option value="">Por confirmar</option>
{legalSources.map((s) => (
<option key={s.id} value={s.id}>
{s.title} · {s.validation_status}
</option>
))}
</select>
</Field>
<button disabled={busy} className={button}>
Guardar rascunho
</button>
</form>
<section className={card}>
<h2 className="text-xl font-bold">Revisão independente</h2>
<p>
Versão {z.version_no}. Outra pessoa gestora deve rever antes da
publicação. Guarde primeiro as alterações.
</p>
<div className="flex gap-4">
<button
className={button}
disabled={busy || form.isDirty}
onClick={() =>
action(`/api/v2/investment/admin/zones/${z.id}/publish`, {
version_no: z.version_no,
})
}
>
Validar e publicar
</button>
<button
className={button}
disabled={busy}
onClick={() =>
action(`/api/v2/investment/admin/zones/${z.id}/suspend`, {
version_no: z.version_no,
})
}
>
Suspender publicação
</button>
</div>
</section>
<section className={card}>
<h2 className="text-xl font-bold">Fontes por rever</h2>
{legalSources.map((s) => (
<article key={s.id} className="my-4">
<p>
{s.title} · {s.diploma} · {s.article} · {s.validation_status}
</p>
<a
className="underline"
href={s.url}
target="_blank"
rel="noreferrer"
>
Consultar documento
</a>
<div className="flex gap-4">
{s.validation_status === "pending" && (
<button
className={button}
disabled={busy}
onClick={() =>
action(
`/api/v2/investment/admin/legal-sources/${s.id}/validate`,
{ version_no: s.version_no },
)
}
>
Validar fonte
</button>
)}
{s.validation_status !== "revoked" && (
<button
className={button}
disabled={busy}
onClick={() =>
action(
`/api/v2/investment/admin/legal-sources/${s.id}/revoke`,
{ version_no: s.version_no },
)
}
>
Revogar referência
</button>
)}
</div>
</article>
))}
</section>
<form
className={card + " grid gap-4 md:grid-cols-2"}
onSubmit={(e) => {
e.preventDefault();
void action(
"/api/v2/investment/admin/legal-sources",
Object.fromEntries(new FormData(e.currentTarget)),
);
}}
>
<h2 className="text-xl font-bold md:col-span-2">Registar fonte jurídica</h2>
{(
[
["title", "Título", "text"],
["url", "URL HTTPS", "url"],
["diploma", "Diploma", "text"],
["article", "Artigo", "text"],
[
"competent_entity",
"Entidade competente indicada no diploma",
"text",
],
["valid_from", "Início de vigência", "date"],
["valid_until", "Fim de vigência, se aplicável", "date"],
] as const
).map(([name, label, type]) => (
<Field key={name} label={label}>
<input
className={input}
name={name}
type={type}
required={name !== "valid_until"}
/>
</Field>
))}
<button className={button} disabled={busy}>
Registar para revisão
</button>
</form>
<section className={card}>
<h2 className="text-xl font-bold">Associações para revisão</h2>
{links.map((l) => (
<div key={l.id}>
<p>
{l.item_id} · {l.association_type} · {l.validation_status}
</p>
<button
className={button}
disabled={busy}
onClick={() =>
action(
`/api/v2/investment/admin/zone-links/${l.id}/${l.validation_status === "pending" ? "validate" : "revoke"}`,
{ version_no: l.version_no },
)
}
>
{l.validation_status === "pending"
? "Validar associação"
: "Revogar associação"}
</button>
</div>
))}
</section>
<section className={card}>
<h2 className="text-xl font-bold">Histórico editorial</h2>
{revisions.map((r) => (
<p key={r.version_no}>
Versão {r.version_no} · {r.action} · {r.created_at}
</p>
))}
</section>
{targets && (
<ZoneRelations
id={z.id}
targets={targets}
sources={legalSources}
relations={relations}
geometries={geometries}
busy={busy}
action={action}
/>
)}
</>
) : (
<>
<p className="whitespace-pre-line">{z.description}</p>
<ZoneMap id={z.id} />
{z.description_en && (
<details>
<summary>English description</summary>
<p lang="en" className="whitespace-pre-line">
{z.description_en}
</p>
</details>
)}
<p>Operador: {operator ?? "Informação pública por disponibilizar"}</p>
{source && (
<section className={card}>
<h2 className="text-xl font-bold">Fonte e vigência</h2>
<a
className="underline"
href={source.url}
target="_blank"
rel="noreferrer"
>
{source.title}
</a>
<p>
{source.diploma} · {source.article} · {source.competent_entity}
</p>
<p>
{source.valid_from} —{" "}
{source.valid_until ?? "Sem fim indicado na referência"} · Versão{" "}
{source.version_no}
</p>
</section>
)}
<section className={card}>
<h2 className="text-xl font-bold">Investimentos relacionados</h2>
{opportunities?.data.map((o) => (
<p key={o.id}>
<Link
className="underline"
href={`/oportunidades/${o.slug}?zone_id=${z.id}`}
>
{o.title}
</Link>
</p>
))}
{!opportunities?.data.length && (
<p>Sem investimentos publicados associados.</p>
)}
<nav aria-label="Paginação">
{opportunities?.prev_page_url && (
<Link href={opportunities.prev_page_url}>Anterior</Link>
)}{" "}
{opportunities?.next_page_url && (
<Link href={opportunities.next_page_url}>Seguinte</Link>
)}
</nav>
</section>
<div className="flex flex-wrap gap-3">
{(
[
["interest", "Manifestar interesse"],
["dossier", "Solicitar dossier"],
["meeting", "Pedir reunião"],
] as const
).map(([intent, label]) => (
<button
key={intent}
className={button}
onClick={() =>
router.post("/investidor/manifestacoes", {
zone_id: z.id,
intent,
})
}
>
{label}
</button>
))}
</div>
<p>
Pedido assistido com conta e consentimento. Não inicia prazo de decisão
administrativa nem confirma uma reunião.
</p>
<section className={card}>
<h2 className="text-xl font-bold">
Clusters, corredores e projectos relacionados
</h2>
{related.map((r) => (
<p key={r.id}>
<Link className="underline" href={`/carteira/${r.id}`}>
{r.title}
</Link>
</p>
))}
{!related.length && <p>Sem relações territoriais publicadas.</p>}
</section>
</>
)}
</Frame>
);
}
+140
View File
@@ -0,0 +1,140 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { Frame, Field, input, button, card, api } from "./shared";
type Zone = {
id: string;
code: string;
name: string;
category: string;
description: string | null;
province: string | null;
version_no: number;
publication_status: string;
validation_status: string;
};
export default function Zones({
records,
filters,
management,
}: {
records: {
data: Zone[];
total: number;
next_page_url: string | null;
prev_page_url: string | null;
};
filters: { q?: string; category?: string };
management: boolean;
}) {
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<Frame
title={management ? "Gestão de ZEE, ZFI e parques" : "ZEE, ZFI e parques industriais"}
>
<p>
A informação territorial não atribui benefícios nem substitui certificados ou
decisões das entidades competentes.
</p>
<nav aria-label="Dimensões de investimento" className="flex flex-wrap gap-4 underline">
<Link href="/clusters">Por Cluster</Link>
<Link href="/corredores">Por Corredor</Link>
<Link href="/zonas?category=zee">Por ZEE</Link>
<Link href="/zonas?category=zfi">Por ZFI</Link>
<Link href="/zonas?category=industrial_park">Parques industriais</Link>
</nav>
<form method="get" className={card + " grid gap-4 md:grid-cols-3"}>
<Field label="Pesquisar por nome ou código">
<input className={input} name="q" defaultValue={filters.q} maxLength={120} />
</Field>
<Field label="Categoria">
<select className={input} name="category" defaultValue={filters.category ?? ""}>
<option value="">Todas</option>
<option value="zee">ZEE</option>
<option value="zfi">ZFI</option>
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
<button className={button}>Pesquisar</button>
</form>
<p role="status">{records.total} registos disponíveis</p>
{!records.total && (
<p className={card}>
Sem registos disponíveis para estes filtros. As zonas aguardam cadastro e
validação documental.
</p>
)}
{records.data.map((zone) => (
<article className={card} key={zone.id}>
<h2 className="text-xl font-bold">
<Link
className="underline"
href={`${management ? "/management/investment/zones" : "/zonas"}/${zone.id}`}
>
{zone.name}
</Link>
</h2>
<p>
{zone.code} · {zone.category.toUpperCase()} ·{" "}
{zone.province ?? "Localização por confirmar"}
</p>
<p>{zone.description}</p>
<p>Validação: {zone.validation_status}</p>
{management && (
<p>
Versão {zone.version_no} · {zone.publication_status}
</p>
)}
</article>
))}
<nav aria-label="Paginação" className="flex gap-4 underline">
{records.prev_page_url && <Link href={records.prev_page_url}>Anterior</Link>}
{records.next_page_url && <Link href={records.next_page_url}>Seguinte</Link>}
</nav>
{management && (
<form
className={card + " space-y-4"}
onSubmit={async (event) => {
event.preventDefault();
const data = Object.fromEntries(new FormData(event.currentTarget));
setBusy(true);
setError("");
try {
await api("/api/v2/investment/admin/zones", data);
router.reload();
} catch (failure) {
setError(
failure instanceof Error
? failure.message
: "Não foi possível guardar. Tente novamente.",
);
} finally {
setBusy(false);
}
}}
>
<h2 className="text-xl font-bold">Criar rascunho</h2>
<Field label="Código">
<input name="code" className={input} required maxLength={80} />
</Field>
<Field label="Nome">
<input name="name" className={input} required maxLength={255} />
</Field>
<Field label="Categoria proposta">
<select name="category" className={input}>
<option value="pending">Pendente de enquadramento</option>
<option value="zee">ZEE</option>
<option value="zfi">ZFI</option>
<option value="industrial_park">Parque industrial</option>
</select>
</Field>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>
Guardar rascunho
</button>
</form>
)}
</Frame>
);
}