import { useRef, useState } from 'react'; import { Link, router } from '@inertiajs/react'; import { Frame, card, input, button } from './shared'; import { profileJson, ProfileValidationError } from '@/lib/profile-json'; import { createOperationKey } from '@/lib/operation-key'; import { guideChoices, guideUrl } from '@/lib/investment-guides'; type Guide = { slug: string; version: string; sha256: string; title: string; reviewed_on: string; scope: string; selection_label?: string; selection_hint?: string; cards_title?: string; eligibility_title?: string; preparation_title?: string; requirements?: GuideRequirement[]; documents?: { id: string; title: string; text: string; paths: string[]; citations: GuideCitation[]; }[]; handoffs?: { title: string; url: string; note: string }[]; instruments: Record< string, { title: string; description: string; risks: string[]; prepare: string[]; sources: string[]; requirements?: GuideRequirement[]; } >; sources: Record< string, { title: string; url: string; edition: string; locator: string; consulted_on: string; sha256: string | null; valid_until?: string; } >; eligibility: { text: string; sources: string[]; citations?: GuideCitation[]; }[]; preparation: { title: string; text: string; sources: string[]; responsible?: string; citations?: GuideCitation[]; }[]; next: string[]; limits: string[]; }; type GuideCitation = { source: string; reference: string; page: number }; type GuideRequirement = { id: string; text: string; kind: 'requirement' | 'exception' | 'gap'; citations: GuideCitation[]; }; type Props = { guide: Guide; instruments: string[]; note: string; case: { id: string; title: string; version: number } | null; saved: { revision: number; at: string; note: string; instruments: string[]; guide: Guide; context: { revision: number }; } | null; canWrite: boolean; historical: boolean; olderEdition: boolean; currentAvailable: boolean; workingCopy: boolean; contextChanged: boolean; unavailableInstruments: string[]; history: { id: string; revision: number; at: string; edition: string }[]; historyNext: number | null; }; export default function InvestmentGuide(props: Props) { return ( ); } function GuideView(props: Props) { const { guide, saved, historical, olderEdition } = props; const dossier = props.case; const [selected, setSelected] = useState(props.instruments); const [note, setNote] = useState(props.note); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [recovery, setRecovery] = useState(null); const [version, setVersion] = useState(dossier?.version ?? 0); const form = useRef(null); const operation = useRef(createOperationKey()); const base = dossier ? `/investimentos/${dossier.id}/guias/${guide.slug}` : `/guias-investimento/${guide.slug}`; const readOnly = historical || olderEdition || (!!dossier && !props.canWrite); const visible = selected.length ? selected : Object.keys(guide.instruments); function sourceLinks(keys: string[]) { return (

Fontes:{' '} {keys.map((key) => ( {guide.sources[key]?.title ?? key} ))}

); } function citations(items: GuideCitation[] = []) { return ( ); } function requirements(items: GuideRequirement[] = []) { return (
    {items.map((item) => (
  • { { gap: 'Por esclarecer', exception: 'Regra com dispensa ou condição específica', requirement: 'Conferir requisito', }[item.kind] } : {' '} {item.text}

    {citations(item.citations)}
  • ))}
); } function choose() { router.visit( guideUrl( '/investimentos', { slug: guide.slug, sha256: guide.sha256, instruments: guideChoices(form.current!), }, true, ), ); } async function save() { if (!dossier || busy || readOnly) return; setBusy(true); setError(''); const values = new FormData(form.current!); const currentNote = values.get('note'); const chosen = guideChoices(form.current!); const text = typeof currentNote === 'string' ? currentNote : note; setNote(text); setSelected(chosen); try { await profileJson(base, { version, operation_key: operation.current, sha256: guide.sha256, instruments: chosen, note: text, }); router.visit(base, { preserveState: false }); } catch (e) { setError( e instanceof Error ? e.message : 'Não foi possível guardar. A nota continua nesta página.', ); if ( e instanceof ProfileValidationError && Object.values(e.fields).length ) setError(Object.values(e.fields).join(' ')); } finally { setBusy(false); } } async function recover() { setBusy(true); try { setRecovery(await profileJson(base, {}, 'GET')); } catch (e) { setError( e instanceof Error ? e.message : 'Não foi possível consultar o dossier.', ); } finally { setBusy(false); } } return ( {dossier && (

Dossier:{' '} {dossier.title}

)}

{guide.scope}

Edição {guide.version} · Conteúdo conferido em{' '} {guide.reviewed_on}.

{saved && (

{historical ? 'Referência histórica' : 'Última referência guardada'} : revisão {saved.revision} · {saved.at} · contexto{' '} {saved.context.revision}. {props.workingCopy && ' Esta preparação ainda não substitui a referência guardada.'}

)} {props.contextChanged && (

Os dados de contexto disponíveis nesta consulta diferem dos utilizados na referência. Confira a sua pertinência; a edição guardada conserva o contexto anterior.

)} {props.unavailableInstruments.length > 0 && (

Esta edição deixou de incluir:{' '} {props.unavailableInstruments.join(', ')}. A selecção e o conteúdo anteriores continuam na referência guardada e no histórico.

)} {(historical || olderEdition) && (

Consulta preservada da edição utilizada.{' '} {props.currentAvailable ? ( Preparar uma nova referência com o guia actual ) : ( 'O guia foi retirado da consulta actual; esta referência continua disponível.' )}

)}
{ e.preventDefault(); if (dossier) void save(); else choose(); }} className={card} >
{guide.selection_label ?? 'Que instrumentos pretende aprofundar?'}

{guide.selection_hint ?? 'Sem selecção, consulte o conjunto. Pode combinar instrumentos; a selecção organiza a consulta e não é uma recomendação.'}

{Object.entries(guide.instruments).map(([code, item]) => ( ))} {dossier && (