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
@@ -1,10 +1,10 @@
import { Link, router } from '@inertiajs/react';
import { useState, useEffect } from 'react';
import { Link, router } from "@inertiajs/react";
import { useState, useEffect } from "react";
import {
TerritoryLevel,
type TerritoryOption,
} from '@/components/investment-territory';
import { Management, Field, button, control } from './shared';
} from "@/components/investment-territory";
import { Management, Field, button, control } from "./shared";
type Values = Record<string, string | number | null>;
type Entry = {
id: number;
@@ -47,43 +47,43 @@ export default function OpportunityDraft({
});
const [busy, setBusy] = useState(false),
[errors, setErrors] = useState<Record<string, string>>({}),
[message, setMessage] = useState(''),
[reason, setReason] = useState(''),
[message, setMessage] = useState(""),
[reason, setReason] = useState(""),
[confirm, setConfirm] = useState(false),
[token, setToken] = useState(etag);
useEffect(() => setToken(etag), [etag]);
const [path, setPath] = useState(territoryPath);
const unavailable = Boolean(
record?.deleted_at || record?.status === 'archived',
record?.deleted_at || record?.status === "archived",
);
const set = (key: string, value: string) =>
setData((d) => ({ ...d, [key]: value }));
async function send(action: 'save' | 'delete' | 'restore') {
async function send(action: "save" | "delete" | "restore") {
if (busy) return;
setBusy(true);
setErrors({});
setMessage('');
setMessage("");
try {
const cookie = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='));
.split("; ")
.find((c) => c.startsWith("XSRF-TOKEN="));
const url =
action === 'save'
action === "save"
? record
? `/management/opportunities/${record.id}/draft`
: '/management/opportunities/drafts'
: "/management/opportunities/drafts"
: `/management/opportunities/${record!.id}/lifecycle`;
const response = await fetch(url, {
method: action === 'save' && record ? 'PUT' : 'POST',
method: action === "save" && record ? "PUT" : "POST",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': cookie
Accept: "application/json",
"Content-Type": "application/json",
"X-XSRF-TOKEN": cookie
? decodeURIComponent(cookie.slice(11))
: '',
: "",
},
body: JSON.stringify(
action === 'save'
action === "save"
? { ...data, etag: token, reason }
: { etag: token, action, reason, confirm },
),
@@ -94,13 +94,13 @@ export default function OpportunityDraft({
Object.fromEntries(
Object.entries(result.errors ?? {}).map(([k, v]) => [
k,
Array.isArray(v) ? v.join(' ') : String(v),
Array.isArray(v) ? v.join(" ") : String(v),
]),
),
);
setMessage(
result.message ??
'Operação falhou; os dados preenchidos foram preservados.',
"Operação falhou; os dados preenchidos foram preservados.",
);
return;
}
@@ -108,15 +108,15 @@ export default function OpportunityDraft({
if (result.etag) setToken(result.etag);
if (!record)
router.visit(`/management/opportunities/${result.id}/edit`);
else if (action !== 'save') router.reload();
else if (action !== "save") router.reload();
} catch {
setMessage(
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
"Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.",
);
} finally {
setBusy(false);
requestAnimationFrame(() =>
document.getElementById('opportunity-result')?.focus(),
document.getElementById("opportunity-result")?.focus(),
);
}
}
@@ -124,8 +124,8 @@ export default function OpportunityDraft({
<Management
title={
record
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
: 'Nova oportunidade'
? `${readOnly ? "Ver" : "Editar"} oportunidade ${record.reference}`
: "Nova oportunidade"
}
>
<Link href="/management/opportunities">Voltar à gestão</Link>
@@ -143,13 +143,13 @@ export default function OpportunityDraft({
<div
id="opportunity-result"
tabIndex={-1}
role={Object.keys(errors).length ? 'alert' : 'status'}
role={Object.keys(errors).length ? "alert" : "status"}
className="rounded border p-3"
>
{message}
{errors.etag && (
<p>
{errors.etag}{' '}
{errors.etag}{" "}
<a
target="_blank"
rel="noreferrer"
@@ -164,7 +164,7 @@ export default function OpportunityDraft({
className="max-w-3xl space-y-4"
onSubmit={(e) => {
e.preventDefault();
void send('save');
void send("save");
}}
>
<fieldset
@@ -179,16 +179,16 @@ export default function OpportunityDraft({
</p>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
"province_id",
"district_id",
"admin_post_id",
"locality_id",
] as const
).map((key, index) => (
<TerritoryLevel
key={`${key}-${path[index - 1]?.id ?? ''}`}
key={`${key}-${path[index - 1]?.id ?? ""}`}
index={index}
parent={path[index - 1]?.id ?? ''}
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
endpoint="/management/territory-options"
fieldError={errors[key]}
@@ -200,10 +200,10 @@ export default function OpportunityDraft({
setPath(next);
setData((previous) => ({
...previous,
province_id: next[0]?.id ?? '',
district_id: next[1]?.id ?? '',
admin_post_id: next[2]?.id ?? '',
locality_id: next[3]?.id ?? '',
province_id: next[0]?.id ?? "",
district_id: next[1]?.id ?? "",
admin_post_id: next[2]?.id ?? "",
locality_id: next[3]?.id ?? "",
}));
}}
/>
@@ -215,9 +215,9 @@ export default function OpportunityDraft({
>
<select
className={control}
value={String(data.opportunity_category ?? '')}
value={String(data.opportunity_category ?? "")}
onChange={(e) =>
set('opportunity_category', e.target.value)
set("opportunity_category", e.target.value)
}
>
<option value="">Por indicar</option>
@@ -227,22 +227,22 @@ export default function OpportunityDraft({
</select>
</Field>
{Object.entries({
title: 'Título oficial',
summary: 'Resumo',
description: 'Descrição',
promoter_name: 'Promotor',
title: "Título oficial",
summary: "Resumo",
description: "Descrição",
promoter_name: "Promotor",
}).map(([key, label]) => (
<Field key={key} label={label} error={errors[key]}>
{key === 'description' || key === 'summary' ? (
{key === "description" || key === "summary" ? (
<textarea
className={control}
value={String(data[key] ?? '')}
value={String(data[key] ?? "")}
onChange={(e) => set(key, e.target.value)}
/>
) : (
<input
className={control}
value={String(data[key] ?? '')}
value={String(data[key] ?? "")}
onChange={(e) => set(key, e.target.value)}
/>
)}
@@ -251,8 +251,8 @@ export default function OpportunityDraft({
<Field label="Sector" error={errors.sector_id}>
<select
className={control}
value={String(data.sector_id ?? '')}
onChange={(e) => set('sector_id', e.target.value)}
value={String(data.sector_id ?? "")}
onChange={(e) => set("sector_id", e.target.value)}
>
<option value="">Por indicar</option>
{sectors.map((s) => (
@@ -268,21 +268,21 @@ export default function OpportunityDraft({
>
<select
className={control}
value={String(data.promoter_type ?? '')}
value={String(data.promoter_type ?? "")}
onChange={(e) =>
set('promoter_type', e.target.value)
set("promoter_type", e.target.value)
}
>
<option value="">Por indicar</option>
{values.promoter_type &&
![
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
"public",
"private",
"ppp",
"cooperative",
"association",
"community",
"other",
].includes(String(values.promoter_type)) && (
<option
value={String(values.promoter_type)}
@@ -292,13 +292,13 @@ export default function OpportunityDraft({
</option>
)}
{[
'public',
'private',
'ppp',
'cooperative',
'association',
'community',
'other',
"public",
"private",
"ppp",
"cooperative",
"association",
"community",
"other",
].map((c) => (
<option key={c}>{c}</option>
))}
@@ -310,19 +310,19 @@ export default function OpportunityDraft({
>
<select
className={control}
value={String(data.maturity_level ?? '')}
value={String(data.maturity_level ?? "")}
onChange={(e) =>
set('maturity_level', e.target.value)
set("maturity_level", e.target.value)
}
>
<option value="">Por indicar</option>
{[
'Ideia identificada',
'Pré-estudo disponível',
'Estudo de viabilidade em curso',
'Projecto estruturado',
'Pronto para investimento',
'Em negociação ou implementação',
"Ideia identificada",
"Pré-estudo disponível",
"Estudo de viabilidade em curso",
"Projecto estruturado",
"Pronto para investimento",
"Em negociação ou implementação",
].map((c, index) => (
<option key={c} value={index + 1}>
{c}
@@ -336,9 +336,9 @@ export default function OpportunityDraft({
>
<input
className={control}
value={String(data.financing_modality ?? '')}
value={String(data.financing_modality ?? "")}
onChange={(e) =>
set('financing_modality', e.target.value)
set("financing_modality", e.target.value)
}
/>
</Field>
@@ -348,13 +348,13 @@ export default function OpportunityDraft({
>
<textarea
className={control}
value={String(data.expected_impact ?? '')}
value={String(data.expected_impact ?? "")}
onChange={(e) =>
set('expected_impact', e.target.value)
set("expected_impact", e.target.value)
}
/>
</Field>
{(data.opportunity_category === 'investment_project' ||
{(data.opportunity_category === "investment_project" ||
(!data.opportunity_category &&
data.estimated_investment_amount != null)) && (
<>
@@ -365,11 +365,11 @@ export default function OpportunityDraft({
<input
className={control}
value={String(
data.estimated_investment_amount ?? '',
data.estimated_investment_amount ?? "",
)}
onChange={(e) =>
set(
'estimated_investment_amount',
"estimated_investment_amount",
e.target.value,
)
}
@@ -383,17 +383,17 @@ export default function OpportunityDraft({
className={control}
value={String(
data.estimated_investment_currency ??
'',
"",
)}
onChange={(e) =>
set(
'estimated_investment_currency',
"estimated_investment_currency",
e.target.value,
)
}
>
<option value="">Por indicar</option>
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
<option key={c}>{c}</option>
))}
</select>
@@ -401,7 +401,7 @@ export default function OpportunityDraft({
</>
)}
{data.opportunity_category &&
data.opportunity_category !== 'investment_project' && (
data.opportunity_category !== "investment_project" && (
<p>
O módulo especializado desta categoria permanece
pendente. Pode guardar a identificação
@@ -437,11 +437,11 @@ export default function OpportunityDraft({
onChange={(e) =>
setConfirm(e.target.checked)
}
/>{' '}
Confirmo a{' '}
/>{" "}
Confirmo a{" "}
{unavailable
? 'restauração'
: 'exclusão lógica/arquivo'}
? "restauração"
: "exclusão lógica/arquivo"}
, preservando histórico e relações
</label>
<button
@@ -450,21 +450,26 @@ export default function OpportunityDraft({
disabled={busy || !confirm}
onClick={() =>
void send(
unavailable ? 'restore' : 'delete',
unavailable ? "restore" : "delete",
)
}
>
{unavailable
? 'Restaurar'
? "Restaurar"
: closedVersion
? 'Arquivar'
: 'Excluir rascunho'}
? "Arquivar"
: "Excluir rascunho"}
</button>
</>
)}
</>
)}
</form>
{record && (
<Link href={`/management/opportunities/${record.id}/resources`}>
Imagens, documentos e localizações
</Link>
)}
{record && (
<Link href={`/management/opportunities/${record.id}/context`}>
Consultar projetos, clusters e relações existentes
@@ -475,7 +480,7 @@ export default function OpportunityDraft({
{history.length ? (
history.map((e) => (
<p key={e.id}>
{e.action} · conta {e.actor_user_id} ·{' '}
{e.action} · conta {e.actor_user_id} ·{" "}
{e.occurred_at}
</p>
))
@@ -1,5 +1,5 @@
import { useForm } from '@inertiajs/react';
import { Management, button } from './shared';
import { useForm } from "@inertiajs/react";
import { Management, button } from "./shared";
export default function Install({
installed,
ready,
@@ -9,6 +9,7 @@ export default function Install({
migration,
backupDate,
rollback,
actionUrl = "/management/opportunity-management-install",
}: {
installed: boolean;
ready: boolean;
@@ -18,13 +19,14 @@ export default function Install({
migration: string;
backupDate: string | null;
rollback: string;
actionUrl?: string;
}) {
const form = useForm({ hash, confirm: false });
return (
<Management title="Ativação da Gestão de Oportunidades">
<p>
Base: {target.database}:{target.port} ·{' '}
{installed ? 'Instalado' : 'Ainda não aplicado'}
Base: {target.database}:{target.port} ·{" "}
{installed ? "Instalado" : "Ainda não aplicado"}
</p>
<ul>
{changes.map((c) => (
@@ -32,17 +34,16 @@ export default function Install({
))}
</ul>
<p>Migração: {migration}</p>
<p>Backup/restauro: {backupDate ?? 'Prova ainda por preparar'}</p>
<p>Backup/restauro: {backupDate ?? "Prova ainda por preparar"}</p>
<p>{rollback}</p>
<p>
Este plano ativa apenas o primeiro incremento; workflow
completo, imagens e módulos especializados permanecem no
backlog.
Este plano ativa apenas as alterações acima; workflow completo e
lacunas restantes permanecem no backlog.
</p>
<form
onSubmit={(e) => {
e.preventDefault();
form.post('/management/opportunity-management-install');
form.post(actionUrl);
}}
>
<label>
@@ -50,9 +51,9 @@ export default function Install({
type="checkbox"
checked={form.data.confirm}
onChange={(e) =>
form.setData('confirm', e.target.checked)
form.setData("confirm", e.target.checked)
}
/>{' '}
/>{" "}
Confirmo a aplicação deste plano
</label>
<button
@@ -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>
);
}