fix: recover simulator cashflow and verify QA continuity and report assumptions
This commit is contained in:
@@ -1,7 +1,11 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
exportMonthlyCashflowCsv,
|
||||
projectMonthlyCashflow,
|
||||
defaultCashflowDraftInputs,
|
||||
restoreCashflowDraftSnapshot,
|
||||
serializeCashflowDraftSnapshot,
|
||||
type CashflowDraftSnapshot,
|
||||
} from '@/lib/monthly-cashflow';
|
||||
import {
|
||||
isSimulationCurrency,
|
||||
@@ -11,28 +15,38 @@ import {
|
||||
export function SimulationCashflowPlanner({
|
||||
currency,
|
||||
onCurrencyChange,
|
||||
snapshot,
|
||||
onSnapshotChange,
|
||||
}: {
|
||||
currency: string;
|
||||
onCurrencyChange: (currency: string) => void;
|
||||
snapshot?: string;
|
||||
onSnapshotChange?: (snapshot: string) => void;
|
||||
}) {
|
||||
const [taxMode, setTaxMode] = useState<'fixed' | 'schedule'>('fixed');
|
||||
const [inputs, setInputs] = useState({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '200000',
|
||||
monthlyOperatingCosts: '150000',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '',
|
||||
monthlyTaxSchedule: Array.from({ length: 12 }, () => ''),
|
||||
vatCreditEstimated: '0',
|
||||
vatRefundRequested: '0',
|
||||
vatRefundRecognized: '0',
|
||||
vatRefundExpectedReceipt: '0',
|
||||
vatRefundExpectedMonth: '',
|
||||
});
|
||||
const restored = restoreCashflowDraftSnapshot(snapshot);
|
||||
const [taxMode, setTaxMode] = useState<'fixed' | 'schedule'>(
|
||||
restored?.taxMode ?? 'fixed',
|
||||
);
|
||||
const [inputs, setInputs] = useState(
|
||||
restored?.inputs ?? defaultCashflowDraftInputs(),
|
||||
);
|
||||
useEffect(() => {
|
||||
const saved = restoreCashflowDraftSnapshot(snapshot);
|
||||
setTaxMode(saved?.taxMode ?? 'fixed');
|
||||
setInputs(saved?.inputs ?? defaultCashflowDraftInputs());
|
||||
}, [snapshot]);
|
||||
function update(
|
||||
next: typeof inputs,
|
||||
mode: CashflowDraftSnapshot['taxMode'] = taxMode,
|
||||
) {
|
||||
setInputs(next);
|
||||
setTaxMode(mode);
|
||||
onSnapshotChange?.(serializeCashflowDraftSnapshot(mode, next));
|
||||
}
|
||||
const set = (
|
||||
key: Exclude<keyof typeof inputs, 'monthlyTaxSchedule'>,
|
||||
value: string,
|
||||
) => setInputs((current) => ({ ...current, [key]: value }));
|
||||
) => update({ ...inputs, [key]: value });
|
||||
const cashflowInput = {
|
||||
...inputs,
|
||||
...(taxMode === 'fixed'
|
||||
@@ -45,6 +59,10 @@ export function SimulationCashflowPlanner({
|
||||
let projection;
|
||||
let error = '';
|
||||
try {
|
||||
if (snapshot && !restored)
|
||||
throw new Error(
|
||||
'Não foi possível recuperar os pressupostos guardados de tesouraria. Reveja os campos antes de voltar a guardar; nenhum resultado foi calculado com dados alternativos.',
|
||||
);
|
||||
projection = projectMonthlyCashflow({ ...cashflowInput, currency });
|
||||
} catch (cause) {
|
||||
error =
|
||||
@@ -97,9 +115,11 @@ export function SimulationCashflowPlanner({
|
||||
role="note"
|
||||
className="rounded bg-amber-50 p-3 text-sm text-amber-950"
|
||||
>
|
||||
Os valores preenchidos ao abrir são exemplos demonstrativos.
|
||||
Confirme ou altere os pressupostos antes de interpretar os
|
||||
resultados ou exportar o CSV.
|
||||
{restored
|
||||
? 'Pressupostos recuperados do rascunho deste investimento; reveja-os antes de interpretar os resultados ou exportar.'
|
||||
: snapshot
|
||||
? 'O rascunho guardado não pôde ser interpretado. Os campos mostram exemplos, que não substituem os dados guardados até os editar.'
|
||||
: 'Os valores preenchidos ao abrir são exemplos demonstrativos. Confirme ou altere os pressupostos antes de interpretar os resultados ou exportar o CSV.'}
|
||||
</p>
|
||||
{projection?.status === 'incomplete' && (
|
||||
<p
|
||||
@@ -121,7 +141,7 @@ export function SimulationCashflowPlanner({
|
||||
type="radio"
|
||||
name="cashflow-tax-mode"
|
||||
checked={taxMode === 'fixed'}
|
||||
onChange={() => setTaxMode('fixed')}
|
||||
onChange={() => update(inputs, 'fixed')}
|
||||
/>
|
||||
Valor mensal fixo
|
||||
</label>
|
||||
@@ -130,7 +150,7 @@ export function SimulationCashflowPlanner({
|
||||
type="radio"
|
||||
name="cashflow-tax-mode"
|
||||
checked={taxMode === 'schedule'}
|
||||
onChange={() => setTaxMode('schedule')}
|
||||
onChange={() => update(inputs, 'schedule')}
|
||||
/>
|
||||
Calendário variável por mês
|
||||
</label>
|
||||
@@ -162,16 +182,16 @@ export function SimulationCashflowPlanner({
|
||||
step="0.01"
|
||||
value={value}
|
||||
onChange={(event) =>
|
||||
setInputs((current) => ({
|
||||
...current,
|
||||
update({
|
||||
...inputs,
|
||||
monthlyTaxSchedule:
|
||||
current.monthlyTaxSchedule.map(
|
||||
inputs.monthlyTaxSchedule.map(
|
||||
(amount, month) =>
|
||||
month === index
|
||||
? event.target.value
|
||||
: amount,
|
||||
),
|
||||
}))
|
||||
})
|
||||
}
|
||||
className="mt-1 w-full rounded border p-2"
|
||||
/>
|
||||
|
||||
@@ -352,6 +352,12 @@ export function SimulationFinancialTools({
|
||||
/>
|
||||
{schedule && isSimulationCurrency(currency) && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Montantes a duas casas decimais; juros e
|
||||
prestação arredondados à unidade monetária
|
||||
mínima, metade para cima. A última prestação
|
||||
ajusta o saldo residual.
|
||||
</p>
|
||||
<p aria-live="polite">
|
||||
Taxa por período: {schedule.periodicRatePercent}
|
||||
%; desembolso líquido: {
|
||||
|
||||
@@ -834,8 +834,10 @@ export function SimulationForm() {
|
||||
}, [openedTool, step]);
|
||||
function openDraftTool(tool: 'calculation' | 'fiscal') {
|
||||
setToolError('');
|
||||
const index = journeySections.findIndex(
|
||||
(section) => section.id === 'tax',
|
||||
const index = journeySections.findIndex((section) =>
|
||||
tool === 'calculation'
|
||||
? ['financial', 'tax'].includes(section.id)
|
||||
: section.id === 'tax',
|
||||
);
|
||||
if (index < 0) {
|
||||
setToolError(
|
||||
@@ -927,6 +929,7 @@ export function SimulationForm() {
|
||||
const [businessLinkError, setBusinessLinkError] = useState('');
|
||||
const [businessLinkBusy, setBusinessLinkBusy] = useState(false);
|
||||
const [continueLaterSaved, setContinueLaterSaved] = useState(false);
|
||||
const [saveAttempt, setSaveAttempt] = useState(0);
|
||||
const calculationInFlightRef = useRef(false);
|
||||
const draftIdRef = useRef<string | null>(null);
|
||||
const draftEtagRef = useRef<string | null>(null);
|
||||
@@ -1322,6 +1325,7 @@ export function SimulationForm() {
|
||||
setSaveStatus('A guardar o rascunho no servidor…');
|
||||
saveQueueRef.current = saveQueueRef.current
|
||||
.then(async () => {
|
||||
if (fingerprint === lastSavedFingerprintRef.current) return;
|
||||
const headers = {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1476,6 +1480,7 @@ export function SimulationForm() {
|
||||
draftCreateKey,
|
||||
draftIdKey,
|
||||
draftKey,
|
||||
saveAttempt,
|
||||
]);
|
||||
|
||||
async function returnToInvestment() {
|
||||
@@ -1700,6 +1705,7 @@ export function SimulationForm() {
|
||||
async function saveAndContinueLater() {
|
||||
if (!draft.purpose) return;
|
||||
setContinueLaterSaved(false);
|
||||
setSaveAttempt((attempt) => attempt + 1);
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 550));
|
||||
await saveQueueRef.current;
|
||||
const target = canSavePersonalData ? draft : getAutosaveSnapshot(draft);
|
||||
@@ -3449,6 +3455,10 @@ export function SimulationForm() {
|
||||
(draft.purpose === 'simulate_only' &&
|
||||
current.id === 'tax')) && (
|
||||
<SimulationCashflowPlanner
|
||||
snapshot={String(draft.cashflow_snapshot ?? '')}
|
||||
onSnapshotChange={(value) =>
|
||||
change('cashflow_snapshot', value)
|
||||
}
|
||||
currency={String(draft.currency ?? '')}
|
||||
onCurrencyChange={(value) => change('currency', value)}
|
||||
/>
|
||||
@@ -3692,36 +3702,49 @@ export function SimulationForm() {
|
||||
documentos nesta simulação exploratória.
|
||||
</p>
|
||||
)}
|
||||
{current.id === 'tax' && (
|
||||
{(current.id === 'tax' || result) && (
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<h4 className="font-semibold">
|
||||
Cenário personalizado de planeamento
|
||||
{current.id === 'tax'
|
||||
? 'Cenário personalizado de planeamento'
|
||||
: 'Resultado histórico seleccionado'}
|
||||
</h4>
|
||||
{draft.fiscal_scenario_mode === 'custom_planning' && (
|
||||
<p
|
||||
role="note"
|
||||
className="rounded bg-slate-50 p-3 text-sm"
|
||||
>
|
||||
Os valores abaixo são pressupostos que
|
||||
introduziu para planeamento. O resultado é uma
|
||||
operação percentual genérica, não uma taxa
|
||||
legal, imposto devido nem confirmação de
|
||||
elegibilidade.
|
||||
{current.id !== 'tax' && result && (
|
||||
<p>
|
||||
Este resultado conserva os pressupostos e a
|
||||
versão da execução seleccionada. Não substitui
|
||||
as entradas deste dossier.
|
||||
</p>
|
||||
)}
|
||||
{draft.fiscal_scenario_mode === 'custom_planning' && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isCalculating}
|
||||
aria-busy={isCalculating}
|
||||
className="rounded-lg bg-emerald-800 px-4 py-3 font-semibold text-white focus-visible:outline-2 disabled:cursor-wait disabled:opacity-60"
|
||||
onClick={() => void runSimulation()}
|
||||
>
|
||||
{isCalculating
|
||||
? 'A calcular…'
|
||||
: 'Validar e calcular no servidor'}
|
||||
</button>
|
||||
)}
|
||||
{current.id === 'tax' &&
|
||||
draft.fiscal_scenario_mode ===
|
||||
'custom_planning' && (
|
||||
<p
|
||||
role="note"
|
||||
className="rounded bg-slate-50 p-3 text-sm"
|
||||
>
|
||||
Os valores abaixo são pressupostos que
|
||||
introduziu para planeamento. O resultado é
|
||||
uma operação percentual genérica, não uma
|
||||
taxa legal, imposto devido nem confirmação
|
||||
de elegibilidade.
|
||||
</p>
|
||||
)}
|
||||
{current.id === 'tax' &&
|
||||
draft.fiscal_scenario_mode ===
|
||||
'custom_planning' && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isCalculating}
|
||||
aria-busy={isCalculating}
|
||||
className="rounded-lg bg-emerald-800 px-4 py-3 font-semibold text-white focus-visible:outline-2 disabled:cursor-wait disabled:opacity-60"
|
||||
onClick={() => void runSimulation()}
|
||||
>
|
||||
{isCalculating
|
||||
? 'A calcular…'
|
||||
: 'Validar e calcular no servidor'}
|
||||
</button>
|
||||
)}
|
||||
{serverError && (
|
||||
<p role="alert" className="text-red-800">
|
||||
{serverError}
|
||||
|
||||
Reference in New Issue
Block a user