feat: demonstrar percurso IVA QA e consolidar revisao
This commit is contained in:
@@ -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