import { Head } from '@inertiajs/react'; import { useRef, useState, type FormEvent } from 'react'; import FiscalQaPreview from '@/components/fiscal-qa-preview'; import { readVersionedArithmeticReportReference } from '@/lib/simulation-form'; import { isApiSimulationCreateResponseV1, isApiSimulationReadResponseV1, isApiSimulationHistoryResponseV1, isApiSimulationResultSnapshotV1, type ApiSimulationExecutionV1, type ApiSimulationHistoryEntryV1, } from '@/lib/simulation-contract'; class ReviewOperationError extends Error {} /** Review-only UI: it calls the existing authenticated QA API and immutable report reader. */ export default function FiscalQaReview({ rule, }: { rule: { id: string; code: string; version: number }; }) { const [base, setBase] = useState(''); const [date, setDate] = useState(''); const [currency, setCurrency] = useState(''); const [declared, setDeclared] = useState(false); const [selected, setSelected] = useState( null, ); const [history, setHistory] = useState([]); const [report, setReport] = useState<{ id: string; hash: string; snapshot: unknown; } | null>(null); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(''); const key = useRef(null); const gate = useRef(false); const changed = () => { key.current = null; }; const statusLabel = (status: string) => ({ queued: 'na fila', running: 'em processamento', completed: 'concluída', failed: 'não concluída', cancelled: 'cancelada', })[status] ?? 'recebida'; async function request( url: string, body?: Record, ): Promise { const xsrf = decodeURIComponent( document.cookie .split('; ') .find((part) => part.startsWith('XSRF-TOKEN=')) ?.slice(11) ?? '', ); const response = await fetch(url, { method: body ? 'POST' : 'GET', credentials: 'same-origin', headers: { Accept: 'application/json', ...(body ? { 'Content-Type': 'application/json', 'X-XSRF-TOKEN': xsrf, 'Idempotency-Key': key.current!, } : {}), }, ...(body ? { body: JSON.stringify(body) } : {}), }); if (!response.ok) throw new ReviewOperationError( response.status === 401 || response.status === 419 ? 'A sessão expirou. Inicie sessão e consulte o histórico antes de voltar a calcular.' : 'Não foi possível concluir a operação. Reveja as entradas e consulte o histórico antes de tentar novamente.', ); return response.json(); } async function action(work: () => Promise) { if (gate.current) return; gate.current = true; setBusy(true); setMessage(''); try { await work(); } catch (cause) { console.error('[fiscal-qa-review]', cause); setMessage( cause instanceof ReviewOperationError ? cause.message : 'Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.', ); } finally { gate.current = false; setBusy(false); } } async function recover(id: string) { const payload = await request(`/api/v1/simulations/${id}`); if (!isApiSimulationReadResponseV1(payload)) throw new ReviewOperationError( 'O resultado guardado tem formato incompatível.', ); setSelected(payload.data); setReport(null); return payload.data; } async function calculate(event: FormEvent) { event.preventDefault(); await action(async () => { key.current ??= crypto.randomUUID(); const payload = await request( `/api/v2/investment/admin/tax-rules/${rule.id}/qa-preview`, { base, currency, reference_date: date, operation: 'internal_general_net', }, ); if (!isApiSimulationCreateResponseV1(payload)) throw new ReviewOperationError( 'A execução devolveu um formato incompatível.', ); let simulation = await recover(payload.data.id); for ( let attempt = 0; attempt < 10 && ['queued', 'running'].includes(simulation.status); attempt++ ) { await new Promise((resolve) => setTimeout(resolve, 500)); simulation = await recover(payload.data.id); } setMessage( simulation.status === 'completed' ? 'Execução concluída e gravada no histórico. Pode recuperar esta execução e consultar o relatório guardado.' : 'A execução foi gravada e continua pendente. Consulte o histórico para a recuperar.', ); }); } async function loadHistory() { const payload = await request( '/api/v1/simulations/history?per_page=10', ); if (!isApiSimulationHistoryResponseV1(payload)) throw new ReviewOperationError( 'O histórico devolveu um formato incompatível.', ); setHistory(payload.data); } async function loadReport() { const reference = readVersionedArithmeticReportReference(selected); if (!selected || !reference) throw new ReviewOperationError( 'O relatório ainda não está disponível para esta execução.', ); const payload = (await request( `/api/v1/simulations/${selected.id}/reports/${reference.id}`, )) as { data?: { id?: string; report_sha256?: string; report_snapshot?: unknown; }; }; if ( payload.data?.id !== reference.id || payload.data.report_sha256 !== reference.report_sha256 || !isApiSimulationResultSnapshotV1(payload.data.report_snapshot) ) { throw new ReviewOperationError( 'O relatório guardado não corresponde à referência desta execução.', ); } setReport({ id: reference.id, hash: reference.report_sha256, snapshot: payload.data.report_snapshot, }); } const field = 'mt-1 block w-full rounded border border-slate-400 p-2'; const button = 'rounded border border-emerald-800 px-4 py-2 font-semibold disabled:opacity-50'; return (

Revisão do lote IVA em QA

{rule.code} · versão {rule.version} · rascunho, sem activação. Cobertura demonstrada: 2026.

Este percurso calcula IVA sobre uma base já apurada, em contexto declarado. Não determina elegibilidade, isenção, saldo de declaração ou valor a pagar. O cálculo exacto não aplica arredondamento automático.

void calculate(event)} className="space-y-4 rounded border p-4" >
{message && (

{message}

)} {selected && (

Execução seleccionada

ID: {selected.id} · estado:{' '} {statusLabel(selected.status)}

)}

Histórico da conta

    {history.map((entry) => (
  • {entry.id} · {statusLabel(entry.status)}{' '}
  • ))}
{report && (

Relatório guardado

ID do relatório: {report.id}

SHA256: {report.hash}

Conteúdo recuperado do relatório imutável, sem novo cálculo.

)}
); }