wip(qa): preserve package one pending functional acceptance

This commit is contained in:
2026-11-20 11:49:47 +02:00
parent 9cd7e905b1
commit 64f282c341
11 changed files with 1327 additions and 0 deletions
@@ -0,0 +1,327 @@
import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan';
import {
buildIntegralFinancialTables,
newReportAssumptions,
isReportAssumptions,
} from '@/lib/integral-financial-report';
import { InvestmentReportTables } from './investment-report-tables';
export function IntegralFinancialPlan({
plan,
onChange,
}: {
plan: BusinessFinancialPlanInput;
onChange: (plan: BusinessFinancialPlanInput) => void;
}) {
if (plan.reportAssumptions && !isReportAssumptions(plan.reportAssumptions))
return (
<p role="alert">
Os dados complementares guardados não têm uma estrutura
reconhecida. Foram preservados e não serão substituídos
automaticamente.
</p>
);
const a =
plan.reportAssumptions ?? newReportAssumptions(plan.periods ?? 12);
const update = (patch: Partial<typeof a>) =>
onChange({ ...plan, reportAssumptions: { ...a, ...patch } });
const numeric = (
label: string,
value: string,
save: (value: 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={(event) => save(event.target.value)}
/>
</label>
);
return (
<details className="my-4 rounded border border-teal-500 p-3">
<summary className="font-semibold">
Relatório financeiro integral — dados do investimento
</summary>
<p className="my-2">
Utiliza as vendas, custos e agendas do plano financeiro. Não
utiliza o cenário sintético. Todos os montantes são projecções
declaradas em {plan.currency || 'moeda por seleccionar'}. Campos
em falta permanecem por determinar; indique zero apenas quando
aplicável.
</p>
<div className="grid gap-3 sm:grid-cols-2">
<label className="grid gap-1 text-sm">
Ano inicial
<input
type="number"
min="1900"
max="9999"
step="1"
className="rounded border p-2"
value={a.startYear}
onChange={(event) =>
update({ startYear: event.target.value })
}
/>
</label>
{numeric(
'Activos fixos anteriores (valor líquido)',
a.openingFixedAssets,
(openingFixedAssets) => update({ openingFixedAssets }),
)}
{numeric(
'Outros activos anteriores',
a.openingOtherAssets,
(openingOtherAssets) => update({ openingOtherAssets }),
)}
{numeric(
'Capital e resultados anteriores',
a.openingEquity,
(openingEquity) => update({ openingEquity }),
)}
<label className="grid gap-1 text-sm">
Tratamento das subvenções
<select
className="rounded border p-2"
value={a.grantsTreatment}
onChange={(event) =>
update({
grantsTreatment: event.target
.value as typeof a.grantsTreatment,
})
}
>
<option value="">Por indicar / sem subvenção</option>
<option value="capital">Capital</option>
<option value="deferred">Passivo diferido</option>
</select>
</label>
<label className="grid gap-1 text-sm">
Natureza dos recebimentos manuais
<select
className="rounded border p-2"
value={a.manualCollectionsKind}
onChange={(event) =>
update({
manualCollectionsKind: event.target
.value as typeof a.manualCollectionsKind,
})
}
>
<option value="">Por indicar / sem montante</option>
<option value="sales">Cobranças de vendas</option>
<option value="other_income">
Outras receitas reconhecidas e recebidas
</option>
</select>
</label>
</div>
<fieldset className="my-3 space-y-2">
<legend>
Despesas de arranque — reconhecidas e pagas na abertura
</legend>
{a.startupExpenses.map((row, index) => (
<div className="grid gap-2 sm:grid-cols-3" key={index}>
<label className="grid text-sm">
Despesa {index + 1}
<input
className="rounded border p-2"
value={row.label}
maxLength={160}
onChange={(event) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index
? {
...entry,
label: event.target
.value,
}
: entry,
),
})
}
/>
</label>
{numeric(
`Montante de arranque ${index + 1}`,
row.amount,
(amount) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index
? { ...entry, amount }
: entry,
),
}),
)}
<button
type="button"
className="rounded border p-2"
onClick={() =>
update({
startupExpenses: a.startupExpenses.filter(
(_, i) => i !== index,
),
})
}
>
Remover despesa
</button>
</div>
))}
<button
type="button"
className="rounded border p-2"
disabled={a.startupExpenses.length >= 40}
onClick={() =>
update({
startupExpenses: [
...a.startupExpenses,
{ label: '', amount: '' },
],
})
}
>
Adicionar despesa de arranque
</button>
</fieldset>
<p className="my-2 text-sm">
Os saldos anteriores têm de reconciliar entre si. Não inclua os
novos activos no saldo anterior, nem os novos capitais nos
resultados anteriores.
</p>
<h5 className="font-semibold">
Despesas de arranque (reconhecidas e pagas na abertura)
</h5>
{a.startupExpenses.map((row, index) => (
<div className="my-2 grid gap-2 sm:grid-cols-3" key={index}>
<label className="grid gap-1 text-sm">
Despesa
<input
className="min-w-0 rounded border p-2"
maxLength={160}
value={row.label}
onChange={(event) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index
? {
...entry,
label: event.target.value,
}
: entry,
),
})
}
/>
</label>
{numeric('Montante de arranque', row.amount, (amount) =>
update({
startupExpenses: a.startupExpenses.map(
(entry, i) =>
i === index ? { ...entry, amount } : entry,
),
}),
)}
<button
type="button"
className="rounded border p-2"
onClick={() =>
update({
startupExpenses: a.startupExpenses.filter(
(_, i) => i !== index,
),
})
}
>
Remover despesa
</button>
</div>
))}
<button
type="button"
className="my-2 rounded border px-3 py-2"
disabled={a.startupExpenses.length >= 40}
onClick={() =>
update({
startupExpenses: [
...a.startupExpenses,
{ label: '', amount: '' },
],
})
}
>
Adicionar despesa de arranque
</button>
<p className="text-sm">
Sem linhas significa que não declarou despesas de arranque; para
confirmar a inexistência, registe uma linha «Sem despesas de
arranque» com zero.
</p>
<label className="my-2 grid gap-1 text-sm">
Fonte ou pressuposto dos impostos estimados
<input
className="rounded border p-2"
maxLength={1000}
value={a.taxSource}
onChange={(event) =>
update({ taxSource: event.target.value })
}
/>
</label>
<details>
<summary>Impostos por mês — estimativa e tesouraria</summary>
<p className="text-sm">
Não activa taxas fiscais nem certifica pagamentos. Preencha
cada mês, incluindo zero declarado.
</p>
{Array.from({ length: plan.periods ?? 12 }, (_, index) => (
<div className="my-2 grid gap-2 sm:grid-cols-2" key={index}>
{numeric(
`Imposto reconhecido — mês ${index + 1}`,
a.taxExpenseByMonth[index] ?? '',
(value) =>
update({
taxExpenseByMonth: Array.from(
{ length: plan.periods ?? 12 },
(_, i) =>
i === index
? value
: (a.taxExpenseByMonth[i] ??
''),
),
}),
)}
{numeric(
`Pagamento fiscal previsto — mês ${index + 1}`,
a.taxPaymentByMonth[index] ?? '',
(value) =>
update({
taxPaymentByMonth: Array.from(
{ length: plan.periods ?? 12 },
(_, i) =>
i === index
? value
: (a.taxPaymentByMonth[i] ??
''),
),
}),
)}
</div>
))}
</details>
<InvestmentReportTables
tables={buildIntegralFinancialTables(plan)}
/>
</details>
);
}
@@ -0,0 +1,83 @@
import {
displayReportMoney,
type InvestmentReportTable,
} from '@/lib/integral-financial-report';
export function InvestmentReportTables({
tables,
}: {
tables: InvestmentReportTable[];
}) {
return (
<div className="space-y-5">
{tables.map((table) => (
<section key={table.id} aria-label={table.title}>
<h4 className="font-semibold">{table.title}</h4>
{table.issues.length > 0 && (
<ul className="list-disc pl-5 text-amber-900">
{[...new Set(table.issues)].map((issue) => (
<li key={issue}>{issue}</li>
))}
</ul>
)}
{table.rows.length > 0 && (
<div
className="overflow-x-auto"
tabIndex={0}
role="region"
aria-label={`Tabela ${table.title}`}
>
<table className="w-full border-collapse text-left text-sm">
<caption className="sr-only">
{table.title}
</caption>
<thead>
<tr>
{table.headers.map((header, index) => (
<th
className="min-w-28 border p-2"
key={index}
>
{header}
</th>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row, i) => (
<tr key={i}>
{row.map((cell, j) =>
j === 0 ? (
<th
className="min-w-40 border p-2 font-medium"
key={j}
>
{cell}
</th>
) : (
<td
className="border p-2 whitespace-nowrap"
key={j}
>
{displayReportMoney(
cell,
)}
</td>
),
)}
</tr>
))}
</tbody>
</table>
</div>
)}
{table.notes.map((note, i) => (
<p className="mt-1 text-sm" key={i}>
{note}
</p>
))}
</section>
))}
</div>
);
}
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
import { InvestmentReportTables } from './investment-report-tables';
import {
createInvestorDossierReport,
createInvestorStageReport,
@@ -259,6 +260,9 @@ function StageReportPreview({
</div>
))}
</dl>
{section.tables && (
<InvestmentReportTables tables={section.tables} />
)}
</section>
))}
{report.limitations.map((text) => (
@@ -20,6 +20,7 @@ import {
import { buildFinancialFiscalBridge } from '@/lib/financial-fiscal-bridge';
import { BusinessPlanWarnings } from '@/components/business-plan-warnings';
import { SimulationAnnualExample } from '@/components/simulation-annual-example';
import { IntegralFinancialPlan } from '@/components/integral-financial-plan';
const emptyPlan: BusinessFinancialPlanInput = {
currency: '',
@@ -938,6 +939,7 @@ export function SimulationBusinessPlan({
}
/>
)}
<IntegralFinancialPlan plan={plan} onChange={savePlan} />
<div className="my-3 flex flex-wrap items-end gap-3 rounded border p-3">
<label className="grid gap-1 text-sm">
Importar plano financeiro InvestMoz (.json, até 60 KB)
@@ -82,6 +82,18 @@ function validCurrency(value: string): boolean {
}
export type BusinessFinancialPlanInput = {
reportAssumptions?: {
startYear: string;
openingFixedAssets: string;
openingOtherAssets: string;
openingEquity: string;
startupExpenses: { label: string; amount: string }[];
taxExpenseByMonth: string[];
taxPaymentByMonth: string[];
taxSource: string;
grantsTreatment: 'capital' | 'deferred' | '';
manualCollectionsKind: 'sales' | 'other_income' | '';
};
/** Synthetic annual demonstration; excluded from investor forecast inputs. */
annualExampleSnapshot?: string;
currency: string;
@@ -0,0 +1,603 @@
import {
forecastBusinessPlan,
monthlyProjectedSales,
type BusinessFinancialPlanInput,
} from './business-financial-plan.ts';
export type InvestmentReportTable = {
id: string;
title: string;
headers: string[];
rows: string[][];
notes: string[];
issues: string[];
};
const cents = (value: string): bigint => {
if (!/^-?\d+(?:\.\d{1,2})?$/.test(value))
throw new Error(
'Preencha os montantes do relatório com até duas casas decimais.',
);
const negative = value.startsWith('-');
const [whole, fraction = ''] = value.replace(/^-/, '').split('.');
const amount = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
return negative ? -amount : amount;
};
export const reportMoney = (amount: bigint): string => {
const abs = amount < 0n ? -amount : amount;
return `${amount < 0n ? '-' : ''}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`;
};
export const displayReportMoney = (value: string) => {
if (!/^-?\d+\.\d{2}$/.test(value)) return value;
const [whole, fraction] = value.split('.');
return `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')},${fraction}`;
};
const positive = (value: bigint) => (value > 0n ? value : 0n);
export function newReportAssumptions(
periods: number,
): NonNullable<BusinessFinancialPlanInput['reportAssumptions']> {
return {
startYear: '',
openingFixedAssets: '',
openingOtherAssets: '',
openingEquity: '',
startupExpenses: [],
taxExpenseByMonth: Array(periods).fill(''),
taxPaymentByMonth: Array(periods).fill(''),
taxSource: '',
grantsTreatment: '',
manualCollectionsKind: '',
};
}
export function isReportAssumptions(
value: unknown,
): value is NonNullable<BusinessFinancialPlanInput['reportAssumptions']> {
if (!value || typeof value !== 'object' || Array.isArray(value))
return false;
const a = value as Record<string, unknown>;
const short = (entry: unknown, length = 40) =>
typeof entry === 'string' && entry.length <= length;
return (
[
'startYear',
'openingFixedAssets',
'openingOtherAssets',
'openingEquity',
].every((key) => short(a[key])) &&
short(a.taxSource, 2000) &&
['', 'capital', 'deferred'].includes(String(a.grantsTreatment)) &&
['', 'sales', 'other_income'].includes(
String(a.manualCollectionsKind),
) &&
['taxExpenseByMonth', 'taxPaymentByMonth'].every(
(key) =>
Array.isArray(a[key]) &&
a[key].length <= 60 &&
a[key].every((entry: unknown) => short(entry)),
) &&
Array.isArray(a.startupExpenses) &&
a.startupExpenses.length <= 40 &&
a.startupExpenses.every(
(entry) =>
entry &&
typeof entry === 'object' &&
short(entry.label, 160) &&
short(entry.amount),
)
);
}
/** Read only declared investor inputs. The synthetic annual example is never used. */
export function buildIntegralFinancialTables(
plan: BusinessFinancialPlanInput,
): InvestmentReportTable[] {
const titles = [
['startup', 'Start-up / arranque'],
['sales', 'Previsão de Vendas'],
['funding', 'Financiamento'],
['break-even', 'Ponto de Equilíbrio'],
['profit-loss', 'Lucros e Perdas'],
['cashflow', 'Fluxo de Caixa'],
['balance', 'Balanço Projectado'],
];
const tables = titles.map(([id, title]) => ({
id,
title,
headers: ['Rubrica', 'Valor'],
rows: [] as string[][],
notes: [
'Projecção com dados declarados; não confirma valores realizados.',
],
issues: [] as string[],
}));
const table = (id: string) => tables.find((entry) => entry.id === id)!;
try {
const result = forecastBusinessPlan(plan);
const a = plan.reportAssumptions;
if (!isReportAssumptions(a))
throw new Error(
'Complete os dados contabilísticos complementares do relatório.',
);
if (
!/^\d{4}$/.test(a.startYear) ||
Number(a.startYear) < 1900 ||
Number(a.startYear) > 9999
)
throw new Error('Indique o ano inicial do relatório (1900–9999).');
const openingFixed = cents(a.openingFixedAssets),
otherAssets = cents(a.openingOtherAssets),
openingEquity = cents(a.openingEquity);
if (
[openingFixed, otherAssets, openingEquity].some(
(value) => value < 0n,
)
)
throw new Error(
'Os saldos iniciais complementares não podem ser negativos.',
);
if (
!Array.isArray(a.startupExpenses) ||
a.startupExpenses.length === 0 ||
a.startupExpenses.length > 40
)
throw new Error(
'Declare as despesas de arranque, incluindo uma linha de zero quando não existirem.',
);
const startup = a.startupExpenses.reduce((total, row) => {
if (
!row.label.trim() ||
row.label.length > 160 ||
cents(row.amount) < 0n
)
throw new Error(
'Cada despesa de arranque exige designação e montante não negativo.',
);
return total + cents(row.amount);
}, 0n);
const count = result.rows.length;
const schedule = (values: string[]) => {
if (!Array.isArray(values) || values.length !== count)
throw new Error(
'Preencha imposto estimado e pagamento fiscal para cada mês, incluindo zero quando aplicável.',
);
return values.map((value) => {
const amount = cents(value);
if (amount < 0n)
throw new Error(
'Os impostos estimados não podem ser negativos.',
);
return amount;
});
};
const taxExpenses = schedule(a.taxExpenseByMonth),
taxPayments = schedule(a.taxPaymentByMonth);
if (!a.taxSource.trim())
throw new Error(
'Indique a fonte ou o pressuposto fiscal, incluindo quando não prevê imposto.',
);
if (
cents(plan.grants) > 0n &&
!['capital', 'deferred'].includes(a.grantsTreatment)
)
throw new Error(
'Escolha o tratamento das subvenções: capital ou passivo diferido.',
);
if (
cents(plan.monthlyCollections) > 0n &&
!['sales', 'other_income'].includes(a.manualCollectionsKind)
)
throw new Error(
'Classifique os recebimentos manuais como vendas ou outras receitas.',
);
const periodHeaders = result.rows.map(
(row) =>
`${Number(a.startYear) + Math.floor((row.month - 1) / 12)}-${String(((row.month - 1) % 12) + 1).padStart(2, '0')}`,
);
const years = [
...new Set(periodHeaders.map((period) => period.slice(0, 4))),
];
const annualIndices = years.map((year) =>
periodHeaders
.map((period, index) => (period.startsWith(year) ? index : -1))
.filter((index) => index >= 0),
);
const headers = [
'Rubrica',
...periodHeaders,
...years.map(
(year, i) =>
`${year}${annualIndices[i].length < 12 ? ' (parcial)' : ''}`,
),
];
const flows = (id: string, label: string, values: bigint[]) =>
table(id).rows.push([
label,
...values.map(reportMoney),
...annualIndices.map((indices) =>
reportMoney(
indices.reduce(
(total, index) => total + values[index],
0n,
),
),
),
]);
const stocks = (id: string, label: string, values: (bigint | null)[]) =>
table(id).rows.push([
label,
...values.map((value) =>
value === null ? 'Por determinar' : reportMoney(value),
),
...annualIndices.map((indices) =>
values[indices.at(-1)!] === null
? 'Por determinar'
: reportMoney(values[indices.at(-1)!]!),
),
]);
for (const id of [
'sales',
'break-even',
'profit-loss',
'cashflow',
'balance',
])
table(id).headers = headers;
table('startup').rows = [
...a.startupExpenses.map((row) => [
row.label,
reportMoney(cents(row.amount)),
]),
['Despesas de arranque', reportMoney(startup)],
[
'Investimento em activos',
reportMoney(cents(plan.assetInvestment)),
],
['Existências iniciais', reportMoney(cents(plan.inventory))],
['Recebíveis iniciais', reportMoney(cents(plan.receivables))],
['Obrigações iniciais', reportMoney(cents(plan.payables))],
[
'Usos líquidos iniciais',
reportMoney(cents(result.initialUses) + startup),
],
];
table('startup').notes.push(
'Despesas de arranque reconhecidas e pagas no início. Saldos patrimoniais anteriores não são novas despesas.',
);
table('funding').rows = [
['Capital introduzido', plan.equity],
['Suprimentos', plan.shareholderLoans],
['Empréstimos', plan.bankLoanProceeds],
['Subvenções declaradas', plan.grants],
['Total de fontes', result.financing],
[
'Usos líquidos com arranque',
reportMoney(cents(result.initialUses) + startup),
],
[
'Diferença por financiar',
reportMoney(cents(result.fundingGap) + startup),
],
[
'Caixa após financiamento e arranque',
reportMoney(
cents(result.openingCashAfterInitialUses) - startup,
),
],
].map(([label, value]) => [label, reportMoney(cents(value))]);
table('funding').notes.push(
'Financiamento insuficiente é aviso não bloqueante. As fontes são pressupostos do plano, não confirmação bancária.',
);
for (const product of plan.products) {
const sales = monthlyProjectedSales({
...plan,
products: [product],
});
if (sales.some((value) => value === null))
throw new Error('Complete a previsão de vendas por produto.');
flows(
'sales',
product.label,
sales.map((value) => cents(value!)),
);
}
flows(
'sales',
'Vendas totais',
result.rows.map((row) => cents(row.revenue)),
);
let cash = cents(result.openingCashAfterInitialUses) - startup;
let receivables = cents(plan.receivables),
obligations = cents(plan.payables),
taxDue = 0n;
let depreciation = 0n,
cumulativeProfit = -startup,
principal = 0n;
let obligationsKnown = true;
const fixed = openingFixed + cents(plan.assetInvestment);
const loans =
cents(plan.bankLoanProceeds) + cents(plan.shareholderLoans);
const grantCapital =
a.grantsTreatment === 'capital' ? cents(plan.grants) : 0n;
const deferredGrant = cents(plan.grants) - grantCapital;
const paidCapital = openingEquity + cents(plan.equity) + grantCapital;
const initialDifference =
cash +
cents(plan.inventory) +
receivables +
fixed +
otherAssets -
obligations -
loans -
deferredGrant -
paidCapital -
cumulativeProfit;
if (initialDifference !== 0n)
table('balance').issues.push(
`Saldos de abertura não reconciliados: diferença ${reportMoney(initialDifference)}. Confira o património e o capital anteriores; não há compensação automática.`,
);
const ledger = result.rows.map((row, i) => {
const otherIncome =
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
: 0n;
const profit =
cents(row.profitBeforeTax) + otherIncome - taxExpenses[i];
const netCash = cents(row.netCashFlow) - taxPayments[i];
const opening = cash;
cash += netCash;
receivables +=
cents(row.revenue) - cents(row.cashCollections) + otherIncome;
const purchases =
row.inventoryReceipts === null
? null
: cents(row.inventoryReceipts);
if (purchases === null) obligationsKnown = false;
if (purchases === null)
table('balance').issues.push(
`Mês ${i + 1}: active e preencha a agenda de compras/recepções para determinar existências e obrigações.`,
);
obligations +=
(purchases ?? 0n) +
cents(row.operatingExpenses) +
cents(row.payrollExpense) +
cents(row.interestExpense) -
cents(row.variableCostPayments) -
cents(row.operatingPayments) -
cents(row.payrollPayments) -
cents(row.interestPayment) -
cents(row.openingPayablesPayments);
taxDue += taxExpenses[i] - taxPayments[i];
depreciation += cents(row.depreciation);
principal += cents(row.principalRepayment);
cumulativeProfit += profit;
const inventory =
row.inventoryClosing === null
? null
: cents(row.inventoryClosing);
if (cents(row.inventoryShortfall ?? '0') > 0n)
table('balance').issues.push(
`Mês ${i + 1}: existências insuficientes para as vendas declaradas.`,
);
if (depreciation > fixed || principal > loans)
table('balance').issues.push(
`Mês ${i + 1}: depreciação superior aos activos ou reembolso superior à dívida; confira os dados.`,
);
const assets =
positive(cash) +
positive(receivables) +
(inventory ?? 0n) +
fixed -
depreciation +
otherAssets +
positive(-obligations) +
positive(-taxDue);
const liabilities =
positive(-cash) +
positive(-receivables) +
positive(obligations) +
positive(taxDue) +
loans -
principal +
deferredGrant;
const capital = paidCapital + cumulativeProfit;
return {
opening,
cash,
receivables,
obligations: obligationsKnown ? obligations : null,
taxDue,
profit,
netCash,
assets: inventory === null || !obligationsKnown ? null : assets,
liabilities: obligationsKnown ? liabilities : null,
capital,
difference:
inventory === null || !obligationsKnown
? null
: assets - liabilities - capital,
loans: loans - principal,
paidCapital,
accumulatedResults: cumulativeProfit,
fixed: fixed - depreciation,
inventory,
};
});
const data = (key: keyof (typeof result.rows)[number]) =>
result.rows.map((row) => cents(String(row[key])));
flows('profit-loss', 'Vendas', data('revenue'));
flows(
'profit-loss',
'Outras receitas de caixa declaradas',
result.rows.map(() =>
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
: 0n,
),
);
for (const [key, label] of [
['variableCost', 'Custo directo'],
['operatingExpenses', 'Despesas operacionais'],
['payrollExpense', 'Pessoal'],
['depreciation', 'Depreciação'],
['interestExpense', 'Juros'],
] as const)
flows('profit-loss', label, data(key));
flows('profit-loss', 'Imposto estimado', taxExpenses);
flows(
'profit-loss',
'Lucro líquido',
ledger.map((row) => row.profit),
);
stocks(
'cashflow',
'Caixa inicial',
ledger.map((row) => row.opening),
);
// Annual opening cash is the first month's opening, not the closing stock.
table('cashflow').rows[0] = [
'Caixa inicial',
...ledger.map((row) => reportMoney(row.opening)),
...annualIndices.map((indices) =>
reportMoney(ledger[indices[0]].opening),
),
];
flows('cashflow', 'Recebimentos', data('cashCollections'));
for (const [key, label] of [
['variableCostPayments', 'Pagamentos de compras'],
['operatingPayments', 'Pagamentos operacionais'],
['payrollPayments', 'Pagamentos de pessoal'],
['interestPayment', 'Juros pagos'],
['principalRepayment', 'Capital reembolsado'],
['openingPayablesPayments', 'Pagamento de obrigações iniciais'],
] as const)
flows('cashflow', label, data(key));
flows('cashflow', 'Pagamento fiscal estimado', taxPayments);
flows(
'cashflow',
'Fluxo líquido',
ledger.map((row) => row.netCash),
);
stocks(
'cashflow',
'Caixa final',
ledger.map((row) => row.cash),
);
for (const [key, label] of [
['cash', 'Caixa líquida'],
['receivables', 'Recebíveis líquidos'],
['obligations', 'Obrigações operacionais líquidas'],
['taxDue', 'Saldo fiscal estimado'],
['fixed', 'Activos fixos líquidos'],
['loans', 'Empréstimos e suprimentos por reembolsar'],
['paidCapital', 'Capital declarado e anterior'],
['accumulatedResults', 'Resultados acumulados, incluindo arranque'],
['assets', 'Total do activo'],
['liabilities', 'Total do passivo'],
['capital', 'Capital e resultados'],
] as const)
stocks(
'balance',
label,
ledger.map((row) => row[key]),
);
table('balance').rows.push([
'Existências',
...ledger.map((row) =>
row.inventory === null
? 'Por determinar'
: reportMoney(row.inventory),
),
...annualIndices.map((indices) =>
ledger[indices.at(-1)!].inventory === null
? 'Por determinar'
: reportMoney(ledger[indices.at(-1)!].inventory!),
),
]);
table('balance').rows.push([
'Diferença do balanço',
...ledger.map((row) =>
row.difference === null
? 'Por determinar'
: reportMoney(row.difference),
),
...annualIndices.map((indices) =>
ledger[indices.at(-1)!].difference === null
? 'Por determinar'
: reportMoney(ledger[indices.at(-1)!].difference!),
),
]);
if (
ledger.some(
(row) => row.difference !== null && row.difference !== 0n,
)
)
table('balance').issues.push(
'Existem períodos não reconciliados; reveja as rubricas indicadas.',
);
table('balance').notes.push(
'Caixa negativa é necessidade de tesouraria no passivo; recebíveis negativos são adiantamentos de clientes; obrigações negativas são adiantamentos a fornecedores. Não são fontes mobilizadas.',
'Capital inicial e activos anteriores são declarados. Depreciação e reembolsos provêm do motor existente. Subvenções: ' +
(a.grantsTreatment || 'sem montante declarado') +
'.',
);
table('profit-loss').notes.push(
'As despesas de arranque constam da abertura, sem repetição mensal. Impostos: ' +
a.taxSource,
);
table('cashflow').notes.push(
'O caixa de abertura já inclui fontes, usos e despesas de arranque; os movimentos iniciais não são repetidos nos meses.',
);
const contributions = result.rows.map(
(row) => cents(row.revenue) - cents(row.variableCost),
);
const fixedCosts = result.rows.map(
(row) =>
cents(row.operatingExpenses) +
cents(row.payrollExpense) +
cents(row.depreciation),
);
const breakEven = (
sales: bigint,
contribution: bigint,
fixedCost: bigint,
) =>
contribution <= 0n
? 'Indeterminado — margem sem contribuição positiva'
: reportMoney(
(fixedCost * sales + contribution / 2n) / contribution,
);
table('break-even').rows = [
[
'Vendas de equilíbrio',
...result.rows.map((row, i) =>
breakEven(
cents(row.revenue),
contributions[i],
fixedCosts[i],
),
),
...annualIndices.map((indices) =>
breakEven(
indices.reduce(
(v, i) => v + cents(result.rows[i].revenue),
0n,
),
indices.reduce((v, i) => v + contributions[i], 0n),
indices.reduce((v, i) => v + fixedCosts[i], 0n),
),
),
],
];
table('break-even').notes.push(
'Vendas de equilíbrio = custos fixos operacionais, pessoal e depreciação ÷ margem de contribuição ponderada. Juros e impostos excluídos. Arredondamento apenas no resultado final, ao centavo.',
);
} catch (error) {
for (const entry of tables)
entry.issues.push(
error instanceof Error
? error.message
: 'Complete os dados do plano financeiro.',
);
}
return tables;
}
@@ -17,6 +17,7 @@ import {
WidthType,
} from 'docx';
import JSZip from 'jszip';
import { displayReportMoney } from './integral-financial-report.ts';
import {
classifyDossierAttachment,
MAX_EMBEDDED_TEXT_BYTES,
@@ -450,6 +451,36 @@ export async function generateProjectDossierDocx(
);
const table = sectionTable(section);
if (table) children.push(table);
for (const entry of section.tables ?? []) {
children.push(
new Paragraph({
text: entry.title,
heading: HeadingLevel.HEADING_2,
}),
);
for (const note of [...entry.issues, ...entry.notes])
children.push(new Paragraph(note));
// Repeat the rubric with at most four periods per page-width table.
for (let start = 1; start < entry.headers.length; start += 4) {
const indices = [
0,
...Array.from(
{ length: Math.min(4, entry.headers.length - start) },
(_, i) => start + i,
),
];
children.push(
tableForDocx(
indices.map((i) => entry.headers[i]),
entry.rows.map((row) =>
indices.map((i) =>
displayReportMoney(row[i] ?? ''),
),
),
),
);
}
}
if (!section.rows.length && !section.paragraphs.length)
children.push(
new Paragraph('Não há informação fornecida nesta secção.'),
@@ -609,6 +640,17 @@ export async function createProjectDossierPrintHtml(
content.push(`<section><h2>${escapeHtml(section.title)}</h2>`);
for (const paragraph of section.paragraphs)
content.push(`<p>${escapeHtml(paragraph)}</p>`);
for (const entry of section.tables ?? []) {
content.push(`<h3>${escapeHtml(entry.title)}</h3>`);
for (const note of [...entry.issues, ...entry.notes])
content.push(`<p>${escapeHtml(note)}</p>`);
content.push(
`<div style="overflow-x:auto">${htmlTable(
entry.headers,
entry.rows.map((row) => row.map(displayReportMoney)),
)}</div>`,
);
}
if (section.rows.length)
content.push(
htmlTable(
@@ -1,4 +1,9 @@
import { displayValue } from './display-value.ts';
import {
buildIntegralFinancialTables,
type InvestmentReportTable,
} from './integral-financial-report.ts';
import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts';
import { fiscalQaRows } from './fiscal-qa-preview.ts';
import { pathStates } from './investor-path.ts';
import {
@@ -60,6 +65,7 @@ export type DossierReportRow = {
classification: string;
};
export type DossierReportSection = {
tables?: InvestmentReportTable[];
id: DossierReportSectionId;
title: string;
private: boolean;
@@ -512,6 +518,11 @@ function makeSections(
}
const finance = sections.get('finance');
const financialPlan = restoreBusinessPlanSnapshot(
text(draft, 'business_plan_snapshot'),
);
if (finance && financialPlan?.reportAssumptions)
finance.tables = buildIntegralFinancialTables(financialPlan);
if (
finance &&
['fiscal_rule_qa_preview', 'fiscal_rule_published'].includes(
@@ -69,6 +69,9 @@ function editor(initialSnapshot) {
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
(name === '@/components/integral-financial-plan'
? { IntegralFinancialPlan: () => null }
: undefined) ??
(name === '@/components/business-plan-warnings'
? { BusinessPlanWarnings: () => null }
: name === '@/components/simulation-annual-example'
@@ -0,0 +1,65 @@
import { newReportAssumptions } from '../../../resources/js/lib/integral-financial-report.ts';
export function financialReportFixture(periods = 24) {
const value = {
currency: 'MZN',
openingCash: '1000',
assetInvestment: '600',
equity: '600',
products: [
{
label: 'Serviço declarado',
monthlyUnits: '10',
unitPrice: '100',
unitVariableCost: '40',
},
],
depreciationLifeMonths: 60,
periods,
...Object.fromEntries(
[
'monthlyCollections',
'monthlyVariableCostPayments',
'monthlyInventoryPurchases',
'monthlyOperatingExpenses',
'monthlyOperatingPayments',
'monthlyPayrollExpense',
'monthlyPayrollPayments',
'inventory',
'receivables',
'payables',
'shareholderLoans',
'bankLoanProceeds',
'grants',
'assetDepreciation',
'monthlyInterestExpense',
'monthlyInterestPayment',
'monthlyPrincipalRepayment',
].map((key) => [key, '0']),
),
};
Object.assign(value, {
monthlyVariableCostPayments: '400',
monthlyInventoryPurchases: '400',
monthlyOperatingExpenses: '100',
monthlyOperatingPayments: '100',
monthlyPayrollExpense: '200',
monthlyPayrollPayments: '200',
assetDepreciation: '600',
salesCollectionLagMonths: 0,
salesCollectionPercent: '100',
openingReceivablesCollectionPercent: '0',
});
value.reportAssumptions = {
...newReportAssumptions(periods),
startYear: '2027',
openingFixedAssets: '0',
openingOtherAssets: '0',
openingEquity: '1000',
startupExpenses: [{ label: 'Constituição', amount: '100' }],
taxExpenseByMonth: Array(periods).fill('30'),
taxPaymentByMonth: Array(periods).fill('20'),
taxSource: 'Hipótese sintética de teste; não é taxa legal',
};
return value;
}
@@ -0,0 +1,175 @@
import { financialReportFixture as plan } from './fixtures/integral-financial-plan.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import JSZip from 'jszip';
import {
buildIntegralFinancialTables,
displayReportMoney,
} from '../../resources/js/lib/integral-financial-report.ts';
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
restoreBusinessPlanSnapshot,
} from '../../resources/js/lib/business-financial-plan.ts';
import {
createProjectDossierReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import {
partitionSimulationDraft,
restoreSimulationDraft,
} from '../../resources/js/lib/simulation-form.ts';
const get = (tables, id, label) =>
tables
.find((table) => table.id === id)
.rows.find((row) => row[0] === label);
void test('seven integrated statements reconcile monthly flows, annual totals and closing stocks without changing the existing engine', () => {
const input = plan(),
before = JSON.stringify(input),
forecast = forecastBusinessPlan(input),
tables = buildIntegralFinancialTables(input);
assert.equal(tables.length, 7);
assert.ok(
tables.every((table) => table.issues.length === 0),
JSON.stringify(tables.map((t) => [t.id, t.issues])),
);
assert.equal(get(tables, 'startup', 'Despesas de arranque')[1], '100.00');
assert.equal(
get(tables, 'funding', 'Caixa após financiamento e arranque')[1],
'900.00',
);
assert.deepEqual(get(tables, 'sales', 'Vendas totais').slice(-2), [
'12000.00',
'12000.00',
]);
assert.deepEqual(get(tables, 'profit-loss', 'Lucro líquido').slice(-2), [
'3120.00',
'3120.00',
]);
assert.deepEqual(get(tables, 'cashflow', 'Caixa inicial').slice(-2), [
'900.00',
'4260.00',
]);
assert.deepEqual(get(tables, 'cashflow', 'Caixa final').slice(-2), [
'4260.00',
'7620.00',
]);
assert.deepEqual(get(tables, 'balance', 'Total do activo').slice(-2), [
'4740.00',
'7980.00',
]);
assert.ok(
get(tables, 'balance', 'Diferença do balanço')
.slice(1)
.every((value) => value === '0.00'),
);
assert.equal(
get(tables, 'break-even', 'Vendas de equilíbrio')[1],
'516.67',
);
assert.equal(JSON.stringify(input), before);
const withoutSupplement = { ...input };
delete withoutSupplement.reportAssumptions;
assert.deepEqual(
forecastBusinessPlan(withoutSupplement),
forecast,
'no changes to approved base forecast',
);
const draft = {
purpose: 'own_investment',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
};
const stored = JSON.parse(
JSON.stringify(partitionSimulationDraft(draft, false)),
);
const recovered = restoreBusinessPlanSnapshot(
restoreSimulationDraft(stored.economic_snapshot, {})
.business_plan_snapshot,
);
assert.deepEqual(buildIntegralFinancialTables(recovered), tables);
});
void test('missing inputs, insufficient inventory and inconsistent opening capital remain explicit, never balancing plugs', () => {
const input = plan(12);
input.reportAssumptions.openingEquity = '999.99';
let tables = buildIntegralFinancialTables(input);
assert.match(
tables.find((t) => t.id === 'balance').issues.join(' '),
/abertura/,
);
assert.equal(get(tables, 'balance', 'Diferença do balanço')[1], '0.01');
input.reportAssumptions.openingEquity = '1000';
input.monthlyInventoryPurchases = '';
tables = buildIntegralFinancialTables(input);
assert.match(
tables.find((t) => t.id === 'balance').issues.join(' '),
/agenda/,
);
assert.equal(
get(tables, 'balance', 'Diferença do balanço')[1],
'Por determinar',
);
input.monthlyInventoryPurchases = '0';
assert.match(
buildIntegralFinancialTables(input)
.find((t) => t.id === 'balance')
.issues.join(' '),
/insuficientes/,
);
input.reportAssumptions.taxExpenseByMonth[0] = '';
assert.ok(
buildIntegralFinancialTables(input).every((t) => t.issues.length > 0),
);
});
void test('partial years, changing product schedules and negative cash keep exact amounts and disclosed assumptions', () => {
const input = plan(13);
input.products[0].unitPriceByPeriod = Array(13).fill('100.01');
input.reportAssumptions.startupExpenses[0].amount = '10000.01';
const tables = buildIntegralFinancialTables(input);
assert.ok(
tables
.find((t) => t.id === 'sales')
.headers.at(-1)
.endsWith('(parcial)'),
);
assert.equal(get(tables, 'sales', 'Vendas totais').at(-1), '1000.10');
assert.equal(get(tables, 'cashflow', 'Caixa inicial')[1], '-9000.01');
assert.ok(
get(tables, 'balance', 'Diferença do balanço')
.slice(1)
.every((value) => value === '0.00'),
);
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 () => {
const input = plan(13);
input.products[0].label = '<script>não executar</script>';
const report = createProjectDossierReport(
{
project_title: 'Teste QA',
business_plan_snapshot: serializeBusinessPlanSnapshot(input),
},
{
selectedSections: new Set(['finance']),
generatedAt: '2026-11-20T12:00:00Z',
},
);
assert.equal(report.sections[0].tables.length, 7);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /Balanço Projectado/);
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>não executar/);
const output = await generateProjectDossierDocx(report, []);
const zip = await JSZip.loadAsync(
output instanceof Blob ? await output.arrayBuffer() : output,
);
const xml = await zip.file('word/document.xml').async('string');
assert.match(xml, /Balanço Projectado/);
assert.match(xml, /Lucros e Perdas/);
assert.match(xml, /7 620,00|7620,00|4 540,00|4540,00/);
});