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)) ?? [],