feat(qa): separate startup resources and trace original example rows

This commit is contained in:
2026-11-20 17:43:34 +02:00
parent 41968bc537
commit 9f7dd7df6d
15 changed files with 1484 additions and 37 deletions
@@ -8,6 +8,7 @@ import { InvestmentReportTables } from './investment-report-tables';
import { BusinessPlanWarnings } from './business-plan-warnings'; import { BusinessPlanWarnings } from './business-plan-warnings';
import { financialPlanWarnings } from '@/lib/financial-plan-warnings'; import { financialPlanWarnings } from '@/lib/financial-plan-warnings';
import { buildAnnualExampleTables } from '@/lib/annual-example-report'; import { buildAnnualExampleTables } from '@/lib/annual-example-report';
import { StartupAssetRequirements } from './startup-asset-requirements';
export function IntegralFinancialPlan({ export function IntegralFinancialPlan({
plan, plan,
@@ -81,6 +82,7 @@ export function IntegralFinancialPlan({
em falta permanecem por determinar; indique zero apenas quando em falta permanecem por determinar; indique zero apenas quando
aplicável. aplicável.
</p> </p>
<StartupAssetRequirements plan={plan} onChange={onChange} />
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2">
<label className="grid gap-1 text-sm"> <label className="grid gap-1 text-sm">
Ano inicial Ano inicial
@@ -96,16 +98,18 @@ export function IntegralFinancialPlan({
} }
/> />
</label> </label>
{numeric( {!plan.startupAssetRequirements &&
'Activos fixos anteriores (valor líquido)', numeric(
a.openingFixedAssets, 'Activos fixos anteriores (valor líquido)',
(openingFixedAssets) => update({ openingFixedAssets }), a.openingFixedAssets,
)} (openingFixedAssets) => update({ openingFixedAssets }),
{numeric( )}
'Outros activos anteriores', {!plan.startupAssetRequirements &&
a.openingOtherAssets, numeric(
(openingOtherAssets) => update({ openingOtherAssets }), 'Outros activos anteriores',
)} a.openingOtherAssets,
(openingOtherAssets) => update({ openingOtherAssets }),
)}
{numeric( {numeric(
'Capital e resultados anteriores', 'Capital e resultados anteriores',
a.openingEquity, a.openingEquity,
@@ -25,6 +25,7 @@ import { MarketAnalysisPlan } from '@/components/market-analysis-plan';
import { FinancialRatiosPlan } from '@/components/financial-ratios-plan'; import { FinancialRatiosPlan } from '@/components/financial-ratios-plan';
import { PlanEconomicClassification } from '@/components/plan-economic-classification'; import { PlanEconomicClassification } from '@/components/plan-economic-classification';
import { FinancialPlanDetails } from '@/components/financial-plan-details'; import { FinancialPlanDetails } from '@/components/financial-plan-details';
import { StartupAssetRequirements } from '@/components/startup-asset-requirements';
const emptyPlan: BusinessFinancialPlanInput = { const emptyPlan: BusinessFinancialPlanInput = {
currency: '', currency: '',
@@ -945,6 +946,7 @@ export function SimulationBusinessPlan({
)} )}
<PlanEconomicClassification plan={plan} onChange={savePlan} /> <PlanEconomicClassification plan={plan} onChange={savePlan} />
<FinancialPlanDetails plan={plan} onChange={savePlan} /> <FinancialPlanDetails plan={plan} onChange={savePlan} />
<StartupAssetRequirements plan={plan} onChange={savePlan} />
<IntegralFinancialPlan plan={plan} onChange={savePlan} /> <IntegralFinancialPlan plan={plan} onChange={savePlan} />
<MarketAnalysisPlan plan={plan} onChange={savePlan} /> <MarketAnalysisPlan plan={plan} onChange={savePlan} />
<FinancialRatiosPlan plan={plan} onChange={savePlan} /> <FinancialRatiosPlan plan={plan} onChange={savePlan} />
@@ -1084,12 +1086,14 @@ export function SimulationBusinessPlan({
</p> </p>
</> </>
)} )}
<MoneyInput {!plan.startupAssetRequirements && (
label="Saldo de caixa inicial" <MoneyInput
value={plan.openingCash} label="Saldo de caixa inicial"
allowNegative value={plan.openingCash}
onChange={(value) => update('openingCash', value)} allowNegative
/> onChange={(value) => update('openingCash', value)}
/>
)}
<label className="block text-sm font-medium"> <label className="block text-sm font-medium">
Horizonte (meses) Horizonte (meses)
<input <input
@@ -0,0 +1,209 @@
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
calculateStartupAssetRequirements,
startupAmount,
} from '@/lib/startup-asset-requirements';
import { newReportAssumptions } from '@/lib/integral-financial-report';
export function StartupAssetRequirements({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
const a =
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
const target = plan.startupAssetRequirements;
let budget:
| ReturnType<typeof calculateStartupAssetRequirements>
| undefined,
error = '';
if (target)
try {
budget = calculateStartupAssetRequirements(plan);
} catch (cause) {
error =
cause instanceof Error
? cause.message
: 'Confira os dados de arranque.';
}
const field = (label: string, value: string, save: (s: string) => void) => (
<label className="grid gap-1 text-sm">
{label}
<input
type="number"
min="0"
step="0.01"
className="min-w-0 rounded border p-2"
value={value}
onChange={(e) => save(e.target.value)}
/>
</label>
);
return (
<section
className="my-3 space-y-3 rounded border p-3"
aria-label="Caixa e activos necessários ao arranque"
>
{!target ? (
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
onChange({
...plan,
startupAssetRequirements: {
cashRequired: '',
otherCurrentAssetsRequired: '',
longTermAssetsRequired: '',
priorAssetInvestment: plan.assetInvestment,
},
})
}
>
Distinguir necessidades de arranque dos recursos disponíveis
</button>
) : target.priorAssetInvestment !== undefined ? (
<button
type="button"
className="rounded border px-3 py-2"
onClick={() =>
onChange({
...plan,
assetInvestment: target.priorAssetInvestment!,
startupAssetRequirements: undefined,
})
}
>
Retirar necessidades e repor investimento anterior (
{target.priorAssetInvestment || 'por preencher'}{' '}
{plan.currency})
</button>
) : null}
{target && (
<>
<p>
A caixa requerida é a reserva pretendida depois das
despesas e aquisições iniciais. A caixa disponível é o
saldo declarado antes de novo financiamento. Fontes
planeadas não são recebimentos realizados. Os activos
disponíveis são os que já existem, na mesma base de
valorização declarada.
</p>
<div className="grid gap-3 sm:grid-cols-2">
{field(
'Caixa requerida após o arranque',
target.cashRequired,
(value) =>
onChange({
...plan,
startupAssetRequirements: {
...target,
cashRequired: value,
},
}),
)}
{field(
'Caixa disponível antes de novo financiamento',
plan.openingCash,
(value) =>
onChange({ ...plan, openingCash: value }),
)}
{field(
'Outros activos correntes requeridos',
target.otherCurrentAssetsRequired,
(value) =>
onChange({
...plan,
startupAssetRequirements: {
...target,
otherCurrentAssetsRequired: value,
},
}),
)}
{field(
'Outros activos correntes disponíveis',
a.openingOtherAssets,
(value) =>
onChange({
...plan,
reportAssumptions: {
...a,
openingOtherAssets: value,
},
}),
)}
{field(
'Activos de longo prazo requeridos',
target.longTermAssetsRequired,
(value) =>
onChange({
...plan,
startupAssetRequirements: {
...target,
longTermAssetsRequired: value,
},
}),
)}
{field(
'Activos de longo prazo disponíveis',
a.openingFixedAssets,
(value) =>
onChange({
...plan,
reportAssumptions: {
...a,
openingFixedAssets: value,
},
}),
)}
</div>
<p>
Existências e recebíveis iniciais já planeados conservam
os campos próprios e integram os activos correntes, sem
serem contados duas vezes. As necessidades são mínimos;
não se presumem vendas de activos excedentários. A
depreciação mantém a base e a vida útil declaradas.
</p>
{error && <p role="alert">{error}</p>}
{budget && (
<>
<p>
Total de activos requeridos:{' '}
{startupAmount(budget.totalRequiredAssets)}{' '}
{plan.currency}. Requisitos brutos, incluindo
despesas de arranque:{' '}
{startupAmount(budget.grossRequirements)}{' '}
{plan.currency}. Aquisições adicionais
calculadas:{' '}
{startupAmount(budget.assetInvestment)}{' '}
{plan.currency}.
</p>
<button
type="button"
className="rounded border p-2"
onClick={() =>
onChange({
...plan,
assetInvestment: startupAmount(
budget!.assetInvestment,
),
})
}
>
Adoptar as aquisições calculadas no cenário
</button>
<p>
A adopção altera apenas o investimento em
activos, com repartição entre correntes e longo
prazo. Não cria financiamento nem substitui a
caixa disponível.
</p>
</>
)}
</>
)}
</section>
);
}
@@ -0,0 +1,351 @@
// Amounts transcribed from the immutable original PN tables T003, T005, T012 and T013. Never used as balancing entries.
export const annualExampleOriginalDetail = {
sourceSha256:
'4f1e1dbc90c8a4888291201898f306c06e2e687843a754a04a9a8a56f459ab99',
sales: [
{
label: 'Publicidade',
annual: ['2137', '3000', '3500'],
monthly2025: [
'100',
'110',
'121',
'133',
'140',
'161',
'177',
'195',
'215',
'237',
'261',
'287',
],
},
{
label: 'Intermediação Comercial',
annual: ['5336', '6000', '6500'],
monthly2025: [
'250',
'275',
'302',
'332',
'365',
'402',
'442',
'486',
'535',
'588',
'647',
'712',
],
},
{
label: 'Comercialização de Commodities',
annual: ['3211', '4000', '4250'],
monthly2025: [
'150',
'165',
'182',
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
],
},
{
label: 'Formação',
annual: ['201', '250', '275'],
monthly2025: [
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'18',
'20',
'22',
'24',
'26',
],
},
],
costs: [
{
label: 'Publicidade',
annual: ['1595', '2500', '3000'],
monthly2025: [
'75',
'82',
'90',
'99',
'109',
'120',
'132',
'145',
'160',
'176',
'194',
'213',
],
},
{
label: 'Intermediação Comercial',
annual: ['4273', '5500', '6000'],
monthly2025: [
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
'471',
'518',
'570',
],
},
{
label: 'Comercialização de Commodities',
annual: ['3211', '3750', '4000'],
monthly2025: [
'150',
'165',
'182',
'200',
'220',
'242',
'266',
'293',
'322',
'354',
'389',
'428',
],
},
{
label: 'Formação',
annual: ['139', '450', '475'],
monthly2025: [
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'18',
],
},
{
label: 'Marketing',
annual: ['1077', '1100', '1200'],
monthly2025: [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
],
},
],
departments: [
{
label: 'DIrecção Comercial',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Direcção de Admin e Finanças',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Serviços',
annual: ['300', '400', '400'],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'annual-and-monthly',
},
{
label: 'Marketing',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Revista Tempo',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Gsetão de Projectos',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
{
label: 'Gabinete Juridico',
annual: ['300', null, null],
monthly2025: [
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
'25',
],
annual2025Origin: 'sum-of-documented-months',
},
],
salesTotals: [
'680',
'748',
'824',
'905',
'990',
'1095',
'1203',
'1324',
'1458',
'1604',
'1765',
'1941',
],
costTotals: [
'586',
'644',
'710',
'781',
'860',
'945',
'1038',
'1142',
'1257',
'1383',
'1520',
'1672',
],
people: {
annual: ['1', '1', '1'],
monthly2025: [
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
'1',
],
},
} as const;
@@ -0,0 +1,64 @@
import { annualExampleOriginalDetail as source } from './annual-example-original-detail.ts';
import type { AnnualReferencePlan } from './business-plan-guidance.ts';
import { reportMoney } from './integral-financial-report.ts';
const cents = (s: string) => {
const [a, b = ''] = s.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
export function reconcileOriginalExample(plan: AnnualReferencePlan) {
const sum = (
rows: readonly { annual: readonly (string | null)[] }[],
year: number,
) =>
rows.reduce(
(n, r) =>
n + (r.annual[year] === null ? 0n : cents(r.annual[year]!)),
0n,
);
return {
years: plan.years.map((y, i) => ({
year: y.year,
sales: reportMoney(cents(y.sales)),
knownSales: reportMoney(sum(source.sales, i)),
salesDifference: reportMoney(cents(y.sales) - sum(source.sales, i)),
costs: reportMoney(cents(y.directCosts)),
knownCosts: reportMoney(sum(source.costs, i)),
costDifference: reportMoney(
cents(y.directCosts) - sum(source.costs, i),
),
payroll: reportMoney(cents(y.payroll)),
knownPayroll: reportMoney(sum(source.departments, i)),
payrollDifference: reportMoney(
cents(y.payroll) - sum(source.departments, i),
),
missingDepartments: source.departments
.filter((r) => r.annual[i] === null)
.map((r) => r.label),
})),
months: source.salesTotals.map((total, i) => {
const sales = source.sales.reduce(
(n, r) => n + cents(r.monthly2025[i]!),
0n,
);
const costs = source.costs.reduce(
(n, r) =>
n +
(r.monthly2025[i] === null ? 0n : cents(r.monthly2025[i]!)),
0n,
);
return {
period: `2025-${String(i + 1).padStart(2, '0')}`,
sourceSales: reportMoney(cents(total!)),
knownSales: reportMoney(sales),
salesDifference: reportMoney(cents(total!) - sales),
sourceCosts: reportMoney(cents(source.costTotals[i]!)),
knownCosts: reportMoney(costs),
costDifference: reportMoney(
cents(source.costTotals[i]!) - costs,
),
};
}),
needed: 'Vendas por serviço que somem 14.537/21.500/23.875 e custos por serviço que somem 12.538/16.200/18.325; distribuição mensal coerente dessas linhas; remuneração de Marketing, Revista Tempo, Gestão de Projectos e Gabinete Jurídico em 2026 e 2027 (total conjunto ainda por repartir: 1.600 em cada ano). As diferenças são diagnóstico documental, não rubricas financeiras.',
};
}
+132 -1
View File
@@ -10,6 +10,8 @@ import {
type InvestmentReportTable, type InvestmentReportTable,
} from './integral-financial-report.ts'; } from './integral-financial-report.ts';
import { buildComplementaryTables } from './complementary-report.ts'; import { buildComplementaryTables } from './complementary-report.ts';
import { annualExampleOriginalDetail as original } from './annual-example-original-detail.ts';
import { reconcileOriginalExample } from './annual-example-reconciliation.ts';
/** Presentation adapter only: uses the approved annual calculation, never converts it into investor movements. */ /** Presentation adapter only: uses the approved annual calculation, never converts it into investor movements. */
export function buildAnnualExampleTables( export function buildAnnualExampleTables(
@@ -80,7 +82,15 @@ export function buildAnnualExampleTables(
['Capital do investidor', plan.investorCapital], ['Capital do investidor', plan.investorCapital],
['Empréstimos', plan.loans], ['Empréstimos', plan.loans],
['Dinheiro adicional angariado', plan.additionalMoney], ['Dinheiro adicional angariado', plan.additionalMoney],
['Total de fontes confirmadas', result.availableFunding], [
'Financiamento disponível declarado no exemplo',
result.availableFunding,
],
['Caixa requerida (objectivo do cenário)', plan.openingCash],
[
'Caixa efectivamente disponível antes do financiamento',
'Não documentado no exemplo original',
],
['Financiamento necessário', result.requiredFunding], ['Financiamento necessário', result.requiredFunding],
[ [
'Capital por mobilizar — hipótese, não financiamento confirmado', 'Capital por mobilizar — hipótese, não financiamento confirmado',
@@ -283,6 +293,127 @@ export function buildAnnualExampleTables(
: undefined, : undefined,
}).map((w) => `Aviso não bloqueante — ${y.year}: ${w.message}`), }).map((w) => `Aviso não bloqueante — ${y.year}: ${w.message}`),
); );
type Month = (typeof result.years)[number]['illustrativeMonths'][number];
const months = result.years.flatMap((y) => y.illustrativeMonths);
const detailedHeaders = [
'Rubrica',
...result.years.flatMap((y) =>
y.illustrativeMonths.map(
(m) => `${y.year}-${String(m.month).padStart(2, '0')}`,
),
),
...headers.slice(1),
];
const expand = (
table: InvestmentReportTable,
fields: Record<string, (m: Month) => string>,
) => {
table.headers = detailedHeaders;
table.rows = table.rows.map((r) => [
r[0],
...months.map((m) => fields[r[0]]?.(m) ?? 'Por determinar'),
...r.slice(1),
]);
};
expand(sales, {
'Vendas totais': (m) => m.sales,
'Custo directo': (m) => m.directCosts,
});
expand(profit, {
Vendas: (m) => m.sales,
'Custo directo': (m) => m.directCosts,
'Margem bruta': (m) => m.grossMargin,
'Despesas operacionais': (m) => m.operatingExpenses,
'Resultado operacional': (m) => m.operatingProfit,
Juros: (m) => m.interest,
'Imposto estimado': (m) => m.taxes,
'Lucro líquido': (m) => m.netProfit,
});
expand(cash, {
'Caixa recebida': (m) => m.cashReceived,
'Caixa gasta': (m) => m.cashSpent,
'Fluxo líquido': (m) => m.cashFlow,
'Caixa final': (m) => m.closingCash,
});
expand(balance, {
'Caixa líquida': (m) => m.closingCash,
'Recebíveis líquidos': (m) => m.receivables,
'Outros activos correntes': () => plan.otherCurrentAssets,
'Activos fixos líquidos': () => plan.longTermAssets,
'Total do activo': (m) => m.closingAssets,
'Obrigações operacionais': (m) => m.operatingLiabilities,
'Saldo fiscal estimado': (m) => m.vatBalance,
'Total do passivo': (m) => m.closingLiabilities,
'Capital e resultados': (m) => m.closingCapital,
'Diferença do balanço': (m) => m.balanceDifference,
});
expand(personnel, {
'Folha de pagamento agregada': (m) => m.payroll,
'Encargos da folha': (m) => m.payrollCharges,
});
const originalRow = (
kind: string,
r: {
label: string;
annual: readonly (string | null)[];
monthly2025: readonly (string | null)[];
},
) => [
`${kind} — ${r.label}`,
...months.map((_, i) =>
i < 12 && r.monthly2025[i] !== null
? reportMoney(BigInt(r.monthly2025[i]!) * 100n)
: 'Não documentado',
),
...r.annual.map((v) =>
v === null ? 'Não documentado' : reportMoney(BigInt(v) * 100n),
),
];
sales.rows.push(
...original.sales.map((r) =>
originalRow('Vendas documentadas no original', r),
),
...original.costs.map((r) =>
originalRow('Custo documentado no original', r),
),
);
personnel.rows.push(
...original.departments.map((r) =>
originalRow('Departamento documentado', r),
),
);
personnel.rows.push([
'Trabalhadores documentados (sem inferir pessoas por departamento)',
...months.map((_, i) => (i < 12 ? '1' : 'Não documentado')),
'1',
'1',
'1',
]);
sales.notes = sales.notes.filter(
(n) => !n.startsWith('Linhas por serviço'),
);
personnel.notes = personnel.notes.filter(
(n) => !n.startsWith('O original não reconcilia'),
);
sales.notes.push(
'Linhas documentadas reproduzem o original para conferência, não são novas parcelas ou ajustamentos dos totais calculados. As células não documentadas não são zero. Os totais mensais calculados são projecções ilustrativas conciliadas com os anuais.',
);
personnel.notes.push(
'Sete departamentos estão documentados no quadro mensal: 7 × 25 = 175 por mês e 2.100 em 2025. Não são sete trabalhadores: o original declara uma pessoa. As quatro linhas anuais omitidas em 2025 resultam da soma dos meses documentados. Não se presume a repartição de 2026/2027.',
);
const reconciliation = reconcileOriginalExample(plan);
for (const year of reconciliation.years) {
sales.notes.push(
`${year.year}: a soma das linhas de vendas documentadas é ${year.knownSales}; o total anual do cenário é ${year.sales}; diferença documental ${year.salesDifference}. Custos documentados ${year.knownCosts}, total ${year.costs}, diferença ${year.costDifference}. Estas diferenças não são rubricas financeiras.`,
);
if (year.missingDepartments.length)
personnel.notes.push(
`${year.year}: ${year.missingDepartments.join(', ')} não têm remuneração anual documentada; as linhas conhecidas somam ${year.knownPayroll}, para uma folha total de ${year.payroll}. Faltam dados para repartir ${year.payrollDifference}; não é um ajustamento contabilístico.`,
);
}
sales.notes.push(
`No primeiro mês original, as linhas de vendas somam ${reconciliation.months[0].knownSales}, mas o total é ${reconciliation.months[0].sourceSales}; os custos documentados somam ${reconciliation.months[0].knownCosts}, para um subtotal de ${reconciliation.months[0].sourceCosts}. Nenhuma linha foi criada para absorver as diferenças.`,
);
return [ return [
startup, startup,
market, market,
+50 -14
View File
@@ -1,4 +1,5 @@
import { csvCell } from './csv.js'; import { csvCell } from './csv.js';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
type ProductLine = { type ProductLine = {
label: string; label: string;
@@ -120,6 +121,12 @@ export type BusinessFinancialPlanInput = {
/** Explicit opt-in; saved forecasts without this choice retain their values. */ /** Explicit opt-in; saved forecasts without this choice retain their values. */
applyAnnualGrowth?: boolean; applyAnnualGrowth?: boolean;
creditTermDays?: string; creditTermDays?: string;
startupAssetRequirements?: {
cashRequired: string;
otherCurrentAssetsRequired: string;
longTermAssetsRequired: string;
priorAssetInvestment?: string;
};
dividendsByPeriod?: string[]; dividendsByPeriod?: string[];
operatingExpenseLines?: { operatingExpenseLines?: {
label: string; label: string;
@@ -195,19 +202,22 @@ export function serializeBusinessPlanSnapshot(
plan: BusinessFinancialPlanInput, plan: BusinessFinancialPlanInput,
): string { ): string {
const snapshot = JSON.stringify({ const snapshot = JSON.stringify({
version: [ version: plan.startupAssetRequirements
'applyAnnualGrowth', ? 19
'creditTermDays', : [
'dividendsByPeriod', 'applyAnnualGrowth',
'operatingExpenseLines', 'creditTermDays',
'fundingBreakdown', 'dividendsByPeriod',
'reportSource', 'operatingExpenseLines',
].some( 'fundingBreakdown',
(key) => 'reportSource',
plan[key as keyof BusinessFinancialPlanInput] !== undefined, ].some(
) (key) =>
? 18 plan[key as keyof BusinessFinancialPlanInput] !==
: 17, undefined,
)
? 18
: 17,
plan: { plan: {
...plan, ...plan,
...(plan.useSupplierPaymentTerms === true ...(plan.useSupplierPaymentTerms === true
@@ -290,7 +300,8 @@ export function restoreBusinessPlanSnapshot(
decoded.version !== 15 && decoded.version !== 15 &&
decoded.version !== 16 && decoded.version !== 16 &&
decoded.version !== 17 && decoded.version !== 17 &&
decoded.version !== 18) || decoded.version !== 18 &&
decoded.version !== 19) ||
!decoded.plan || !decoded.plan ||
typeof decoded.plan !== 'object' typeof decoded.plan !== 'object'
) )
@@ -310,6 +321,21 @@ export function restoreBusinessPlanSnapshot(
return null; return null;
const shortText = (v: unknown) => const shortText = (v: unknown) =>
typeof v === 'string' && v.length <= 160; typeof v === 'string' && v.length <= 160;
if (plan.startupAssetRequirements !== undefined) {
const r = plan.startupAssetRequirements as Record<string, unknown>;
if (
decoded.version < 19 ||
!r ||
![
'cashRequired',
'otherCurrentAssetsRequired',
'longTermAssetsRequired',
].every((k) => shortText(r[k])) ||
(r.priorAssetInvestment !== undefined &&
!shortText(r.priorAssetInvestment))
)
return null;
}
if ( if (
plan.creditTermDays !== undefined && plan.creditTermDays !== undefined &&
!shortText(plan.creditTermDays) !shortText(plan.creditTermDays)
@@ -1414,6 +1440,16 @@ export function compareBusinessScenarios(input: BusinessFinancialPlanInput) {
/** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */ /** Forecast separates invoiced sales, collections, accounting expenses and cash payments. */
export function forecastBusinessPlan(input: BusinessFinancialPlanInput) { export function forecastBusinessPlan(input: BusinessFinancialPlanInput) {
if (input.startupAssetRequirements) {
const needs = calculateStartupAssetRequirements(input);
if (
cents(input.assetInvestment, 'Investimento em activos') !==
needs.assetInvestment
)
throw Error(
'As aquisições do cenário não correspondem às necessidades de activos. Confira os valores e adopte as aquisições calculadas.',
);
}
if ( if (
input.creditTermDays?.trim() && input.creditTermDays?.trim() &&
(!/^\d+$/.test(input.creditTermDays) || (!/^\d+$/.test(input.creditTermDays) ||
@@ -569,12 +569,33 @@ export function calculateAnnualReferencePlan(plan: AnnualReferencePlan) {
month: i + 1, month: i + 1,
sales: decimal(revenue), sales: decimal(revenue),
directCosts: decimal(monthlyCosts[i]), directCosts: decimal(monthlyCosts[i]),
grossMargin: decimal(revenue - monthlyCosts[i]),
payroll: decimal(monthlyExpenses[0][i]),
payrollCharges: decimal(monthlyExpenses[1][i]),
otherOperatingExpenses: decimal(monthlyExpenses[2][i]),
operatingExpenses: decimal(
monthlyExpenses[0][i] +
monthlyExpenses[1][i] +
monthlyExpenses[2][i],
),
operatingProfit: decimal(
profit + monthlyExpenses[3][i] + monthlyExpenses[4][i],
),
interest: decimal(monthlyExpenses[3][i]),
taxes: decimal(monthlyExpenses[4][i]),
netProfit: decimal(profit), netProfit: decimal(profit),
cashReceived: decimal(received), cashReceived: decimal(received),
cashSpent: decimal(spent), cashSpent: decimal(spent),
cashFlow: decimal(received - spent),
closingCash: decimal(monthCash), closingCash: decimal(monthCash),
receivables: decimal(monthReceivables), receivables: decimal(monthReceivables),
operatingLiabilities: decimal(monthLiabilities), operatingLiabilities: decimal(monthLiabilities),
vatBalance: decimal(monthVatBalance),
closingAssets: decimal(monthAssets),
closingLiabilities: decimal(
monthLiabilities + monthVatBalance + money(plan.loans),
),
closingCapital: decimal(projectedCapital + monthResults),
balanceDifference: decimal( balanceDifference: decimal(
monthAssets - monthAssets -
monthLiabilities - monthLiabilities -
+5 -1
View File
@@ -41,7 +41,11 @@ export function financialPlanWarningMetrics(
creditDays: inputCreditDays(plan.creditTermDays), creditDays: inputCreditDays(plan.creditTermDays),
fundingGap: fundingGap:
year === 0 year === 0
? read('funding', 'Diferença por financiar', 1) ? (read(
'funding',
'Falta para a reserva requerida (projecção)',
1,
) ?? read('funding', 'Diferença por financiar', 1))
: undefined, : undefined,
netProfit: read('profit-loss', 'Lucro líquido', col), netProfit: read('profit-loss', 'Lucro líquido', col),
sales, sales,
+120 -2
View File
@@ -3,6 +3,7 @@ import {
monthlyProjectedSales, monthlyProjectedSales,
type BusinessFinancialPlanInput, type BusinessFinancialPlanInput,
} from './business-financial-plan.ts'; } from './business-financial-plan.ts';
import { calculateStartupAssetRequirements } from './startup-asset-requirements.ts';
export type InvestmentReportTable = { export type InvestmentReportTable = {
id: string; id: string;
@@ -147,8 +148,12 @@ export function buildIntegralFinancialTables(
Number(a.startYear) > 9999 Number(a.startYear) > 9999
) )
throw new Error('Indique o ano inicial do relatório (1900–9999).'); throw new Error('Indique o ano inicial do relatório (1900–9999).');
const needs = plan.startupAssetRequirements
? calculateStartupAssetRequirements(plan)
: undefined;
const openingFixed = cents(a.openingFixedAssets), const openingFixed = cents(a.openingFixedAssets),
otherAssets = cents(a.openingOtherAssets), otherAssets =
cents(a.openingOtherAssets) + (needs?.currentAcquisition ?? 0n),
openingEquity = cents(a.openingEquity); openingEquity = cents(a.openingEquity);
if ( if (
[openingFixed, otherAssets, openingEquity].some( [openingFixed, otherAssets, openingEquity].some(
@@ -286,6 +291,72 @@ export function buildIntegralFinancialTables(
table('startup').notes.push( table('startup').notes.push(
'Despesas de arranque reconhecidas e pagas no início. Saldos patrimoniais anteriores não são novas despesas.', 'Despesas de arranque reconhecidas e pagas no início. Saldos patrimoniais anteriores não são novas despesas.',
); );
if (needs) {
table('startup').headers = [
'Rubrica',
'Requerido',
'Disponível antes de financiamento',
];
table('startup').rows = [
...a.startupExpenses.map((r) => [
r.label,
reportMoney(cents(r.amount)),
'Despesa planeada, não pagamento realizado',
]),
[
'Despesas de arranque',
reportMoney(startup),
'Por realizar no cenário',
],
[
'Caixa',
reportMoney(needs.cashRequired),
reportMoney(needs.cashAvailable),
],
[
'Outros activos correntes',
reportMoney(needs.currentRequired),
reportMoney(needs.currentAvailable),
],
[
'Activos de longo prazo',
reportMoney(needs.fixedRequired),
reportMoney(needs.fixedAvailable),
],
[
'Total de activos requeridos',
reportMoney(needs.totalRequiredAssets),
reportMoney(
needs.cashAvailable +
needs.currentAvailable +
needs.fixedAvailable,
),
],
[
'Requisitos brutos de arranque',
reportMoney(needs.grossRequirements),
'Disponibilidade não se presume',
],
[
'Existências/recebíveis iniciais já planeados',
reportMoney(needs.currentAlreadyPlanned),
'Não são disponibilidade confirmada',
],
[
'Aquisições adicionais correntes',
reportMoney(needs.currentAcquisition),
'Por adquirir',
],
[
'Aquisições adicionais de longo prazo',
reportMoney(needs.fixedAcquisition),
'Por adquirir',
],
];
table('startup').notes.push(
'Caixa requerida é a reserva desejada após o arranque; caixa disponível é o saldo declarado antes de novo financiamento. Valores disponíveis são declarados, não certificados. Não se presume liquidação de activos excedentários.',
);
}
table('funding').rows = [ table('funding').rows = [
...(plan.fundingBreakdown ...(plan.fundingBreakdown
? [ ? [
@@ -323,6 +394,50 @@ export function buildIntegralFinancialTables(
), ),
], ],
].map(([label, value]) => [label, reportMoney(cents(value))]); ].map(([label, value]) => [label, reportMoney(cents(value))]);
if (needs) {
const projectedCash =
cents(result.openingCashAfterInitialUses) - startup;
const plannedLabels: Record<string, string> = {
'Capital introduzido': 'Capital planeado',
Suprimentos: 'Suprimentos planeados',
Empréstimos: 'Empréstimos planeados',
'Subvenções declaradas': 'Subvenções planeadas',
'Total de fontes': 'Total de fontes planeadas',
};
table('funding').rows = table('funding')
.rows.filter(
(row) => row[0] !== 'Caixa após financiamento e arranque',
)
.map(([label, value]) => [
plannedLabels[label] ?? label,
value,
]);
table('funding').rows.push(
[
'Requisitos brutos de arranque',
reportMoney(needs.grossRequirements),
],
[
'Caixa disponível antes de financiamento',
reportMoney(needs.cashAvailable),
],
[
'Reserva de caixa requerida após arranque',
reportMoney(needs.cashRequired),
],
[
'Caixa projectada após arranque com fontes planeadas',
reportMoney(projectedCash),
],
[
'Falta para a reserva requerida (projecção)',
reportMoney(positive(needs.cashRequired - projectedCash)),
],
);
table('funding').notes.push(
'Capital, empréstimos e subvenções são fontes planeadas do cenário, não financiamento realizado. A diferença original entre usos e fontes conserva a fórmula aprovada; a falta para a reserva inclui separadamente o objectivo de caixa e a disponibilidade declarada.',
);
}
table('funding').notes.push( table('funding').notes.push(
'Financiamento insuficiente é aviso não bloqueante. As fontes são pressupostos do plano, não confirmação bancária.', 'Financiamento insuficiente é aviso não bloqueante. As fontes são pressupostos do plano, não confirmação bancária.',
); );
@@ -353,7 +468,10 @@ export function buildIntegralFinancialTables(
principal = 0n; principal = 0n;
let distributedDividends = 0n; let distributedDividends = 0n;
let obligationsKnown = true; let obligationsKnown = true;
const fixed = openingFixed + cents(plan.assetInvestment); const fixed =
openingFixed +
cents(plan.assetInvestment) -
(needs?.currentAcquisition ?? 0n);
const loans = const loans =
cents(plan.bankLoanProceeds) + cents(plan.shareholderLoans); cents(plan.bankLoanProceeds) + cents(plan.shareholderLoans);
const grantCapital = const grantCapital =
@@ -673,6 +673,7 @@ function makeSections(
})); }));
finance.paragraphs = [ 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.', '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.',
'Aviso não bloqueante — O detalhe original por serviço e departamento contém diferenças documentais ainda não reconciliadas. Os totais calculados usam os anuais aprovados; as linhas originais são identificadas separadamente e não são somadas como ajustamentos. A reprodução integral dos dados originais não está validada.',
]; ];
try { try {
const example = buildAnnualExampleTables(financialPlan); const example = buildAnnualExampleTables(financialPlan);
@@ -0,0 +1,70 @@
import type { BusinessFinancialPlanInput } from './business-financial-plan.ts';
const money = (value: string | undefined, label: string) => {
if (!value || !/^\d+(?:\.\d{1,2})?$/.test(value))
throw Error(
`Indique ${label}, com até duas casas decimais; use zero apenas quando conhecido.`,
);
const [a, b = ''] = value.split('.');
return BigInt(a) * 100n + BigInt(b.padEnd(2, '0'));
};
const positive = (n: bigint) => (n > 0n ? n : 0n);
export const startupAmount = (n: bigint) =>
`${n / 100n}.${String(n % 100n).padStart(2, '0')}`;
/** Requirements are targets; the existing cash equation still uses available opening balances and declared financing. */
export function calculateStartupAssetRequirements(
plan: BusinessFinancialPlanInput,
) {
const target = plan.startupAssetRequirements;
if (!target)
throw Error('Indique as necessidades de caixa e activos do arranque.');
const cashRequired = money(target.cashRequired, 'a caixa requerida');
const currentRequired = money(
target.otherCurrentAssetsRequired,
'os activos correntes requeridos',
);
const fixedRequired = money(
target.longTermAssetsRequired,
'os activos de longo prazo requeridos',
);
const cashAvailable = money(
plan.openingCash,
'a caixa disponível antes do financiamento',
);
const currentAvailable = money(
plan.reportAssumptions?.openingOtherAssets,
'os outros activos correntes disponíveis',
);
const fixedAvailable = money(
plan.reportAssumptions?.openingFixedAssets,
'os activos de longo prazo disponíveis',
);
// Inventory and receivables are already initial uses in the approved engine, not acquisitions to count twice.
const currentAlreadyPlanned =
money(plan.inventory, 'as existências iniciais planeadas') +
money(plan.receivables, 'os recebíveis iniciais planeados');
const currentAcquisition = positive(
currentRequired - currentAvailable - currentAlreadyPlanned,
);
const fixedAcquisition = positive(fixedRequired - fixedAvailable);
const startupExpenses = (
plan.reportAssumptions?.startupExpenses ?? []
).reduce((sum, r) => sum + money(r.amount, r.label), 0n);
return {
cashRequired,
currentRequired,
fixedRequired,
cashAvailable,
currentAvailable,
fixedAvailable,
currentAlreadyPlanned,
currentAcquisition,
fixedAcquisition,
assetInvestment: currentAcquisition + fixedAcquisition,
totalRequiredAssets: cashRequired + currentRequired + fixedRequired,
grossRequirements:
startupExpenses + cashRequired + currentRequired + fixedRequired,
startupExpenses,
};
}
@@ -152,10 +152,10 @@ void test('the full example shares the saved snapshot and its eleven tables and
recovered = reload(p); recovered = reload(p);
const tables = buildAnnualExampleTables(recovered); const tables = buildAnnualExampleTables(recovered);
assert.equal(tables.length, 11); assert.equal(tables.length, 11);
assert.equal(cell(tables, 'sales', 'Vendas totais', 1), '14537.25'); assert.equal(cell(tables, 'sales', 'Vendas totais', 37), '14537.25');
assert.equal(cell(tables, 'balance', 'Diferença do balanço', 1), '0.00'); assert.equal(cell(tables, 'balance', 'Diferença do balanço', 1), '0.00');
assert.equal( assert.equal(
cell(tables, 'personnel', 'Folha de pagamento agregada', 1), cell(tables, 'personnel', 'Folha de pagamento agregada', 37),
'2100.00', '2100.00',
); );
assert.deepEqual(forecastBusinessPlan(recovered), before); assert.deepEqual(forecastBusinessPlan(recovered), before);
@@ -44,7 +44,9 @@ void test('one startup editor retains all rows and persists an edit without dupl
? annual ? annual
: name === './business-plan-warnings' : name === './business-plan-warnings'
? { BusinessPlanWarnings: () => null } ? { BusinessPlanWarnings: () => null }
: require(name), : name === './startup-asset-requirements'
? { StartupAssetRequirements: () => null }
: require(name),
module, module,
module.exports, module.exports,
); );
@@ -0,0 +1,432 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import ts from 'typescript';
import JSZip from 'jszip';
import { financialReportFixture } from './fixtures/integral-financial-plan.mjs';
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import {
buildIntegralFinancialTables,
newReportAssumptions,
} from '../../resources/js/lib/integral-financial-report.ts';
import * as requirements from '../../resources/js/lib/startup-asset-requirements.ts';
import {
newAnnualReferencePlan,
serializeAnnualExampleSnapshot,
calculateAnnualReferencePlan,
} from '../../resources/js/lib/business-plan-guidance.ts';
import { buildAnnualExampleTables } from '../../resources/js/lib/annual-example-report.ts';
import { annualExampleOriginalDetail as original } from '../../resources/js/lib/annual-example-original-detail.ts';
import { reconcileOriginalExample } from '../../resources/js/lib/annual-example-reconciliation.ts';
import {
createIntegralFinancialReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import { selectPlanCae } from '../../resources/js/lib/cae-mozambique.ts';
const cell = (ts, id, label, col) =>
ts.find((t) => t.id === id).rows.find((r) => r[0] === label)[col];
const cents = (s) => BigInt(s.replace('.', ''));
const reload = (p) =>
restoreBusinessPlanSnapshot(serializeBusinessPlanSnapshot(p));
function startup() {
const p = financialReportFixture(12);
for (const key of [
'monthlyPayrollExpense',
'monthlyPayrollPayments',
'monthlyOperatingExpenses',
'monthlyOperatingPayments',
'monthlyInventoryPurchases',
'monthlyVariableCostPayments',
'assetDepreciation',
'monthlyInterestExpense',
'monthlyInterestPayment',
'monthlyPrincipalRepayment',
])
p[key] = '0';
Object.assign(p, {
openingCash: '20000',
inventory: '10000',
receivables: '5000',
assetInvestment: '600',
equity: '0',
economicClassification: selectPlanCae('55111'),
startupAssetRequirements: {
cashRequired: '90000',
otherCurrentAssetsRequired: '150000',
longTermAssetsRequired: '260250',
priorAssetInvestment: '600',
},
});
p.products = [
{
label: 'Sem vendas no ensaio de arranque',
monthlyUnits: '0',
unitPrice: '1',
unitVariableCost: '0',
},
];
Object.assign(p.reportAssumptions, {
openingOtherAssets: '10000',
openingFixedAssets: '55000',
openingEquity: '85000',
startYear: '2025',
startupExpenses: newAnnualReferencePlan().startupExpenses,
taxExpenseByMonth: Array(12).fill('0'),
taxPaymentByMonth: Array(12).fill('0'),
});
return p;
}
void test('F16 distinguishes required and available cash/assets without treating planned equity as received funding', () => {
const p = startup(),
budget = requirements.calculateStartupAssetRequirements(p);
assert.equal(
requirements.startupAmount(budget.grossRequirements),
'1825250.00',
);
assert.equal(
requirements.startupAmount(budget.currentAcquisition),
'125000.00',
);
assert.equal(
requirements.startupAmount(budget.fixedAcquisition),
'205250.00',
);
assert.throws(() => forecastBusinessPlan(p), /aquisições/);
p.assetInvestment = requirements.startupAmount(budget.assetInvestment);
let tables = buildIntegralFinancialTables(p);
assert.ok(
tables.every((t) => !t.issues.length),
JSON.stringify(tables.flatMap((t) => t.issues)),
);
assert.equal(cell(tables, 'startup', 'Caixa', 1), '90000.00');
assert.equal(cell(tables, 'startup', 'Caixa', 2), '20000.00');
assert.equal(
cell(
tables,
'funding',
'Falta para a reserva requerida (projecção)',
1,
),
'1740250.00',
);
p.equity = '1740250';
tables = buildIntegralFinancialTables(p);
assert.equal(
cell(
tables,
'funding',
'Caixa projectada após arranque com fontes planeadas',
1,
),
'90000.00',
);
assert.equal(
cell(tables, 'funding', 'Caixa disponível antes de financiamento', 1),
'20000.00',
);
assert.equal(
cell(tables, 'balance', 'Activos fixos líquidos', 1),
'260250.00',
);
assert.equal(cell(tables, 'balance', 'Total do activo', 1), '500250.00');
for (const v of tables
.find((t) => t.id === 'balance')
.rows.find((r) => r[0] === 'Diferença do balanço')
.slice(1))
assert.equal(v, '0.00');
assert.match(
tables.find((t) => t.id === 'funding').notes.join(' '),
/não financiamento realizado/,
);
assert.equal(
cell(tables, 'funding', 'Total de fontes planeadas', 1),
'1740250.00',
);
assert.ok(
!tables
.find((t) => t.id === 'funding')
.rows.some((r) => r[0] === 'Capital introduzido'),
);
});
void test('F16 preserves legacy formulas and guards missing data, double counting, snapshot version and CAE', () => {
const old = financialReportFixture(12),
before = forecastBusinessPlan(old);
assert.deepEqual(forecastBusinessPlan(reload(old)), before);
const p = startup();
p.assetInvestment = requirements.startupAmount(
requirements.calculateStartupAssetRequirements(p).assetInvestment,
);
const s = serializeBusinessPlanSnapshot(p);
assert.equal(JSON.parse(s).version, 19);
const saved = reload(p);
assert.deepEqual(saved.economicClassification, p.economicClassification);
assert.deepEqual(
saved.startupAssetRequirements,
p.startupAssetRequirements,
);
assert.deepEqual(
buildIntegralFinancialTables(saved),
buildIntegralFinancialTables(p),
);
const bad = JSON.parse(s);
bad.version = 18;
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(bad)), null);
p.startupAssetRequirements.cashRequired = '';
assert.throws(
() => requirements.calculateStartupAssetRequirements(p),
/caixa requerida/,
);
p.startupAssetRequirements.cashRequired = '90000';
p.reportAssumptions.openingOtherAssets = '';
assert.throws(
() => requirements.calculateStartupAssetRequirements(p),
/disponíveis/,
);
});
void test('F16 real editor adopts only acquisitions on explicit action and can restore the earlier investment', () => {
const source = fs.readFileSync(
new URL(
'../../resources/js/components/startup-asset-requirements.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/startup-asset-requirements'
? requirements
: name === '@/lib/integral-financial-report'
? { newReportAssumptions }
: require(name),
module,
module.exports,
);
let p = startup();
delete p.startupAssetRequirements;
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 render = () =>
module.exports.StartupAssetRequirements({
plan: p,
onChange: (n) => {
p = reload(n);
assert.ok(p);
},
});
nodes(render())
.find((n) => n.type === 'button')
.props.onClick();
assert.equal(p.assetInvestment, '600');
for (const [label, value] of [
['Caixa requerida após o arranque', '90000'],
['Outros activos correntes requeridos', '150000'],
['Activos de longo prazo requeridos', '260250'],
]) {
const l = nodes(render()).find(
(n) => n.type === 'label' && text(n).startsWith(label),
);
nodes(l)
.find((n) => n.type === 'input')
.props.onChange({ target: { value } });
}
nodes(render())
.find((n) => n.type === 'button' && text(n).includes('Adoptar'))
.props.onClick();
assert.equal(p.assetInvestment, '330250.00');
assert.equal(p.equity, '0');
assert.equal(p.openingCash, '20000');
nodes(render())
.find((n) => n.type === 'button' && text(n).includes('Retirar'))
.props.onClick();
assert.equal(p.assetInvestment, '600');
assert.equal(p.startupAssetRequirements, undefined);
});
void test('F31 recovers seven documented departments and identifies the exact unsolved source discrepancies', () => {
const reconciled = reconcileOriginalExample(newAnnualReferencePlan());
assert.equal(original.sales.length, 4);
assert.equal(original.costs.length, 5);
assert.equal(original.departments.length, 7);
assert.deepEqual(
reconciled.years.map((y) => y.salesDifference),
['3652.00', '8250.00', '9350.00'],
);
assert.deepEqual(
reconciled.years.map((y) => y.costDifference),
['2243.00', '2900.00', '3650.00'],
);
assert.equal(reconciled.months[0].knownSales, '510.00');
assert.equal(reconciled.months[0].sourceSales, '680.00');
assert.equal(reconciled.months[0].knownCosts, '431.00');
assert.equal(reconciled.months[0].sourceCosts, '586.00');
assert.equal(reconciled.years[0].payrollDifference, '0.00');
assert.equal(reconciled.years[0].missingDepartments.length, 0);
for (const y of reconciled.years.slice(1)) {
assert.equal(y.missingDepartments.length, 4);
assert.equal(y.payrollDifference, '1600.00');
}
assert.equal(original.departments[3].annual[1], null);
});
void test('F31 carries all 36 calculated months, original service/department rows and unchanged annual totals into one eleven-table report', () => {
const annual = newAnnualReferencePlan(),
p = financialReportFixture(12);
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
p.reportSource = 'annual_example';
const source = calculateAnnualReferencePlan(annual),
tables = buildAnnualExampleTables(reload(p));
assert.equal(tables.length, 11);
const sales = tables.find((t) => t.id === 'sales');
assert.equal(sales.headers.length, 40);
assert.equal(sales.headers[1], '2025-01');
assert.equal(sales.headers[36], '2027-12');
for (let year = 0; year < 3; year++) {
const start = year * 12 + 1,
end = start + 12,
col = 37 + year;
for (const [id, label] of [
['sales', 'Vendas totais'],
['sales', 'Custo directo'],
['profit-loss', 'Lucro líquido'],
['cashflow', 'Caixa recebida'],
['cashflow', 'Caixa gasta'],
['cashflow', 'Fluxo líquido'],
['personnel', 'Folha de pagamento agregada'],
]) {
const row = tables
.find((t) => t.id === id)
.rows.find((r) => r[0] === label);
assert.equal(
row.slice(start, end).reduce((sum, v) => sum + cents(v), 0n),
cents(row[col]),
`${id}/${label}/${year}`,
);
}
assert.equal(
cell(tables, 'cashflow', 'Caixa final', col),
cell(tables, 'cashflow', 'Caixa final', end - 1),
);
}
for (const amount of tables
.find((t) => t.id === 'balance')
.rows.find((r) => r[0] === 'Diferença do balanço')
.slice(1))
assert.equal(amount, '0.00');
assert.equal(
cell(
tables,
'sales',
'Vendas documentadas no original — Publicidade',
1,
),
'100.00',
);
assert.equal(
cell(
tables,
'sales',
'Vendas documentadas no original — Publicidade',
37,
),
'2137.00',
);
assert.equal(
cell(tables, 'sales', 'Custo documentado no original — Marketing', 1),
'Não documentado',
);
assert.equal(
cell(tables, 'personnel', 'Departamento documentado — Marketing', 37),
'300.00',
);
assert.equal(
cell(tables, 'personnel', 'Departamento documentado — Marketing', 38),
'Não documentado',
);
assert.equal(source.years[0].closingAssets, '501475.00');
assert.equal(source.years[0].closingLiabilities, '1641.00');
assert.equal(source.years[0].closingCapital, '499834.00');
assert.equal(
cell(
tables,
'funding',
'Caixa efectivamente disponível antes do financiamento',
1,
),
'Não documentado no exemplo original',
);
});
void test('F16/F31 persistence and existing Word/print exports preserve the same requirements, all months and source gaps', async () => {
const p = startup();
p.assetInvestment = requirements.startupAmount(
requirements.calculateStartupAssetRequirements(p).assetInvestment,
);
p.equity = '1740250';
const annual = newAnnualReferencePlan();
annual.years[0].sales = '14537.25';
p.annualExampleSnapshot = serializeAnnualExampleSnapshot(annual);
for (const mode of ['investor', 'annual_example']) {
p.reportSource = mode;
const restored = reload(p),
before = JSON.stringify(p);
const report = createIntegralFinancialReport(
{
business_plan_snapshot: serializeBusinessPlanSnapshot(restored),
project_title: 'QA F16/F31',
},
{ generatedAt: '2026-11-20T12:00:00Z' },
);
assert.equal(report.sections[0].tables.length, 11);
assert.equal(JSON.stringify(p), before);
const html = await createProjectDossierPrintHtml(report, []),
doc = await generateProjectDossierDocx(report, []),
zip = await JSZip.loadAsync(
doc instanceof Blob ? await doc.arrayBuffer() : doc,
),
xml = await zip.file('word/document.xml').async('string');
for (const s of mode === 'investor'
? [
'Disponível antes de financiamento',
'Caixa requerida',
'não financiamento realizado',
]
: [
'2025-01',
'2027-12',
'Vendas documentadas no original',
'Departamento documentado',
'Não documentado',
]) {
assert.ok((html + xml).includes(s), s);
}
if (mode === 'annual_example') {
assert.match(xml, /14 537,25/);
assert.match(xml, /documental/);
}
}
});