feat: persist investor warning limits and preserve financial snapshots in QA

This commit is contained in:
2026-11-21 20:55:34 +02:00
parent c144425e77
commit a4ecc8a5a9
26 changed files with 1239 additions and 48 deletions
@@ -1,3 +1,4 @@
import { WarningLimitsEditor } from './warning-limits-editor';
import { SupplierAdvancesEditor } from '@/components/supplier-advances';
import { PeriodInvestmentsEditor } from '@/components/period-investments';
import CurrencySelect from '@/components/currency-select';
@@ -954,6 +955,7 @@ export function SimulationBusinessPlan({
<FinancialDayTerms plan={plan} onChange={savePlan} />
<SupplierAdvancesEditor plan={plan} onChange={savePlan} />
<PeriodInvestmentsEditor plan={plan} onChange={savePlan} />
<WarningLimitsEditor plan={plan} onChange={savePlan} />
<StartupAssetRequirements
plan={plan}
onChange={savePlan}
@@ -2580,6 +2582,7 @@ export function SimulationBusinessPlan({
{!plan.reportAssumptions &&
plan.reportSource !== 'annual_example' && (
<BusinessPlanWarnings
limits={plan.warningLimits}
metrics={{
currency,
fundingGap: Number(result.fundingGap),
@@ -0,0 +1,104 @@
import { useRef, useState } from 'react';
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
defaultPlanWarningLimits,
isPlanWarningLimits,
type PlanWarningLimits,
} from '@/lib/business-plan-guidance';
const fields: [keyof PlanWarningLimits, string][] = [
['grossMarginPercent', 'Margem bruta de aviso (%)'],
['cashExpenseMonths', 'Cobertura de despesas em caixa (meses)'],
['annualGrowthPercent', 'Crescimento anual de aviso (%)'],
['creditDays', 'Prazo de recebimento de aviso (dias)'],
['debtAssetsPercent', 'D\u00edvida sobre activos de aviso (%)'],
];
export function WarningLimitsEditor({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (p: BusinessFinancialPlanInput) => void;
}) {
const root = useRef<HTMLFieldSetElement>(null);
const [error, setError] = useState('');
return (
<details className="my-4 rounded border p-3">
<summary>Limites dos avisos</summary>
<p className="my-2 text-sm">
{
'Ajuste os limiares dos avisos de planeamento. Os valores financeiros e os erros de preenchimento mant\u00eam-se. O prazo em dias aplica-se quando foi indicado nesse formato.'
}
</p>
<p role="status">
{plan.warningLimits
? 'Limites personalizados guardados neste plano.'
: 'Limites habituais do simulador.'}
</p>
<fieldset
key={JSON.stringify(plan.warningLimits)}
ref={root}
className="my-3 grid gap-3 sm:grid-cols-2"
>
<legend className="sr-only">Limiares de planeamento</legend>
{fields.map(([key, label]) => (
<label key={key} className="grid gap-1 text-sm">
{label}
<input
className="min-w-0 rounded border p-2"
type="number"
step="any"
name={key}
defaultValue={
(plan.warningLimits ??
defaultPlanWarningLimits)[key]
}
/>
</label>
))}
</fieldset>
{error && (
<p role="alert" className="text-sm text-red-800">
{error}
</p>
)}
<div className="flex flex-wrap gap-3">
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => {
const next = Object.fromEntries(
fields.map(([key]) => [
key,
root.current?.querySelector<HTMLInputElement>(
`input[name="${key}"]`,
)?.valueAsNumber,
]),
);
if (!isPlanWarningLimits(next)) {
setError(
'Preencha os cinco limites com n\u00fameros finitos; meses e dias devem ser n\u00e3o negativos.',
);
return;
}
setError('');
onChange({ ...plan, warningLimits: next });
}}
>
Aplicar limites ao plano
</button>
<button
type="button"
className="rounded border px-3 py-2"
onClick={() => {
const next = { ...plan };
delete next.warningLimits;
setError('');
onChange(next);
}}
>
Repor limites habituais
</button>
</div>
</details>
);
}
+61 -45
View File
@@ -1,3 +1,7 @@
import {
isPlanWarningLimits,
type PlanWarningLimits,
} from './business-plan-guidance.ts';
import {
advanceEventLabels,
buildSupplierAdvances,
@@ -100,6 +104,7 @@ function validCurrency(value: string): boolean {
}
export type BusinessFinancialPlanInput = {
warningLimits?: PlanWarningLimits;
periodInvestments?: PeriodInvestments;
/** Explicit opt-in. Missing keeps all historical calculations unchanged. */
dayTerms?: DayTerms;
@@ -225,31 +230,33 @@ export function serializeBusinessPlanSnapshot(
): string {
const snapshot = JSON.stringify({
version:
plan.periodInvestments !== undefined
? 23
: plan.accountingRegime !== undefined
? 22
: plan.supplierAdvances !== undefined
? 21
: plan.dayTerms !== undefined
? 20
: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[
key as keyof BusinessFinancialPlanInput
] !== undefined,
)
? 18
: 17,
plan.warningLimits !== undefined
? 24
: plan.periodInvestments !== undefined
? 23
: plan.accountingRegime !== undefined
? 22
: plan.supplierAdvances !== undefined
? 21
: plan.dayTerms !== undefined
? 20
: plan.startupAssetRequirements
? 19
: [
'applyAnnualGrowth',
'creditTermDays',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[
key as keyof BusinessFinancialPlanInput
] !== undefined,
)
? 18
: 17,
plan: {
...plan,
...(plan.useSupplierPaymentTerms === true
@@ -337,29 +344,37 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 20 &&
decoded.version !== 21 &&
decoded.version !== 22 &&
decoded.version !== 23) ||
decoded.version !== 23 &&
decoded.version !== 24) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
return null;
const plan = decoded.plan as Record<string, unknown>;
if (
(decoded.version === 24 && plan.warningLimits === undefined) ||
(plan.warningLimits !== undefined &&
(decoded.version !== 24 ||
!isPlanWarningLimits(plan.warningLimits)))
)
return null;
if (decoded.version === 23 && plan.periodInvestments === undefined)
return null;
if (
plan.periodInvestments !== undefined &&
(decoded.version !== 23 ||
(![23, 24].includes(decoded.version) ||
!isPeriodInvestments(plan.periodInvestments))
)
return null;
if (
plan.dayTerms !== undefined &&
(![20, 21, 22, 23].includes(decoded.version) ||
(![20, 21, 22, 23, 24].includes(decoded.version) ||
!isDayTerms(plan.dayTerms))
)
return null;
if (
plan.supplierAdvances !== undefined &&
(![21, 22, 23].includes(decoded.version) ||
(![21, 22, 23, 24].includes(decoded.version) ||
!isSupplierAdvances(plan.supplierAdvances))
)
return null;
@@ -377,7 +392,7 @@ export function restoreBusinessPlanSnapshot(
return null;
if (
plan.accountingRegime !== undefined &&
(![22, 23].includes(decoded.version!) ||
(![22, 23, 24].includes(decoded.version!) ||
typeof plan.accountingRegime !== 'string' ||
!['PGC-PE', 'PGC-NIRF'].includes(plan.accountingRegime))
)
@@ -391,7 +406,7 @@ export function restoreBusinessPlanSnapshot(
const advances = plan.supplierAdvances as SupplierAdvances | undefined;
if (
advances?.regime === 'PGC-NIRF' &&
(![22, 23].includes(decoded.version!) ||
(![22, 23, 24].includes(decoded.version!) ||
plan.accountingRegime !== 'PGC-NIRF')
)
return null;
@@ -521,7 +536,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
[12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) &&
(!Object.hasOwn(plan, 'inventoryPurchaseSchedule') ||
@@ -534,7 +549,7 @@ export function restoreBusinessPlanSnapshot(
plan.inventoryPurchaseSchedule !== null
) {
if (
![12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
![12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.inventoryPurchaseSchedule) ||
@@ -559,7 +574,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
[13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) &&
!Object.hasOwn(plan, 'monthlyVariableCostPaymentsByPeriod')
@@ -568,7 +583,7 @@ export function restoreBusinessPlanSnapshot(
if (
plan.monthlyVariableCostPaymentsByPeriod !== undefined &&
plan.monthlyVariableCostPaymentsByPeriod !== null &&
(![13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
(![13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) ||
!Array.isArray(plan.monthlyVariableCostPaymentsByPeriod) ||
@@ -635,9 +650,9 @@ export function restoreBusinessPlanSnapshot(
if (openingCollectionRate < 0n || openingCollectionRate > 100_000_000n)
return null;
if (
[7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
Number(decoded.version),
)
[
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24,
].includes(Number(decoded.version))
) {
if (
!Array.isArray(plan.openingReceivablesInstallments) ||
@@ -708,7 +723,7 @@ export function restoreBusinessPlanSnapshot(
)
return null;
if (
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
)
) {
@@ -747,7 +762,7 @@ export function restoreBusinessPlanSnapshot(
const schedule = plan[field];
if (
schedule !== undefined &&
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
(![11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) ||
!Array.isArray(schedule) ||
@@ -837,9 +852,9 @@ export function restoreBusinessPlanSnapshot(
const costSchedule = productData.unitVariableCostByPeriod;
const validMoneySchedule = (values: unknown) =>
values === undefined ||
([10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23].includes(
Number(decoded.version),
) &&
([
10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24,
].includes(Number(decoded.version)) &&
Array.isArray(values) &&
values.length >= Number(plan.periods) &&
values.length <= 60 &&
@@ -847,7 +862,8 @@ export function restoreBusinessPlanSnapshot(
return (
(schedule !== undefined &&
(![
9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22,
9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23,
24,
].includes(Number(decoded.version)) ||
!Array.isArray(schedule) ||
schedule.length < Number(plan.periods) ||
@@ -885,7 +901,7 @@ export function restoreBusinessPlanSnapshot(
entry.paymentLagMonths < 0 ||
entry.paymentLagMonths > 12)) ||
(entry.paymentInstallments !== undefined &&
(![16, 17, 20, 21, 22, 23].includes(
(![16, 17, 20, 21, 22, 23, 24].includes(
Number(decoded.version),
) ||
!Array.isArray(
+20 -1
View File
@@ -12,6 +12,23 @@ export const defaultPlanWarningLimits: PlanWarningLimits = {
creditDays: 90,
debtAssetsPercent: 70,
};
export function isPlanWarningLimits(
value: unknown,
): value is PlanWarningLimits {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const limits = value as Record<string, unknown>;
return (
Object.keys(limits).length === 5 &&
Object.keys(defaultPlanWarningLimits).every(
(key) =>
typeof limits[key] === 'number' &&
Number.isFinite(limits[key]) &&
(!['cashExpenseMonths', 'creditDays'].includes(key) ||
Number(limits[key]) >= 0),
)
);
}
export type PlanWarning = { id: string; message: string };
export type PlanWarningMetrics = {
optionalTexts?: { label: string; value: string }[];
@@ -81,7 +98,9 @@ export function businessPlanWarnings(
)
add(
'cash',
'A caixa disponível cobre menos de um mês de despesas. Considere reforçar o financiamento.',
limits.cashExpenseMonths === 1
? 'A caixa disponível cobre menos de um mês de despesas. Considere reforçar o financiamento.'
: `A caixa disponível cobre menos de ${limits.cashExpenseMonths.toLocaleString('pt-MZ')} meses de despesas. Considere reforçar o financiamento.`,
);
if (
metrics.growthPercent !== undefined &&
+4 -1
View File
@@ -100,7 +100,10 @@ export function financialPlanWarnings(
? undefined
: (metrics.directCosts * 12) / count,
};
const warnings = businessPlanWarnings(adjusted).map((w) => ({
const warnings = businessPlanWarnings(
adjusted,
plan.warningLimits,
).map((w) => ({
...w,
id: `${year}-${w.id}`,
message: `${year}: ${w.message}`,