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"; type Values = Record; type Entry = { id: number; reference: string; status: string; deleted_at: string | null; management_version: number; }; export default function OpportunityDraft({ record, values, etag, readOnly, closedVersion, classification, sectors, categories, history, territoryPath, resourcesInstalled = false, }: { record: Entry | null; values: Values; etag: string | null; readOnly: boolean; closedVersion: boolean; classification: string; sectors: { id: number; name: string }[]; categories: string[]; territoryPath: TerritoryOption[]; resourcesInstalled?: boolean; history: { id: string; action: string; actor_user_id: number; occurred_at: string; }[]; }) { const [data, setData] = useState({ ...values, creation_key: crypto.randomUUID(), }); const [busy, setBusy] = useState(false), [errors, setErrors] = 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", ); const set = (key: string, value: string) => setData((d) => ({ ...d, [key]: value })); async function send(action: "save" | "delete" | "restore") { if (busy) return; setBusy(true); setErrors({}); setMessage(""); try { const cookie = document.cookie .split("; ") .find((c) => c.startsWith("XSRF-TOKEN=")); const url = action === "save" ? record ? `/management/opportunities/${record.id}/draft` : "/management/opportunities/drafts" : `/management/opportunities/${record!.id}/lifecycle`; const response = await fetch(url, { method: action === "save" && record ? "PUT" : "POST", headers: { Accept: "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": cookie ? decodeURIComponent(cookie.slice(11)) : "", }, body: JSON.stringify( action === "save" ? { ...data, etag: token, reason } : { etag: token, action, reason, confirm }, ), }); const result = await response.json(); if (!response.ok) { setErrors( Object.fromEntries( Object.entries(result.errors ?? {}).map(([k, v]) => [ k, Array.isArray(v) ? v.join(" ") : String(v), ]), ), ); setMessage( result.message ?? "Operação falhou; os dados preenchidos foram preservados.", ); return; } setMessage(result.message); if (result.etag) setToken(result.etag); if (!record) router.visit(`/management/opportunities/${result.id}/edit`); else if (action !== "save") router.reload(); } catch { setMessage( "Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.", ); } finally { setBusy(false); requestAnimationFrame(() => document.getElementById("opportunity-result")?.focus(), ); } } return ( Voltar à gestão

Classificação de origem: {classification}. Esta classificação não cria associações territoriais.

{closedVersion && (

Versão anterior fechada. As alterações são guardadas numa nova versão de rascunho; a ficha publicada permanece intacta. Este incremento não submete, aprova ou publica.

)}
{message} {errors.etag && (

{errors.etag}{" "} Abrir versão atual

)}
{ e.preventDefault(); void send("save"); }} >

Hierarquia do cadastro territorial existente. Alterar esta seleção não cria relações com projetos/clusters.

{( [ "province_id", "district_id", "admin_post_id", "locality_id", ] as const ).map((key, index) => ( { const next = [ ...path.slice(0, index), ...(value ? [value] : []), ]; 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 ?? "", })); }} /> ))}
{Object.entries({ title: "Título oficial", summary: "Resumo", description: "Descrição", promoter_name: "Promotor", }).map(([key, label]) => ( {key === "description" || key === "summary" ? (