oportunidades 2
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-09 08:48:42 +02:00
parent 7ecfe3d543
commit 60784a2ed2
14 changed files with 1496 additions and 125 deletions
@@ -0,0 +1,596 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import {
TerritoryLevel,
type TerritoryOption,
} from "@/components/investment-territory";
import { Management, Field, button, control } from "./shared";
type Payload = Record<string, string | number | boolean | null | object>;
type Resource = {
id: string;
version: number;
deleted_at: string | null;
payload: Payload;
territoryPath?: TerritoryOption[];
file?: {
file_name: string;
malware_scan_status: string;
malware_engine: string | null;
sha256: string;
};
};
type Kind = "locations" | "images" | "documents";
const fields: Record<Kind, string[]> = {
locations: [
"title",
"address",
"operational_unit",
"role_description",
"area_value",
"area_unit",
"allocation_percentage",
"multi_district_rationale",
"source_reference",
"source_date",
],
images: [
"title",
"caption",
"alt_text",
"author_source",
"captured_at",
"rights_valid_until",
"role_description",
"sort_order",
"source_reference",
],
documents: [
"title",
"category",
"issuer",
"edition",
"source_date",
"valid_until",
"source_reference",
"section",
"supported_statement",
],
};
const labels: Record<string, string> = {
title: "Título",
address: "Referência física",
operational_unit: "Unidade operacional",
role_description: "Descrição do papel outro",
area_value: "Área",
area_unit: "Unidade de área",
allocation_percentage: "Distribuição (%)",
multi_district_rationale: "Fundamento multidistrito/interprovincial",
source_reference: "Fonte / referência",
source_date: "Data da fonte",
caption: "Legenda",
alt_text: "Texto alternativo",
author_source: "Autor / fonte",
captured_at: "Data da imagem",
rights_valid_until: "Validade dos direitos",
sort_order: "Ordem",
category: "Categoria documental",
issuer: "Emissor",
edition: "Edição / versão",
valid_until: "Validade",
section: "Página / secção",
supported_statement: "Afirmação fundamentada",
};
const choices: Record<string, string[]> = {
role: [
"headquarters",
"production",
"raw_material",
"storage",
"logistics",
"market",
"support",
"other",
],
imageRole: [
"cover",
"gallery",
"location",
"asset",
"product",
"plan",
"rendering",
"evidence",
"other",
],
territorial_purpose: ["implementation", "context", "impact", "coverage"],
rights_status: ["owned", "licensed", "authorized", "public_domain"],
visibility: ["internal", "authenticated", "public"],
classification: ["public", "internal", "confidential", "restricted"],
};
export default function OpportunityResources({
opportunity,
etag,
resources,
existingLocations,
assessment,
}: {
opportunity: {
id: number;
title: string | null;
status: string;
deleted_at: string | null;
};
etag: string;
resources: Record<Kind, Resource[]>;
existingLocations: { id: string; name: string; location_type: string }[];
assessment: string[];
}) {
const [kind, setKind] = useState<Kind>("locations");
const [editing, setEditing] = useState<Resource | null>(null);
const [payload, setPayload] = useState<Payload>({});
const [path, setPath] = useState<TerritoryOption[]>([]);
const [geometry, setGeometry] = useState("");
const [file, setFile] = useState<File | null>(null);
const [reason, setReason] = useState("");
const [confirm, setConfirm] = useState(false);
const [key, setKey] = useState(() => crypto.randomUUID());
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [errors, setErrors] = useState<Record<string, string>>({});
const set = (name: string, value: Payload[string]) =>
setPayload((previous) => ({ ...previous, [name]: value }));
function select(nextKind: Kind, record: Resource | null = null) {
setKind(nextKind);
setEditing(record);
setPayload(record?.payload ?? {});
setPath(record?.territoryPath ?? []);
setGeometry(
record?.payload.geometry
? JSON.stringify(record.payload.geometry)
: "",
);
setFile(null);
setKey(crypto.randomUUID());
setConfirm(false);
setErrors({});
}
async function execute(action: "save" | "delete" | "restore") {
if (busy) return;
setBusy(true);
setErrors({});
setMessage("");
try {
const form = new FormData();
form.set("etag", etag);
form.set("reason", reason);
form.set("creation_key", key);
if (editing) form.set("version", String(editing.version));
if (action === "save") {
const values = { ...payload };
if (kind === "locations") {
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
].forEach(
(name, index) =>
(values[name] = path[index]?.id ?? null),
);
values.geometry = geometry ? JSON.parse(geometry) : null;
}
form.set("payload", JSON.stringify(values));
if (file) form.set("file", file);
} else {
form.set("action", action);
form.set("confirm", confirm ? "1" : "0");
}
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ""}${action === "save" ? "" : "/lifecycle"}`;
const csrf =
document.cookie
.split("; ")
.find((v) => v.startsWith("XSRF-TOKEN="))
?.split("=")
.slice(1)
.join("=") ?? "";
const result = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"X-XSRF-TOKEN": decodeURIComponent(csrf),
},
body: form,
});
const data = await result.json();
if (!result.ok) {
setErrors(
Object.fromEntries(
Object.entries(data.errors ?? {}).map(
([name, value]) => [
name,
Array.isArray(value)
? value.join(" ")
: String(value),
],
),
),
);
throw new Error(data.message ?? `Falha HTTP ${result.status}`);
}
setMessage(data.message);
setEditing(null);
setPayload({});
setPath([]);
setGeometry("");
setFile(null);
setKey(crypto.randomUUID());
setConfirm(false);
router.reload({
onFinish: () =>
document.getElementById("resource-result")?.focus(),
});
} catch (error) {
setMessage(
error instanceof Error
? error.message
: "Falha de ligação; preenchimento preservado.",
);
} finally {
setBusy(false);
setTimeout(
() => document.getElementById("resource-result")?.focus(),
0,
);
}
}
const unavailable =
!!opportunity.deleted_at || opportunity.status === "archived";
return (
<Management title="Imagens, documentos e localizações">
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
Regressar ao rascunho #{opportunity.id}
</Link>
<p>
Recursos de preparação. Não alteram automaticamente a ficha
pública ou relações territoriais aceites. ClamD real pendente;
scan simulado nunca verifica ficheiros reais.
</p>
<div
id="resource-result"
role="status"
tabIndex={-1}
className="rounded border p-3"
>
{message ||
"Guardar é independente de validar, submeter e publicar."}
{errors.etag && <p>{errors.etag}</p>}
</div>
<section>
<h2>Conferência e pendências</h2>
<ul>
{assessment.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</section>
{existingLocations.length > 0 && (
<section>
<h2>Ligações territoriais existentes preservadas</h2>
{existingLocations.map((r) => (
<p key={r.id}>
{r.name} · {r.location_type}
</p>
))}
</section>
)}
<nav className="flex flex-wrap gap-3">
{(["locations", "images", "documents"] as Kind[]).map((k) => (
<button
className={button}
key={k}
disabled={busy}
onClick={() => select(k)}
>
{k === "locations"
? "Localizações"
: k === "images"
? "Imagens"
: "Documentos"}
</button>
))}
</nav>
<section>
{resources[kind].map((r) => (
<article key={r.id} className="my-3 rounded border p-3">
<p>
{String(
r.payload.title ??
r.file?.file_name ??
"Recurso incompleto",
)}{" "}
· v{r.version} ·{" "}
{r.deleted_at
? "eliminado logicamente"
: "rascunho"}
</p>
{r.file && (
<p>
Scan: {r.file.malware_scan_status} · motor:{" "}
{r.file.malware_engine ?? "não executado"} ·
hash: {r.file.sha256}
</p>
)}
<button
className={button}
onClick={() => select(kind, r)}
>
Ver / editar / restaurar
</button>
{r.file?.malware_scan_status === "clean" &&
!r.deleted_at && (
<a
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
>
Consultar original autorizado
</a>
)}
</article>
))}
</section>
<form
onSubmit={(event) => {
event.preventDefault();
void execute("save");
}}
className="space-y-3"
>
<h2>
{editing
? "Editar recurso / nova versão"
: "Novo recurso incompleto"}
</h2>
{kind === "locations" && (
<div>
{[0, 1, 2, 3].map((index) => (
<TerritoryLevel
key={index}
index={index}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
onChange={(value) =>
setPath((previous) =>
value
? [
...previous.slice(0, index),
value,
]
: previous.slice(0, index),
)
}
fieldError={
errors[
[
"province_id",
"district_id",
"admin_post_id",
"locality_id",
][index]
]
}
/>
))}
</div>
)}
{kind !== "locations" && (
<Field
label="Original / substituir por nova versão"
error={errors.file}
>
<input
aria-label="Original / substituir por nova versão"
type="file"
accept={
kind === "images"
? ".jpg,.jpeg,.png,.webp"
: ".pdf,.docx,.xlsx,.png,.jpg,.jpeg"
}
onChange={(event) =>
setFile(event.target.files?.[0] ?? null)
}
/>
<p>
Armazenamento privado cifrado, original e versões
preservados; sem acesso até scan limpo.
</p>
</Field>
)}
{fields[kind].map((name) => (
<Field
key={name}
label={labels[name]}
error={errors[name] ?? errors[`payload.${name}`]}
>
<input
aria-label={labels[name]}
className={control}
value={String(payload[name] ?? "")}
type={
name.includes("date") ||
name.endsWith("_at") ||
name.endsWith("_until")
? "date"
: "text"
}
onChange={(event) =>
set(name, event.target.value || null)
}
/>
</Field>
))}
{(kind === "locations"
? ["role", "territorial_purpose"]
: kind === "images"
? ["imageRole", "rights_status", "visibility"]
: ["classification", "visibility"]
).map((name) => (
<Field
key={name}
label={name}
error={
errors[
`payload.${name === "imageRole" ? "role" : name}`
]
}
>
<select
className={control}
aria-label={name}
value={String(
payload[name === "imageRole" ? "role" : name] ??
"",
)}
onChange={(event) =>
set(
name === "imageRole" ? "role" : name,
event.target.value || null,
)
}
>
<option value="">Pendente</option>
{choices[name].map((option) => (
<option key={option}>{option}</option>
))}
</select>
</Field>
))}
{kind === "locations" && (
<Field
label="GeoJSON documentado (opcional)"
error={errors.geometry}
>
<textarea
className={control}
value={geometry}
onChange={(event) =>
setGeometry(event.target.value)
}
/>
<p>
Sem coordenadas continua consultável. Limite oficial
em falta aparece como pendência espacial.
</p>
</Field>
)}
{kind === "images" &&
(["location_id", "rights_document_id"] as const).map(
(name) => (
<Field
key={name}
label={name}
error={errors[`payload.${name}`]}
>
<select
className={control}
value={String(payload[name] ?? "")}
onChange={(event) =>
set(name, event.target.value || null)
}
>
<option value="">Pendente</option>
{resources[
name === "location_id"
? "locations"
: "documents"
]
.filter((r) => !r.deleted_at)
.map((r) => (
<option value={r.id} key={r.id}>
{String(
r.payload.title ??
r.file?.file_name ??
r.id,
)}
</option>
))}
</select>
</Field>
),
)}
{kind !== "documents" && (
<label>
<input
type="checkbox"
checked={
!!payload[
kind === "images"
? "is_cover"
: "is_primary"
]
}
onChange={(event) =>
set(
kind === "images"
? "is_cover"
: "is_primary",
event.target.checked,
)
}
/>
{kind === "images"
? "Selecionar capa de preparação"
: "Localização principal"}
</label>
)}
<Field
label="Motivo (20–1000 caracteres)"
error={errors.reason}
>
<textarea
className={control}
aria-label="Motivo (20–1000 caracteres)"
value={reason}
onChange={(event) => setReason(event.target.value)}
/>
</Field>
{editing && (
<label>
<input
type="checkbox"
checked={confirm}
onChange={(event) =>
setConfirm(event.target.checked)
}
/>
Confirmar exclusão lógica / restauração
</label>
)}
<div className="flex flex-wrap gap-3">
<button
className={button}
disabled={busy || unavailable || !!editing?.deleted_at}
>
Guardar recurso
</button>
{editing && (
<button
type="button"
className={button}
disabled={busy || unavailable}
onClick={() =>
void execute(
editing.deleted_at ? "restore" : "delete",
)
}
>
{editing.deleted_at
? "Restaurar recurso"
: "Excluir recurso logicamente"}
</button>
)}
</div>
</form>
</Management>
);
}