Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import { fiscalQaRows } from "@/lib/fiscal-qa-preview";
|
||||
|
||||
export default function FiscalQaPreview({ snapshot }: { snapshot: unknown }) {
|
||||
const rows = fiscalQaRows(snapshot);
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<section
|
||||
aria-label="Resultado fiscal preservado"
|
||||
className="my-3 rounded border border-amber-700 bg-amber-50 p-3"
|
||||
>
|
||||
<h5 className="font-semibold">
|
||||
{rows[0][1]} — cálculo exacto sem arredondamento
|
||||
</h5>
|
||||
<dl className="mt-2 space-y-2 text-sm">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="font-medium">{label}</dt>
|
||||
<dd className="break-all">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { SimulationPublishedIva, type PublishedIvaInput } from './simulation-published-iva';
|
||||
import {
|
||||
PublicDocumentContent,
|
||||
type PublicDocument,
|
||||
} from '@/components/public-document-content';
|
||||
import { DossierPrefill } from '@/components/dossier-prefill';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import FiscalQaPreview from './fiscal-qa-preview';
|
||||
import { displayValue } from '@/lib/display-value';
|
||||
import {
|
||||
useCallback,
|
||||
@@ -886,6 +888,7 @@ export function SimulationForm() {
|
||||
() => readVersionedArithmeticReportReference(result),
|
||||
[result],
|
||||
);
|
||||
const isFiscalQaPreview = ['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(arithmeticSnapshot?.scenario_kind));
|
||||
const versionedReportMissing =
|
||||
arithmeticResult.integrity === 'versioned' &&
|
||||
arithmeticReportReference === null;
|
||||
@@ -2157,15 +2160,15 @@ export function SimulationForm() {
|
||||
);
|
||||
}
|
||||
|
||||
async function runSimulation() {
|
||||
async function runSimulation(publishedInput?: PublishedIvaInput) {
|
||||
if (calculationInFlightRef.current) return;
|
||||
const validation = validateSimulationDraft(draft, 'tax');
|
||||
if (draft.fiscal_scenario_mode === 'custom_planning') {
|
||||
const validation = publishedInput ? {} : validateSimulationDraft(draft, 'tax');
|
||||
if (!publishedInput && draft.fiscal_scenario_mode === 'custom_planning') {
|
||||
Object.assign(validation, validateCustomFiscalPlanning(draft));
|
||||
}
|
||||
setErrors(validation);
|
||||
setServerError('');
|
||||
if (draft.fiscal_scenario_mode !== 'custom_planning') return;
|
||||
if (!publishedInput && draft.fiscal_scenario_mode !== 'custom_planning') return;
|
||||
if (Object.keys(validation).length) {
|
||||
document
|
||||
.getElementById(`field-${Object.keys(validation)[0]}`)
|
||||
@@ -2176,7 +2179,7 @@ export function SimulationForm() {
|
||||
setIsCalculating(true);
|
||||
try {
|
||||
const xsrf = csrfToken();
|
||||
const body = {
|
||||
const body = publishedInput ?? {
|
||||
base: draft.base,
|
||||
rate: draft.rate,
|
||||
reduction: draft.reduction,
|
||||
@@ -2284,7 +2287,7 @@ export function SimulationForm() {
|
||||
}
|
||||
}
|
||||
if (
|
||||
JSON.stringify({
|
||||
publishedInput || JSON.stringify({
|
||||
base: draft.base,
|
||||
rate: draft.rate,
|
||||
reduction: draft.reduction,
|
||||
@@ -2304,7 +2307,7 @@ export function SimulationForm() {
|
||||
'O cálculo não foi concluído. Os dados introduzidos foram preservados.',
|
||||
);
|
||||
}
|
||||
sessionStorage.removeItem(idempotencyStorageKey);
|
||||
if (!publishedInput) sessionStorage.removeItem(idempotencyStorageKey);
|
||||
} catch (cause) {
|
||||
setServerError(
|
||||
cause instanceof Error
|
||||
@@ -3598,6 +3601,7 @@ export function SimulationForm() {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{current.id === 'tax' && <SimulationPublishedIva busy={isCalculating} onCalculate={runSimulation} />}
|
||||
{current.id === 'tax' && (
|
||||
<div
|
||||
id="draft-tool-fiscal"
|
||||
@@ -3695,8 +3699,8 @@ export function SimulationForm() {
|
||||
O período e as respostas servem para encaminhar uma
|
||||
exploração informativa. A residência é auto-indicada ou
|
||||
fica por determinar; não é inferida por nacionalidade ou
|
||||
dias de presença. Regras de 2026 continuam pendentes de
|
||||
validação e este formulário não determina cumprimento
|
||||
dias de presença. Cada cálculo identifica a regra, versão, cobertura e
|
||||
limitações; este formulário não determina cumprimento
|
||||
fiscal. Um crédito estimado de IVA não significa pedido
|
||||
aprovado nem dinheiro disponível. Não carregue
|
||||
documentos nesta simulação exploratória.
|
||||
@@ -3705,7 +3709,7 @@ export function SimulationForm() {
|
||||
{(current.id === 'tax' || result) && (
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<h4 className="font-semibold">
|
||||
{current.id === 'tax'
|
||||
{isFiscalQaPreview ? (arithmeticSnapshot?.scenario_kind === 'fiscal_rule_published' ? 'IVA pela versão publicada seleccionada' : 'Pré-visualização fiscal QA seleccionada') : current.id === 'tax'
|
||||
? 'Cenário personalizado de planeamento'
|
||||
: 'Resultado histórico seleccionado'}
|
||||
</h4>
|
||||
@@ -3769,7 +3773,7 @@ export function SimulationForm() {
|
||||
submetido.
|
||||
</p>
|
||||
)}
|
||||
{result.status === 'completed' && (
|
||||
{result.status === 'completed' && !isFiscalQaPreview && (
|
||||
<p>
|
||||
Resultado aritmético indicativo:{' '}
|
||||
<strong className="break-all">
|
||||
@@ -3806,9 +3810,10 @@ export function SimulationForm() {
|
||||
taxas legais, elegibilidade ou obrigação
|
||||
fiscal.
|
||||
</p>
|
||||
{isFiscalQaPreview && <FiscalQaPreview snapshot={result.result_snapshot} />}
|
||||
{result.status === 'completed' && (
|
||||
<div className="mt-3 space-y-2 border-t pt-3">
|
||||
{arithmeticResult.integrity !==
|
||||
{!isFiscalQaPreview && arithmeticResult.integrity !==
|
||||
'invalid' && (
|
||||
<details className="rounded border p-3">
|
||||
<summary className="cursor-pointer font-semibold focus-visible:outline-2">
|
||||
@@ -4179,8 +4184,7 @@ export function SimulationForm() {
|
||||
'não identificada',
|
||||
'não identificada',
|
||||
)}{' '}
|
||||
· resultado
|
||||
aritmético{' '}
|
||||
· {['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(source.result_snapshot.scenario_kind)) ? 'IVA calculado exacto' : 'resultado aritmético'}{' '}
|
||||
{displayScalar(
|
||||
sourceResult.value ??
|
||||
(sourceResult.integrity ===
|
||||
@@ -4419,7 +4423,9 @@ export function SimulationForm() {
|
||||
e, se já escolhido, o cálculo percentual
|
||||
personalizado. Consultar parâmetros fiscais
|
||||
apresenta fontes e lacunas; não determina imposto
|
||||
devido.
|
||||
devido. Na etapa Operação fiscal encontra também
|
||||
o cálculo de IVA geral sobre base líquida, quando
|
||||
activado, com âmbito e versão identificados.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export type PublishedIvaInput = {
|
||||
scenario_kind: 'fiscal_rule_published';
|
||||
base: string;
|
||||
currency: 'MZN';
|
||||
reference_date: string;
|
||||
operation: 'internal_general_net';
|
||||
scope_declared: boolean;
|
||||
};
|
||||
|
||||
export function SimulationPublishedIva({ busy, onCalculate }: {
|
||||
busy: boolean;
|
||||
onCalculate: (input: PublishedIvaInput) => Promise<void>;
|
||||
}) {
|
||||
const [available, setAvailable] = useState(false);
|
||||
const [message, setMessage] = useState('A consultar disponibilidade do cálculo de IVA…');
|
||||
const [base, setBase] = useState('');
|
||||
const [date, setDate] = useState('');
|
||||
const [currency, setCurrency] = useState('');
|
||||
const [declared, setDeclared] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
fetch('/api/v1/fiscal-consumer', { credentials: 'same-origin', headers: { Accept: 'application/json' } })
|
||||
.then(async (response) => {
|
||||
if (!response.ok) throw new Error();
|
||||
const payload = await response.json();
|
||||
if (!active) return;
|
||||
setAvailable(payload?.data?.enabled === true);
|
||||
setMessage(typeof payload?.data?.message === 'string' ? payload.data.message : 'Cálculo de IVA indisponível.');
|
||||
}).catch(() => { if (active) setMessage('Não foi possível consultar a disponibilidade do IVA. As entradas e históricos foram preservados.'); });
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
|
||||
async function calculate() {
|
||||
if (!/^\d+(?:\.\d+)?$/.test(base) || base.length > 40 || !date || currency !== 'MZN') {
|
||||
setError('Indique uma base líquida decimal válida, a moeda MZN e a data de exigibilidade. As entradas foram preservadas.');
|
||||
return;
|
||||
}
|
||||
setError('');
|
||||
await onCalculate({ scenario_kind: 'fiscal_rule_published', base, currency: 'MZN', reference_date: date,
|
||||
operation: 'internal_general_net', scope_declared: declared });
|
||||
// Refresh after admission/refusal so a suspension is reflected without discarding inputs.
|
||||
try {
|
||||
const response = await fetch('/api/v1/fiscal-consumer', { credentials: 'same-origin', headers: { Accept: 'application/json' } });
|
||||
if (!response.ok) return;
|
||||
const payload = await response.json();
|
||||
setAvailable(payload?.data?.enabled === true);
|
||||
if (typeof payload?.data?.message === 'string') setMessage(payload.data.message);
|
||||
} catch { /* The execution flow already preserves and reports connection errors. */ }
|
||||
}
|
||||
|
||||
return <section aria-label="IVA geral sobre base líquida" className="space-y-3 rounded border border-emerald-700 p-4">
|
||||
<h4 className="font-semibold">IVA geral sobre base líquida</h4>
|
||||
<p role="status">{message}</p>
|
||||
<p className="text-sm">Cobertura: exigibilidade em 2026, operação interna à taxa geral. A base tributável é indicada por si; não é copiada do orçamento. Sem isenções, taxas reduzidas, bases especiais, importações, deduções, declaração ou pagamento. O cálculo não valida o enquadramento jurídico.</p>
|
||||
<fieldset disabled={busy} className="space-y-3">
|
||||
<label className="block">Base tributável líquida (decimal, com ponto)<input aria-label="Base tributável líquida" inputMode="decimal" value={base} onChange={(e) => setBase(e.target.value)} className="block rounded border p-2" /></label>
|
||||
<label className="block">Moeda da base<select aria-label="Moeda da base IVA" value={currency} onChange={(e) => setCurrency(e.target.value)} className="block rounded border p-2"><option value="">Seleccione</option><option value="MZN">MZN</option></select></label>
|
||||
<label className="block">Data de exigibilidade declarada<input aria-label="Data de exigibilidade IVA" type="date" min="2026-01-01" max="2026-12-31" value={date} onChange={(e) => setDate(e.target.value)} className="block rounded border p-2" /></label>
|
||||
<label className="block"><input type="checkbox" checked={declared} onChange={(e) => setDeclared(e.target.checked)} /> Declaro operação interna à taxa geral, base líquida já apurada e ausência das excepções acima.</label>
|
||||
<p className="text-sm">Sem esta declaração, o resultado fica indeterminado. O valor calculado conserva a precisão decimal; não é saldo a pagar.</p>
|
||||
<button type="button" disabled={!available || busy} onClick={() => void calculate()} className="rounded bg-emerald-800 px-4 py-2 text-white disabled:opacity-50">{busy ? 'A calcular…' : 'Calcular IVA e gravar'}</button>
|
||||
</fieldset>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { isApiSimulationResultSnapshotV1 } from "./simulation-contract.ts";
|
||||
|
||||
export function fiscalQaRows(value: unknown): Array<[string, string]> {
|
||||
if (!isApiSimulationResultSnapshotV1(value)) return [];
|
||||
const snapshot = value as unknown as Record<string, unknown>;
|
||||
if (!["fiscal_rule_qa_preview", "fiscal_rule_published"].includes(String(snapshot.scenario_kind))) return [];
|
||||
const published = snapshot.scenario_kind === "fiscal_rule_published";
|
||||
const provenance = snapshot.fiscal_provenance as
|
||||
Record<string, unknown> | undefined;
|
||||
const rule = provenance?.rule as Record<string, unknown> | undefined;
|
||||
const source = rule?.source as Record<string, unknown> | undefined;
|
||||
const parameters = rule?.parameters as
|
||||
Record<string, Record<string, unknown>> | undefined;
|
||||
const intermediate = snapshot.intermediate as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const text = (item: unknown) =>
|
||||
typeof item === "string" || typeof item === "number"
|
||||
? String(item)
|
||||
: "não disponível";
|
||||
return [
|
||||
["Relatório", published ? "IVA pela versão publicada; ver enquadramento abaixo" : "Pré-visualização fiscal QA de rascunho — sem activação"],
|
||||
[
|
||||
"IVA calculado (exacto; não é saldo a pagar)",
|
||||
value.result.value ?? "Indeterminado",
|
||||
],
|
||||
["Explicação", value.result.explanation],
|
||||
["Base tributável declarada", text(snapshot.base)],
|
||||
["Taxa cadastrada (%)", text(parameters?.IVA_GENERAL_RATE?.value)],
|
||||
["Moeda explícita", text(value.context.currency)],
|
||||
["Data de exigibilidade declarada", value.context.reference_date],
|
||||
[
|
||||
"Enquadramento",
|
||||
provenance?.scope_status === "undetermined" ? "Indeterminado: falta declaração do enquadramento" : "Declarado pelo utilizador; não validado juridicamente",
|
||||
],
|
||||
[
|
||||
"Regra / versão / estado",
|
||||
`${text(rule?.rule_code)} / ${text(rule?.rule_version)} / ${published ? "publicada no momento da admissão" : "rascunho"}`,
|
||||
],
|
||||
[
|
||||
"Vigência cadastrada",
|
||||
`${text(rule?.valid_from)} até ${rule?.valid_until === null ? "sem termo indicado" : text(rule?.valid_until)}`,
|
||||
],
|
||||
[
|
||||
"Fonte da taxa",
|
||||
`${text(source?.diploma)} — ${text(source?.article)}`,
|
||||
],
|
||||
["Hash do exemplar da taxa", text(rule?.source_sha256)],
|
||||
["Representação racional exacta", text(intermediate?.result)],
|
||||
[
|
||||
"Arredondamento",
|
||||
"Não aplicado. Valor calculado preservado sem truncar ou arredondar; apresentação monetária separada.",
|
||||
],
|
||||
[
|
||||
"Limitações",
|
||||
published ? "Cobertura de 2026; operação interna geral em MZN; sem excepções, deduções, declaração ou saldo a pagar." : "Regra não publicada; cobertura demonstrada em 2026; sem deduções, declaração ou saldo a pagar.",
|
||||
],
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { displayValue } from './display-value.ts';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import {
|
||||
buildProjectDossierRows,
|
||||
type ProjectDossierRow,
|
||||
@@ -344,6 +345,11 @@ function makeSections(
|
||||
}
|
||||
|
||||
const finance = sections.get('finance');
|
||||
if (finance && ['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(currentCalculation?.snapshot?.scenario_kind)) && currentCalculation?.snapshot) {
|
||||
for (const [field, value] of fiscalQaRows(currentCalculation.snapshot)) {
|
||||
finance.rows.push({ field, value, origin: 'Snapshot fiscal preservado; sem recálculo', classification: 'Cálculo exacto; ver estado da regra no snapshot; não é saldo a pagar' });
|
||||
}
|
||||
}
|
||||
if (finance && currentCalculation) {
|
||||
const snapshot = currentCalculation.snapshot;
|
||||
const result =
|
||||
@@ -417,10 +423,12 @@ function makeSections(
|
||||
{
|
||||
field: 'Fórmula e valores usados',
|
||||
value:
|
||||
snapshot && typeof snapshot.formula_version === 'string'
|
||||
['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(snapshot?.scenario_kind))
|
||||
? `Base tributável declarada × taxa cadastrada ÷ 100; cálculo decimal exacto, sem arredondamento. Ver regra e proveniência acima.`
|
||||
: snapshot && typeof snapshot.formula_version === 'string'
|
||||
? `Fórmula ${snapshot.formula_version}; base ${displayValue(snapshot.base, 'não disponível')}; taxa ${displayValue(snapshot.rate_percent, 'não disponível')}%; redução ${displayValue(snapshot.reduction_percent, 'não disponível')}%; moeda ${displayValue(snapshot.currency, 'não indicada')}`
|
||||
: 'A fórmula não foi identificada no snapshot; ver explicação da execução',
|
||||
origin: 'Snapshot guardado; sem aplicação de regra legal',
|
||||
origin: ['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(snapshot?.scenario_kind)) ? (snapshot?.scenario_kind === 'fiscal_rule_published' ? 'Versão publicada na admissão; sem validação jurídica da operação' : 'Snapshot QA de regra em rascunho; sem activação ou validação jurídica da operação') : 'Snapshot guardado; sem aplicação de regra legal',
|
||||
classification: 'Reutilização do resultado existente',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { csvCell } from './csv.js';
|
||||
import { fiscalQaRows } from './fiscal-qa-preview.ts';
|
||||
import { isApiSimulationResultSnapshotV1 } from './simulation-contract.ts';
|
||||
|
||||
export type SimulationDraft = Record<string, string | string[]>;
|
||||
@@ -1674,6 +1675,19 @@ export function readArithmeticSnapshot(
|
||||
}
|
||||
const result = snapshot as Record<string, unknown>;
|
||||
const value = result.indicative_total;
|
||||
if (['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(result.scenario_kind))) {
|
||||
const presentation = result.presentation as Record<string, unknown> | undefined;
|
||||
if (isApiSimulationResultSnapshotV1(result) && fiscalQaRows(result).length > 0 &&
|
||||
result.result.value === value && presentation?.value === value &&
|
||||
presentation?.rounding_applied === false && result.context.currency === 'MZN' &&
|
||||
result.result.unit === 'MZN' &&
|
||||
((result.result.status === 'calculated' && typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value)) ||
|
||||
(result.result.status === 'indeterminate' && value === null && result.result.missing_inputs.length > 0))) {
|
||||
return { integrity: 'versioned', value: value as string | null,
|
||||
context: result.context as unknown as Record<string, unknown>, explanation: result.result.explanation };
|
||||
}
|
||||
return { integrity: 'invalid', value: null, context: null, explanation: null };
|
||||
}
|
||||
if (typeof value !== 'string' || !/^(?:\d+)(?:\.\d+)?$/.test(value)) {
|
||||
return {
|
||||
integrity: 'invalid',
|
||||
@@ -1848,6 +1862,13 @@ export function exportCompletedArithmeticCsv(
|
||||
);
|
||||
}
|
||||
const result = simulation.result_snapshot as Record<string, unknown>;
|
||||
if (['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(String(result.scenario_kind))) {
|
||||
const rows = fiscalQaRows(result);
|
||||
const report = readVersionedArithmeticReportReference(simulation);
|
||||
if (!rows.length || !report) throw new Error('A pré-visualização fiscal não corresponde ao relatório preservado.');
|
||||
return `\uFEFF${[...rows, ['ID do relatório', report.id], ['Hash do relatório', report.report_sha256], ['Data de exportação', exportedAt]]
|
||||
.map((field) => field.map(csvCell).join(',')).join('\r\n')}`;
|
||||
}
|
||||
const decimal = (value: unknown, label: string) => {
|
||||
if (typeof value !== 'string' || !/^(?:\d+)(?:\.\d+)?$/.test(value))
|
||||
throw new Error(
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
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<ApiSimulationExecutionV1 | null>(
|
||||
null,
|
||||
);
|
||||
const [history, setHistory] = useState<ApiSimulationHistoryEntryV1[]>([]);
|
||||
const [report, setReport] = useState<{
|
||||
id: string;
|
||||
hash: string;
|
||||
snapshot: unknown;
|
||||
} | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const key = useRef<string | null>(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<string, string>,
|
||||
): Promise<unknown> {
|
||||
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<void>) {
|
||||
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 (
|
||||
<main className="mx-auto max-w-4xl space-y-5 p-6">
|
||||
<Head title="Revisão do lote IVA em QA" />
|
||||
<h1 className="text-2xl font-semibold">
|
||||
Revisão do lote IVA em QA
|
||||
</h1>
|
||||
<p>
|
||||
{rule.code} · versão {rule.version} · rascunho, sem activação.
|
||||
Cobertura demonstrada: 2026.
|
||||
</p>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<form
|
||||
onSubmit={(event) => void calculate(event)}
|
||||
className="space-y-4 rounded border p-4"
|
||||
>
|
||||
<fieldset disabled={busy} className="space-y-4">
|
||||
<label className="block">
|
||||
Base tributável líquida declarada (decimal com ponto)
|
||||
<input
|
||||
className={field}
|
||||
required
|
||||
inputMode="decimal"
|
||||
pattern="[0-9]+(\.[0-9]+)?"
|
||||
value={base}
|
||||
onChange={(event) => {
|
||||
setBase(event.target.value);
|
||||
changed();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Moeda explícita
|
||||
<select
|
||||
className={field}
|
||||
required
|
||||
value={currency}
|
||||
onChange={(event) => {
|
||||
setCurrency(event.target.value);
|
||||
changed();
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
<option value="MZN">MZN — Metical</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Data de exigibilidade declarada
|
||||
<input
|
||||
className={field}
|
||||
type="date"
|
||||
required
|
||||
value={date}
|
||||
onChange={(event) => {
|
||||
setDate(event.target.value);
|
||||
changed();
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
checked={declared}
|
||||
onChange={(event) => {
|
||||
setDeclared(event.target.checked);
|
||||
changed();
|
||||
}}
|
||||
/>
|
||||
Declaro para este ensaio uma operação interna à taxa
|
||||
geral, sem isenção, taxa reduzida ou base especial. Esta
|
||||
declaração não é validação jurídica.
|
||||
</label>
|
||||
<button className={button} type="submit">
|
||||
Calcular e gravar no histórico QA
|
||||
</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
{message && (
|
||||
<p role="status" className="rounded bg-slate-100 p-3">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
{selected && (
|
||||
<section
|
||||
aria-label="Execução seleccionada"
|
||||
className="space-y-2"
|
||||
>
|
||||
<h2 className="font-semibold">Execução seleccionada</h2>
|
||||
<p className="break-all">
|
||||
ID: {selected.id} · estado:{" "}
|
||||
{statusLabel(selected.status)}
|
||||
</p>
|
||||
<FiscalQaPreview snapshot={selected.result_snapshot} />
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || selected.status !== "completed"}
|
||||
onClick={() => void action(loadReport)}
|
||||
>
|
||||
Consultar relatório guardado
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico da conta" className="space-y-3">
|
||||
<h2 className="font-semibold">Histórico da conta</h2>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void action(loadHistory)}
|
||||
>
|
||||
Carregar histórico
|
||||
</button>
|
||||
<ul className="space-y-2">
|
||||
{history.map((entry) => (
|
||||
<li
|
||||
key={entry.id}
|
||||
className="break-all rounded border p-3"
|
||||
>
|
||||
{entry.id} · {statusLabel(entry.status)}{" "}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void action(async () => {
|
||||
await recover(entry.id);
|
||||
setMessage(
|
||||
"Execução recuperada do histórico, sem recalcular.",
|
||||
);
|
||||
})
|
||||
}
|
||||
>
|
||||
Recuperar {entry.id}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{report && (
|
||||
<section
|
||||
aria-label="Relatório guardado"
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Relatório guardado
|
||||
</h2>
|
||||
<p className="break-all">ID do relatório: {report.id}</p>
|
||||
<p className="break-all">SHA256: {report.hash}</p>
|
||||
<p>
|
||||
Conteúdo recuperado do relatório imutável, sem novo
|
||||
cálculo.
|
||||
</p>
|
||||
<FiscalQaPreview snapshot={report.snapshot} />
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user