vrsao 2
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-08 14:02:01 +02:00
parent bdd766c68a
commit 1106509116
354 changed files with 48275 additions and 24635 deletions
+36 -36
View File
@@ -59,7 +59,7 @@ const assumptions = {
periods: 12,
};
test('financial forecast reconciles revenue, finance sources, working capital and monthly cash', () => {
void test('financial forecast reconciles revenue, finance sources, working capital and monthly cash', () => {
const result = forecastBusinessPlan(assumptions);
assert.equal(result.workingCapital, '25000.00');
assert.equal(result.initialUses, '125000.00');
@@ -90,7 +90,7 @@ test('financial forecast reconciles revenue, finance sources, working capital an
assert.equal(result.endingCash, '113000.00');
});
test('opening payable installments reduce cash without changing profit and retain unpaid balances', () => {
void test('opening payable installments reduce cash without changing profit and retain unpaid balances', () => {
const opening = {
...assumptions,
periods: 3,
@@ -171,7 +171,7 @@ test('opening payable installments reduce cash without changing profit and retai
);
});
test('opening payable schedule caps cent rounding at the remaining balance', () => {
void test('opening payable schedule caps cent rounding at the remaining balance', () => {
const rounded = forecastBusinessPlan({
...assumptions,
periods: 2,
@@ -213,7 +213,7 @@ test('opening payable schedule caps cent rounding at the remaining balance', ()
assert.equal(rounded.openingPayablesAtEnd, '0.00');
});
test('monthly unit schedules drive revenue, costs, inventory and scenario volume', () => {
void test('monthly unit schedules drive revenue, costs, inventory and scenario volume', () => {
const seasonal = {
...assumptions,
periods: 3,
@@ -286,7 +286,7 @@ test('monthly unit schedules drive revenue, costs, inventory and scenario volume
);
});
test('monthly unit schedules must match the horizon and contain valid quantities', () => {
void test('monthly unit schedules must match the horizon and contain valid quantities', () => {
assert.throws(
() =>
forecastBusinessPlan({
@@ -331,7 +331,7 @@ test('monthly unit schedules must match the horizon and contain valid quantities
);
});
test('monthly prices and unit costs affect revenue, consumption and scenarios', () => {
void test('monthly prices and unit costs affect revenue, consumption and scenarios', () => {
const plan = {
...assumptions,
periods: 3,
@@ -385,7 +385,7 @@ test('monthly prices and unit costs affect revenue, consumption and scenarios',
);
});
test('monthly money schedules cover the horizon and reject invalid amounts', () => {
void test('monthly money schedules cover the horizon and reject invalid amounts', () => {
assert.throws(
() =>
forecastBusinessPlan({
@@ -430,7 +430,7 @@ test('monthly money schedules cover the horizon and reject invalid amounts', ()
);
});
test('monthly operating and payroll expense schedules remain separate from payments', () => {
void test('monthly operating and payroll expense schedules remain separate from payments', () => {
const result = forecastBusinessPlan({
...assumptions,
periods: 3,
@@ -486,7 +486,7 @@ test('monthly operating and payroll expense schedules remain separate from payme
assert.equal(scenarios.favorable.result.rows[0].payrollExpense, '450.00');
});
test('monthly operating schedules require full horizon, exact cents and current snapshot version', () => {
void test('monthly operating schedules require full horizon, exact cents and current snapshot version', () => {
assert.throws(
() =>
forecastBusinessPlan({
@@ -546,7 +546,7 @@ test('monthly operating schedules require full horizon, exact cents and current
assert.match(csv, /Pagamentos de pessoal/);
});
test('losses and negative closing cash remain visible instead of being clamped to zero', () => {
void test('losses and negative closing cash remain visible instead of being clamped to zero', () => {
const result = forecastBusinessPlan({
...assumptions,
openingCash: '-100',
@@ -569,7 +569,7 @@ test('losses and negative closing cash remain visible instead of being clamped t
assert.ok(Number(result.endingCash) < 0);
});
test('principal repayments affect cash but are excluded from profit expenses', () => {
void test('principal repayments affect cash but are excluded from profit expenses', () => {
const withPrincipal = forecastBusinessPlan(assumptions);
const withoutPrincipal = forecastBusinessPlan({
...assumptions,
@@ -586,7 +586,7 @@ test('principal repayments affect cash but are excluded from profit expenses', (
);
});
test('depreciation allocation reconciles exactly over useful life', () => {
void test('depreciation allocation reconciles exactly over useful life', () => {
const result = forecastBusinessPlan({
...assumptions,
assetDepreciation: '100.00',
@@ -599,7 +599,7 @@ test('depreciation allocation reconciles exactly over useful life', () => {
);
});
test('missing currency, products, invalid numbers and invalid horizons are explicit errors', () => {
void test('missing currency, products, invalid numbers and invalid horizons are explicit errors', () => {
assert.throws(
() => forecastBusinessPlan({ ...assumptions, currency: '' }),
/moeda ISO/,
@@ -643,7 +643,7 @@ test('missing currency, products, invalid numbers and invalid horizons are expli
);
});
test('versioned plan snapshots restore assumptions and reject unsupported or oversized data', () => {
void test('versioned plan snapshots restore assumptions and reject unsupported or oversized data', () => {
const saved = serializeBusinessPlanSnapshot(assumptions);
assert.deepEqual(restoreBusinessPlanSnapshot(saved), assumptions);
assert.equal(
@@ -976,7 +976,7 @@ test('versioned plan snapshots restore assumptions and reject unsupported or ove
);
});
test('business plan serializer refuses snapshots above the server storage limit', () => {
void test('business plan serializer refuses snapshots above the server storage limit', () => {
assert.throws(
() =>
serializeBusinessPlanSnapshot({
@@ -992,7 +992,7 @@ test('business plan serializer refuses snapshots above the server storage limit'
);
});
test('sales invoicing and receipts follow an optional declared collection lag', () => {
void test('sales invoicing and receipts follow an optional declared collection lag', () => {
const delayed = forecastBusinessPlan({
...assumptions,
monthlyCollections: '0',
@@ -1024,7 +1024,7 @@ test('sales invoicing and receipts follow an optional declared collection lag',
assert.equal(sameMonth.totalProfitBeforeTax, delayed.totalProfitBeforeTax);
});
test('scheduled collection percentage keeps unpaid invoices in receivables with exact rounding', () => {
void test('scheduled collection percentage keeps unpaid invoices in receivables with exact rounding', () => {
const partial = forecastBusinessPlan({
...assumptions,
monthlyCollections: '0',
@@ -1071,7 +1071,7 @@ test('scheduled collection percentage keeps unpaid invoices in receivables with
);
});
test('sales recovery applies only to overdue invoices and never exceeds open balances', () => {
void test('sales recovery applies only to overdue invoices and never exceeds open balances', () => {
const recovered = forecastBusinessPlan({
...assumptions,
monthlyCollections: '0',
@@ -1142,7 +1142,7 @@ test('sales recovery applies only to overdue invoices and never exceeds open bal
);
});
test('opening receivables affect cash only when a month and collection percentage are declared', () => {
void test('opening receivables affect cash only when a month and collection percentage are declared', () => {
const unscheduled = forecastBusinessPlan({
...assumptions,
monthlyCollections: '0',
@@ -1190,7 +1190,7 @@ test('opening receivables affect cash only when a month and collection percentag
);
});
test('opening receivable installments reconcile to the initial balance across months', () => {
void test('opening receivable installments reconcile to the initial balance across months', () => {
const scheduled = forecastBusinessPlan({
...assumptions,
monthlyCollections: '0',
@@ -1263,7 +1263,7 @@ test('opening receivable installments reconcile to the initial balance across mo
);
});
test('opening receivable installments cap independently rounded cents at the available balance', () => {
void test('opening receivable installments cap independently rounded cents at the available balance', () => {
const rounded = forecastBusinessPlan({
...assumptions,
receivables: '0.01',
@@ -1280,7 +1280,7 @@ test('opening receivable installments cap independently rounded cents at the ava
assert.equal(rounded.openingReceivablesAtEnd, '0.00');
});
test('inventory purchases, consumption, closing stock and stock shortfall reconcile independently of payments', () => {
void test('inventory purchases, consumption, closing stock and stock shortfall reconcile independently of payments', () => {
const supplied = forecastBusinessPlan({
...assumptions,
inventory: '0',
@@ -1302,7 +1302,7 @@ test('inventory purchases, consumption, closing stock and stock shortfall reconc
assert.equal(supplied.rows[0].variableCostPayments, '0.00');
});
test('inventory lead time separates monthly orders, receipts, shortages and goods still in transit', () => {
void test('inventory lead time separates monthly orders, receipts, shortages and goods still in transit', () => {
const result = forecastBusinessPlan({
...assumptions,
inventory: '0',
@@ -1333,7 +1333,7 @@ test('inventory lead time separates monthly orders, receipts, shortages and good
assert.equal(result.endingCash, noDelay.endingCash);
});
test('monthly inventory purchase schedule reconciles variable orders, lead times, receipts and transit', () => {
void test('monthly inventory purchase schedule reconciles variable orders, lead times, receipts and transit', () => {
const result = forecastBusinessPlan({
...assumptions,
periods: 4,
@@ -1436,7 +1436,7 @@ test('monthly inventory purchase schedule reconciles variable orders, lead times
assert.match(csv, /Prazo da encomenda \(meses\)/);
});
test('monthly variable purchase payments affect cash independently from inventory orders and profit', () => {
void test('monthly variable purchase payments affect cash independently from inventory orders and profit', () => {
const base = {
...assumptions,
periods: 3,
@@ -1464,7 +1464,7 @@ test('monthly variable purchase payments affect cash independently from inventor
);
});
test('product inventory schedules reconcile independently and do not transfer stock between products', () => {
void test('product inventory schedules reconcile independently and do not transfer stock between products', () => {
const plan = {
...assumptions,
periods: 2,
@@ -1542,7 +1542,7 @@ test('product inventory schedules reconcile independently and do not transfer st
);
});
test('supplier payment terms drive purchase cash flow and expose amounts due beyond the horizon', () => {
void test('supplier payment terms drive purchase cash flow and expose amounts due beyond the horizon', () => {
const plan = {
...assumptions,
periods: 2,
@@ -1624,7 +1624,7 @@ test('supplier payment terms drive purchase cash flow and expose amounts due bey
);
});
test('supplier order installments reconcile exact cents, cash dates and unallocated balances', () => {
void test('supplier order installments reconcile exact cents, cash dates and unallocated balances', () => {
const plan = {
...assumptions,
periods: 2,
@@ -1691,7 +1691,7 @@ test('supplier order installments reconcile exact cents, cash dates and unalloca
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(snapshot)), null);
});
test('business assumptions survive the existing encrypted-draft snapshot split and restore', () => {
void test('business assumptions survive the existing encrypted-draft snapshot split and restore', () => {
const encoded = serializeBusinessPlanSnapshot(assumptions);
const snapshots = partitionSimulationDraft({
purpose: 'own_investment',
@@ -1709,7 +1709,7 @@ test('business assumptions survive the existing encrypted-draft snapshot split a
);
});
test('presentation currency conversion requires and reports its rate, date, and declared source', () => {
void test('presentation currency conversion requires and reports its rate, date, and declared source', () => {
const result = forecastBusinessPlan({
...assumptions,
presentationCurrency: 'USD',
@@ -1760,7 +1760,7 @@ test('presentation currency conversion requires and reports its rate, date, and
);
});
test('CSV marks presentation currency conversion as an unverified user planning assumption', () => {
void test('CSV marks presentation currency conversion as an unverified user planning assumption', () => {
const csv = exportBusinessPlanCsv(
{
...assumptions,
@@ -1779,7 +1779,7 @@ test('CSV marks presentation currency conversion as an unverified user planning
);
});
test('business plan export carries its assumptions, formulas, period, currency, and matching result', () => {
void test('business plan export carries its assumptions, formulas, period, currency, and matching result', () => {
const csv = exportBusinessPlanCsv(
{ ...assumptions, periods: 1 },
'2026-10-02T10:00:00.000Z',
@@ -1805,7 +1805,7 @@ test('business plan export carries its assumptions, formulas, period, currency,
assert.match(csv, /Existências em trânsito no fim do horizonte,0\.00/);
});
test('business plan CSV preserves declared monthly product schedules', () => {
void test('business plan CSV preserves declared monthly product schedules', () => {
const csv = exportBusinessPlanCsv(
{
...assumptions,
@@ -1826,7 +1826,7 @@ test('business plan CSV preserves declared monthly product schedules', () => {
assert.ok(csv.includes('"[""40"",""55"",""30"",""20""]"'));
});
test('CSV export exposes the sales collection assumption and outstanding receivable', () => {
void test('CSV export exposes the sales collection assumption and outstanding receivable', () => {
const csv = exportBusinessPlanCsv(
{
...assumptions,
@@ -1849,7 +1849,7 @@ test('CSV export exposes the sales collection assumption and outstanding receiva
);
});
test('business plan CSV neutralizes formula-like labels and preserves negative financial values', () => {
void test('business plan CSV neutralizes formula-like labels and preserves negative financial values', () => {
const csv = exportBusinessPlanCsv({
...assumptions,
products: [
@@ -1865,7 +1865,7 @@ test('business plan CSV neutralizes formula-like labels and preserves negative f
assert.match(csv, /Diferença entre usos e fontes,-5000\.00/);
});
test('financial scenarios expose user-declared changes without creating tax values', () => {
void test('financial scenarios expose user-declared changes without creating tax values', () => {
const scenarioPlan = {
...assumptions,
periods: 1,
+60 -16
View File
@@ -8,17 +8,30 @@ import {
updateBusinessLocation,
} from '../../resources/js/lib/business-locations.ts';
test('location paths survive draft encoding and malformed drafts are ignored safely', () => {
void test('location paths survive draft encoding and malformed drafts are ignored safely', () => {
const paths = [
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
{ province_id: 'province-b', district_id: '', admin_post_id: '', locality_id: '' },
{
province_id: 'province-a',
district_id: 'district-a',
admin_post_id: '',
locality_id: '',
},
{
province_id: 'province-b',
district_id: '',
admin_post_id: '',
locality_id: '',
},
];
assert.deepEqual(decodeBusinessLocations(encodeBusinessLocations(paths)), paths);
assert.deepEqual(
decodeBusinessLocations(encodeBusinessLocations(paths)),
paths,
);
assert.deepEqual(decodeBusinessLocations('{invalid'), []);
assert.deepEqual(decodeBusinessLocations('null'), []);
});
test('changing a parent clears every dependent selection in only that row', () => {
void test('changing a parent clears every dependent selection in only that row', () => {
const initial = {
province_id: 'province-a',
district_id: 'district-a',
@@ -26,7 +39,12 @@ test('changing a parent clears every dependent selection in only that row', () =
locality_id: 'locality-a',
};
const rows = [initial, emptyBusinessLocation()];
const updated = updateBusinessLocation(rows, 0, 'district_id', 'district-b');
const updated = updateBusinessLocation(
rows,
0,
'district_id',
'district-b',
);
assert.deepEqual(updated[0], {
province_id: 'province-a',
district_id: 'district-b',
@@ -36,14 +54,40 @@ test('changing a parent clears every dependent selection in only that row', () =
assert.deepEqual(updated[1], emptyBusinessLocation());
});
test('overlapping paths are detected while separate administrative branches remain valid', () => {
assert.equal(hasDuplicateBusinessLocationPath([
{ province_id: 'province-a', district_id: '', admin_post_id: '', locality_id: '' },
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
]), true);
assert.equal(hasDuplicateBusinessLocationPath([
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
{ province_id: 'province-a', district_id: 'district-b', admin_post_id: '', locality_id: '' },
emptyBusinessLocation(),
]), false);
void test('overlapping paths are detected while separate administrative branches remain valid', () => {
assert.equal(
hasDuplicateBusinessLocationPath([
{
province_id: 'province-a',
district_id: '',
admin_post_id: '',
locality_id: '',
},
{
province_id: 'province-a',
district_id: 'district-a',
admin_post_id: '',
locality_id: '',
},
]),
true,
);
assert.equal(
hasDuplicateBusinessLocationPath([
{
province_id: 'province-a',
district_id: 'district-a',
admin_post_id: '',
locality_id: '',
},
{
province_id: 'province-a',
district_id: 'district-b',
admin_post_id: '',
locality_id: '',
},
emptyBusinessLocation(),
]),
false,
);
});
+6 -3
View File
@@ -2,16 +2,19 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { csvCell, csvCellWithDelimiter } from '../../resources/js/lib/csv.js';
test('CSV cells neutralize formula prefixes after spaces or controls', () => {
void test('CSV cells neutralize formula prefixes after spaces or controls', () => {
assert.equal(csvCell('=SUM(A1:A2)'), "'=SUM(A1:A2)");
assert.equal(csvCell('\t@SUM(A1:A2)'), "'\t@SUM(A1:A2)");
assert.equal(csvCell('\uFEFF+cmd'), "'\uFEFF+cmd");
assert.equal(csvCell('-2+cmd'), "'-2+cmd");
});
test('CSV cells preserve numeric negatives and quote/escape delimiters', () => {
void test('CSV cells preserve numeric negatives and quote/escape delimiters', () => {
assert.equal(csvCell('-5000.00'), '-5000.00');
assert.equal(csvCellWithDelimiter('Planeado; realizado', ';'), '"Planeado; realizado"');
assert.equal(
csvCellWithDelimiter('Planeado; realizado', ';'),
'"Planeado; realizado"',
);
assert.equal(csvCell('Operação, mensal'), '"Operação, mensal"');
assert.equal(csvCell('=HYPERLINK("x")'), '"\'=HYPERLINK(""x"")"');
});
+15 -15
View File
@@ -17,7 +17,7 @@ function cents(value) {
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
}
test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
void test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
const data = {
budgetPeriod: 'Mensal',
loan: {
@@ -59,7 +59,7 @@ test('financial tools snapshot persists editable calculations and rejects malfor
);
});
test('loan payment handles zero interest exactly', () => {
void test('loan payment handles zero interest exactly', () => {
assert.deepEqual(calculateLoanPayment('1200.00', '0', 12), {
monthlyPayment: '100.00',
totalPaid: '1200.00',
@@ -67,7 +67,7 @@ test('loan payment handles zero interest exactly', () => {
});
});
test('loan payment computes a reproducible amortized estimate', () => {
void test('loan payment computes a reproducible amortized estimate', () => {
assert.deepEqual(calculateLoanPayment('1000.00', '12', 12), {
monthlyPayment: '88.85',
totalPaid: '1066.19',
@@ -75,7 +75,7 @@ test('loan payment computes a reproducible amortized estimate', () => {
});
});
test('break-even rounds required units upward and rejects nonpositive margin', () => {
void test('break-even rounds required units upward and rejects nonpositive margin', () => {
assert.deepEqual(calculateBreakEven('100.00', '30.00', '20.00'), {
contributionPerUnit: '10.00',
breakEvenUnits: '10',
@@ -85,7 +85,7 @@ test('break-even rounds required units upward and rejects nonpositive margin', (
assert.throws(() => calculateBreakEven('10', '20', '20'), /superior/);
});
test('an invalid indicator does not hide independent financial calculations', () => {
void test('an invalid indicator does not hide independent financial calculations', () => {
const result = calculateFinancialTools({
loan: {
principal: '1200',
@@ -110,7 +110,7 @@ test('an invalid indicator does not hide independent financial calculations', ()
assert.equal(result.budget.value?.operatingBalance, '-100.00');
});
test('funding gap distinguishes zero from a negative surplus', () => {
void test('funding gap distinguishes zero from a negative surplus', () => {
assert.deepEqual(calculateFundingGap('100.00', '120.00'), {
gap: '-20.00',
reconciles: false,
@@ -118,12 +118,12 @@ test('funding gap distinguishes zero from a negative surplus', () => {
});
});
test('invalid precision and negative inputs are rejected', () => {
void test('invalid precision and negative inputs are rejected', () => {
assert.throws(() => calculateFundingGap('-1', '0'), /decimal/);
assert.throws(() => calculateLoanPayment('1.001', '0', 1), /casas/);
});
test('loan schedule supports nominal rates, interest-only grace and separate fees', () => {
void test('loan schedule supports nominal rates, interest-only grace and separate fees', () => {
const result = buildLoanSchedule({
principal: '1200.00',
annualRatePercent: '12',
@@ -159,7 +159,7 @@ test('loan schedule supports nominal rates, interest-only grace and separate fee
}
});
test('loan schedule reconciles exact cents and adjusts the final installment', () => {
void test('loan schedule reconciles exact cents and adjusts the final installment', () => {
const result = buildLoanSchedule({
principal: '1000.01',
annualRatePercent: '7.123456',
@@ -181,7 +181,7 @@ test('loan schedule reconciles exact cents and adjusts the final installment', (
);
});
test('effective annual rate is converted to the selected repayment period', () => {
void test('effective annual rate is converted to the selected repayment period', () => {
const result = buildLoanSchedule({
principal: '1000',
annualRatePercent: '12',
@@ -203,7 +203,7 @@ test('effective annual rate is converted to the selected repayment period', () =
assert.equal(quarterly.schedule.at(-1).closingBalance, '0.00');
});
test('loan schedules reconcile across rates, periodicities and grace periods', () => {
void test('loan schedules reconcile across rates, periodicities and grace periods', () => {
for (const periodMonths of [1, 2, 3, 4, 6, 12]) {
for (const rateType of ['nominal', 'effective']) {
for (const annualRatePercent of ['0', '8.500000', '24']) {
@@ -254,7 +254,7 @@ test('loan schedules reconcile across rates, periodicities and grace periods', (
}
});
test('budget preserves an operating deficit and rejects invalid values', () => {
void test('budget preserves an operating deficit and rejects invalid values', () => {
assert.deepEqual(calculateBudget(['100.00', '25.50'], ['140.00']), {
incomeTotal: '125.50',
expenseTotal: '140.00',
@@ -264,7 +264,7 @@ test('budget preserves an operating deficit and rejects invalid values', () => {
assert.throws(() => calculateBudget(['0'], ['-1']), /não negativo/);
});
test('budget distinguishes absent income or expense rows from explicit zero', () => {
void test('budget distinguishes absent income or expense rows from explicit zero', () => {
assert.throws(() => calculateBudget([], ['0']), /pelo menos uma linha/);
assert.throws(() => calculateBudget(['0'], []), /pelo menos uma linha/);
assert.deepEqual(calculateBudget(['0'], ['0']), {
@@ -275,7 +275,7 @@ test('budget distinguishes absent income or expense rows from explicit zero', ()
});
});
test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
void test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
const base = {
principal: '1000',
annualRatePercent: '0',
@@ -297,7 +297,7 @@ test('loan terms reject invalid periodicity, excessive grace and commission larg
);
});
test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
void test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
const csv = exportFinancialToolsCsv({
currency: 'MZN',
generatedAt: '2026-10-02T10:00:00.000Z',
@@ -36,7 +36,7 @@ const plan = {
periods: 2,
};
test('financial to fiscal bridge reconciles accounting result while leaving tax base indeterminate', () => {
void test('financial to fiscal bridge reconciles accounting result while leaving tax base indeterminate', () => {
const forecast = forecastBusinessPlan(plan);
const bridge = buildFinancialFiscalBridge(forecast);
const byCode = Object.fromEntries(
@@ -90,7 +90,7 @@ test('financial to fiscal bridge reconciles accounting result while leaving tax
);
});
test('financial bridge separates opening receivables and scheduled sales collections', () => {
void test('financial bridge separates opening receivables and scheduled sales collections', () => {
const forecast = forecastBusinessPlan({
...plan,
receivables: '200.00',
@@ -127,7 +127,7 @@ test('financial bridge separates opening receivables and scheduled sales collect
assert.equal(bridge.taxableBase.status, 'indeterminate');
});
test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
void test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
const forecast = forecastBusinessPlan({
...plan,
periods: 2,
@@ -156,7 +156,7 @@ test('bridge maps monthly recognised expenses but keeps scheduled payments in ca
assert.equal(bridge.taxableBase.status, 'indeterminate');
});
test('financial bridge rejects a corrupted monthly cash schedule', () => {
void test('financial bridge rejects a corrupted monthly cash schedule', () => {
const forecast = forecastBusinessPlan(plan);
const corrupted = {
...forecast,
+155
View File
@@ -0,0 +1,155 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
guidanceFinance,
guidanceFinancialTools,
} from '../../resources/js/lib/investor-guidance-finance.ts';
import { buildProjectDossierRows } from '../../resources/js/lib/project-dossier.ts';
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
import {
forecastBusinessPlan,
serializeBusinessPlanSnapshot,
compareBusinessScenarios,
} from '../../resources/js/lib/business-financial-plan.ts';
const assumptions = {
currency: 'MZN',
openingCash: '0',
products: [
{
label: 'Serviço',
monthlyUnits: '100',
unitPrice: '1000',
unitVariableCost: '400',
},
],
monthlyCollections: '90000',
salesCollectionLagMonths: null,
salesCollectionPercent: '100',
salesRecoverySchedule: [],
monthlyVariableCostPayments: '42000',
monthlyVariableCostPaymentsByPeriod: null,
monthlyInventoryPurchases: '40000',
inventoryPurchaseLeadMonths: 0,
inventoryPurchaseSchedule: null,
useInventoryPurchaseSchedule: false,
useProductInventorySchedule: false,
useSupplierPaymentTerms: false,
monthlyOperatingExpenses: '20000',
monthlyOperatingPayments: '18000',
monthlyPayrollExpense: '15000',
monthlyPayrollPayments: '15000',
assetInvestment: '100000',
inventory: '20000',
receivables: '10000',
openingReceivablesCollectionMonth: null,
openingReceivablesCollectionPercent: '100',
openingReceivablesInstallments: [],
openingPayablesInstallments: [],
payables: '5000',
equity: '80000',
shareholderLoans: '0',
bankLoanProceeds: '50000',
grants: '0',
assetDepreciation: '100000',
depreciationLifeMonths: 60,
monthlyInterestExpense: '1200',
monthlyInterestPayment: '1000',
monthlyPrincipalRepayment: '5000',
periods: 12,
};
void test('guidance reuses the dossier calculator report and preserves partial indeterminacy', () => {
const source = {
budgetPeriod: 'Mensal',
loan: {
principal: '',
rate: '',
months: '',
rateType: 'nominal',
periodMonths: '',
gracePeriods: '',
upfrontFee: '',
recurringFee: '',
},
breakEven: { fixed: '', price: '', variable: '' },
funding: { total: '1000', secured: '400' },
incomes: [{ label: 'Receita QA', amount: '300' }],
expenses: [{ label: 'Custo QA', amount: '200' }],
};
const draft = {
financial_tools_snapshot: serializeFinancialToolsSnapshot(source),
currency: 'MZN',
};
const result = guidanceFinancialTools(draft);
assert.deepEqual(
result.rows,
buildProjectDossierRows(draft).filter(
(row) => row[0] === 'Plano financeiro',
),
);
assert.deepEqual(result.assumptions, source);
assert.equal(
guidanceFinancialTools({ financial_tools_snapshot: '{"version":999}' }),
null,
);
assert.equal(guidanceFinancialTools(null), null);
});
void test('guidance keeps missing, malformed and unsupported financial snapshots indeterminate', () => {
for (const snapshot of [
undefined,
'',
'{}',
'{invalid',
'{"version":999,"plan":{}}',
]) {
const view = guidanceFinance(
snapshot ? { business_plan_snapshot: snapshot } : null,
);
assert.equal(view.status, 'indeterminate');
assert.equal(view.result, null);
}
});
void test('guidance uses exact deterministic outputs and preserves negative cash and original assumptions', () => {
const plan = { ...assumptions, monthlyCollections: '0' };
const snapshot = serializeBusinessPlanSnapshot(plan);
const view = guidanceFinance({ business_plan_snapshot: snapshot });
assert.equal(view.status, 'calculated');
assert.deepEqual(view.result, forecastBusinessPlan(view.assumptions));
assert.equal(view.result.endingCash.startsWith('-'), true);
assert.equal(view.tax, 'indeterminate');
assert.equal(view.scenarios, null);
assert.equal(snapshot, serializeBusinessPlanSnapshot(plan));
});
void test('guidance scenarios are the existing deterministic scenario tool without success probabilities', () => {
const scenario = {
...assumptions,
scenarioAdjustments: {
favorable: {
unitVolumePercent: '10',
unitPricePercent: '5',
unitCostPercent: '0',
operatingCostsPercent: '0',
cashCollectionsPercent: '10',
},
unfavorable: {
unitVolumePercent: '-10',
unitPricePercent: '-5',
unitCostPercent: '10',
operatingCostsPercent: '10',
cashCollectionsPercent: '-10',
},
},
};
const view = guidanceFinance({
business_plan_snapshot: serializeBusinessPlanSnapshot(scenario),
});
assert.deepEqual(
view.scenarios,
compareBusinessScenarios(view.assumptions),
);
assert.equal('success_probability' in view, false);
});
+11 -11
View File
@@ -5,7 +5,7 @@ import {
projectMonthlyCashflow,
} from '../../resources/js/lib/monthly-cashflow.ts';
test('projects exact monthly balances and reconciles cumulative net flow', () => {
void test('projects exact monthly balances and reconciles cumulative net flow', () => {
const result = projectMonthlyCashflow({
openingCash: '100.00',
monthlyRevenue: '200.00',
@@ -19,7 +19,7 @@ test('projects exact monthly balances and reconciles cumulative net flow', () =>
assert.equal(result.firstDeficitMonth, null);
});
test('flags the first projected deficit without changing input values', () => {
void test('flags the first projected deficit without changing input values', () => {
const result = projectMonthlyCashflow({
openingCash: '0',
monthlyRevenue: '50',
@@ -32,7 +32,7 @@ test('flags the first projected deficit without changing input values', () => {
assert.equal(result.endingCash, '-100.00');
});
test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
void test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
const base = {
openingCash: '0',
monthlyRevenue: '100',
@@ -71,7 +71,7 @@ test('keeps VAT credit stages out of cash and includes only an explicitly foreca
);
});
test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
void test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
const result = projectMonthlyCashflow({
openingCash: '100',
monthlyRevenue: '200',
@@ -101,7 +101,7 @@ test('unknown assessed tax keeps the cash projection incomplete instead of assum
assert.equal(declaredZero.endingCash, '180.00');
});
test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
void test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
const result = projectMonthlyCashflow({
openingCash: '100',
monthlyRevenue: '200',
@@ -118,7 +118,7 @@ test('monthly tax calendar applies varying user assumptions and reconciles each
assert.equal(result.endingCash, '360.00');
});
test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
void test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
const result = projectMonthlyCashflow({
openingCash: '100',
monthlyRevenue: '200',
@@ -142,7 +142,7 @@ test('a missing month remains indeterminate while known months and tax amounts r
assert.equal(result.endingCashBeforeUnassessedTax, '510.00');
});
test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
void test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
const base = {
openingCash: '0',
monthlyRevenue: '100',
@@ -165,7 +165,7 @@ test('monthly tax schedule requires one entry per month and cannot conflict with
);
});
test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
void test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
assert.equal(
projectMonthlyCashflow({
openingCash: '-1.00',
@@ -200,7 +200,7 @@ test('allows an opening cash deficit and rejects excess-precision or invalid hor
);
});
test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
void test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
const csv = exportMonthlyCashflowCsv(
{
openingCash: '10.00',
@@ -233,7 +233,7 @@ test('CSV export includes assumptions, monthly totals and an explicit scope note
assert.match(csv, /^\uFEFF/);
});
test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
void test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
const csv = exportMonthlyCashflowCsv(
{
openingCash: '0',
@@ -259,7 +259,7 @@ test('CSV export records each monthly tax assumption and unknown month explicitl
assert.match(csv, /Pressuposto mensal de imposto,Mês 3,0/);
});
test('cash flow CSV neutralizes formula-like assumption text', () => {
void test('cash flow CSV neutralizes formula-like assumption text', () => {
const csv = exportMonthlyCashflowCsv({
openingCash: '10.00',
monthlyRevenue: '20.00',
+83
View File
@@ -0,0 +1,83 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
portalNavigation,
currentNavigationGroup,
currentNavigationItem,
} from '../../resources/js/lib/portal-navigation.ts';
void test('public and authenticated navigation share groups without revealing management', () => {
const publicGroups = portalNavigation({
authenticated: false,
manager: false,
});
const investor = portalNavigation({ authenticated: true, manager: false });
assert.deepEqual(publicGroups.slice(0, 3), investor.slice(0, 3));
assert.deepEqual(
publicGroups.map((g) => g.id),
['explore', 'prepare', 'support', 'partnerships', 'account'],
);
const hrefs = JSON.stringify(investor);
assert.equal(hrefs.includes('/management/'), false);
assert.equal(JSON.stringify(publicGroups).includes('/login'), true);
assert.equal(hrefs.includes('/investidor/profile'), true);
assert.equal(hrefs.includes('/balcao-virtual'), true);
});
void test('management and optional modules follow permissions and feature flags', () => {
const groups = portalNavigation({
authenticated: true,
manager: true,
businesses: true,
education: true,
ai: true,
});
assert.equal(groups.at(-1).id, 'management');
assert.equal(JSON.stringify(groups).includes('/investidor/negocios'), true);
assert.equal(JSON.stringify(groups).includes('/management/ai'), true);
assert.equal(
JSON.stringify(
portalNavigation({
authenticated: false,
manager: false,
education: false,
}),
).includes('/educacao'),
false,
);
});
void test('detail URLs and filtered catalogue pages retain the current group', () => {
const groups = portalNavigation({ authenticated: true, manager: true });
for (const url of [
'/carteira/project/fixture',
'/zonas?category=zee',
'/zonas/fixture',
'/oportunidades/fixture',
])
assert.equal(currentNavigationGroup(groups, url), 'explore');
assert.equal(
currentNavigationGroup(
groups,
'/balcao-virtual/dossiers/fixture?phase=market',
),
'support',
);
assert.equal(
currentNavigationGroup(groups, '/investidor/profile'),
'account',
);
assert.equal(
currentNavigationGroup(groups, '/management/crm/leads/fixture'),
'management',
);
assert.equal(currentNavigationGroup(groups, '/unknown'), null);
assert.equal(
currentNavigationItem(groups, '/carteira?q=QA&kind=project'),
'projects',
);
assert.equal(
currentNavigationItem(groups, '/zonas?category=zee&q=QA'),
'zee',
);
});
+217 -55
View File
@@ -10,75 +10,190 @@ import {
classifyDossierAttachment,
validateDossierAttachments,
} from '../../resources/js/lib/project-dossier-report.ts';
import { serializeBusinessPlanSnapshot, forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
import {
serializeBusinessPlanSnapshot,
forecastBusinessPlan,
} from '../../resources/js/lib/business-financial-plan.ts';
const allSections = new Set(dossierReportSections.map((section) => section.id));
function simplePlan() {
return {
currency: 'MZN', openingCash: '0', products: [{ label: 'Pão', monthlyUnits: '100', unitPrice: '50', unitVariableCost: '20' }],
monthlyCollections: '100', monthlyVariableCostPayments: '100', monthlyOperatingExpenses: '500', monthlyOperatingPayments: '500',
monthlyPayrollExpense: '0', monthlyPayrollPayments: '0', assetInvestment: '0', inventory: '0', receivables: '0', payables: '0',
equity: '10000', shareholderLoans: '0', bankLoanProceeds: '0', grants: '0', assetDepreciation: '0', depreciationLifeMonths: 12,
monthlyInterestExpense: '0', monthlyInterestPayment: '0', monthlyPrincipalRepayment: '0', periods: 12,
currency: 'MZN',
openingCash: '0',
products: [
{
label: 'Pão',
monthlyUnits: '100',
unitPrice: '50',
unitVariableCost: '20',
},
],
monthlyCollections: '100',
monthlyVariableCostPayments: '100',
monthlyOperatingExpenses: '500',
monthlyOperatingPayments: '500',
monthlyPayrollExpense: '0',
monthlyPayrollPayments: '0',
assetInvestment: '0',
inventory: '0',
receivables: '0',
payables: '0',
equity: '10000',
shareholderLoans: '0',
bankLoanProceeds: '0',
grants: '0',
assetDepreciation: '0',
depreciationLifeMonths: 12,
monthlyInterestExpense: '0',
monthlyInterestPayment: '0',
monthlyPrincipalRepayment: '0',
periods: 12,
};
}
test('incomplete dossier identifies unknowns without inventing zeroes', () => {
const report = createProjectDossierReport({}, { selectedSections: allSections, generatedAt: '2026-10-04T10:00:00.000Z' });
void test('incomplete dossier identifies unknowns without inventing zeroes', () => {
const report = createProjectDossierReport(
{},
{
selectedSections: allSections,
generatedAt: '2026-10-04T10:00:00.000Z',
},
);
assert.equal(report.title, 'Não informado');
assert.equal(report.sections.find((section) => section.id === 'summary').rows[0].value, 'Não informado');
assert.match(report.sections.find((section) => section.id === 'resources').rows[0].value, /Informação insuficiente/);
assert.equal(
report.sections.find((section) => section.id === 'summary').rows[0]
.value,
'Não informado',
);
assert.match(
report.sections.find((section) => section.id === 'resources').rows[0]
.value,
/Informação insuficiente/,
);
assert.doesNotMatch(JSON.stringify(report), /"value":"0(\.00)?"/);
});
test('report sections are selected explicitly and preserve declared versus estimated provenance', () => {
void test('report sections are selected explicitly and preserve declared versus estimated provenance', () => {
const selected = new Set(['summary', 'market', 'sources']);
const report = createProjectDossierReport({ project_title: 'Moagem', market_assumption: 'procura crescente', market_source: 'entrevista própria; 2026-09-01' }, { selectedSections: selected, version: 'Revisão 3' });
assert.deepEqual(report.sections.map((section) => section.id), ['summary', 'market', 'sources']);
const report = createProjectDossierReport(
{
project_title: 'Moagem',
market_assumption: 'procura crescente',
market_source: 'entrevista própria; 2026-09-01',
},
{ selectedSections: selected, version: 'Revisão 3' },
);
assert.deepEqual(
report.sections.map((section) => section.id),
['summary', 'market', 'sources'],
);
const market = report.sections.find((section) => section.id === 'market');
assert.ok(market.rows.some((row) => row.value === 'procura crescente' && row.classification === 'Informação declarada, não verificada'));
assert.ok(
market.rows.some(
(row) =>
row.value === 'procura crescente' &&
row.classification === 'Informação declarada, não verificada',
),
);
assert.equal(report.version, 'Revisão 3');
});
test('business plan values in the dossier equal the existing simulator forecast', () => {
void test('business plan values in the dossier equal the existing simulator forecast', () => {
const plan = simplePlan();
const expected = forecastBusinessPlan(plan);
const snapshot = serializeBusinessPlanSnapshot(plan);
const report = createProjectDossierReport({ project_title: 'Padaria', currency: 'MZN', business_plan_snapshot: snapshot }, { selectedSections: allSections });
const report = createProjectDossierReport(
{
project_title: 'Padaria',
currency: 'MZN',
business_plan_snapshot: snapshot,
},
{ selectedSections: allSections },
);
const finance = report.sections.find((section) => section.id === 'finance');
const row = (field) => finance.rows.find((item) => item.field === field).value;
assert.equal(row('Facturação no horizonte'), `${expected.totalRevenue} MZN`);
assert.equal(row('Resultado antes de impostos'), `${expected.totalProfitBeforeTax} MZN`);
const row = (field) =>
finance.rows.find((item) => item.field === field).value;
assert.equal(
row('Facturação no horizonte'),
`${expected.totalRevenue} MZN`,
);
assert.equal(
row('Resultado antes de impostos'),
`${expected.totalProfitBeforeTax} MZN`,
);
assert.equal(row('Caixa final projectada'), `${expected.endingCash} MZN`);
assert.equal(row('Reconciliação do financiamento'), expected.fundingStatus);
});
test('an attached simulator execution keeps its exact snapshot result, explanation and version', () => {
const report = createProjectDossierReport({ project_title: 'Pequena indústria' }, {
selectedSections: allSections,
currentCalculation: {
status: 'completed', version: 4, updatedAt: '2026-10-03T12:00:00Z', reportChecksum: 'a'.repeat(64),
snapshot: {
contract_version: 1, indicative_total: '1250.75',
formula_version: 'v2', base: '2000', rate_percent: '75', reduction_percent: '16.6', currency: 'MZN',
context: { reference_date: '2026-10-03', engine_version: 'engine-4', scenario_version: 4 },
result: { status: 'calculated', value: '1250.75', unit: null, explanation: 'Cálculo indicativo guardado.', missing_inputs: [], source_ids: [] },
void test('an attached simulator execution keeps its exact snapshot result, explanation and version', () => {
const report = createProjectDossierReport(
{ project_title: 'Pequena indústria' },
{
selectedSections: allSections,
currentCalculation: {
status: 'completed',
version: 4,
updatedAt: '2026-10-03T12:00:00Z',
reportChecksum: 'a'.repeat(64),
snapshot: {
contract_version: 1,
indicative_total: '1250.75',
formula_version: 'v2',
base: '2000',
rate_percent: '75',
reduction_percent: '16.6',
currency: 'MZN',
context: {
reference_date: '2026-10-03',
engine_version: 'engine-4',
scenario_version: 4,
},
result: {
status: 'calculated',
value: '1250.75',
unit: null,
explanation: 'Cálculo indicativo guardado.',
missing_inputs: [],
source_ids: [],
},
},
},
},
});
);
const finance = report.sections.find((section) => section.id === 'finance');
assert.equal(finance.rows.find((row) => row.field === 'Resultado indicativo').value, '1250.75');
assert.equal(finance.rows.find((row) => row.field === 'Explicação e dados em falta').value, 'Cálculo indicativo guardado.');
assert.equal(finance.rows.find((row) => row.field === 'Revisão do resultado').value, '4');
assert.equal(finance.rows.find((row) => row.field === 'Hash SHA-256 do relatório associado').value, 'a'.repeat(64));
assert.equal(
finance.rows.find((row) => row.field === 'Resultado indicativo').value,
'1250.75',
);
assert.equal(
finance.rows.find((row) => row.field === 'Explicação e dados em falta')
.value,
'Cálculo indicativo guardado.',
);
assert.equal(
finance.rows.find((row) => row.field === 'Revisão do resultado').value,
'4',
);
assert.equal(
finance.rows.find(
(row) => row.field === 'Hash SHA-256 do relatório associado',
).value,
'a'.repeat(64),
);
});
test('DOCX is a readable OpenXML package with Portuguese accents, tables and page fields', async () => {
const report = createProjectDossierReport({ project_title: 'Produção de café', project_summary: 'Ideia com acção e localização.' }, { selectedSections: allSections, version: 'Revisão 2' });
void test('DOCX is a readable OpenXML package with Portuguese accents, tables and page fields', async () => {
const report = createProjectDossierReport(
{
project_title: 'Produção de café',
project_summary: 'Ideia com acção e localização.',
},
{ selectedSections: allSections, version: 'Revisão 2' },
);
const blob = await generateProjectDossierDocx(report, [], true);
const bytes = new Uint8Array(await blob.arrayBuffer());
assert.deepEqual([...bytes.slice(0, 2)], [0x50, 0x4b]);
assert.deepEqual(Array.from(bytes.subarray(0, 2)), [0x50, 0x4b]);
const zip = await JSZip.loadAsync(bytes);
const documentXml = await zip.file('word/document.xml').async('string');
const footerXml = await zip.file('word/footer1.xml').async('string');
@@ -89,13 +204,23 @@ test('DOCX is a readable OpenXML package with Portuguese accents, tables and pag
assert.ok(zip.file('[Content_Types].xml'));
});
test('CSV and plain-text annexes are embedded, while other originals get a ZIP index', async () => {
const csv = new File(['Produto;Quantidade\r\nCafé;12'], 'tabela.csv', { type: 'text/csv' });
const pdf = new File(['%PDF-1.7 example'], '../apoio.pdf', { type: 'application/pdf' });
void test('CSV and plain-text annexes are embedded, while other originals get a ZIP index', async () => {
const csv = new File(['Produto;Quantidade\r\nCafé;12'], 'tabela.csv', {
type: 'text/csv',
});
const pdf = new File(['%PDF-1.7 example'], '../apoio.pdf', {
type: 'application/pdf',
});
assert.equal(classifyDossierAttachment(csv), 'csv');
assert.equal(classifyDossierAttachment(pdf), 'original-only');
const attachments = [{ file: csv, include: true, caption: '' }, { file: pdf, include: true, caption: '' }];
const report = createProjectDossierReport({ project_title: 'Projecto de café' }, { selectedSections: allSections });
const attachments = [
{ file: csv, include: true, caption: '' },
{ file: pdf, include: true, caption: '' },
];
const report = createProjectDossierReport(
{ project_title: 'Projecto de café' },
{ selectedSections: allSections },
);
const docx = await generateProjectDossierDocx(report, attachments, true);
const docxZip = await JSZip.loadAsync(await docx.arrayBuffer());
const xml = await docxZip.file('word/document.xml').async('string');
@@ -110,20 +235,44 @@ test('CSV and plain-text annexes are embedded, while other originals get a ZIP i
assert.match(index, /Conteúdo não incorporado; original preservado/);
});
test('PNG photographs are embedded in the Word package with an image relationship and caption', async () => {
const pngBytes = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/aZkAAAAASUVORK5CYII=', 'base64');
void test('PNG photographs are embedded in the Word package with an image relationship and caption', async () => {
const pngBytes = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/aZkAAAAASUVORK5CYII=',
'base64',
);
const photo = new File([pngBytes], 'local.jpg', { type: 'image/png' });
const report = createProjectDossierReport({ project_title: 'Projecto com fotografia' }, { selectedSections: allSections });
const docx = await generateProjectDossierDocx(report, [{ file: photo, include: true, caption: 'Localização declarada' }], true);
const report = createProjectDossierReport(
{ project_title: 'Projecto com fotografia' },
{ selectedSections: allSections },
);
const docx = await generateProjectDossierDocx(
report,
[{ file: photo, include: true, caption: 'Localização declarada' }],
true,
);
const zip = await JSZip.loadAsync(await docx.arrayBuffer());
const mediaPath = Object.keys(zip.files).find((path) => /^word\/media\/.+\.png$/.test(path));
const mediaPath = Object.keys(zip.files).find((path) =>
/^word\/media\/.+\.png$/.test(path),
);
assert.ok(mediaPath);
assert.match(await zip.file('word/document.xml').async('string'), /Localização declarada/);
assert.match(await zip.file('word/_rels/document.xml.rels').async('string'), new RegExp(`Target="media/${mediaPath.split('/').at(-1)}"`));
assert.match(
await zip.file('word/document.xml').async('string'),
/Localização declarada/,
);
assert.match(
await zip.file('word/_rels/document.xml.rels').async('string'),
new RegExp(`Target="media/${mediaPath.split('/').at(-1)}"`),
);
});
test('print/PDF HTML escapes user content and explains omitted annexes', async () => {
const report = createProjectDossierReport({ project_title: '<script>alert(1)</script>', project_summary: 'Acentuação: localização.' }, { selectedSections: new Set(['summary', 'annexes']) });
void test('print/PDF HTML escapes user content and explains omitted annexes', async () => {
const report = createProjectDossierReport(
{
project_title: '<script>alert(1)</script>',
project_summary: 'Acentuação: localização.',
},
{ selectedSections: new Set(['summary', 'annexes']) },
);
const pdf = await createProjectDossierPrintHtml(report, [], false);
assert.doesNotMatch(pdf, /<script>alert\(1\)<\/script>/);
assert.match(pdf, /&lt;script&gt;/);
@@ -131,9 +280,22 @@ test('print/PDF HTML escapes user content and explains omitted annexes', async (
assert.match(pdf, /@page\{size:A4/);
});
test('attachment limits block oversized or excessive selections', () => {
void test('attachment limits block oversized or excessive selections', () => {
assert.equal(validateDossierAttachments([{ size: 1 }]), null);
assert.match(validateDossierAttachments(Array.from({ length: 11 }, () => ({ size: 1 }))), /máximo 10/);
assert.match(validateDossierAttachments([{ size: 15 * 1024 * 1024 + 1 }]), /15 MB/);
assert.match(validateDossierAttachments(Array.from({ length: 4 }, () => ({ size: 15 * 1024 * 1024 }))), /50 MB/);
assert.match(
validateDossierAttachments(
Array.from({ length: 11 }, () => ({ size: 1 })),
),
/máximo 10/,
);
assert.match(
validateDossierAttachments([{ size: 15 * 1024 * 1024 + 1 }]),
/15 MB/,
);
assert.match(
validateDossierAttachments(
Array.from({ length: 4 }, () => ({ size: 15 * 1024 * 1024 })),
),
/50 MB/,
);
});
+44 -7
View File
@@ -1,15 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readRows, exportProjectDossierCsv } from '../../resources/js/lib/project-dossier.ts';
import {
readRows,
exportProjectDossierCsv,
} from '../../resources/js/lib/project-dossier.ts';
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
test('structured planner tolerates incomplete or malformed snapshots', () => {
void test('structured planner tolerates incomplete or malformed snapshots', () => {
assert.deepEqual(readRows('not-json', ['name']), []);
assert.deepEqual(readRows('{"x":1}', ['name']), []);
});
test('project export labels user market claims and insufficient finance evidence', () => {
const csv = exportProjectDossierCsv({ market_assumption: 'procura alta', market_source: '', project_title: '=1+1', project_team_snapshot: JSON.stringify([{ competency: 'Gestão', state: 'gap', action: 'Formação', estimated_cost: '20', due_date: '' }]), project_execution_snapshot: JSON.stringify([{ title: 'Abrir', due_date: '', status: 'planned', planned_amount: '10', actual_amount: '' }]) });
void test('project export labels user market claims and insufficient finance evidence', () => {
const csv = exportProjectDossierCsv({
market_assumption: 'procura alta',
market_source: '',
project_title: '=1+1',
project_team_snapshot: JSON.stringify([
{
competency: 'Gestão',
state: 'gap',
action: 'Formação',
estimated_cost: '20',
due_date: '',
},
]),
project_execution_snapshot: JSON.stringify([
{
title: 'Abrir',
due_date: '',
status: 'planned',
planned_amount: '10',
actual_amount: '',
},
]),
});
assert.match(csv, /Informação declarada, não verificada/);
assert.match(csv, /Informação insuficiente/);
assert.match(csv, /'=1\+1/);
@@ -18,16 +43,28 @@ test('project export labels user market claims and insufficient finance evidence
assert.match(csv, /Marco 1/);
});
test('project dossier exports readable financial assumptions and verified calculator outputs', () => {
void test('project dossier exports readable financial assumptions and verified calculator outputs', () => {
const financial_tools_snapshot = serializeFinancialToolsSnapshot({
budgetPeriod: 'Mensal',
loan: { principal: '100000', rate: '18', months: '24', rateType: 'nominal', periodMonths: '1', gracePeriods: '0', upfrontFee: '0', recurringFee: '0' },
loan: {
principal: '100000',
rate: '18',
months: '24',
rateType: 'nominal',
periodMonths: '1',
gracePeriods: '0',
upfrontFee: '0',
recurringFee: '0',
},
breakEven: { fixed: '50000', price: '1000', variable: '600' },
funding: { total: '1000000', secured: '250000' },
incomes: [{ label: 'Vendas', amount: '200000' }],
expenses: [{ label: 'Operação', amount: '150000' }],
});
const csv = exportProjectDossierCsv({ financial_tools_snapshot, currency: 'MZN' });
const csv = exportProjectDossierCsv({
financial_tools_snapshot,
currency: 'MZN',
});
assert.match(csv, /Unidades estimadas;125;/);
assert.match(csv, /Diferença por financiar;750000\.00 MZN;/);
assert.match(csv, /Saldo operacional estimado;50000\.00 MZN;/);
+108 -31
View File
@@ -1,45 +1,122 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getProjectReadiness, readPlannedRiskResponses, serializePlannedRiskResponses } from '../../resources/js/lib/project-readiness.ts';
import {
getProjectReadiness,
readPlannedRiskResponses,
serializePlannedRiskResponses,
} from '../../resources/js/lib/project-readiness.ts';
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
test('idea journey reuses one dossier and exposes the six requested stages', () => {
const sections = getSimulationSections({ purpose: 'simulate_only', journey_type: 'small_business' });
assert.deepEqual(sections.map((section) => section.title), [
'Ideia e objectivos', 'Clientes e mercado', 'Localização e recursos',
'Equipa e execução', 'Investimento e financiamento', 'Resultados, riscos e plano',
]);
});
test('missing customer details remain visible even if the answer says yes', () => {
const items = getProjectReadiness({ purpose: 'simulate_only', journey_type: 'small_business', customer_validation_status: 'yes' });
assert.ok(items.some((item) => item.id === 'customers' && item.kind === 'missing'));
assert.ok(items.every((item) => !('probability' in item) && !('severity' in item)));
});
test('not applicable suppresses only the matching readiness prompts', () => {
const items = getProjectReadiness({
target_customers: '', customer_validation_status: 'not_applicable',
cost_estimate_status: 'not_applicable', location_assessment_status: 'not_applicable',
funding_status: 'not_applicable', project_team_snapshot: '[]',
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
const sections = getSimulationSections({
purpose: 'simulate_only',
journey_type: 'small_business',
});
assert.equal(items.some((item) => ['customers', 'costs', 'location', 'funding'].includes(item.id)), false);
assert.deepEqual(
sections.map((section) => section.title),
[
'Ideia e objectivos',
'Clientes e mercado',
'Localização e recursos',
'Equipa e execução',
'Investimento e financiamento',
'Resultados, riscos e plano',
],
);
});
test('planned responses round-trip and invalid data is ignored', () => {
const source = [{ risk_id: 'customers', action: 'Falar com clientes', owner: 'Equipa', estimated_cost: '20', due_date: '2026-11-10' }];
assert.deepEqual(readPlannedRiskResponses({ project_risk_responses_snapshot: serializePlannedRiskResponses(source) }), source);
assert.deepEqual(readPlannedRiskResponses({ project_risk_responses_snapshot: 'invalid' }), []);
void test('missing customer details remain visible even if the answer says yes', () => {
const items = getProjectReadiness({
purpose: 'simulate_only',
journey_type: 'small_business',
customer_validation_status: 'yes',
});
assert.ok(
items.some(
(item) => item.id === 'customers' && item.kind === 'missing',
),
);
assert.ok(
items.every(
(item) => !('probability' in item) && !('severity' in item),
),
);
});
test('dossier report includes generated gaps and user response plans without inventing summary data', () => {
const draft = { project_title: 'Projecto de teste', project_questionnaire_version: 'investmoz-project-dossier-2026-10-05.1', project_risk_responses_snapshot: JSON.stringify([{ risk_id: 'customers', action: 'Fazer entrevistas', owner: 'Equipa', estimated_cost: '', due_date: '' }]) };
const report = createProjectDossierReport(draft, { selectedSections: new Set(['summary', 'risk']), version: '1' });
void test('not applicable suppresses only the matching readiness prompts', () => {
const items = getProjectReadiness({
target_customers: '',
customer_validation_status: 'not_applicable',
cost_estimate_status: 'not_applicable',
location_assessment_status: 'not_applicable',
funding_status: 'not_applicable',
project_team_snapshot: '[]',
});
assert.equal(
items.some((item) =>
['customers', 'costs', 'location', 'funding'].includes(item.id),
),
false,
);
});
void test('planned responses round-trip and invalid data is ignored', () => {
const source = [
{
risk_id: 'customers',
action: 'Falar com clientes',
owner: 'Equipa',
estimated_cost: '20',
due_date: '2026-11-10',
},
];
assert.deepEqual(
readPlannedRiskResponses({
project_risk_responses_snapshot:
serializePlannedRiskResponses(source),
}),
source,
);
assert.deepEqual(
readPlannedRiskResponses({
project_risk_responses_snapshot: 'invalid',
}),
[],
);
});
void test('dossier report includes generated gaps and user response plans without inventing summary data', () => {
const draft = {
project_title: 'Projecto de teste',
project_questionnaire_version: 'investmoz-project-dossier-2026-10-05.1',
project_risk_responses_snapshot: JSON.stringify([
{
risk_id: 'customers',
action: 'Fazer entrevistas',
owner: 'Equipa',
estimated_cost: '',
due_date: '',
},
]),
};
const report = createProjectDossierReport(draft, {
selectedSections: new Set(['summary', 'risk']),
version: '1',
});
const summary = report.sections.find((section) => section.id === 'summary');
const risk = report.sections.find((section) => section.id === 'risk');
assert.match(summary.paragraphs.join(' '), /Projecto de teste/);
assert.match(risk.rows.map((row) => `${row.field}: ${row.value}`).join(' '), /Clientes ainda pouco definidos/);
assert.match(risk.rows.map((row) => row.value).join(' '), /Fazer entrevistas/);
assert.match(risk.rows.map((row) => row.value).join(' '), /Resposta planeada/);
assert.match(
risk.rows.map((row) => `${row.field}: ${row.value}`).join(' '),
/Clientes ainda pouco definidos/,
);
assert.match(
risk.rows.map((row) => row.value).join(' '),
/Fazer entrevistas/,
);
assert.match(
risk.rows.map((row) => row.value).join(' '),
/Resposta planeada/,
);
});
+4 -4
View File
@@ -7,7 +7,7 @@ import {
simulationCatalogChoices,
} from '../../resources/js/lib/simulation-api.ts';
test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
void test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
assert.equal(
await readSimulationApiJson(
new Response('<html>gateway error</html>', {
@@ -28,7 +28,7 @@ test('malformed and non-JSON API bodies do not leak parser exceptions', async ()
);
});
test('API error messages prefer validated field details and reject malformed shapes', () => {
void test('API error messages prefer validated field details and reject malformed shapes', () => {
assert.equal(
simulationApiErrorMessage({
message: 'Validation failed',
@@ -47,7 +47,7 @@ test('API error messages prefer validated field details and reject malformed sha
assert.equal(simulationApiErrorMessage('<html>error</html>'), undefined);
});
test('polling failures explain that an accepted calculation may still be pending', () => {
void test('polling failures explain that an accepted calculation may still be pending', () => {
assert.equal(
simulationPollingFailureMessage(null),
'O cenário foi recebido, mas não foi possível confirmar o estado do cálculo. Consulte o histórico antes de tentar novamente.',
@@ -58,7 +58,7 @@ test('polling failures explain that an accepted calculation may still be pending
);
});
test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
void test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
assert.deepEqual(simulationCatalogChoices({ data: [] }), []);
assert.deepEqual(
simulationCatalogChoices({
+11 -11
View File
@@ -86,7 +86,7 @@ const apiJob = {
error_code: null,
};
test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
void test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
const openapi = JSON.parse(
await readFile(
new URL(
@@ -184,7 +184,7 @@ test('OpenAPI matches decimal-string inputs and execution response guards', asyn
}
});
test('currency codes are explicit and must be present in the supported currency catalog', () => {
void test('currency codes are explicit and must be present in the supported currency catalog', () => {
assert.equal(isSimulationCurrency('MZN'), true);
assert.equal(isSimulationCurrency('USD'), true);
assert.equal(isSimulationCurrency('mzn'), false);
@@ -195,7 +195,7 @@ test('currency codes are explicit and must be present in the supported currency
assert.equal(simulationCurrencyOptions.includes('KWD'), false);
});
test('calculated values preserve exact decimal strings, including zero', () => {
void test('calculated values preserve exact decimal strings, including zero', () => {
assert.deepEqual(
validateSimulationResult({
status: 'calculated',
@@ -209,7 +209,7 @@ test('calculated values preserve exact decimal strings, including zero', () => {
);
});
test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
void test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
assert.equal(isApiSimulationResultSnapshotV1(apiSnapshot), true);
assert.equal(
isApiSimulationResultSnapshotV1({
@@ -265,7 +265,7 @@ test('API v1 wire envelope preserves exact zero and validates indeterminate stat
);
});
test('simulation creation and polling responses require a valid execution view', () => {
void test('simulation creation and polling responses require a valid execution view', () => {
const queuedExecution = { ...apiExecution };
delete queuedExecution.result_snapshot;
assert.equal(
@@ -355,7 +355,7 @@ test('simulation creation and polling responses require a valid execution view',
);
});
test('history and encrypted-draft endpoints reject malformed envelopes', () => {
void test('history and encrypted-draft endpoints reject malformed envelopes', () => {
assert.equal(isApiSimulationHistoryResponseV1(apiHistory), true);
assert.equal(
isApiSimulationHistoryResponseV1({
@@ -405,7 +405,7 @@ test('history and encrypted-draft endpoints reject malformed envelopes', () => {
);
});
test('questionnaire, report, job and error envelopes match their server contracts', () => {
void test('questionnaire, report, job and error envelopes match their server contracts', () => {
assert.equal(
isApiQuestionnaireReadResponseV1({
data: {
@@ -510,7 +510,7 @@ test('questionnaire, report, job and error envelopes match their server contract
assert.equal(isApiErrorV1({ errors: { base: 'Invalid' } }), false);
});
test('wire contract guards survive a real JSON encode/decode round trip', () => {
void test('wire contract guards survive a real JSON encode/decode round trip', () => {
const wirePayloads = [
[isApiSimulationReadResponseV1, { data: apiExecution }],
[
@@ -540,7 +540,7 @@ test('wire contract guards survive a real JSON encode/decode round trip', () =>
}
});
test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
void test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
assert.deepEqual(
validateSimulationResult({
status: 'indeterminate',
@@ -565,7 +565,7 @@ test('indeterminate results require missing inputs and cannot carry a numeric va
);
});
test('estimated and not-applicable states must be explicit', () => {
void test('estimated and not-applicable states must be explicit', () => {
assert.deepEqual(
validateSimulationResult({
status: 'estimated',
@@ -601,7 +601,7 @@ test('estimated and not-applicable states must be explicit', () => {
);
});
test('every tax component remains indeterminate until an approved effective rule exists', () => {
void test('every tax component remains indeterminate until an approved effective rule exists', () => {
assert.deepEqual(fiscalComponentCodes, [
'IRPS',
'INSS',
@@ -12,7 +12,7 @@ const openapi = JSON.parse(
),
);
test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
void test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
const operation =
openapi.paths['/simulation-drafts/{id}/conversions']?.post;
assert.ok(operation);
+88 -56
View File
@@ -19,7 +19,7 @@ import {
getFiscalPeriodRange,
} from '../../resources/js/lib/simulation-form.ts';
test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
void test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
assert.deepEqual(
getFiscalPeriodRange({
fiscal_period: '2024',
@@ -68,7 +68,7 @@ test('fiscal period range requires and respects exact annual, monthly, quarterly
);
});
test('searchable choice keyboard navigation starts at the first result and stays in bounds', () => {
void test('searchable choice keyboard navigation starts at the first result and stays in bounds', () => {
assert.equal(moveSearchChoiceIndex(-1, 1, 3), 0);
assert.equal(moveSearchChoiceIndex(-1, -1, 3), 2);
assert.equal(moveSearchChoiceIndex(0, -1, 3), 0);
@@ -77,7 +77,7 @@ test('searchable choice keyboard navigation starts at the first result and stays
assert.equal(moveSearchChoiceIndex(0, -1, -1), -1);
});
test('anonymous arithmetic journey skips formal investor and project sections', () => {
void test('anonymous arithmetic journey skips formal investor and project sections', () => {
assert.deepEqual(
getSimulationSections({ purpose: 'simulate_only' }).map(
(section) => section.id,
@@ -90,7 +90,7 @@ test('anonymous arithmetic journey skips formal investor and project sections',
);
});
test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
void test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
const draft = {
journey_type: 'small_business',
purpose: 'simulate_only',
@@ -98,35 +98,39 @@ test('small business exploratory draft includes idea and finance without mandato
};
assert.deepEqual(
getSimulationSections(draft).map((section) => section.id),
[
'purpose',
'market',
'location',
'team',
'financial',
'review',
],
['purpose', 'market', 'location', 'team', 'financial', 'review'],
);
assert.deepEqual(validateSimulationDraft(draft, 'market'), {});
const ideaFields = [...simulationFieldGroups.project, ...simulationFieldGroups.market].filter((field) =>
field.showWhen?.(draft),
).filter((field, index, all) => all.findIndex((candidate) => candidate.key === field.key) === index);
const ideaFields = [
...simulationFieldGroups.project,
...simulationFieldGroups.market,
]
.filter((field) => field.showWhen?.(draft))
.filter(
(field, index, all) =>
all.findIndex((candidate) => candidate.key === field.key) ===
index,
);
for (const key of [
'project_title',
'project_summary',
'project_problem',
'target_customers',
'value_proposition',
'market_assumption',
'market_source',
'project_type',
'sector_id',
'activity_id',
'products_services',
'maturity_stage',
'expected_start_date',
'project_duration_years',
]) assert.ok(ideaFields.some((field) => field.key === key), `missing ${key}`);
'project_title',
'project_summary',
'project_problem',
'target_customers',
'value_proposition',
'market_assumption',
'market_source',
'project_type',
'sector_id',
'activity_id',
'products_services',
'maturity_stage',
'expected_start_date',
'project_duration_years',
])
assert.ok(
ideaFields.some((field) => field.key === key),
`missing ${key}`,
);
assert.equal(
ideaFields.some((field) =>
typeof field.required === 'function'
@@ -145,26 +149,54 @@ test('small business exploratory draft includes idea and finance without mandato
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
});
test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
void test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
const selected = replaceSimulationValue({}, 'journey_type', 'investor');
assert.equal(selected.purpose, 'simulate_only');
const sections = getSimulationSections(selected).map((section) => section.id);
const sections = getSimulationSections(selected).map(
(section) => section.id,
);
assert.deepEqual(sections, [
'purpose', 'project', 'location', 'financial', 'tax', 'scenarios', 'procedures', 'review',
'purpose',
'project',
'location',
'financial',
'tax',
'scenarios',
'procedures',
'review',
]);
for (const sectionId of ['project', 'location', 'financial', 'tax', 'procedures']) {
for (const sectionId of [
'project',
'location',
'financial',
'tax',
'procedures',
]) {
assert.deepEqual(validateSimulationDraft(selected, sectionId), {});
}
const fieldsVisible = (group) => simulationFieldGroups[group].filter((field) => field.showWhen?.(selected) ?? true);
assert.ok(fieldsVisible('project').some((field) => field.key === 'activity_id'));
assert.ok(fieldsVisible('location').some((field) => field.key === 'infrastructure_needs'));
assert.ok(fieldsVisible('financial').some((field) => field.key === 'total_investment'));
const fieldsVisible = (group) =>
simulationFieldGroups[group].filter(
(field) => field.showWhen?.(selected) ?? true,
);
assert.ok(
fieldsVisible('project').some((field) => field.key === 'activity_id'),
);
assert.ok(
fieldsVisible('location').some(
(field) => field.key === 'infrastructure_needs',
),
);
assert.ok(
fieldsVisible('financial').some(
(field) => field.key === 'total_investment',
),
);
assert.equal(simulationFieldGroups.procedures[0].showWhen(selected), true);
assert.ok(simulationOptions.infrastructure.includes('raw_materials'));
assert.ok(simulationOptions.infrastructure.includes('legal_requirements'));
});
test('public journeys offer distinct section paths for personal, small business, company, and investor', () => {
void test('public journeys offer distinct section paths for personal, small business, company, and investor', () => {
assert.deepEqual(
getSimulationSections({
journey_type: 'personal',
@@ -214,7 +246,7 @@ test('public journeys offer distinct section paths for personal, small business,
assert.equal(advancedSimulationFields.has('deductible_costs'), true);
});
test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
void test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
assert.deepEqual(
replaceSimulationValue(
{
@@ -237,7 +269,7 @@ test('switching to anonymous mode keeps non-sensitive journey and detail choices
);
});
test('changing territorial or sector parents clears every dependent value', () => {
void test('changing territorial or sector parents clears every dependent value', () => {
assert.deepEqual(
replaceSimulationValue(
{
@@ -261,7 +293,7 @@ test('changing territorial or sector parents clears every dependent value', () =
);
});
test('changing the purpose preserves private and project answers for later correction', () => {
void test('changing the purpose preserves private and project answers for later correction', () => {
const next = replaceSimulationValue(
{
purpose: 'own_investment',
@@ -284,7 +316,7 @@ test('changing the purpose preserves private and project answers for later corre
});
});
test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
void test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
const base = {
purpose: 'simulate_only',
fiscal_period: '2026',
@@ -300,7 +332,7 @@ test('approved-parameter fiscal mode does not ask users to enter a rate', () =>
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
});
test('custom planning mode requires user assumptions and validates percentage limits', () => {
void test('custom planning mode requires user assumptions and validates percentage limits', () => {
const base = {
purpose: 'simulate_only',
fiscal_period: '2026',
@@ -339,7 +371,7 @@ test('custom planning mode requires user assumptions and validates percentage li
);
});
test('fiscal intake asks only component-specific questions and leaves residence unresolved when unknown', () => {
void test('fiscal intake asks only component-specific questions and leaves residence unresolved when unknown', () => {
assert.equal(
simulationOptions.fiscal_period.includes(
String(new Date().getFullYear() + 1),
@@ -416,7 +448,7 @@ test('fiscal intake asks only component-specific questions and leaves residence
);
});
test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
void test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
const errors = validateSimulationDraft(
{
currency: 'USD',
@@ -435,7 +467,7 @@ test('financial reconciliation reports a mismatch without inventing a fiscal val
);
});
test('autosave omits identity and contact fields from browser storage', () => {
void test('autosave omits identity and contact fields from browser storage', () => {
assert.deepEqual(
getAutosaveSnapshot({
total_investment: '50',
@@ -449,7 +481,7 @@ test('autosave omits identity and contact fields from browser storage', () => {
);
});
test('server draft snapshots split private identity from economic values', () => {
void test('server draft snapshots split private identity from economic values', () => {
assert.deepEqual(
partitionSimulationDraft({
journey_type: 'personal',
@@ -518,7 +550,7 @@ test('server draft snapshots split private identity from economic values', () =>
);
});
test('anonymous server snapshots omit personal values and labels before transmission', () => {
void test('anonymous server snapshots omit personal values and labels before transmission', () => {
assert.deepEqual(
partitionSimulationDraft(
{
@@ -544,7 +576,7 @@ test('anonymous server snapshots omit personal values and labels before transmis
);
});
test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
void test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
const restored = restoreSimulationDraft(
{
purpose: 'own_investment',
@@ -562,7 +594,7 @@ test('server-owned converted simulation snapshots are restored separately from e
);
});
test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
void test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
const simulation = {
id: '12345678-aaaa-bbbb-cccc-123456789abc',
status: 'completed',
@@ -649,7 +681,7 @@ test('completed arithmetic CSV preserves calculation details without exporting p
);
});
test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
void test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
const snapshot = {
contract_version: 1,
context: { scenario_version: 4 },
@@ -696,7 +728,7 @@ test('versioned arithmetic report reference requires the exact current snapshot
);
});
test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
void test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
assert.throws(
() =>
exportCompletedArithmeticCsv({
@@ -727,7 +759,7 @@ test('versioned arithmetic CSV refuses a result envelope that differs from the l
);
});
test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
void test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
const snapshot = {
indicative_total: '10.00',
legal_interpretation: false,
@@ -769,7 +801,7 @@ test('versioned arithmetic CSV refuses a report from another scenario revision',
);
});
test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
void test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
const snapshot = {
indicative_total: '0.20',
legal_interpretation: false,
@@ -812,7 +844,7 @@ test('arithmetic result reader exposes only reconciled versioned or legacy value
);
});
test('arithmetic result CSV neutralizes formula-like report metadata', () => {
void test('arithmetic result CSV neutralizes formula-like report metadata', () => {
const csv = exportCompletedArithmeticCsv({
id: '=HYPERLINK("https://example.invalid")',
status: 'completed',
+2 -2
View File
@@ -14,7 +14,7 @@ const simulator = readFileSync(
'utf8',
);
test('portal home hero exposes a direct public simulator link', () => {
void test('portal home hero exposes a direct public simulator link', () => {
const hero = homePage.slice(
homePage.indexOf('function Hero('),
homePage.indexOf('function SectorGrid('),
@@ -23,7 +23,7 @@ test('portal home hero exposes a direct public simulator link', () => {
assert.match(hero, /Planear finanças/);
});
test('completed simulator result keeps public interest submission independent', () => {
void test('completed simulator result keeps public interest submission independent', () => {
assert.match(simulator, /href="\/manifestar-interesse"/);
assert.match(
simulator,
+18 -10
View File
@@ -1,17 +1,25 @@
import assert from "node:assert/strict";
import test from "node:test";
import { replaceTerritoryPath } from "../../resources/js/lib/territory-path.js";
import assert from 'node:assert/strict';
import test from 'node:test';
import { replaceTerritoryPath } from '../../resources/js/lib/territory-path.js';
test("changing a parent replaces its value and clears every descendant", () => {
const path = ["province-a", "district-a", "post-a", "locality-a"];
void test('changing a parent replaces its value and clears every descendant', () => {
const path = ['province-a', 'district-a', 'post-a', 'locality-a'];
assert.deepEqual(replaceTerritoryPath(path, 0, "province-b"), ["province-b"]);
assert.deepEqual(replaceTerritoryPath(path, 1, "district-b"), ["province-a", "district-b"]);
assert.deepEqual(replaceTerritoryPath(path, 0, 'province-b'), [
'province-b',
]);
assert.deepEqual(replaceTerritoryPath(path, 1, 'district-b'), [
'province-a',
'district-b',
]);
});
test("clearing a level also clears that level and all descendants", () => {
const path = ["province-a", "district-a", "post-a", "locality-a"];
void test('clearing a level also clears that level and all descendants', () => {
const path = ['province-a', 'district-a', 'post-a', 'locality-a'];
assert.deepEqual(replaceTerritoryPath(path, 0), []);
assert.deepEqual(replaceTerritoryPath(path, 2, null), ["province-a", "district-a"]);
assert.deepEqual(replaceTerritoryPath(path, 2, null), [
'province-a',
'district-a',
]);
});