fix: complete InvesteMoz validation and error corrections

This commit is contained in:
2026-10-29 21:47:33 +02:00
parent 63147312e2
commit daf8623441
718 changed files with 127308 additions and 20959 deletions
@@ -1,7 +1,7 @@
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 { 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,
@@ -9,7 +9,7 @@ import {
isApiSimulationResultSnapshotV1,
type ApiSimulationExecutionV1,
type ApiSimulationHistoryEntryV1,
} from "@/lib/simulation-contract";
} from '@/lib/simulation-contract';
class ReviewOperationError extends Error {}
@@ -19,9 +19,9 @@ export default function FiscalQaReview({
}: {
rule: { id: string; code: string; version: number };
}) {
const [base, setBase] = useState("");
const [date, setDate] = useState("");
const [currency, setCurrency] = useState("");
const [base, setBase] = useState('');
const [date, setDate] = useState('');
const [currency, setCurrency] = useState('');
const [declared, setDeclared] = useState(false);
const [selected, setSelected] = useState<ApiSimulationExecutionV1 | null>(
null,
@@ -33,7 +33,7 @@ export default function FiscalQaReview({
snapshot: unknown;
} | null>(null);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [message, setMessage] = useState('');
const key = useRef<string | null>(null);
const gate = useRef(false);
const changed = () => {
@@ -41,12 +41,12 @@ export default function FiscalQaReview({
};
const statusLabel = (status: string) =>
({
queued: "na fila",
running: "em processamento",
completed: "concluída",
failed: "não concluída",
cancelled: "cancelada",
})[status] ?? "recebida";
queued: 'na fila',
running: 'em processamento',
completed: 'concluída',
failed: 'não concluída',
cancelled: 'cancelada',
})[status] ?? 'recebida';
async function request(
url: string,
@@ -54,20 +54,20 @@ export default function FiscalQaReview({
): Promise<unknown> {
const xsrf = decodeURIComponent(
document.cookie
.split("; ")
.find((part) => part.startsWith("XSRF-TOKEN="))
?.slice(11) ?? "",
.split('; ')
.find((part) => part.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
const response = await fetch(url, {
method: body ? "POST" : "GET",
credentials: "same-origin",
method: body ? 'POST' : 'GET',
credentials: 'same-origin',
headers: {
Accept: "application/json",
Accept: 'application/json',
...(body
? {
"Content-Type": "application/json",
"X-XSRF-TOKEN": xsrf,
"Idempotency-Key": key.current!,
'Content-Type': 'application/json',
'X-XSRF-TOKEN': xsrf,
'Idempotency-Key': key.current!,
}
: {}),
},
@@ -76,8 +76,8 @@ export default function FiscalQaReview({
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.",
? '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();
}
@@ -86,15 +86,15 @@ export default function FiscalQaReview({
if (gate.current) return;
gate.current = true;
setBusy(true);
setMessage("");
setMessage('');
try {
await work();
} catch (cause) {
console.error("[fiscal-qa-review]", 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.",
: 'Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.',
);
} finally {
gate.current = false;
@@ -106,7 +106,7 @@ export default function FiscalQaReview({
const payload = await request(`/api/v1/simulations/${id}`);
if (!isApiSimulationReadResponseV1(payload))
throw new ReviewOperationError(
"O resultado guardado tem formato incompatível.",
'O resultado guardado tem formato incompatível.',
);
setSelected(payload.data);
setReport(null);
@@ -123,38 +123,38 @@ export default function FiscalQaReview({
base,
currency,
reference_date: date,
operation: "internal_general_net",
operation: 'internal_general_net',
},
);
if (!isApiSimulationCreateResponseV1(payload))
throw new ReviewOperationError(
"A execução devolveu um formato incompatível.",
'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);
['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.",
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",
'/api/v1/simulations/history?per_page=10',
);
if (!isApiSimulationHistoryResponseV1(payload))
throw new ReviewOperationError(
"O histórico devolveu um formato incompatível.",
'O histórico devolveu um formato incompatível.',
);
setHistory(payload.data);
}
@@ -163,7 +163,7 @@ export default function FiscalQaReview({
const reference = readVersionedArithmeticReportReference(selected);
if (!selected || !reference)
throw new ReviewOperationError(
"O relatório ainda não está disponível para esta execução.",
'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}`,
@@ -180,7 +180,7 @@ export default function FiscalQaReview({
!isApiSimulationResultSnapshotV1(payload.data.report_snapshot)
) {
throw new ReviewOperationError(
"O relatório guardado não corresponde à referência desta execução.",
'O relatório guardado não corresponde à referência desta execução.',
);
}
setReport({
@@ -190,9 +190,9 @@ export default function FiscalQaReview({
});
}
const field = "mt-1 block w-full rounded border border-slate-400 p-2";
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";
'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" />
@@ -287,13 +287,13 @@ export default function FiscalQaReview({
>
<h2 className="font-semibold">Execução seleccionada</h2>
<p className="break-all">
ID: {selected.id} · estado:{" "}
ID: {selected.id} · estado:{' '}
{statusLabel(selected.status)}
</p>
<FiscalQaPreview snapshot={selected.result_snapshot} />
<button
className={button}
disabled={busy || selected.status !== "completed"}
disabled={busy || selected.status !== 'completed'}
onClick={() => void action(loadReport)}
>
Consultar relatório guardado
@@ -313,9 +313,9 @@ export default function FiscalQaReview({
{history.map((entry) => (
<li
key={entry.id}
className="break-all rounded border p-3"
className="rounded border p-3 break-all"
>
{entry.id} · {statusLabel(entry.status)}{" "}
{entry.id} · {statusLabel(entry.status)}{' '}
<button
className={button}
disabled={busy}
@@ -323,7 +323,7 @@ export default function FiscalQaReview({
void action(async () => {
await recover(entry.id);
setMessage(
"Execução recuperada do histórico, sem recalcular.",
'Execução recuperada do histórico, sem recalcular.',
);
})
}