fix: persist annual demonstration through existing simulation drafts

This commit is contained in:
2026-11-20 11:11:38 +02:00
parent 18dda022a0
commit 51d31d3790
9 changed files with 341 additions and 11 deletions
@@ -1,7 +1,8 @@
import { useState } from 'react';
import {
calculateAnnualReferencePlan,
newAnnualReferencePlan,
restoreAnnualExampleSnapshot,
serializeAnnualExampleSnapshot,
type AnnualReferencePlan,
} from '@/lib/business-plan-guidance';
import { businessPlanNumberError } from '@/lib/business-financial-plan';
@@ -59,10 +60,29 @@ function ExampleNumber({
</label>
);
}
export function SimulationAnnualExample({ currency }: { currency: string }) {
const [plan, setPlan] = useState<AnnualReferencePlan>(
newAnnualReferencePlan,
);
export function SimulationAnnualExample({
currency,
snapshot,
onSnapshotChange,
}: {
currency: string;
snapshot?: string;
onSnapshotChange?: (snapshot: string) => void;
}) {
const recovered = restoreAnnualExampleSnapshot(snapshot);
if (snapshot && !recovered)
return (
<p role="alert">
Não foi possível recuperar o cenário de exemplo. O conteúdo
guardado foi preservado; não será substituído.
</p>
);
const plan = recovered ?? newAnnualReferencePlan();
const setPlan = (
update: (previous: AnnualReferencePlan) => AnnualReferencePlan,
) => {
onSnapshotChange?.(serializeAnnualExampleSnapshot(update(plan)));
};
let result: ReturnType<typeof calculateAnnualReferencePlan> | undefined;
let error = '';
try {
@@ -89,10 +109,13 @@ export function SimulationAnnualExample({ currency }: { currency: string }) {
Cenário anual de exemplo — editável
</h4>
<p className="text-sm">
Valores fornecidos no plano de referência. Moeda de
apresentação: {currency || 'por seleccionar no plano'}. As
edições deste ensaio ficam nesta demonstração; os dados do
investimento continuam no seu formulário.
Dados sintéticos de demonstração, com totais do plano de
referência e projecções ilustrativas. Moeda de apresentação:{' '}
{currency || 'por seleccionar no plano'}. As edições deste
ensaio acompanham o rascunho do simulador numa secção separada.
Sem sessão, retome no mesmo navegador; com sessão autenticada,
utilize o rascunho da sua conta para retomar noutro dispositivo.
Estes valores não substituem os dados reais do investimento.
</p>
<p className="rounded border border-amber-400 p-3 text-sm">
Linhas mensais por reconciliar. Conservam-se os totais anuais
@@ -929,7 +929,15 @@ export function SimulationBusinessPlan({
? 'Fechar cenário de exemplo'
: 'Carregar cenário anual de exemplo'}
</button>
{showExample && <SimulationAnnualExample currency={currency} />}
{showExample && (
<SimulationAnnualExample
currency={currency}
snapshot={plan.annualExampleSnapshot}
onSnapshotChange={(annualExampleSnapshot) =>
savePlan({ ...plan, annualExampleSnapshot })
}
/>
)}
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
<label className="grid gap-1 text-sm">
Importar plano financeiro InvestMoz (.json, até 60 KB)
@@ -82,6 +82,8 @@ function validCurrency(value: string): boolean {
}
export type BusinessFinancialPlanInput = {
/** Synthetic annual demonstration; excluded from investor forecast inputs. */
annualExampleSnapshot?: string;
currency: string;
annualGrowthPercent?: string;
presentationCurrency?: string;
@@ -201,6 +201,88 @@ export function newAnnualReferencePlan(): AnnualReferencePlan {
};
}
/** Preserve incomplete numeric drafts as entered, but accept only the example's schema. */
export function restoreAnnualExampleSnapshot(
snapshot?: string,
): AnnualReferencePlan | null {
if (!snapshot || snapshot.length > 12000) return null;
try {
const decoded = JSON.parse(snapshot);
if (
decoded.version !== 1 ||
decoded.kind !== 'synthetic-annual-example'
)
return null;
const plan = decoded.plan;
const template = newAnnualReferencePlan();
const numericDraft = (value: unknown) =>
typeof value === 'string' && value.length <= 40;
for (const key of [
'openingCash',
'otherCurrentAssets',
'longTermAssets',
'ownerCapital',
'investorCapital',
'loans',
'additionalMoney',
] as const)
if (!numericDraft(plan[key])) return null;
if (
!Array.isArray(plan.startupExpenses) ||
plan.startupExpenses.length !== template.startupExpenses.length ||
plan.startupExpenses.some(
(row: { label: unknown; amount: unknown }, i: number) =>
row.label !== template.startupExpenses[i].label ||
!numericDraft(row.amount),
)
)
return null;
if (
!Array.isArray(plan.years) ||
plan.years.length !== template.years.length ||
plan.years.some(
(row: Record<string, unknown>, i: number) =>
row.year !== template.years[i].year ||
Object.keys(template.years[i]).some(
(key) => key !== 'year' && !numericDraft(row[key]),
),
)
)
return null;
// Do not accept unrelated fields or investor data into this example.
if (
JSON.stringify(Object.keys(plan).sort()) !==
JSON.stringify(Object.keys(template).sort()) ||
plan.years.some(
(row: Record<string, unknown>, i: number) =>
JSON.stringify(Object.keys(row).sort()) !==
JSON.stringify(Object.keys(template.years[i]).sort()),
) ||
plan.startupExpenses.some(
(row: Record<string, unknown>) =>
Object.keys(row).sort().join(',') !== 'amount,label',
)
)
return null;
return plan as AnnualReferencePlan;
} catch {
return null;
}
}
export function serializeAnnualExampleSnapshot(
plan: AnnualReferencePlan,
): string {
const snapshot = JSON.stringify({
version: 1,
kind: 'synthetic-annual-example',
plan,
});
if (!restoreAnnualExampleSnapshot(snapshot))
throw new Error('Não foi possível guardar o cenário de exemplo.');
return snapshot;
}
function money(value: string): bigint {
if (value.length > 40 || !/^\d+(?:\.\d{1,2})?$/.test(value.trim()))
throw new Error(