feat(qa): integrate financial example, growth, dividends and detailed declarations

This commit is contained in:
2026-11-20 14:59:36 +02:00
parent b2cfa93945
commit 9c34af0406
13 changed files with 1532 additions and 54 deletions
@@ -3,20 +3,23 @@ import {
businessPlanWarnings,
type PlanWarningMetrics,
type PlanWarningLimits,
type PlanWarning,
} from '@/lib/business-plan-guidance';
export function BusinessPlanWarnings({
metrics,
metrics = {},
limits,
warnings: suppliedWarnings,
}: {
metrics: PlanWarningMetrics;
metrics?: PlanWarningMetrics;
limits?: PlanWarningLimits;
warnings?: PlanWarning[];
}) {
const [dismissed, setDismissed] = useState<string[]>([]);
const scope = JSON.stringify(metrics);
const warnings = businessPlanWarnings(metrics, limits).filter(
(warning) => !dismissed.includes(`${scope}:${warning.id}`),
);
const scope = JSON.stringify([metrics, suppliedWarnings, limits]);
const warnings = (
suppliedWarnings ?? businessPlanWarnings(metrics, limits)
).filter((warning) => !dismissed.includes(`${scope}:${warning.id}`));
if (!warnings.length) return null;
return (
<aside
@@ -0,0 +1,325 @@
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
newAnnualReferencePlan,
serializeAnnualExampleSnapshot,
} from '@/lib/business-plan-guidance';
/** Optional declarations share the existing plan snapshot; no independent storage. */
export function FinancialPlanDetails({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
const input = (label: string, value: string, save: (s: string) => void) => (
<label className="grid gap-1 text-sm">
{label}
<input
className="min-w-0 rounded border p-2"
type="number"
min="0"
step="0.01"
value={value}
onChange={(e) => save(e.target.value)}
/>
</label>
);
return (
<details className="my-3 space-y-3 rounded border p-3">
<summary className="font-semibold">
Crescimento, despesas discriminadas, capital e dividendos
</summary>
<label className="grid gap-1">
Fonte do relatório financeiro consolidado
<select
className="rounded border p-2"
value={plan.reportSource ?? 'investor'}
onChange={(e) =>
onChange({
...plan,
reportSource: e.target.value as
| 'investor'
| 'annual_example',
...(e.target.value === 'annual_example' &&
!plan.annualExampleSnapshot
? {
annualExampleSnapshot:
serializeAnnualExampleSnapshot(
newAnnualReferencePlan(),
),
}
: {}),
})
}
>
<option value="investor">Plano do investidor</option>
<option value="annual_example">
Exemplo sintético anual editável
</option>
</select>
</label>
<p className="text-sm">
A escolha do exemplo muda apenas a fonte do relatório, sem
substituir as entradas do investidor. As edições do exemplo são
feitas em «Carregar cenário anual de exemplo» e acompanham a
mesma versão guardada. Escolha novamente «Plano do investidor»
para regressar.
</p>
<label className="flex gap-2">
<input
type="checkbox"
checked={plan.applyAnnualGrowth ?? false}
onChange={(e) =>
onChange({
...plan,
applyAnnualGrowth: e.target.checked,
})
}
/>
Projectar os anos seguintes com o crescimento anual declarado
</label>
<p className="text-sm">
Aplica o crescimento às quantidades a partir do segundo ano,
conservando preços e custos unitários. Agendas mensais
explícitas prevalecem. A taxa é uma hipótese, não uma previsão
de procura.
</p>
<label className="flex gap-2">
<input
type="checkbox"
checked={!!plan.operatingExpenseLines}
onChange={(e) =>
onChange({
...plan,
operatingExpenseLines: e.target.checked
? [
'Rendas',
'Seguros',
'Utilidades',
'Marketing',
'Outras despesas',
].map((label, i) => ({
label,
monthlyAmount:
i === 4
? plan.monthlyOperatingExpenses
: '0',
...(i === 4 &&
plan.monthlyOperatingExpensesByPeriod
? {
amountsByPeriod: [
...plan.monthlyOperatingExpensesByPeriod,
],
}
: {}),
}))
: undefined,
})
}
/>
Discriminar despesas operacionais
</label>
{plan.operatingExpenseLines && (
<p className="text-sm">
O total anterior começa em Outras despesas; redistribua
apenas montantes conhecidos. As linhas substituem o total
reconhecido, sem alterar pagamentos. Depreciação e juros
mantêm os campos próprios. Agendas existentes permanecem nas
linhas respectivas.
</p>
)}
{plan.operatingExpenseLines?.map((line, index) => (
<div key={index}>
{input(line.label, line.monthlyAmount, (value) =>
onChange({
...plan,
operatingExpenseLines:
plan.operatingExpenseLines!.map((r, i) =>
i === index
? { ...r, monthlyAmount: value }
: r,
),
}),
)}
{line.amountsByPeriod && (
<div className="grid gap-2 sm:grid-cols-3">
{line.amountsByPeriod.map((value, month) => (
<div key={month}>
{input(
`${line.label}, mês ${month + 1}`,
value,
(next) =>
onChange({
...plan,
operatingExpenseLines:
plan.operatingExpenseLines!.map(
(r, i) =>
i === index
? {
...r,
amountsByPeriod:
r.amountsByPeriod!.map(
(
v,
m,
) =>
m ===
month
? next
: v,
),
}
: r,
),
}),
)}
</div>
))}
</div>
)}
</div>
))}
<label className="flex gap-2">
<input
type="checkbox"
checked={!!plan.fundingBreakdown}
onChange={(e) =>
onChange({
...plan,
fundingBreakdown: e.target.checked
? {
ownerCapital: '',
investorCapital: '',
additionalCapital: '',
}
: undefined,
})
}
/>
Discriminar o capital introduzido
</label>
{plan.fundingBreakdown && (
<>
<p className="text-sm">
Capital adicional angariado é apenas capital próprio.
Empréstimos, suprimentos e subvenções conservam os
campos próprios. A soma deve corresponder ao capital
introduzido.
</p>
<div className="grid gap-3 sm:grid-cols-3">
{(
[
['ownerCapital', 'Capital do proprietário'],
['investorCapital', 'Capital do investidor'],
[
'additionalCapital',
'Capital adicional angariado',
],
] as const
).map(([key, label]) => (
<div key={key}>
{input(
label,
plan.fundingBreakdown![key],
(value) => {
const f = {
...plan.fundingBreakdown!,
[key]: value,
};
const values = Object.values(f);
const valid = values.every((v) =>
/^\d+(?:\.\d{1,2})?$/.test(v),
);
const total = values.reduce(
(sum, v) => {
if (
!/^\d+(?:\.\d{1,2})?$/.test(
v,
)
)
return sum;
const [a, b = ''] =
v.split('.');
return (
sum +
BigInt(a) * 100n +
BigInt(b.padEnd(2, '0'))
);
},
0n,
);
onChange({
...plan,
fundingBreakdown: f,
...(valid
? {
equity: `${total / 100n}.${String(total % 100n).padStart(2, '0')}`,
}
: {}),
});
},
)}
</div>
))}
</div>
</>
)}
<label className="flex gap-2">
<input
type="checkbox"
checked={!!plan.dividendsByPeriod}
onChange={(e) =>
onChange({
...plan,
dividendsByPeriod: e.target.checked
? Array(plan.periods ?? 12).fill('0')
: undefined,
})
}
/>
Planear dividendos distribuídos por mês
</label>
{plan.dividendsByPeriod && (
<>
<p className="text-sm">
Começa sem distribuições (zero). Cada dividendo reduz
caixa e capital; não é despesa nem reduz o lucro. São
hipóteses de distribuição, não pagamentos executados ou
autorização jurídica.
</p>
<div className="grid gap-2 sm:grid-cols-3">
{Array.from(
{ length: plan.periods ?? 12 },
(_, month) => (
<div key={month}>
{input(
`Dividendos, mês ${month + 1}`,
plan.dividendsByPeriod?.[month] ?? '',
(value) =>
onChange({
...plan,
dividendsByPeriod: Array.from(
{
length:
plan.periods ?? 12,
},
(_, i) =>
i === month
? value
: (plan
.dividendsByPeriod?.[
i
] ?? ''),
),
}),
)}
</div>
),
)}
</div>
</>
)}
</details>
);
}
@@ -5,6 +5,9 @@ import {
isReportAssumptions,
} from '@/lib/integral-financial-report';
import { InvestmentReportTables } from './investment-report-tables';
import { BusinessPlanWarnings } from './business-plan-warnings';
import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
import { buildAnnualExampleTables } from '@/lib/annual-example-report';
export function IntegralFinancialPlan({
plan,
@@ -13,6 +16,30 @@ export function IntegralFinancialPlan({
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
if (plan.reportSource === 'annual_example') {
try {
return (
<section aria-label="Relatório do exemplo sintético">
<h4>Relatório do exemplo sintético anual</h4>
<p>
As onze tabelas abaixo usam o exemplo editável. Os dados
reais do investimento ficam conservados separadamente.
</p>
<InvestmentReportTables
tables={buildAnnualExampleTables(plan)}
/>
</section>
);
} catch (error) {
return (
<p role="alert">
{error instanceof Error
? error.message
: 'Confira o cenário de exemplo.'}
</p>
);
}
}
if (plan.reportAssumptions && !isReportAssumptions(plan.reportAssumptions))
return (
<p role="alert">
@@ -258,6 +285,12 @@ export function IntegralFinancialPlan({
<InvestmentReportTables
tables={buildIntegralFinancialTables(plan)}
/>
<BusinessPlanWarnings
warnings={financialPlanWarnings(
plan,
buildIntegralFinancialTables(plan),
)}
/>
</details>
);
}
@@ -24,6 +24,7 @@ import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
import { PlanEconomicClassification } from '@/components/plan-economic-classification';
import { FinancialPlanDetails } from '@/components/financial-plan-details';
const emptyPlan: BusinessFinancialPlanInput = {
currency: '',
@@ -943,6 +944,7 @@ export function SimulationBusinessPlan({
/>
)}
<PlanEconomicClassification plan={plan} onChange={savePlan} />
<FinancialPlanDetails plan={plan} onChange={savePlan} />
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
<MarketAnalysisPlan plan={plan} onChange={savePlan} />
<FinancialRatiosPlan plan={plan} onChange={savePlan} />
@@ -1901,13 +1903,22 @@ export function SimulationBusinessPlan({
</p>
</>
)}
<MoneyInput
label="Despesas operacionais reconhecidas"
value={plan.monthlyOperatingExpenses}
onChange={(value) =>
update('monthlyOperatingExpenses', value)
}
/>
{!plan.operatingExpenseLines ? (
<MoneyInput
label="Despesas operacionais reconhecidas"
value={plan.monthlyOperatingExpenses}
onChange={(value) =>
update('monthlyOperatingExpenses', value)
}
/>
) : (
<p>
Despesas operacionais: calculadas a partir das
linhas discriminadas acima. Os pagamentos conservam
a sua agenda própria; o total e a agenda agregados
anteriores ficam preservados.
</p>
)}
<MoneyInput
label="Pagamento de despesas operacionais"
value={plan.monthlyOperatingPayments}
@@ -1938,6 +1949,11 @@ export function SimulationBusinessPlan({
</p>
)}
{moneyScheduleFields
.filter(
({ key }) =>
!plan.operatingExpenseLines ||
key !== 'monthlyOperatingExpensesByPeriod',
)
.filter(
({ key }) =>
!plan.useSupplierPaymentTerms ||
@@ -2541,15 +2557,19 @@ export function SimulationBusinessPlan({
>
Exportar plano em CSV
</button>
<BusinessPlanWarnings
metrics={{
currency,
fundingGap: Number(result.fundingGap),
growthPercent: plan.annualGrowthPercent?.trim()
? Number(plan.annualGrowthPercent)
: undefined,
}}
/>
{!plan.reportAssumptions &&
plan.reportSource !== 'annual_example' && (
<BusinessPlanWarnings
metrics={{
currency,
fundingGap: Number(result.fundingGap),
growthPercent:
plan.annualGrowthPercent?.trim()
? Number(plan.annualGrowthPercent)
: undefined,
}}
/>
)}
{result.fundingStatus !== 'shortfall' && (
<p
role="status"
+299
View File
@@ -0,0 +1,299 @@
import {
calculateAnnualReferencePlan,
calculateDecisionRatios,
restoreAnnualExampleSnapshot,
businessPlanWarnings,
} from './business-plan-guidance.ts';
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import {
reportMoney,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import { buildComplementaryTables } from './complementary-report.ts';
/** Presentation adapter only: uses the approved annual calculation, never converts it into investor movements. */
export function buildAnnualExampleTables(
input: BusinessFinancialPlanInput,
): InvestmentReportTable[] {
const plan = restoreAnnualExampleSnapshot(input.annualExampleSnapshot);
if (!plan)
throw new Error(
'Carregue e guarde primeiro o cenário anual de exemplo.',
);
const result = calculateAnnualReferencePlan(plan);
const notes = [
`Exemplo sintético; projecções ilustrativas em ${input.currency || 'moeda por seleccionar'}. Não são dados reais do investidor.`,
'Totais anuais preservados. A distribuição dos 36 meses é ilustrativa e reconciliada, não uma reprodução das linhas mensais inconsistentes do documento.',
];
const make = (
id: string,
title: string,
headers: string[],
rows: string[][],
): InvestmentReportTable => ({
id,
title,
headers,
rows: rows.map((row) =>
row.map((v, i) =>
i > 0 && /^-?\d+(?:\.\d{1,2})?$/.test(v)
? `${v.split('.')[0]}.${(v.split('.')[1] ?? '').padEnd(2, '0')}`
: v,
),
),
notes: id === 'startup' ? [...notes] : [],
issues: [],
});
const headers = ['Rubrica', ...plan.years.map((y) => String(y.year))];
const value = (n: number) => n.toFixed(2);
const row = (
label: string,
get: (y: (typeof result.years)[number], i: number) => string,
) => [label, ...result.years.map(get)];
const startup = make(
'startup',
'Start-up — exemplo',
['Rubrica', 'Montante'],
[
...plan.startupExpenses.map((r) => [r.label, r.amount]),
['Despesas de arranque', result.startupExpenses],
['Caixa necessária', plan.openingCash],
['Outros activos correntes', plan.otherCurrentAssets],
['Activos de longo prazo', plan.longTermAssets],
['Total de activos', result.assets],
['Requisitos totais', result.requiredFunding],
],
);
const sales = make('sales', 'Previsão de Vendas — exemplo', headers, [
row('Vendas totais', (y) => y.sales),
row('Custo directo', (y) => y.directCosts),
]);
sales.notes.push(
'Linhas por serviço do original não reconciliam com os totais anuais aceites. Mantêm-se agregadas; não se inventa a diferença por produto.',
);
const funding = make(
'funding',
'Financiamento — exemplo',
['Rubrica', 'Montante'],
[
['Capital do proprietário', plan.ownerCapital],
['Capital do investidor', plan.investorCapital],
['Empréstimos', plan.loans],
['Dinheiro adicional angariado', plan.additionalMoney],
['Total de fontes confirmadas', result.availableFunding],
['Financiamento necessário', result.requiredFunding],
[
'Capital por mobilizar — hipótese, não financiamento confirmado',
result.capitalToMobilise,
],
['Diferença por financiar', result.fundingGap],
],
);
const breakeven = make(
'break-even',
'Ponto de Equilíbrio — exemplo',
headers,
[
row('Receita mensal de equilíbrio', (y) =>
y.monthlyBreakEven === null
? 'Por determinar'
: value(y.monthlyBreakEven),
),
row('Custos fixos mensais', (y) => value(y.monthlyFixedCosts)),
],
);
const profit = make('profit-loss', 'Lucros e Perdas — exemplo', headers, [
row('Vendas', (y) => y.sales),
row('Custo directo', (y) => y.directCosts),
row('Margem bruta', (y) => y.grossMargin),
row('Despesas operacionais', (y) => y.operatingExpenses),
row('Resultado operacional', (y) => y.operatingProfit),
row('Juros', (_, i) => plan.years[i].interest),
row('Imposto estimado', (_, i) => plan.years[i].taxes),
row('Lucro líquido', (y) => y.netProfit),
]);
const cash = make('cashflow', 'Fluxo de Caixa — exemplo', headers, [
row('Caixa recebida', (_, i) => plan.years[i].cashReceived),
row('Caixa gasta', (_, i) => plan.years[i].cashSpent),
row('Fluxo líquido', (y) => y.cashFlow),
row('Caixa final', (y) => y.closingCash),
]);
const balance = make('balance', 'Balanço — exemplo', headers, [
row('Caixa líquida', (y) => y.closingCash),
row('Recebíveis líquidos', (y) => y.receivables),
row('Outros activos correntes', () => plan.otherCurrentAssets),
row('Activos fixos líquidos', () => plan.longTermAssets),
row('Total do activo', (y) => y.closingAssets),
row('Obrigações operacionais', (y) => y.operatingLiabilities),
row('Saldo fiscal estimado', (y) => y.vatBalance),
row('Total do passivo', (y) => y.closingLiabilities),
row('Capital e resultados', (y) => y.closingCapital),
row('Diferença do balanço', (y) => y.balanceDifference),
]);
balance.notes.push(
'Capital por mobilizar é hipótese de projecção explicitamente identificada; não é uma fonte obtida nem uma compensação contabilística.',
);
const cents = (s: string) => {
const negative = s.startsWith('-');
const [a, b = ''] = s.replace('-', '').split('.');
const n = BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
return negative ? -n : n;
};
const projectedCapital =
cents(result.availableFunding) +
cents(result.capitalToMobilise) -
cents(plan.loans);
const ratios = result.years.map((y, i) => {
try {
return calculateDecisionRatios(
{
cash: y.closingCash,
receivables: y.receivables,
inventory: '0',
otherCurrentAssets: plan.otherCurrentAssets,
longTermAssets: plan.longTermAssets,
accumulatedDepreciation: '0',
currentLiabilities: reportMoney(
cents(y.operatingLiabilities) + cents(y.vatBalance),
),
longTermLiabilities: plan.loans,
paidCapital: reportMoney(projectedCapital),
retainedResults: reportMoney(
cents(y.closingCapital) -
projectedCapital -
cents(y.netProfit),
),
periodResult: y.netProfit,
},
y.sales,
i ? result.years[i - 1].sales : undefined,
);
} catch {
return {
salesGrowth:
y.growthPercent === null ? null : y.growthPercent / 100,
currentLiquidity: null,
debtAssets: null,
netMargin:
y.netMarginPercent === null
? null
: y.netMarginPercent / 100,
returnOnEquity: null,
};
}
});
const ratio = make(
'ratios',
'Rácios financeiros — exemplo',
headers,
(
[
['salesGrowth', 'Crescimento das vendas', true],
['currentLiquidity', 'Liquidez corrente', false],
['debtAssets', 'Endividamento', true],
['netMargin', 'Margem líquida', true],
['returnOnEquity', 'Retorno do capital', true],
] as const
).map(([key, label, percent]) => [
label,
...ratios.map((r) =>
r?.[key] == null
? 'Por determinar'
: `${value(r[key]! * (percent ? 100 : 1)).replace('.', ',')}${percent ? '%' : '×'}`,
),
]),
);
const marketInput = {
...input,
marketAnalysis: {
baseYear: '2025',
years: '5',
segments: [
['Publicidade', '100000', '45'],
['Marketing Digital', '800', '50'],
['Intermediação Comercial', '150', '50'],
['eCommerce', '50000', '65'],
['Consultoria Financeira', '10', '75'],
['Formação', '500', '75'],
['Comunicação', '100', '15'],
['Eventos', '10', '5'],
].map(([label, customers, growthPercent]) => ({
label,
customers,
growthPercent,
basis: 'Hipótese ilustrativa do documento PN, tabela T002; não é procura demonstrada.',
})),
},
};
const market = buildComplementaryTables({}, marketInput)[0];
market.notes.push(
'Linha Desenvolvimento de aplicativos sem base numérica legível no original: não introduzida como zero. Projecções recalculadas pelas fórmulas do modelo; não se copiam totais inconsistentes.',
);
const milestones = make(
'milestones',
'Marcos — exemplo',
[
'Marco',
'Início',
'Término',
'Orçamento',
'Responsável',
'Departamento',
],
[
'Produzir Portal',
'Produzir Plano de Negócios',
'Contratar Pessoal Administrativo',
'Contratar Pessoal Vendas',
'Contratar Gestores do Portal',
].map((label) => [
label,
'2026-07-01',
'2026-07-31',
'0.00',
'Osmane Nala (exemplo do documento)',
'DG',
]),
);
const personnel = make('personnel', 'Pessoal — exemplo', headers, [
row('Folha de pagamento agregada', (_, i) => plan.years[i].payroll),
row('Encargos da folha', (_, i) => plan.years[i].payrollCharges),
]);
personnel.notes.push(
'O original não reconcilia remunerações por departamento com a folha agregada. Preservados os totais anuais aceites; quantidade e repartição por função permanecem por determinar, sem inventar trabalhadores ou salários.',
);
for (const y of result.years)
profit.notes.push(
...businessPlanWarnings({
currency: input.currency,
sales: Number(y.sales),
directCosts: Number(y.directCosts),
netProfit: Number(y.netProfit),
monthlyExpenses: y.monthlyFixedCosts,
monthlyBreakEven: y.monthlyBreakEven,
cash: Number(y.closingCash),
growthPercent: y.growthPercent ?? undefined,
assets: Number(y.closingAssets),
liabilities: Number(y.closingLiabilities),
ownAndInvestorCapital:
Number(plan.ownerCapital) + Number(plan.investorCapital),
fundingGap:
y.year === result.years[0].year
? Number(result.fundingGap)
: undefined,
}).map((w) => `Aviso não bloqueante — ${y.year}: ${w.message}`),
);
return [
startup,
market,
sales,
milestones,
personnel,
funding,
breakeven,
profit,
cash,
balance,
ratio,
];
}
+181 -25
View File
@@ -117,6 +117,20 @@ export type BusinessFinancialPlanInput = {
annualExampleSnapshot?: string;
currency: string;
annualGrowthPercent?: string;
/** Explicit opt-in; saved forecasts without this choice retain their values. */
applyAnnualGrowth?: boolean;
dividendsByPeriod?: string[];
operatingExpenseLines?: {
label: string;
monthlyAmount: string;
amountsByPeriod?: string[];
}[];
fundingBreakdown?: {
ownerCapital: string;
investorCapital: string;
additionalCapital: string;
};
reportSource?: 'investor' | 'annual_example';
presentationCurrency?: string;
fxRate?: string;
fxDate?: string;
@@ -180,7 +194,18 @@ export function serializeBusinessPlanSnapshot(
plan: BusinessFinancialPlanInput,
): string {
const snapshot = JSON.stringify({
version: 17,
version: [
'applyAnnualGrowth',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some(
(key) =>
plan[key as keyof BusinessFinancialPlanInput] !== undefined,
)
? 18
: 17,
plan: {
...plan,
...(plan.useSupplierPaymentTerms === true
@@ -262,12 +287,64 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 14 &&
decoded.version !== 15 &&
decoded.version !== 16 &&
decoded.version !== 17) ||
decoded.version !== 17 &&
decoded.version !== 18) ||
!decoded.plan ||
typeof decoded.plan !== 'object'
)
return null;
const plan = decoded.plan as Record<string, unknown>;
if (
decoded.version < 18 &&
[
'applyAnnualGrowth',
'dividendsByPeriod',
'operatingExpenseLines',
'fundingBreakdown',
'reportSource',
].some((key) => plan[key] !== undefined)
)
return null;
const shortText = (v: unknown) =>
typeof v === 'string' && v.length <= 160;
const amounts = (v: unknown) =>
Array.isArray(v) && v.length <= 60 && v.every(shortText);
if (
(plan.applyAnnualGrowth !== undefined &&
typeof plan.applyAnnualGrowth !== 'boolean') ||
(plan.reportSource !== undefined &&
(typeof plan.reportSource !== 'string' ||
!['investor', 'annual_example'].includes(
plan.reportSource,
))) ||
(plan.dividendsByPeriod !== undefined &&
!amounts(plan.dividendsByPeriod))
)
return null;
if (
plan.operatingExpenseLines !== undefined &&
(!Array.isArray(plan.operatingExpenseLines) ||
plan.operatingExpenseLines.length > 40 ||
plan.operatingExpenseLines.some(
(r: Record<string, unknown>) =>
!r ||
!shortText(r.label) ||
!shortText(r.monthlyAmount) ||
(r.amountsByPeriod !== undefined &&
!amounts(r.amountsByPeriod)),
))
)
return null;
if (plan.fundingBreakdown !== undefined) {
const f = plan.fundingBreakdown as Record<string, unknown>;
if (
!f ||
!['ownerCapital', 'investorCapital', 'additionalCapital'].every(
(k) => shortText(f[k]),
)
)
return null;
}
// A blank percentage is an unfinished draft, not a zero assumption.
// Editable recovery also retains invalid percentages for correction.
// The zero below is only an upper-bound validation accumulator, never
@@ -468,7 +545,7 @@ export function restoreBusinessPlanSnapshot(
if (scheduledRate > 100_000_000n) return null;
}
if (
decoded.version === 17 &&
decoded.version >= 17 &&
!Array.isArray(plan.openingPayablesInstallments)
)
return null;
@@ -476,7 +553,7 @@ export function restoreBusinessPlanSnapshot(
plan.openingPayablesInstallments !== undefined &&
(!Array.isArray(plan.openingPayablesInstallments) ||
plan.openingPayablesInstallments.length > 60 ||
(decoded.version !== 17 &&
(decoded.version < 17 &&
plan.openingPayablesInstallments.length > 0) ||
plan.openingPayablesInstallments.some(
(entry) =>
@@ -871,7 +948,7 @@ export function monthlyProjectedSales(
)
return null;
total += multiplyQuantity(
quantity(units),
projectedUnits(input, product, month),
cents(price, `Preço de ${product.label}`),
);
}
@@ -879,6 +956,30 @@ export function monthlyProjectedSales(
});
}
/** Grow quantities only when no monthly quantity was explicitly declared. Prices and unit costs remain declared inputs. */
function projectedUnits(
input: BusinessFinancialPlanInput,
product: ProductLine,
month: number,
): bigint {
const explicit = product.monthlyUnitsByPeriod?.[month];
if (explicit !== undefined) return quantity(explicit);
let value = quantity(product.monthlyUnits);
if (!input.applyAnnualGrowth) return value;
const rate = percentMicro(
input.annualGrowthPercent ?? '',
'Crescimento anual',
);
if (rate < 0n) throw new Error('Este valor não pode ser negativo.');
// percentMicro uses millionths of a percentage point.
const denominator = percentMicro('100', 'Crescimento anual');
const years = Math.floor(month / 12);
const numerator = (denominator + rate) ** BigInt(years);
const divisor = denominator ** BigInt(years);
value = (value * numerator + divisor / 2n) / divisor;
return value;
}
/** Existing purchase orders are planning references, never a proxy for deductible VAT or invoice dates. */
export function monthlyProjectedPurchaseOrders(
input: BusinessFinancialPlanInput,
@@ -1186,19 +1287,37 @@ function applyScenario(
),
}))
: base.inventoryPurchaseSchedule,
monthlyOperatingExpenses: moneyChange(
base.monthlyOperatingExpenses,
adjustment.operatingCostsPercent,
'Despesas operacionais',
),
monthlyOperatingExpensesByPeriod:
base.monthlyOperatingExpensesByPeriod?.map((amount, month) =>
monthlyOperatingExpenses: base.operatingExpenseLines
? base.monthlyOperatingExpenses
: moneyChange(
base.monthlyOperatingExpenses,
adjustment.operatingCostsPercent,
'Despesas operacionais',
),
operatingExpenseLines: base.operatingExpenseLines?.map((line) => ({
...line,
monthlyAmount: moneyChange(
line.monthlyAmount,
adjustment.operatingCostsPercent,
line.label,
),
amountsByPeriod: line.amountsByPeriod?.map((value) =>
moneyChange(
amount,
value,
adjustment.operatingCostsPercent,
`Despesas operacionais mes ${month + 1}`,
line.label,
),
),
})),
monthlyOperatingExpensesByPeriod: base.operatingExpenseLines
? base.monthlyOperatingExpensesByPeriod
: base.monthlyOperatingExpensesByPeriod?.map((amount, month) =>
moneyChange(
amount,
adjustment.operatingCostsPercent,
`Despesas operacionais mes ${month + 1}`,
),
),
monthlyOperatingPayments: moneyChange(
base.monthlyOperatingPayments,
adjustment.operatingCostsPercent,
@@ -1287,6 +1406,17 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
if (input.fundingBreakdown) {
const f = input.fundingBreakdown;
const total =
cents(f.ownerCapital, 'Capital do proprietário') +
cents(f.investorCapital, 'Capital do investidor') +
cents(f.additionalCapital, 'Capital adicional');
if (total !== cents(input.equity, 'Capital introduzido'))
throw new Error(
'O capital discriminado não corresponde ao capital introduzido. Confira os campos de financiamento.',
);
}
if (input.annualGrowthPercent?.trim()) {
if (
percentMicro(
@@ -1591,7 +1721,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
return {
units:
unitsByPeriod?.map(quantity) ??
Array(periods).fill(quantity(product.monthlyUnits)),
Array.from({ length: periods }, (_, month) =>
projectedUnits(input, product, month),
),
prices: parseMoneySchedule(
priceSchedule,
basePrice,
@@ -1740,10 +1872,9 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
.map((entry) => entry.leadMonths)
: Array<number>(periods).fill(inventoryPurchaseLeadMonths);
const inventoryProjectionEnabled = inventoryPurchasesByPeriod !== null;
const operatingExpenses = cents(
input.monthlyOperatingExpenses,
'Despesas operacionais',
);
const operatingExpenses = input.operatingExpenseLines
? 0n
: cents(input.monthlyOperatingExpenses, 'Despesas operacionais');
const moneySchedule = (
schedule: string[] | undefined,
base: bigint,
@@ -1820,11 +1951,32 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
variablePayments,
'Pagamentos de compras',
);
const operatingExpenseByPeriod = moneySchedule(
input.monthlyOperatingExpensesByPeriod,
operatingExpenses,
'Despesas operacionais',
);
let operatingExpenseByPeriod: bigint[] = input.operatingExpenseLines
? []
: moneySchedule(
input.monthlyOperatingExpensesByPeriod,
operatingExpenses,
'Despesas operacionais',
);
if (input.operatingExpenseLines) {
if (!input.operatingExpenseLines.length)
throw new Error('Acrescente pelo menos uma despesa discriminada.');
const schedules = input.operatingExpenseLines.map((line) => {
if (!line.label.trim())
throw new Error('Indique a designação da despesa.');
return moneySchedule(
line.amountsByPeriod,
cents(line.monthlyAmount, line.label),
line.label,
);
});
operatingExpenseByPeriod = Array.from({ length: periods }, (_, month) =>
schedules.reduce((sum, s) => sum + s[month], 0n),
);
}
const dividends = input.dividendsByPeriod
? moneySchedule(input.dividendsByPeriod, 0n, 'Dividendos')
: Array<bigint>(periods).fill(0n);
const operatingPayments = cents(
input.monthlyOperatingPayments,
'Pagamentos operacionais',
@@ -2192,7 +2344,8 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
periodPayrollPayment +
interestPayment +
principalRepayment +
openingPayablesPayments;
openingPayablesPayments +
dividends[month - 1];
const netCashFlow = allCollections - totalPayments;
cash += netCashFlow;
totalProfitBeforeTax += profitBeforeTax;
@@ -2256,6 +2409,7 @@ export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
payrollPayments: format(periodPayrollPayment),
interestPayment: format(interestPayment),
principalRepayment: format(principalRepayment),
dividends: format(dividends[month - 1]),
netCashFlow: format(netCashFlow),
closingCash: format(cash),
});
@@ -3170,6 +3324,7 @@ export function exportBusinessPlanCsv(
'Pagamento de compras',
'Resultado antes impostos',
'Pagamento capital',
...(input.dividendsByPeriod ? ['Dividendos distribuídos'] : []),
'Fluxo líquido',
'Caixa final',
],
@@ -3203,6 +3358,7 @@ export function exportBusinessPlanCsv(
row.variableCostPayments,
row.profitBeforeTax,
row.principalRepayment,
...(input.dividendsByPeriod ? [row.dividends] : []),
row.netCashFlow,
row.closingCash,
]),
+108
View File
@@ -0,0 +1,108 @@
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
import {
businessPlanWarnings,
type PlanWarningMetrics,
} from './business-plan-guidance.ts';
import type { InvestmentReportTable } from './integral-financial-report.ts';
/** Only use determined values from the same tables/version, never replace missing amounts by zero. */
export function financialPlanWarningMetrics(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
const periods = plan.periods ?? 12;
const read = (id: string, label: string, column: number) => {
const t = tables.find((t) => t.id === id);
if (!t || t.issues.length) return undefined;
const value = t.rows.find((r) => r[0] === label)?.[column];
return value && /^-?\d+(?:\.\d{1,2})?$/.test(value)
? Number(value)
: undefined;
};
return Array.from({ length: Math.ceil(periods / 12) }, (_, year) => {
const col = periods + year + 1;
const count = Math.min(12, periods - year * 12);
const sales = read('sales', 'Vendas totais', col);
const costs = read('profit-loss', 'Custo directo', col);
const operating = read('profit-loss', 'Despesas operacionais', col);
const payroll = read('profit-loss', 'Pessoal', col);
const depreciation = read('profit-loss', 'Depreciação', col);
const fixed =
operating !== undefined &&
payroll !== undefined &&
depreciation !== undefined
? operating + payroll + depreciation
: undefined;
const previous = year
? read('sales', 'Vendas totais', col - 1)
: undefined;
const metrics: PlanWarningMetrics = {
currency: plan.currency,
fundingGap:
year === 0
? read('funding', 'Diferença por financiar', 1)
: undefined,
netProfit: read('profit-loss', 'Lucro líquido', col),
sales,
directCosts: costs,
monthlyExpenses: fixed === undefined ? undefined : fixed / count,
monthlyBreakEven:
sales &&
costs !== undefined &&
fixed !== undefined &&
sales > costs
? fixed / count / ((sales - costs) / sales)
: undefined,
cash: read('cashflow', 'Caixa final', col),
growthPercent:
previous && sales !== undefined && count === 12
? (sales / previous - 1) * 100
: year === 0 && plan.annualGrowthPercent?.trim()
? Number(plan.annualGrowthPercent)
: undefined,
assets: read('balance', 'Total do activo', col),
liabilities: read('balance', 'Total do passivo', col),
ownAndInvestorCapital: /^\d+(?:\.\d{1,2})?$/.test(plan.equity)
? Number(plan.equity)
: undefined,
};
return {
year: Number(plan.reportAssumptions?.startYear) + year,
metrics,
count,
};
});
}
export function financialPlanWarnings(
plan: BusinessFinancialPlanInput,
tables: InvestmentReportTable[],
) {
return financialPlanWarningMetrics(plan, tables).flatMap(
({ year, metrics, count }) => {
// The warning helper compares a full year's sales to a monthly threshold.
const adjusted = {
...metrics,
sales:
metrics.sales === undefined
? undefined
: (metrics.sales * 12) / count,
directCosts:
metrics.directCosts === undefined
? undefined
: (metrics.directCosts * 12) / count,
};
const warnings = businessPlanWarnings(adjusted).map((w) => ({
...w,
id: `${year}-${w.id}`,
message: `${year}: ${w.message}`,
}));
if ((plan.salesCollectionLagMonths ?? 0) > 3)
warnings.push({
id: `${year}-credit`,
message: `${year}: O prazo de recebimento é superior a três meses no modelo mensal e pressiona a caixa. Confirme o prazo indicado.`,
});
return warnings;
},
);
}
+38 -2
View File
@@ -287,6 +287,22 @@ export function buildIntegralFinancialTables(
'Despesas de arranque reconhecidas e pagas no início. Saldos patrimoniais anteriores não são novas despesas.',
);
table('funding').rows = [
...(plan.fundingBreakdown
? [
[
'Capital do proprietário',
plan.fundingBreakdown.ownerCapital,
],
[
'Capital do investidor',
plan.fundingBreakdown.investorCapital,
],
[
'Capital adicional angariado',
plan.fundingBreakdown.additionalCapital,
],
]
: []),
['Capital introduzido', plan.equity],
['Suprimentos', plan.shareholderLoans],
['Empréstimos', plan.bankLoanProceeds],
@@ -335,6 +351,7 @@ export function buildIntegralFinancialTables(
let depreciation = 0n,
cumulativeProfit = -startup,
principal = 0n;
let distributedDividends = 0n;
let obligationsKnown = true;
const fixed = openingFixed + cents(plan.assetInvestment);
const loans =
@@ -393,6 +410,7 @@ export function buildIntegralFinancialTables(
depreciation += cents(row.depreciation);
principal += cents(row.principalRepayment);
cumulativeProfit += profit;
distributedDividends += cents(row.dividends);
const inventory =
row.inventoryClosing === null
? null
@@ -421,7 +439,8 @@ export function buildIntegralFinancialTables(
loans -
principal +
deferredGrant;
const capital = paidCapital + cumulativeProfit;
const capital =
paidCapital + cumulativeProfit - distributedDividends;
return {
opening,
cash,
@@ -439,7 +458,7 @@ export function buildIntegralFinancialTables(
: assets - liabilities - capital,
loans: loans - principal,
paidCapital,
accumulatedResults: cumulativeProfit,
accumulatedResults: cumulativeProfit - distributedDividends,
fixed: fixed - depreciation,
inventory,
};
@@ -464,6 +483,21 @@ export function buildIntegralFinancialTables(
['interestExpense', 'Juros'],
] as const)
flows('profit-loss', label, data(key));
for (const line of plan.operatingExpenseLines ?? [])
flows(
'profit-loss',
`Despesa: ${line.label}`,
result.rows.map((_, i) =>
cents(line.amountsByPeriod?.[i] ?? line.monthlyAmount),
),
);
table('profit-loss').notes.push(
...(plan.operatingExpenseLines
? [
'As despesas discriminadas são componentes do total operacional, não despesas adicionais.',
]
: []),
);
flows('profit-loss', 'Imposto estimado', taxExpenses);
flows(
'profit-loss',
@@ -494,6 +528,8 @@ export function buildIntegralFinancialTables(
] as const)
flows('cashflow', label, data(key));
flows('cashflow', 'Pagamento fiscal estimado', taxPayments);
if (plan.dividendsByPeriod)
flows('cashflow', 'Dividendos distribuídos', data('dividends'));
flows(
'cashflow',
'Fluxo líquido',
+67 -2
View File
@@ -10,6 +10,8 @@ import {
} from './integral-financial-report.ts';
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { financialPlanWarnings } from './financial-plan-warnings.ts';
import { buildAnnualExampleTables } from './annual-example-report.ts';
import { pathStates } from './investor-path.ts';
import {
buildProjectDossierRows,
@@ -543,8 +545,17 @@ function makeSections(
const section = sections.get(id as DossierReportSectionId);
if (section) section.tables = [complementaryTables[i]];
}
if (finance && financialPlan?.reportAssumptions) {
if (
finance &&
financialPlan?.reportAssumptions &&
financialPlan.reportSource !== 'annual_example'
) {
finance.tables = buildIntegralFinancialTables(financialPlan);
finance.paragraphs.push(
...financialPlanWarnings(financialPlan, finance.tables).map(
(w) => `Aviso não bloqueante — ${w.message}`,
),
);
finance.tables.push(
buildFinancialRatiosTable(financialPlan, finance.tables),
);
@@ -581,6 +592,9 @@ function makeSections(
'Pagamentos de pessoal',
'Juros pagos',
'Capital reembolsado',
...(financialPlan.dividendsByPeriod
? ['Dividendos distribuídos']
: []),
'Pagamento de obrigações iniciais',
'Pagamento fiscal estimado',
]),
@@ -649,7 +663,53 @@ function makeSections(
});
}
}
if (finance && currentCalculation) {
if (finance && financialPlan?.reportSource === 'annual_example') {
finance.rows = finance.rows
.filter((row) => row.field === 'Classificação CAE do plano')
.map((row) => ({
...row,
classification:
'Contexto do investimento preservado; não é a classificação do exemplo sintético',
}));
finance.paragraphs = [
'Exemplo sintético anual editável, da mesma versão guardada do plano. Não representa dados reais do investidor nem financiamento confirmado. As entradas do investidor permanecem preservadas.',
];
try {
const example = buildAnnualExampleTables(financialPlan);
finance.tables = example.filter(
(t) =>
!['market-analysis', 'milestones', 'personnel'].includes(
t.id,
),
);
for (const [sectionId, tableId] of [
['market', 'market-analysis'],
['execution', 'milestones'],
['team', 'personnel'],
] as const) {
const section = sections.get(sectionId);
if (section) {
section.tables = example.filter((t) => t.id === tableId);
section.rows = [];
section.paragraphs = [
'Dados sintéticos de referência do exemplo anual; não são dados reais do investidor.',
];
}
}
} catch (error) {
finance.tables = [];
finance.paragraphs.push(
error instanceof Error
? error.message
: 'Não foi possível recuperar o exemplo.',
);
}
}
if (
finance &&
currentCalculation &&
financialPlan?.reportSource !== 'annual_example'
) {
const snapshot = currentCalculation.snapshot;
const result =
snapshot &&
@@ -939,6 +999,11 @@ export function createIntegralFinancialReport(
: []),
`Tabelas incluídas: ${ordered.length} de 11. Os valores provêm do mesmo plano e dos dados complementares guardados.`,
'Projecções para avaliar o investimento; não são contas realizadas nem confirmação de financiamento. Campos em falta e indicadores indeterminados mantêm-se identificados.',
...(finance?.paragraphs.filter(
(p) =>
p.startsWith('Aviso não bloqueante') ||
p.startsWith('Exemplo sintético anual'),
) ?? []),
],
rows:
finance?.rows.filter((row) => summary.has(row.field)) ?? [],
@@ -83,6 +83,18 @@ function editor(initialSnapshot) {
'@/lib/business-financial-plan': business,
'@/lib/simulation-contract': contract,
'@/lib/financial-fiscal-bridge': bridge,
'@/components/financial-plan-details': {
FinancialPlanDetails: () => null,
},
'@/components/market-analysis-plan': {
MarketAnalysisPlan: () => null,
},
'@/components/financial-ratios-plan': {
FinancialRatiosPlan: () => null,
},
'@/components/plan-economic-classification': {
PlanEconomicClassification: () => null,
},
}[name] ??
require(name),
module,
@@ -0,0 +1,413 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import JSZip from 'jszip';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
import * as guidance from '../../resources/js/lib/business-plan-guidance.ts';
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import {
forecastBusinessPlan,
monthlyProjectedSales,
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
compareBusinessScenarios,
exportBusinessPlanCsv,
} from '../../resources/js/lib/business-financial-plan.ts';
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
import { financialPlanWarnings } from '../../resources/js/lib/financial-plan-warnings.ts';
import { buildAnnualExampleTables } from '../../resources/js/lib/annual-example-report.ts';
import {
newAnnualReferencePlan,
serializeAnnualExampleSnapshot,
} from '../../resources/js/lib/business-plan-guidance.ts';
import {
createProjectDossierReport,
createIntegralFinancialReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
const cell = (tables, id, label, index) =>
tables.find((t) => t.id === id).rows.find((r) => r[0] === label)[index];
const reload = (p) =>
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p));
void test('annual growth is explicit, reaches all dependent forecasts and preserves declared monthly overrides', () => {
const p = financialReportFixture(36);
p.annualGrowthPercent = '150';
const unchanged = forecastBusinessPlan(p);
assert.equal(unchanged.rows[12].revenue, '1000.00');
p.applyAnnualGrowth = true;
const result = forecastBusinessPlan(reload(p));
assert.equal(result.rows[12].revenue, '2500.00');
assert.equal(result.rows[24].revenue, '6250.00');
assert.equal(result.rows[12].variableCost, '1000.00');
assert.deepEqual(
monthlyProjectedSales(p),
result.rows.map((r) => r.revenue),
);
p.products[0].monthlyUnitsByPeriod = Array(36).fill('7');
assert.equal(forecastBusinessPlan(p).rows[24].revenue, '700.00');
const tables = buildIntegralFinancialTables({
...p,
products: [{ ...p.products[0], monthlyUnitsByPeriod: undefined }],
});
assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '12000.00');
assert.equal(cell(tables, 'sales', 'Vendas totais', 38), '30000.00');
assert.equal(cell(tables, 'sales', 'Vendas totais', 39), '75000.00');
});
void test('dividends reduce cash and capital equally, never profit; monthly and annual balances stay exact', () => {
const p = financialReportFixture(13),
base = buildIntegralFinancialTables(p);
p.dividendsByPeriod = Array(13).fill('25.25');
const updated = reload(p),
tables = buildIntegralFinancialTables(updated);
assert.equal(forecastBusinessPlan(updated).rows[0].dividends, '25.25');
for (let col = 1; col <= 13; col++) {
assert.equal(
cell(tables, 'profit-loss', 'Lucro líquido', col),
cell(base, 'profit-loss', 'Lucro líquido', col),
);
const cents = (s) => BigInt(s.replace('.', ''));
assert.equal(
cents(cell(base, 'balance', 'Capital e resultados', col)) -
cents(cell(tables, 'balance', 'Capital e resultados', col)),
2525n * BigInt(col),
);
assert.equal(
cents(cell(base, 'cashflow', 'Caixa final', col)) -
cents(cell(tables, 'cashflow', 'Caixa final', col)),
2525n * BigInt(col),
);
assert.equal(
cell(tables, 'balance', 'Diferença do balanço', col),
'0.00',
);
}
assert.equal(
cell(tables, 'cashflow', 'Dividendos distribuídos', 14),
'303.00',
);
assert.equal(
cell(tables, 'cashflow', 'Dividendos distribuídos', 15),
'25.25',
);
p.dividendsByPeriod[0] = '-1';
assert.throws(() => forecastBusinessPlan(p));
p.dividendsByPeriod = ['25'];
assert.throws(() => forecastBusinessPlan(p));
});
void test('operating components replace rather than add the old aggregate; capital splits reconcile and survive recovery', () => {
const p = financialReportFixture(13);
p.operatingExpenseLines = [
{ label: 'Rendas', monthlyAmount: '10.25' },
{ label: 'Seguros', monthlyAmount: '20.75' },
];
p.fundingBreakdown = {
ownerCapital: '200.25',
investorCapital: '300.25',
additionalCapital: '99.50',
};
const recovered = reload(p);
assert.deepEqual(recovered.operatingExpenseLines, p.operatingExpenseLines);
assert.deepEqual(recovered.fundingBreakdown, p.fundingBreakdown);
const tables = buildIntegralFinancialTables(recovered);
assert.equal(
forecastBusinessPlan(recovered).rows[0].operatingExpenses,
'31.00',
);
assert.equal(
cell(tables, 'profit-loss', 'Despesas operacionais', 14),
'372.00',
);
assert.equal(cell(tables, 'profit-loss', 'Despesa: Rendas', 14), '123.00');
assert.equal(cell(tables, 'funding', 'Capital do investidor', 1), '300.25');
assert.equal(cell(tables, 'balance', 'Diferença do balanço', 13), '0.00');
recovered.monthlyOperatingExpenses = '';
recovered.monthlyOperatingExpensesByPeriod = [''];
assert.equal(
forecastBusinessPlan(recovered).rows[0].operatingExpenses,
'31.00',
);
p.equity = '601';
assert.throws(() => forecastBusinessPlan(p), /capital discriminado/);
p.equity = '600';
p.operatingExpenseLines[0].monthlyAmount = '';
assert.throws(() => forecastBusinessPlan(p));
assert.equal(reload({ ...p, dividendsByPeriod: [5] }), null);
});
void test('the full example shares the saved snapshot and its eleven tables and exports change together, leaving investor inputs untouched', async () => {
const p = financialReportFixture(13),
annual = newAnnualReferencePlan();
annual.years[0].sales = '14537.25';
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
p.reportSource = 'annual_example';
const before = forecastBusinessPlan(p),
recovered = reload(p);
const tables = buildAnnualExampleTables(recovered);
assert.equal(tables.length, 11);
assert.equal(cell(tables, 'sales', 'Vendas totais', 1), '14537.25');
assert.equal(cell(tables, 'balance', 'Diferença do balanço', 1), '0.00');
assert.equal(
cell(tables, 'personnel', 'Folha de pagamento agregada', 1),
'2100.00',
);
assert.deepEqual(forecastBusinessPlan(recovered), before);
const report = createProjectDossierReport(
{
project_title: 'QA sintético',
business_plan_snapshot: serializeBusinessPlanSnapshot(recovered),
},
{
selectedSections: new Set([
'finance',
'market',
'execution',
'team',
]),
generatedAt: '2026-11-20T12:00:00Z',
},
);
const all = report.sections.flatMap((s) => s.tables ?? []);
assert.equal(all.length, 11);
assert.deepEqual(
all.find((t) => t.id === 'sales'),
tables.find((t) => t.id === 'sales'),
);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /14 537,25/);
assert.match(html, /Exemplo sintético/);
const blob = await generateProjectDossierDocx(report, []),
zip = await JSZip.loadAsync(
blob instanceof Blob ? await blob.arrayBuffer() : blob,
),
xml = await zip.file('word/document.xml').async('string');
assert.match(xml, /14 537,25/);
assert.match(xml, /Capital por mobilizar/);
recovered.reportSource = 'investor';
assert.equal(
buildIntegralFinancialTables(recovered)
.find((t) => t.id === 'sales')
.rows.find((r) => r[0] === 'Vendas totais')[1],
'1000.00',
);
});
void test('financial warnings use the actual report metrics, remain non-blocking and reach print exports', async () => {
const p = financialReportFixture(12);
p.products[0].unitVariableCost = '90';
p.bankLoanProceeds = '30000';
p.equity = '0';
p.salesCollectionLagMonths = 4;
p.applyAnnualGrowth = false;
p.annualGrowthPercent = '150';
p.monthlyInventoryPurchases = '900';
p.monthlyVariableCostPayments = '900';
const tables = buildIntegralFinancialTables(p);
assert.ok(
tables.every((t) => !t.issues.length),
JSON.stringify(tables.flatMap((t) => t.issues)),
);
const warnings = financialPlanWarnings(p, tables),
ids = warnings.map((w) => w.id);
for (const id of [
'loss',
'margin',
'break-even',
'cash',
'growth',
'credit',
'debt',
'capital',
]) {
// Cash may be abundant because the declared loan is large; test that condition separately.
if (id !== 'cash')
assert.ok(
ids.some((s) => s.endsWith('-' + id)),
id,
);
}
const low = structuredClone(tables);
low
.find((t) => t.id === 'cashflow')
.rows.find((r) => r[0] === 'Caixa final')[13] = '0.00';
assert.ok(
financialPlanWarnings(p, low).some((w) => w.id.endsWith('-cash')),
);
const report = createProjectDossierReport(
{ business_plan_snapshot: serializeBusinessPlanSnapshot(p) },
{
selectedSections: new Set(['finance']),
generatedAt: '2026-11-20T12:00:00Z',
},
);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /Aviso não bloqueante/);
assert.match(html, /margem bruta é baixa/);
const integral = createIntegralFinancialReport({
business_plan_snapshot: serializeBusinessPlanSnapshot(p),
});
assert.match(
await createProjectDossierPrintHtml(integral, []),
/margem bruta é baixa/,
);
});
void test('new declarations retain strict recovery boundaries and scenario adjustments reach operating components', () => {
const p = financialReportFixture(12);
p.operatingExpenseLines = [{ label: 'Renda', monthlyAmount: '10.25' }];
p.dividendsByPeriod = Array(12).fill('2.25');
const adjustment = {
unitVolumePercent: '0',
unitPricePercent: '0',
unitCostPercent: '0',
operatingCostsPercent: '100',
cashCollectionsPercent: '0',
};
p.scenarioAdjustments = {
favorable: adjustment,
unfavorable: { ...adjustment, operatingCostsPercent: '-50' },
};
const scenarios = compareBusinessScenarios(p);
assert.equal(scenarios.favorable.result.rows[0].operatingExpenses, '20.50');
assert.equal(
scenarios.unfavorable.result.rows[0].operatingExpenses,
'5.13',
);
assert.match(exportBusinessPlanCsv(p), /Dividendos distribuídos/);
assert.equal(
restoreBusinessPlanSnapshot(
serializeBusinessPlanSnapshot({
...p,
dividendsByPeriod: ['0', null],
}),
),
null,
);
assert.equal(
restoreBusinessPlanSnapshot(
serializeBusinessPlanSnapshot({
...p,
fundingBreakdown: { ownerCapital: 0 },
}),
),
null,
);
assert.equal(
restoreBusinessPlanSnapshot(
serializeBusinessPlanSnapshot({ ...p, reportSource: 'foreign' }),
),
null,
);
p.fundingBreakdown = {
ownerCapital: '1',
investorCapital: '0',
additionalCapital: '0',
};
assert.throws(() => forecastBusinessPlan(p), /capital discriminado/);
});
void test('version 18 protects the added financial semantics and preserves prior payables, CAE and the legacy version 17 inputs', () => {
const legacy = financialReportFixture(12);
legacy.economicClassification = selectPlanCae('55111');
legacy.openingPayablesInstallments = [{ month: 2, percent: '50' }];
assert.equal(JSON.parse(serializeBusinessPlanSnapshot(legacy)).version, 17);
const p = { ...legacy, dividendsByPeriod: Array(12).fill('0') };
const snapshot = serializeBusinessPlanSnapshot(p);
assert.equal(JSON.parse(snapshot).version, 18);
const recovered = restoreBusinessPlanSnapshot(snapshot);
assert.deepEqual(
recovered.economicClassification,
legacy.economicClassification,
);
assert.deepEqual(
recovered.openingPayablesInstallments,
legacy.openingPayablesInstallments,
);
const downgraded = JSON.parse(snapshot);
downgraded.version = 17;
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(downgraded)), null);
assert.deepEqual(
forecastBusinessPlan(recovered),
forecastBusinessPlan({ ...legacy, dividendsByPeriod: undefined }),
);
});
void test('actual editor controls preserve declarations through snapshot reload and an explicit return from example to investor report', () => {
const source = fs.readFileSync(
new URL(
'../../resources/js/components/financial-plan-details.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} },
require = createRequire(import.meta.url);
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
name === '@/lib/business-plan-guidance' ? guidance : require(name),
module,
module.exports,
);
let plan = financialReportFixture(13);
const render = () =>
module.exports.FinancialPlanDetails({
plan,
onChange: (next) => {
plan = reload(next);
assert.ok(plan);
},
});
const nodes = (n) =>
Array.isArray(n)
? n.flatMap(nodes)
: n && typeof n === 'object'
? [n, ...nodes(n.props?.children)]
: [];
const text = (n) =>
typeof n === 'string'
? n
: Array.isArray(n)
? n.map(text).join('')
: n && typeof n === 'object'
? text(n.props?.children)
: '';
const field = (label) => {
const node = nodes(render()).find(
(n) => n.type === 'label' && text(n).includes(label),
);
assert.ok(node, label);
return nodes(node).find(
(n) => n.type === 'input' || n.type === 'select',
);
};
field('Projectar os anos seguintes').props.onChange({
target: { checked: true },
});
assert.equal(plan.applyAnnualGrowth, true);
field('Planear dividendos').props.onChange({ target: { checked: true } });
field('Dividendos, mês 1').props.onChange({ target: { value: '12.25' } });
assert.equal(plan.dividendsByPeriod[0], '12.25');
const select = () => nodes(render()).find((n) => n.type === 'select');
select().props.onChange({ target: { value: 'annual_example' } });
assert.equal(plan.reportSource, 'annual_example');
assert.ok(plan.annualExampleSnapshot);
assert.equal(buildAnnualExampleTables(plan).length, 11);
select().props.onChange({ target: { value: 'investor' } });
assert.equal(plan.reportSource, 'investor');
assert.equal(plan.dividendsByPeriod[0], '12.25');
assert.equal(plan.products[0].monthlyUnits, '10');
});
@@ -8,6 +8,8 @@ import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import * as report from '../../resources/js/lib/integral-financial-report.ts';
import * as warnings from '../../resources/js/lib/financial-plan-warnings.ts';
import * as annual from '../../resources/js/lib/annual-example-report.ts';
import {
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
@@ -36,7 +38,13 @@ void test('one startup editor retains all rows and persists an edit without dupl
? report
: name === './investment-report-tables'
? { InvestmentReportTables: () => null }
: require(name),
: name === '@/lib/financial-plan-warnings'
? warnings
: name === '@/lib/annual-example-report'
? annual
: name === './business-plan-warnings'
? { BusinessPlanWarnings: () => null }
: require(name),
module,
module.exports,
);
@@ -226,7 +226,7 @@ void test('partial years, changing product schedules and negative cash keep exac
assert.equal(displayReportMoney('-1234567.89'), '-1 234 567,89');
});
void test('dossier print and Word exports include the same seven statements, escape labels and split wide tables', async () => {
void test('dossier print and Word exports include the seven statements and approved ratios, escape labels and split wide tables', async () => {
const input = plan(13);
input.products[0].label = '<script>não executar</script>';
const report = createProjectDossierReport(
@@ -239,7 +239,7 @@ void test('dossier print and Word exports include the same seven statements, esc
generatedAt: '2026-11-20T12:00:00Z',
},
);
assert.equal(report.sections[0].tables.length, 7);
assert.equal(report.sections[0].tables.length, 8);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /Balanço Projectado/);
assert.match(html, /&lt;script&gt;/);