import { useEffect, useRef, useState } from 'react'; import { Link, router } from '@inertiajs/react'; import { Frame, card, input, button } from '@/pages/investment/shared'; import { profileJson, ProfileValidationError } from '@/lib/profile-json'; import { createOperationKey } from '@/lib/operation-key'; import { PreparationAttempt, swotDimensions, type SwotRow, type Workspace, } from '@/lib/investment-preparation'; const apiStates: Record = { preparing: 'Em preparação', ready: 'Pronto para entrega', delivery_recorded: 'Entrega registada', decision_received: 'Decisão recebida', }; const externalKinds: Record = { delivery: 'Entrega externa', clarification: 'Pedido de esclarecimento', response: 'Resposta ao esclarecimento', decision: 'Decisão recebida', }; export default function Preparation({ workspace }: { workspace: Workspace }) { return ( ); } function PreparationEditor({ initial }: { initial: Workspace }) { const [view, setView] = useState(initial), [tab, setTab] = useState<'apiex' | 'swot'>('apiex'); const [swot, setSwot] = useState({ ...initial.swot, object_key: initial.swot.object_key || 'investment:' + initial.case.id, source_fingerprint: initial.swot.source_fingerprint || initial.swot_fingerprint, }); const [note, setNote] = useState(initial.apiex.note ?? ''), [additional, setAdditional] = useState( initial.apiex.additional_documents, ); const [reason, setReason] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState(''), [pending, setPending] = useState(false), [recovery, setRecovery] = useState(null); const [apiDirty, setApiDirty] = useState(false), [swotDirty, setSwotDirty] = useState(false); const dirty = tab === 'apiex' ? apiDirty : swotDirty; function setDirty(value: boolean) { if (tab === 'apiex') setApiDirty(value); else setSwotDirty(value); } const [external, setExternal] = useState({ kind: 'delivery', date: '', reference: '', proof_document: '', export_id: '', related_id: '', outcome: '', }); const [action, setAction] = useState({ conclusion_id: '', kind: 'risk', title: '', }); const attempt = useRef(new PreparationAttempt()), running = useRef(false); const base = '/investimentos/' + view.case.id + '/preparacao', query = view.initial_scope ? '?history_scope=dossier' : view.opportunity ? '?opportunity=' + encodeURIComponent(view.opportunity) : ''; useEffect(() => { const unsaved = apiDirty || swotDirty || pending || busy; if (!unsaved) return; const leave = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ''; }; window.addEventListener('beforeunload', leave); const off = router.on('before', (event) => { if ( !window.confirm( 'Existem campos locais ou uma confirmação pendente. Sair sem os guardar?', ) ) event.preventDefault(); }); return () => { window.removeEventListener('beforeunload', leave); off(); }; }, [apiDirty, swotDirty, pending, busy]); function download(id: string) { const a = document.createElement('a'); a.href = base + '/exportar/' + encodeURIComponent(id) + query; a.download = ''; a.click(); } async function send(body: Record) { if (running.current) return; running.current = true; setBusy(true); setError(''); try { const next = (await profileJson(base, body)) as Workspace; setView(next); attempt.current.complete(); setPending(false); setRecovery(null); if (body.action === 'swot_save' || body.action === 'swot_restore') { setSwot({ ...next.swot, source_fingerprint: next.swot.source_fingerprint || next.swot_fingerprint, }); setSwotDirty(false); } if (body.action === 'swot_review') setSwot((old) => ({ ...old, source_fingerprint: next.swot.source_fingerprint, })); if (body.action === 'apiex_save') setApiDirty(false); if (body.action === 'external') setExternal((old) => ({ ...old, date: '', reference: '', proof_document: '', related_id: '', outcome: '', })); if (body.action === 'apiex_export') { download(String(body.operation_key)); setExternal((old) => ({ ...old, export_id: String(body.operation_key), })); setNotice( 'Pacote preparado para descarga. Exportar não submete nem regista entrega externa.', ); } else setNotice( 'Versão ' + next.version + ' guardada. Dados e histórico anteriores preservados.', ); } catch (e) { setError( e instanceof Error ? e.message : 'Não foi possível confirmar a gravação.', ); setPending(true); if ( e instanceof ProfileValidationError && (e.status === null || (e.status >= 400 && e.status < 500 && e.status !== 408)) ) { attempt.current.complete(); setPending(false); setError(e.message + ' ' + Object.values(e.fields).join(' ')); } } finally { running.current = false; setBusy(false); } } function act(kind: string, data: Record = {}) { if (running.current || pending) return; void send( attempt.current.start( view.version, view.opportunity, kind, data, reason.trim() || 'Operador confere e guarda esta versão do dossier', ), ); } async function consult() { if (running.current) return; running.current = true; setBusy(true); try { setRecovery( (await profileJson(base + query, {}, 'GET')) as Workspace, ); } catch (e) { setError(e instanceof Error ? e.message : 'Consulta indisponível'); } finally { running.current = false; setBusy(false); } } function adopt() { if (!recovery || !attempt.current.canAdopt(recovery)) return; setView(recovery); setSwot({ ...recovery.swot, object_key: recovery.swot.object_key || 'investment:' + view.case.id, source_fingerprint: recovery.swot.source_fingerprint || recovery.swot_fingerprint, }); setNote(recovery.apiex.note ?? ''); setAdditional(recovery.apiex.additional_documents); attempt.current.complete(); setPending(false); setApiDirty(false); setSwotDirty(false); setRecovery(null); } async function olderHistory() { if (running.current || busy || !view.history_next) return; running.current = true; setBusy(true); try { const next = (await profileJson( base + query + (query ? '&' : '?') + 'history_before=' + view.history_next, {}, 'GET', )) as Workspace; setView((old) => ({ ...old, history: [ ...new Map( [...old.history, ...next.history].map((h) => [ h.version, h, ]), ).values(), ], history_next: next.history_next, })); } catch (e) { setError( e instanceof Error ? e.message : 'Não foi possível consultar o histórico.', ); } finally { running.current = false; setBusy(false); } } function keepLocal() { if (!recovery || !attempt.current.canAdopt(recovery)) return; setView(recovery); setApiDirty(true); setSwotDirty(true); attempt.current.complete(); setPending(false); setRecovery(null); setNotice( 'Campos locais mantidos; fontes e versão do servidor actualizadas. Compare,guarde e reveja antes de avançar.', ); } const change = (id: string, patch: Partial) => { setSwot((old) => ({ ...old, rows: old.rows.map((r) => (r.id === id ? { ...r, ...patch } : r)), })); setDirty(true); }; const exportId = external.export_id || (view.apiex.exports.length === 1 ? view.apiex.exports[0].id : ''); const locked = busy || pending; return (

{view.case.title} · Oportunidade:{' '} {view.opportunity_label ?? 'contexto único do dossier'} · Versão{' '} {view.version}

Voltar ao mesmo dossier {view.historical && (

Oportunidade retirada das escolhas actuais. Consulta histórica preservada; não são alteradas as escolhas nem os dados actuais do dossier.

)}

Preparação privada. Não há ligação de recepção electrónica APIEX. Exportação, entrega externa e decisão são registos distintos. A SWOT apoia a decisão; não produz pontuação automática.

{error && (

{error} Os campos locais foram conservados.

)} {notice &&

{notice}

} {pending && (

A confirmação está pendente. Repetir conserva exactamente a mesma tentativa,sem duplicar o registo.

)} {recovery && (

Versão do servidor: {recovery.version}

Consultar não substitui os campos locais. Compare antes de recuperar.

                            {JSON.stringify(
                                { apiex: recovery.apiex, swot: recovery.swot },
                                null,
                                2,
                            )}
                        
)}
{tab === 'apiex' ? ( <>

1. Requisitos — {apiStates[view.api_state]}

Alterar dados e enquadramento reutilizados

Dados do investidor,empresa,oportunidade e localização provêm do contexto autorizado. Não é formulário oficial nem aprovação.

Resumo dos dados reutilizados — consultar
                                        {JSON.stringify(
                                            view.context.fields,
                                            null,
                                            2,
                                        )}
                                    
    {view.assessment.requirements.map((r) => (
  • {r.label}:{' '} {r.state === 'not_applicable' ? 'Não aplicável' : r.available ? 'Disponível' : r.state === 'indeterminate' ? 'Por determinar' : 'Em falta/indisponível'}

    {r.reason} ·{' '} {r.source.reference}

  • ))}
{!!view.api_issues.length && (

Falta completar ou conferir

    {view.api_issues.map((v, i) => (
  • {v}
  • ))}
)}

2. Documentos e modelos existentes

Completar ou associar documentos no mesmo dossier {' '} Consultar modelos e documentos na biblioteca deste contexto

Os anexos exigidos são incluídos pela associação existente. Escolha outros modelos/documentos já disponíveis,sem criar formulários oficiais.

Anexos adicionais — consultar ou alterar {view.documents.map((d) => ( ))}