import assert from 'node:assert/strict'; import test from 'node:test'; import { businessPlanWarnings, defaultPlanWarningLimits, newAnnualReferencePlan, calculateAnnualReferencePlan, } from '../../resources/js/lib/business-plan-guidance.ts'; import { forecastBusinessPlan, serializeBusinessPlanSnapshot, restoreBusinessPlanSnapshot, } from '../../resources/js/lib/business-financial-plan.ts'; import { validateSimulationDraft } from '../../resources/js/lib/simulation-form.ts'; import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts'; function businessPlan() { const amounts = [ 'monthlyCollections', 'monthlyVariableCostPayments', 'monthlyInventoryPurchases', 'monthlyOperatingExpenses', 'monthlyOperatingPayments', 'monthlyPayrollExpense', 'monthlyPayrollPayments', 'inventory', 'receivables', 'payables', 'equity', 'shareholderLoans', 'bankLoanProceeds', 'grants', 'assetDepreciation', 'monthlyInterestExpense', 'monthlyInterestPayment', 'monthlyPrincipalRepayment', ]; return { ...Object.fromEntries(amounts.map((key) => [key, '0'])), currency: 'MZN', openingCash: '1000', assetInvestment: '200', products: [ { label: 'Serviço sintético', monthlyUnits: '10', unitPrice: '100', unitVariableCost: '40', }, ], depreciationLifeMonths: 60, periods: 12, annualGrowthPercent: '250', }; } void test('insufficient funding and growth above 100 percent remain valid, saved assumptions with nonblocking warnings', () => { const plan = businessPlan(); const snapshot = serializeBusinessPlanSnapshot(plan); const restored = restoreBusinessPlanSnapshot(snapshot); assert.equal(restored.annualGrowthPercent, '250'); const result = forecastBusinessPlan(restored); assert.equal(result.fundingGap, '200.00'); assert.equal( result.totalRevenue, '12000.00', 'a growth target must not overwrite declared sales', ); assert.equal( validateSimulationDraft( { business_plan_snapshot: snapshot }, 'financial', ).business_plan_snapshot, undefined, ); const warnings = businessPlanWarnings({ fundingGap: Number(result.fundingGap), growthPercent: Number(restored.annualGrowthPercent), currency: 'MZN', }); assert.deepEqual( warnings.map((warning) => warning.id), ['funding', 'growth'], ); const report = createProjectDossierReport( { business_plan_snapshot: snapshot }, { selectedSections: new Set(['finance']), generatedAt: '2026-11-20T08:00:00Z', }, ); assert.match(JSON.stringify(report), /aviso não bloqueante/); assert.match(JSON.stringify(report), /Crescimento anual pretendido/); assert.match(JSON.stringify(report), /250%/); }); void test('owner annual reference reconciles exact startup, margins, profits, cash and unrounded break-even', () => { const source = newAnnualReferencePlan(), before = JSON.stringify(source); const result = calculateAnnualReferencePlan(source), first = result.years[0]; assert.equal(result.startupExpenses, '1325000.00'); assert.equal(result.assets, '500250.00'); assert.equal(result.requiredFunding, '1825250.00'); assert.equal(result.availableFunding, '0.00'); assert.equal(result.fundingGap, '1825250.00'); assert.equal(first.grossMargin, '1999.00'); assert.equal(first.operatingExpenses, '2415.00'); assert.equal(first.operatingProfit, '-416.00'); assert.equal(first.netProfit, '-416.00'); assert.equal(first.cashFlow, '756.00'); assert.equal(first.closingCash, '90756.00'); assert.equal(Math.round(first.monthlyBreakEven), 1464); assert.ok( Math.abs(first.monthlyBreakEven - 2415 / 12 / (1999 / 14537)) < 1e-10, ); assert.equal(result.years[1].netProfit, '1456.00'); assert.equal(result.years[2].netProfit, '1631.00'); assert.equal(result.years[2].closingCash, '93498.00'); assert.equal(result.monthlyStatus, 'por reconciliar'); assert.equal('monthlyRows' in result, false); assert.deepEqual( result.years.map((year) => year.operatingLiabilities), ['1641.00', '1417.00', '1598.00'], ); assert.deepEqual( result.years.map((year) => year.receivables), ['469.00', '694.00', '771.00'], ); assert.deepEqual( result.years.map((year) => year.closingAssets), ['501475.00', '502707.00', '504519.00'], ); assert.equal(result.capitalToMobilise, '1825250.00'); const cents = (value) => BigInt(value.replace('.', '')); for (const [index, year] of result.years.entries()) { assert.equal(year.balanceDifference, '0.00'); assert.equal(year.illustrativeMonths.length, 12); for (const key of [ 'sales', 'directCosts', 'netProfit', 'cashReceived', 'cashSpent', ]) { const expected = key === 'netProfit' ? year[key] : source.years[index][key]; assert.equal( year.illustrativeMonths.reduce( (sum, row) => sum + cents(row[key]), 0n, ), cents(Number(expected).toFixed(2)), ); } for (const month of year.illustrativeMonths) assert.equal(month.balanceDifference, '0.00'); const last = year.illustrativeMonths.at(-1); for (const key of [ 'closingCash', 'receivables', 'operatingLiabilities', ]) assert.equal(last[key], year[key]); } const warnings = businessPlanWarnings({ fundingGap: Number(result.fundingGap), netProfit: Number(first.netProfit), sales: Number(first.sales), directCosts: Number(first.directCosts), monthlyBreakEven: first.monthlyBreakEven, }); assert.ok(warnings.some((warning) => warning.id === 'loss')); assert.ok(warnings.some((warning) => warning.id === 'break-even')); assert.equal(JSON.stringify(source), before); }); void test('derived ledger reconciles edited cents and surplus funding without altering annual inputs', () => { const plan = newAnnualReferencePlan(); plan.ownerCapital = '2000000.01'; plan.years[0].sales = '14537.01'; plan.years[0].cashSpent = '15783.01'; plan.years[0].payrollCharges = '315.01'; plan.years[0].vatPaid = '2470.99'; const before = JSON.stringify(plan); const result = calculateAnnualReferencePlan(plan); assert.equal(result.capitalToMobilise, '0.00'); assert.equal(result.years[0].closingCash, '265506.00'); assert.equal(result.years[0].receivables, '469.01'); assert.equal(result.years[0].vatBalance, '0.01'); for (const year of result.years) { assert.equal(year.balanceDifference, '0.00'); for (const month of year.illustrativeMonths) assert.equal(month.balanceDifference, '0.00'); assert.equal( year.illustrativeMonths.at(-1).closingCash, year.closingCash, ); } assert.equal(JSON.stringify(plan), before); plan.years[0].vatReceived = '16539.01'; assert.throws(() => calculateAnnualReferencePlan(plan), /IVA/); }); void test('reference edits update dependent totals and preserve data when an input is invalid', () => { const source = newAnnualReferencePlan(); source.startupExpenses[0].amount = '25000.25'; assert.equal( calculateAnnualReferencePlan(source).requiredFunding, '1825250.25', ); source.years[0].sales = ''; assert.throws( () => calculateAnnualReferencePlan(source), /Preencha este campo para continuar/, ); assert.equal(source.startupExpenses[0].amount, '25000.25'); source.years[0].sales = '0'; assert.throws( () => calculateAnnualReferencePlan(source), /Indique as vendas previstas/, ); source.years[0].sales = '100'; assert.throws(() => calculateAnnualReferencePlan(source), /não há margem/); }); void test('warning limits are configurable and equality at the threshold is not a warning', () => { assert.deepEqual(businessPlanWarnings({ growthPercent: 100 }), []); assert.deepEqual( businessPlanWarnings( { growthPercent: 250 }, { ...defaultPlanWarningLimits, annualGrowthPercent: 300 }, ), [], ); assert.equal(businessPlanWarnings({ creditDays: 91 })[0].id, 'credit'); assert.deepEqual(businessPlanWarnings({ creditDays: 90 }), []); });