import { ProactivePublicationFields, ProactiveSummary, newPublicProactive, type ProactivePublic, type ProactiveEvidence, type ProactiveOptions, } from '@/components/proactive-investment'; import { Link, router } from '@inertiajs/react'; import { useState } from 'react'; import { createOperationKey } from '@/lib/operation-key'; import { profileJson, ProfileValidationError } from '@/lib/profile-json'; import { Management, Field, control, button } from './shared'; type Draft = { proactive_public?: ProactivePublic; proactive_reviewed?: boolean; title: string; summary: string; description: string; limitations: string; source_reference: string; edition: string; source_date: string; sector_id: number | null; territory_ids: string[]; }; type Projection = { title: string; summary: string; description: string; sector_id: number | null; maturity_label: string; territories: { id: string; label: string }[]; proactive?: ProactivePublic; }; type Preview = { token: string; action: 'disclose' | 'withdraw'; projection: Projection; current: { title: string; summary: string; description: string; status: string; }; }; export default function OpportunityPromotion({ proactiveEnabled = false, proactiveKind, proactiveRelations = [], proactiveEvidence = [], proactiveOptions, record, initial, etag, publicNow, reauthenticationRequired, sectors, territories, history, }: { proactiveRelations?: { id: string; label: string; relationship: string }[]; proactiveEnabled?: boolean; proactiveKind?: string; proactiveEvidence?: ProactiveEvidence[]; proactiveOptions?: ProactiveOptions; record: { id: number; reference: string }; initial: Draft; etag: string; publicNow: boolean; reauthenticationRequired: boolean; sectors: { id: number; name: string }[]; territories: { id: string; name: string; location_type: string }[]; history: { id: string; action: string; actor_user_id: number; occurred_at: string; }[]; }) { const [draft, setDraft] = useState({ ...initial, source_date: initial.source_date ?? '', ...(proactiveEnabled ? { proactive_public: initial.proactive_public ?? { ...newPublicProactive(), group: proactiveKind ?? 'ideas', }, proactive_reviewed: false, } : {}), }); const [preview, setPreview] = useState(null); const [operationKey, setOperationKey] = useState(createOperationKey); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(''); const [errors, setErrors] = useState>({}); const [needsMfa, setNeedsMfa] = useState(reauthenticationRequired); function change(key: K, value: Draft[K]) { setDraft((current) => ({ ...current, [key]: value })); setPreview(null); setConfirmed(false); } function report(error: unknown) { setMessage( error instanceof Error ? error.message : 'Não foi possível concluir. A ficha anterior foi preservada.', ); setErrors(error instanceof ProfileValidationError ? error.fields : {}); if (error instanceof ProfileValidationError && error.reauthenticate) setNeedsMfa(true); } function renewAuthentication() { router.post( '/logout', {}, { onSuccess: () => router.visit( `/minhas-oportunidades/${record.id}/divulgacao`, ), }, ); } async function prepare(action: 'disclose' | 'withdraw') { setBusy(true); setMessage(''); setErrors({}); setPreview(null); setConfirmed(false); try { const result = await profileJson( `/minhas-oportunidades/${record.id}/divulgacao/previa`, { ...draft, etag, action }, ); setPreview(result); setOperationKey(createOperationKey()); } catch (error) { report(error); } finally { setBusy(false); } } async function publish() { if (!preview || !confirmed) return; setBusy(true); setErrors({}); try { const result = await profileJson( `/minhas-oportunidades/${record.id}/divulgacao/confirmar`, { token: preview.token, operation_key: operationKey, reason, confirm: confirmed, }, ); setMessage(result.message); setPreview(null); setConfirmed(false); router.reload(); } catch (error) { report(error); } finally { setBusy(false); } } const labels: Record = { promotional_summary_published: 'Resumo divulgado', promotional_summary_updated: 'Resumo actualizado', promotional_summary_withdrawn: 'Resumo retirado', }; return ( Voltar à oportunidade

Prepare o resumo público e reveja a prévia antes de confirmar. A divulgação fica identificada como Em preparação{' '} e não autoriza a execução do investimento. Documentos e contactos do cadastro continuam privados.

{publicNow ? 'Resumo actualmente divulgado.' : 'Resumo não divulgado.'}{' '} {message}

{needsMfa && (

Entre novamente com a sua conta e MFA para confirmar esta operação. O cadastro guardado permanece disponível; a prévia ainda não confirmada terá de ser preparada novamente.{' '}

)} {Object.entries(errors).map(([key, value]) => (

{key}: {value}

))}
{ e.preventDefault(); void prepare('disclose'); }} > {proactiveEnabled && draft.proactive_public && ( { change('proactive_public', v); change('proactive_reviewed', false); }} evidence={proactiveEvidence} relations={proactiveRelations} options={proactiveOptions} reviewed={Boolean(draft.proactive_reviewed)} onReview={(v) => change('proactive_reviewed', v)} /> )} change('title', e.target.value)} />