import OpportunityProfileActions from '@/components/opportunity-profile-actions'; import OpportunityCanonicalFields, { type CanonicalOptions, } from '@/components/opportunity-canonical-fields'; import { Link, router, usePage } from '@inertiajs/react'; import TerritoryGeometryPreview from '@/components/territory-geometry-preview'; import { useState, useEffect } from 'react'; import { TerritoryLevel, type TerritoryOption, } from '@/components/investment-territory'; import { Management, Field, button, control, states } 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, maturityCatalogue, }: { 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; maturityCatalogue: { version: string; stages: Record; legacyVersion: string; legacyLabels: Record; }; history: { id: string; action: string; actor_user_id: number; occurred_at: string; }[]; }) { const { basePath = '/management/opportunities', profileMode = false, profileOrganization, profileContext, profileAccess, profileActions = [], canonicalOptions, workflowState, workflowTasks = [], workflowParticipants, publicationPreview, publicationState, auth, canEditDraft = false, } = usePage<{ basePath?: string; profileMode?: boolean; profileOrganization?: string | null; profileActions?: string[]; profileContext?: Record | null; profileAccess?: { contexts: { organization_id: string | null; type: string }[]; } | null; publicationPreview?: { title: string; summary: string; description: string; }; workflowParticipants?: { publishers: { id: number; name: string }[]; validators: { id: number; name: string; technical: boolean; legal: boolean; }[]; }; canonicalOptions?: CanonicalOptions; workflowState?: string; publicationState?: { scope: string; label: string; public_catalog: boolean; }; workflowTasks?: { id: string; title: string; status: string; assignee_user_id: number | null; due_at: string | null; }[]; auth: { user: { id: number } }; canEditDraft?: boolean; }>().props; const [data, setData] = useState({ ...values, ...(profileMode ? { organization_id: record ? (profileOrganization ?? null) : (profileAccess?.contexts[0]?.organization_id ?? null), opportunity_category: values.opportunity_category ?? profileAccess?.contexts[0]?.type ?? '', } : {}), 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 archiveAvailable = Boolean(usePage().props.opportunityManagement); const set = (key: string, value: string) => setData((d) => ({ ...d, [key]: value })); async function send(action: 'save' | 'delete' | 'archive' | '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 ? `${basePath}/${record.id}/draft` : `${basePath}/drafts` : `${basePath}/${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(`${basePath}/${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 ( {profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'} {profileMode && record && readOnly && canEditDraft && ( Editar proposta privada )} {profileMode && !record && ( )} {profileMode && record && (

Estado da preparação:{' '} {(workflowState ?? record.status) === 'published' ? 'Versão disponibilizada' : (states[workflowState ?? record.status] ?? workflowState ?? record.status)} . {publicationState?.label}.{' '} {profileContext?.request_archive ? 'Pedido de arquivo registado; aguarda decisão independente.' : ''}{' '} O Promotor solicita arquivo; não elimina nem restaura oportunidades.

)}

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. Guardar não submete: use as ações do workflow para revisão, aprovação e publicação independentes.

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

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

)}
{ e.preventDefault(); void send('save'); }} > {!profileMode && (

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' ? (