File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
decodeBusinessLocations,
|
||||
emptyBusinessLocation,
|
||||
encodeBusinessLocations,
|
||||
hasDuplicateBusinessLocationPath,
|
||||
updateBusinessLocation,
|
||||
} from '../../resources/js/lib/business-locations.ts';
|
||||
|
||||
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: '' },
|
||||
];
|
||||
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', () => {
|
||||
const initial = {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-a',
|
||||
admin_post_id: 'post-a',
|
||||
locality_id: 'locality-a',
|
||||
};
|
||||
const rows = [initial, emptyBusinessLocation()];
|
||||
const updated = updateBusinessLocation(rows, 0, 'district_id', 'district-b');
|
||||
assert.deepEqual(updated[0], {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-b',
|
||||
admin_post_id: '',
|
||||
locality_id: '',
|
||||
});
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
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', () => {
|
||||
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', () => {
|
||||
assert.equal(csvCell('-5000.00'), '-5000.00');
|
||||
assert.equal(csvCellWithDelimiter('Planeado; realizado', ';'), '"Planeado; realizado"');
|
||||
assert.equal(csvCell('Operação, mensal'), '"Operação, mensal"');
|
||||
assert.equal(csvCell('=HYPERLINK("x")'), '"\'=HYPERLINK(""x"")"');
|
||||
});
|
||||
@@ -0,0 +1,338 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildLoanSchedule,
|
||||
calculateBreakEven,
|
||||
calculateBudget,
|
||||
calculateFinancialTools,
|
||||
calculateFundingGap,
|
||||
calculateLoanPayment,
|
||||
exportFinancialToolsCsv,
|
||||
restoreFinancialToolsSnapshot,
|
||||
serializeFinancialToolsSnapshot,
|
||||
} from '../../resources/js/lib/financial-calculators.ts';
|
||||
|
||||
function cents(value) {
|
||||
const [whole, fraction = ''] = value.split('.');
|
||||
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
||||
}
|
||||
|
||||
test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
|
||||
const data = {
|
||||
budgetPeriod: 'Mensal',
|
||||
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: 'Renda', amount: '15000' }],
|
||||
};
|
||||
const snapshot = serializeFinancialToolsSnapshot(data);
|
||||
assert.deepEqual(restoreFinancialToolsSnapshot(snapshot), data);
|
||||
assert.equal(restoreFinancialToolsSnapshot('{"version":2}'), null);
|
||||
assert.equal(restoreFinancialToolsSnapshot('x'.repeat(30001)), null);
|
||||
assert.equal(
|
||||
restoreFinancialToolsSnapshot(
|
||||
serializeFinancialToolsSnapshot({ ...data, incomes: [] }),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
restoreFinancialToolsSnapshot(
|
||||
serializeFinancialToolsSnapshot({
|
||||
...data,
|
||||
incomes: Array.from({ length: 51 }, () => ({
|
||||
label: 'x',
|
||||
amount: '1',
|
||||
})),
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('loan payment handles zero interest exactly', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1200.00', '0', 12), {
|
||||
monthlyPayment: '100.00',
|
||||
totalPaid: '1200.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('loan payment computes a reproducible amortized estimate', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1000.00', '12', 12), {
|
||||
monthlyPayment: '88.85',
|
||||
totalPaid: '1066.19',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
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',
|
||||
breakEvenRevenue: '300.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
assert.throws(() => calculateBreakEven('10', '20', '20'), /superior/);
|
||||
});
|
||||
|
||||
test('an invalid indicator does not hide independent financial calculations', () => {
|
||||
const result = calculateFinancialTools({
|
||||
loan: {
|
||||
principal: '1200',
|
||||
annualRatePercent: '0',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
},
|
||||
breakEven: {
|
||||
fixedCosts: '100',
|
||||
unitPrice: '20',
|
||||
variableCostPerUnit: '20',
|
||||
},
|
||||
funding: { totalInvestment: '5000', securedFunding: '1000' },
|
||||
incomes: ['500'],
|
||||
expenses: ['600'],
|
||||
});
|
||||
|
||||
assert.equal(result.loan.value?.schedule[0].totalPayment, '100.00');
|
||||
assert.match(result.breakEven.error ?? '', /superior/);
|
||||
assert.equal(result.funding.value?.gap, '4000.00');
|
||||
assert.equal(result.budget.value?.operatingBalance, '-100.00');
|
||||
});
|
||||
|
||||
test('funding gap distinguishes zero from a negative surplus', () => {
|
||||
assert.deepEqual(calculateFundingGap('100.00', '120.00'), {
|
||||
gap: '-20.00',
|
||||
reconciles: false,
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
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', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1200.00',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 4,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
gracePeriods: 2,
|
||||
upfrontFee: '10',
|
||||
recurringFee: '2',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '1.000000');
|
||||
assert.equal(result.netDisbursed, '1190.00');
|
||||
assert.equal(result.schedule[0].interest, '12.00');
|
||||
assert.equal(result.schedule[0].principal, '0.00');
|
||||
assert.equal(result.schedule[0].fee, '2.00');
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.principal), 0n),
|
||||
120000n,
|
||||
);
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.totalPayment),
|
||||
0n,
|
||||
) + cents(result.upfrontFee),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
for (const row of result.schedule) {
|
||||
assert.equal(
|
||||
cents(row.openingBalance) - cents(row.principal),
|
||||
cents(row.closingBalance),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('loan schedule reconciles exact cents and adjusts the final installment', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000.01',
|
||||
annualRatePercent: '7.123456',
|
||||
termMonths: 7,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '0.593621');
|
||||
assert.equal(result.totalInterest, '23.88');
|
||||
assert.equal(result.totalPaid, '1023.89');
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.principal), 0n),
|
||||
100001n,
|
||||
);
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.totalPayment), 0n),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
});
|
||||
|
||||
test('effective annual rate is converted to the selected repayment period', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 12,
|
||||
rateType: 'effective',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '12.000000');
|
||||
assert.equal(result.schedule[0].interest, '120.00');
|
||||
assert.equal(result.totalPaid, '1120.00');
|
||||
const quarterly = buildLoanSchedule({
|
||||
principal: '1000',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 3,
|
||||
rateType: 'effective',
|
||||
});
|
||||
assert.equal(quarterly.periodicRatePercent, '2.873734');
|
||||
assert.equal(quarterly.schedule.at(-1).closingBalance, '0.00');
|
||||
});
|
||||
|
||||
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']) {
|
||||
for (const gracePeriods of [0, 2]) {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '12345.67',
|
||||
annualRatePercent,
|
||||
termMonths: periodMonths * 12,
|
||||
periodMonths,
|
||||
rateType,
|
||||
gracePeriods,
|
||||
upfrontFee: '15.25',
|
||||
recurringFee: '2.37',
|
||||
});
|
||||
|
||||
assert.equal(result.schedule.length, 12);
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.principal),
|
||||
0n,
|
||||
),
|
||||
1_234_567n,
|
||||
);
|
||||
for (const row of result.schedule) {
|
||||
assert.equal(
|
||||
cents(row.openingBalance) - cents(row.principal),
|
||||
cents(row.closingBalance),
|
||||
);
|
||||
assert.ok(cents(row.closingBalance) >= 0n);
|
||||
}
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.totalPayment),
|
||||
0n,
|
||||
) + cents(result.upfrontFee),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
assert.equal(
|
||||
cents(result.totalPaid),
|
||||
1_234_567n +
|
||||
cents(result.totalInterest) +
|
||||
cents(result.totalFees),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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',
|
||||
operatingBalance: '-14.50',
|
||||
status: 'estimated',
|
||||
});
|
||||
assert.throws(() => calculateBudget(['0'], ['-1']), /não negativo/);
|
||||
});
|
||||
|
||||
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']), {
|
||||
incomeTotal: '0.00',
|
||||
expenseTotal: '0.00',
|
||||
operatingBalance: '0.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
|
||||
const base = {
|
||||
principal: '1000',
|
||||
annualRatePercent: '0',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
};
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, periodMonths: 5 }),
|
||||
/Periodicidade/,
|
||||
);
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, gracePeriods: 12 }),
|
||||
/carência/,
|
||||
);
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, upfrontFee: '1001' }),
|
||||
/exceder o capital/,
|
||||
);
|
||||
});
|
||||
|
||||
test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
|
||||
const csv = exportFinancialToolsCsv({
|
||||
currency: 'MZN',
|
||||
generatedAt: '2026-10-02T10:00:00.000Z',
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '1200',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
gracePeriods: 0,
|
||||
upfrontFee: '10',
|
||||
recurringFee: '2',
|
||||
},
|
||||
breakEven: {
|
||||
fixedCosts: '1000',
|
||||
unitPrice: '30',
|
||||
variableCostPerUnit: '20',
|
||||
},
|
||||
funding: { totalInvestment: '5000', securedFunding: '3000' },
|
||||
incomes: [
|
||||
{ label: '=HYPERLINK("https://example.invalid")', amount: '2500' },
|
||||
],
|
||||
expenses: [{ label: 'Operação, mensal', amount: '1800' }],
|
||||
});
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /financial-tools-v1/);
|
||||
assert.match(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /2026-10-02T10:00:00\.000Z/);
|
||||
assert.match(csv, /Período do orçamento e dos custos fixos,Mensal/);
|
||||
assert.match(csv, /saldo decrescente/i);
|
||||
assert.match(csv, /Saldo operacional,,700\.00/);
|
||||
assert.match(csv, /Unidades de equilíbrio,100/);
|
||||
assert.match(csv, /Diferença por financiar,2000\.00/);
|
||||
assert.match(csv, /"'=HYPERLINK/);
|
||||
assert.match(csv, /"Operação, mensal"/);
|
||||
assert.match(csv, /não inclui impostos/);
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { buildFinancialFiscalBridge } from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
const plan = {
|
||||
currency: 'MZN',
|
||||
openingCash: '0',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço',
|
||||
monthlyUnits: '10',
|
||||
unitPrice: '100',
|
||||
unitVariableCost: '30',
|
||||
},
|
||||
],
|
||||
monthlyCollections: '800',
|
||||
monthlyVariableCostPayments: '250',
|
||||
monthlyOperatingExpenses: '100',
|
||||
monthlyOperatingPayments: '80',
|
||||
monthlyPayrollExpense: '50',
|
||||
monthlyPayrollPayments: '40',
|
||||
assetInvestment: '0',
|
||||
inventory: '0',
|
||||
receivables: '0',
|
||||
payables: '0',
|
||||
equity: '0',
|
||||
shareholderLoans: '0',
|
||||
bankLoanProceeds: '0',
|
||||
grants: '0',
|
||||
assetDepreciation: '0',
|
||||
depreciationLifeMonths: 12,
|
||||
monthlyInterestExpense: '10',
|
||||
monthlyInterestPayment: '5',
|
||||
monthlyPrincipalRepayment: '60',
|
||||
periods: 2,
|
||||
};
|
||||
|
||||
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(
|
||||
bridge.accountingLines.map((line) => [line.code, line]),
|
||||
);
|
||||
const cents = (value) => {
|
||||
const [whole, fraction] = value.split('.');
|
||||
return BigInt(whole) * 100n + BigInt(fraction);
|
||||
};
|
||||
const accountingProfit = [
|
||||
byCode.revenue.total,
|
||||
...Object.values(byCode)
|
||||
.filter((line) => line.accountingEffect === 'expense')
|
||||
.map((line) => `-${line.total}`),
|
||||
].reduce((sum, value) => sum + cents(value), 0n);
|
||||
|
||||
assert.equal(bridge.status, 'incomplete');
|
||||
assert.equal(bridge.accountingProfitBeforeTax, '1080.00');
|
||||
assert.equal(accountingProfit, cents(bridge.accountingProfitBeforeTax));
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
assert.equal(bridge.taxableBase.amount, null);
|
||||
assert.ok(
|
||||
bridge.taxableBase.missingInputs.includes(
|
||||
'expense_deductibility_classification',
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
bridge.accountingLines.every(
|
||||
(line) => line.taxTreatment === 'unclassified',
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(byCode.revenue.monthlyAmounts[0].amount, '1000.00');
|
||||
assert.equal(byCode.cost_of_sales.monthlyAmounts[0].amount, '300.00');
|
||||
assert.equal(bridge.cashSchedule[0].collections, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].collectionMode, 'manual');
|
||||
assert.equal(bridge.cashSchedule[0].salesCollections, null);
|
||||
assert.equal(bridge.cashSchedule[0].openingReceivablesCollections, '0.00');
|
||||
assert.equal(bridge.cashSchedule[0].otherCollections, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].collectionsTotal, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].principalRepayments, '60.00');
|
||||
assert.equal(
|
||||
bridge.accountingLines.some(
|
||||
(line) => line.code === 'principal_repayment',
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.notEqual(
|
||||
bridge.cashSchedule[0].collections,
|
||||
byCode.revenue.monthlyAmounts[0].amount,
|
||||
);
|
||||
});
|
||||
|
||||
test('financial bridge separates opening receivables and scheduled sales collections', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
receivables: '200.00',
|
||||
monthlyCollections: '0',
|
||||
salesCollectionLagMonths: 0,
|
||||
salesCollectionPercent: '75',
|
||||
openingReceivablesCollectionMonth: 1,
|
||||
openingReceivablesCollectionPercent: '50',
|
||||
periods: 1,
|
||||
});
|
||||
const bridge = buildFinancialFiscalBridge(forecast);
|
||||
assert.deepEqual(bridge.cashSchedule[0], {
|
||||
period: 1,
|
||||
collectionMode: 'scheduled',
|
||||
salesCollections: '750.00',
|
||||
openingReceivablesBalance: '100.00',
|
||||
openingReceivablesCollections: '100.00',
|
||||
otherCollections: '0.00',
|
||||
collections: '850.00',
|
||||
collectionsTotal: '850.00',
|
||||
salesReceivablesBalance: '250.00',
|
||||
supplierPayments: '250.00',
|
||||
operatingPayments: '80.00',
|
||||
personnelPayments: '40.00',
|
||||
interestPayments: '5.00',
|
||||
principalRepayments: '60.00',
|
||||
netCashFlow: '415.00',
|
||||
closingCash: '215.00',
|
||||
});
|
||||
assert.equal(
|
||||
bridge.accountingLines.find((line) => line.code === 'revenue').total,
|
||||
'1000.00',
|
||||
);
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
periods: 2,
|
||||
monthlyOperatingExpensesByPeriod: ['100', '250'],
|
||||
monthlyOperatingPaymentsByPeriod: ['20', '300'],
|
||||
monthlyPayrollExpenseByPeriod: ['50', '75'],
|
||||
monthlyPayrollPaymentsByPeriod: ['0', '100'],
|
||||
});
|
||||
const bridge = buildFinancialFiscalBridge(forecast);
|
||||
const byCode = Object.fromEntries(
|
||||
bridge.accountingLines.map((line) => [line.code, line]),
|
||||
);
|
||||
|
||||
assert.deepEqual(byCode.operating_expenses.monthlyAmounts, [
|
||||
{ period: 1, amount: '100.00' },
|
||||
{ period: 2, amount: '250.00' },
|
||||
]);
|
||||
assert.deepEqual(byCode.personnel.monthlyAmounts, [
|
||||
{ period: 1, amount: '50.00' },
|
||||
{ period: 2, amount: '75.00' },
|
||||
]);
|
||||
assert.equal(bridge.cashSchedule[0].operatingPayments, '20.00');
|
||||
assert.equal(bridge.cashSchedule[0].personnelPayments, '0.00');
|
||||
assert.equal(bridge.cashSchedule[1].operatingPayments, '300.00');
|
||||
assert.equal(bridge.cashSchedule[1].personnelPayments, '100.00');
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('financial bridge rejects a corrupted monthly cash schedule', () => {
|
||||
const forecast = forecastBusinessPlan(plan);
|
||||
const corrupted = {
|
||||
...forecast,
|
||||
rows: forecast.rows.map((row, index) =>
|
||||
index === 0 ? { ...row, closingCash: '999999.00' } : row,
|
||||
),
|
||||
};
|
||||
assert.throws(
|
||||
() => buildFinancialFiscalBridge(corrupted),
|
||||
/saldo de caixa mensal não reconcilia/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
exportMonthlyCashflowCsv,
|
||||
projectMonthlyCashflow,
|
||||
} from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
|
||||
test('projects exact monthly balances and reconciles cumulative net flow', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100.00',
|
||||
monthlyRevenue: '200.00',
|
||||
monthlyOperatingCosts: '150.00',
|
||||
monthlyDebtService: '10.00',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.rows[0].closingCash, '140.00');
|
||||
assert.equal(result.endingCash, '180.00');
|
||||
assert.equal(result.firstDeficitMonth, null);
|
||||
});
|
||||
|
||||
test('flags the first projected deficit without changing input values', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '50',
|
||||
monthlyOperatingCosts: '75',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 4,
|
||||
});
|
||||
assert.equal(result.firstDeficitMonth, 1);
|
||||
assert.equal(result.endingCash, '-100.00');
|
||||
});
|
||||
|
||||
test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '10',
|
||||
vatCreditEstimated: '80',
|
||||
vatRefundRequested: '70',
|
||||
vatRefundRecognized: '60',
|
||||
periods: 3,
|
||||
};
|
||||
const withoutReceipt = projectMonthlyCashflow(base);
|
||||
assert.equal(withoutReceipt.endingCash, '270.00');
|
||||
assert.equal(withoutReceipt.rows[0].taxAssessed, '10.00');
|
||||
assert.equal(withoutReceipt.rows[0].vatRefundExpectedReceipt, '0.00');
|
||||
const withReceipt = projectMonthlyCashflow({
|
||||
...base,
|
||||
vatRefundExpectedReceipt: '60',
|
||||
vatRefundExpectedMonth: '2',
|
||||
});
|
||||
assert.equal(withReceipt.rows[1].vatRefundExpectedReceipt, '60.00');
|
||||
assert.equal(withReceipt.endingCash, '330.00');
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({ ...base, vatRefundExpectedReceipt: '60' }),
|
||||
/mês previsto/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
...base,
|
||||
vatRefundExpectedReceipt: '60.01',
|
||||
vatRefundExpectedMonth: '2',
|
||||
}),
|
||||
/não pode exceder o montante reconhecido/,
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '150',
|
||||
monthlyDebtService: '10',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.status, 'incomplete');
|
||||
assert.equal(result.endingCash, null);
|
||||
assert.equal(result.endingCashBeforeUnassessedTax, '180.00');
|
||||
assert.equal(result.firstDeficitMonth, null);
|
||||
assert.equal(result.rows[0].taxAssessed, null);
|
||||
assert.equal(result.rows[0].netFlow, null);
|
||||
assert.equal(result.rows[0].closingCash, null);
|
||||
assert.equal(result.rows[0].netFlowBeforeUnassessedTax, '40.00');
|
||||
assert.equal(result.rows[0].closingCashBeforeUnassessedTax, '140.00');
|
||||
|
||||
const declaredZero = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '150',
|
||||
monthlyDebtService: '10',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(declaredZero.status, 'estimated');
|
||||
assert.equal(declaredZero.endingCash, '180.00');
|
||||
});
|
||||
|
||||
test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '50',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['10', '30'],
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.status, 'estimated');
|
||||
assert.equal(result.rows[0].taxAssessed, '10.00');
|
||||
assert.equal(result.rows[0].closingCash, '240.00');
|
||||
assert.equal(result.rows[1].openingCash, '240.00');
|
||||
assert.equal(result.rows[1].taxAssessed, '30.00');
|
||||
assert.equal(result.endingCash, '360.00');
|
||||
});
|
||||
|
||||
test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '50',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['10', '', '30'],
|
||||
periods: 3,
|
||||
});
|
||||
assert.equal(result.status, 'incomplete');
|
||||
assert.equal(result.rows[0].closingCash, '240.00');
|
||||
assert.equal(result.rows[1].taxAssessed, null);
|
||||
assert.equal(result.rows[1].netFlow, null);
|
||||
assert.equal(result.rows[1].closingCash, null);
|
||||
assert.equal(result.rows[1].netFlowBeforeUnassessedTax, '150.00');
|
||||
assert.equal(result.rows[1].closingCashBeforeUnassessedTax, '390.00');
|
||||
assert.equal(result.rows[2].openingCash, null);
|
||||
assert.equal(result.rows[2].taxAssessed, '30.00');
|
||||
assert.equal(result.rows[2].netFlow, '120.00');
|
||||
assert.equal(result.rows[2].closingCash, null);
|
||||
assert.equal(result.endingCash, null);
|
||||
assert.equal(result.endingCashBeforeUnassessedTax, '510.00');
|
||||
});
|
||||
|
||||
test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
periods: 2,
|
||||
};
|
||||
assert.throws(
|
||||
() => projectMonthlyCashflow({ ...base, monthlyTaxSchedule: ['10'] }),
|
||||
/cada mês projectado/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
...base,
|
||||
monthlyTaxAssessed: '5',
|
||||
monthlyTaxSchedule: ['10', '20'],
|
||||
}),
|
||||
/não ambos/,
|
||||
);
|
||||
});
|
||||
|
||||
test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
|
||||
assert.equal(
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '-1.00',
|
||||
monthlyRevenue: '0',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 1,
|
||||
}).endingCash,
|
||||
'-1.00',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '1.001',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
}),
|
||||
/duas casas/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '0',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
periods: 61,
|
||||
}),
|
||||
/60 meses/,
|
||||
);
|
||||
});
|
||||
|
||||
test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '10.00',
|
||||
monthlyRevenue: '20.00',
|
||||
monthlyOperatingCosts: '5.00',
|
||||
monthlyDebtService: '0.00',
|
||||
currency: 'MZN',
|
||||
periods: 2,
|
||||
},
|
||||
'2026-10-03T10:00:00.000Z',
|
||||
);
|
||||
assert.match(csv, /Saldo inicial,10\.00/);
|
||||
assert.match(csv, /Moeda,MZN/);
|
||||
assert.match(csv, /monthly-cashflow-v1/);
|
||||
assert.match(csv, /2026-10-03T10:00:00\.000Z/);
|
||||
assert.match(csv, /Horizonte,2 meses/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Valores do formulário; os valores pré-preenchidos podem ser exemplos demonstrativos/,
|
||||
);
|
||||
assert.match(csv, /Estado,incomplete/);
|
||||
assert.match(csv, /indeterminado; não informado/);
|
||||
assert.match(csv, /Fluxo líquido,Saldo final/);
|
||||
assert.match(csv, /indeterminado/);
|
||||
assert.match(csv, /antes de imposto não informado/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Crédito estimado, pedido e montante reconhecido não entram no caixa/,
|
||||
);
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
});
|
||||
|
||||
test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['12.50', '', '0'],
|
||||
currency: 'MZN',
|
||||
periods: 3,
|
||||
},
|
||||
'2026-10-03T10:00:00.000Z',
|
||||
);
|
||||
assert.match(csv, /Calendário variável; consultar valores mensais abaixo/);
|
||||
assert.match(
|
||||
csv,
|
||||
/pressuposto do utilizador, não cálculo ou confirmação de obrigação fiscal/,
|
||||
);
|
||||
assert.match(csv, /Pressuposto mensal de imposto,Mês 1,12\.50/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Pressuposto mensal de imposto,Mês 2,indeterminado; não informado/,
|
||||
);
|
||||
assert.match(csv, /Pressuposto mensal de imposto,Mês 3,0/);
|
||||
});
|
||||
|
||||
test('cash flow CSV neutralizes formula-like assumption text', () => {
|
||||
const csv = exportMonthlyCashflowCsv({
|
||||
openingCash: '10.00',
|
||||
monthlyRevenue: '20.00',
|
||||
monthlyOperatingCosts: '5.00',
|
||||
monthlyDebtService: '0.00',
|
||||
currency: 'MZN',
|
||||
vatRefundExpectedMonth: '=HYPERLINK("https://example.invalid")',
|
||||
periods: 1,
|
||||
});
|
||||
assert.match(
|
||||
csv,
|
||||
/Mês previsto do recebimento IVA,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import {
|
||||
createProjectDossierPrintHtml,
|
||||
createProjectDossierReport,
|
||||
dossierReportSections,
|
||||
generateProjectDossierDocx,
|
||||
generateProjectDossierPackage,
|
||||
classifyDossierAttachment,
|
||||
validateDossierAttachments,
|
||||
} from '../../resources/js/lib/project-dossier-report.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,
|
||||
};
|
||||
}
|
||||
|
||||
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.doesNotMatch(JSON.stringify(report), /"value":"0(\.00)?"/);
|
||||
});
|
||||
|
||||
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 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.equal(report.version, 'Revisão 3');
|
||||
});
|
||||
|
||||
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 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`);
|
||||
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: [] },
|
||||
},
|
||||
},
|
||||
});
|
||||
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));
|
||||
});
|
||||
|
||||
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]);
|
||||
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');
|
||||
assert.match(documentXml, /Produção de café/);
|
||||
assert.match(documentXml, /Classificação/);
|
||||
assert.match(documentXml, /projecto/);
|
||||
assert.match(footerXml, /PAGE/);
|
||||
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' });
|
||||
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 docx = await generateProjectDossierDocx(report, attachments, true);
|
||||
const docxZip = await JSZip.loadAsync(await docx.arrayBuffer());
|
||||
const xml = await docxZip.file('word/document.xml').async('string');
|
||||
assert.match(xml, /Café/);
|
||||
assert.match(xml, /Este formato não foi incorporado/);
|
||||
const bundle = await generateProjectDossierPackage(docx, attachments, true);
|
||||
const bundleZip = await JSZip.loadAsync(await bundle.arrayBuffer());
|
||||
assert.ok(bundleZip.file('Anexos/tabela.csv'));
|
||||
assert.ok(bundleZip.file('Anexos/apoio.pdf'));
|
||||
const index = await bundleZip.file('indice-anexos.txt').async('string');
|
||||
assert.match(index, /Conteúdo não incorporado/);
|
||||
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');
|
||||
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 zip = await JSZip.loadAsync(await docx.arrayBuffer());
|
||||
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)}"`));
|
||||
});
|
||||
|
||||
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, /<script>/);
|
||||
assert.match(pdf, /não foram seleccionados|secção de anexos foi omitida/);
|
||||
assert.match(pdf, /@page\{size:A4/);
|
||||
});
|
||||
|
||||
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/);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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', () => {
|
||||
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: '' }]) });
|
||||
assert.match(csv, /Informação declarada, não verificada/);
|
||||
assert.match(csv, /Informação insuficiente/);
|
||||
assert.match(csv, /'=1\+1/);
|
||||
assert.match(csv, /Secção;Campo;Valor;Origem \/ estado/);
|
||||
assert.match(csv, /Gestão; gap; resposta: Formação/);
|
||||
assert.match(csv, /Marco 1/);
|
||||
});
|
||||
|
||||
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' },
|
||||
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' });
|
||||
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;/);
|
||||
assert.doesNotMatch(csv, /"\{""version""/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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: '[]',
|
||||
});
|
||||
assert.equal(items.some((item) => ['customers', 'costs', 'location', 'funding'].includes(item.id)), false);
|
||||
});
|
||||
|
||||
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' }), []);
|
||||
});
|
||||
|
||||
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/);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
readSimulationApiJson,
|
||||
simulationApiErrorMessage,
|
||||
simulationPollingFailureMessage,
|
||||
simulationCatalogChoices,
|
||||
} from '../../resources/js/lib/simulation-api.ts';
|
||||
|
||||
test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
|
||||
assert.equal(
|
||||
await readSimulationApiJson(
|
||||
new Response('<html>gateway error</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
status: 502,
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
await readSimulationApiJson(
|
||||
new Response('{"truncated":', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('API error messages prefer validated field details and reject malformed shapes', () => {
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({
|
||||
message: 'Validation failed',
|
||||
errors: { base: ['Base is required'], rate: ['Rate is invalid'] },
|
||||
}),
|
||||
'Base is required Rate is invalid',
|
||||
);
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({ message: 'Try again' }),
|
||||
'Try again',
|
||||
);
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({ errors: { base: 'invalid' } }),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(simulationApiErrorMessage('<html>error</html>'), undefined);
|
||||
});
|
||||
|
||||
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.',
|
||||
);
|
||||
assert.equal(
|
||||
simulationPollingFailureMessage({ message: 'Acesso expirado' }),
|
||||
'Acesso expirado',
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
|
||||
assert.deepEqual(simulationCatalogChoices({ data: [] }), []);
|
||||
assert.deepEqual(
|
||||
simulationCatalogChoices({
|
||||
data: [
|
||||
{ id: 'country-1', label: 'Moçambique' },
|
||||
{ value: 2, name: 'Província de Maputo' },
|
||||
{ id: 'incomplete', label: '' },
|
||||
null,
|
||||
],
|
||||
}),
|
||||
[
|
||||
{ id: 'country-1', label: 'Moçambique' },
|
||||
{ id: '2', label: 'Província de Maputo' },
|
||||
],
|
||||
);
|
||||
assert.throws(() => simulationCatalogChoices('<html>gateway error</html>'));
|
||||
});
|
||||
@@ -0,0 +1,620 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
isApiErrorV1,
|
||||
isApiQuestionnaireReadResponseV1,
|
||||
isApiSimulationJobsReadResponseV1,
|
||||
isApiSimulationReportReadResponseV1,
|
||||
isApiSimulationDraftAttachResponseV1,
|
||||
isApiSimulationDraftReadResponseV1,
|
||||
isApiSimulationDraftWriteResponseV1,
|
||||
isApiSimulationHistoryResponseV1,
|
||||
fiscalComponentCodes,
|
||||
indeterminateFiscalComponent,
|
||||
isApiSimulationCreateResponseV1,
|
||||
isApiSimulationReadResponseV1,
|
||||
isApiSimulationResultSnapshotV1,
|
||||
isSimulationCurrency,
|
||||
simulationCurrencyFractionDigits,
|
||||
simulationCurrencyOptions,
|
||||
validateSimulationResult,
|
||||
} from '../../resources/js/lib/simulation-contract.ts';
|
||||
|
||||
const apiSnapshot = {
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-03',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 1,
|
||||
engine_version: 'portal-arithmetic-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.000000',
|
||||
unit: null,
|
||||
explanation: 'Arithmetic indicative.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
indicative_total: '0.000000',
|
||||
legal_interpretation: false,
|
||||
formula_version: 'portal-arithmetic-v1',
|
||||
};
|
||||
const apiExecution = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
status: 'queued',
|
||||
version_no: 1,
|
||||
result_snapshot: null,
|
||||
};
|
||||
const apiDraft = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
version_no: 2,
|
||||
snapshot_sha256: 'a'.repeat(64),
|
||||
personal_snapshot: [],
|
||||
economic_snapshot: { purpose: 'simulate_only' },
|
||||
simulation_sources: [],
|
||||
updated_at: '2026-10-03T12:30:00.000000Z',
|
||||
};
|
||||
const apiHistory = {
|
||||
data: [
|
||||
{
|
||||
id: apiExecution.id,
|
||||
scope: 'personal',
|
||||
organization_name: null,
|
||||
status: 'completed',
|
||||
version_no: 1,
|
||||
created_at: '2026-10-03T12:00:00.000000Z',
|
||||
updated_at: '2026-10-03T12:00:01.000000Z',
|
||||
has_ready_report: true,
|
||||
},
|
||||
],
|
||||
meta: { current_page: 1, last_page: 1, per_page: 10, total: 1 },
|
||||
};
|
||||
const apiJob = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
simulation_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
job_type: 'execute',
|
||||
status: 'succeeded',
|
||||
attempts: 1,
|
||||
available_at: '2026-10-03T12:00:00.000000Z',
|
||||
started_at: '2026-10-03T12:00:01.000000Z',
|
||||
finished_at: '2026-10-03T12:00:02.000000Z',
|
||||
error_code: null,
|
||||
};
|
||||
|
||||
test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
|
||||
const openapi = JSON.parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
'../../docs/investmoz/simulations/openapi.json',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const schemas = openapi.components.schemas;
|
||||
|
||||
assert.ok(schemas.DecimalInputString.pattern.includes(String.raw`\.`));
|
||||
assert.equal(
|
||||
schemas.SimulationInput.properties.base.allOf[0].$ref,
|
||||
'#/components/schemas/DecimalInputString',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.SimulationInput.properties.rate.allOf[0].$ref,
|
||||
'#/components/schemas/PercentageInputString',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.UpdateScenarioInput.properties.base.allOf[0].$ref,
|
||||
'#/components/schemas/DecimalInputString',
|
||||
);
|
||||
assert.deepEqual(schemas.SimulationExecutionV1.properties.status.enum, [
|
||||
'queued',
|
||||
'running',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations'].post.responses['202'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationCreateResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/history'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationHistoryResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulation-drafts/current'].get.responses['200']
|
||||
.content['application/json'].schema.$ref,
|
||||
'#/components/schemas/SimulationDraftReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/questionnaires/{code}'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/QuestionnaireReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/jobs'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationJobsReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/scenarios/{scenarioId}'].patch
|
||||
.responses['202'].content['application/json'].schema.$ref,
|
||||
'#/components/schemas/SimulationReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/scenarios/{scenarioId}'].patch
|
||||
.responses['422'].content['application/json'].schema.$ref,
|
||||
'#/components/schemas/ApiErrorV1',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.SimulationHistoryResponseV1.properties.meta.properties.per_page
|
||||
.maximum,
|
||||
50,
|
||||
);
|
||||
for (const pathItem of Object.values(openapi.paths)) {
|
||||
for (const operation of Object.values(pathItem)) {
|
||||
for (const [status, response] of Object.entries(
|
||||
operation.responses ?? {},
|
||||
)) {
|
||||
if (!/^4\d\d$/.test(status)) continue;
|
||||
assert.equal(
|
||||
response.content?.['application/json']?.schema?.$ref,
|
||||
'#/components/schemas/ApiErrorV1',
|
||||
`HTTP ${status} must use the shared API error contract`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
assert.equal(isSimulationCurrency('XYZ'), false);
|
||||
assert.equal(simulationCurrencyFractionDigits('JPY'), 0);
|
||||
assert.equal(simulationCurrencyFractionDigits('KWD'), 3);
|
||||
assert.equal(simulationCurrencyOptions.includes('JPY'), false);
|
||||
assert.equal(simulationCurrencyOptions.includes('KWD'), false);
|
||||
});
|
||||
|
||||
test('calculated values preserve exact decimal strings, including zero', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'calculated',
|
||||
value: '0.00',
|
||||
unit: 'MZN',
|
||||
explanation: 'Cenário aritmético.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
|
||||
assert.equal(isApiSimulationResultSnapshotV1(apiSnapshot), true);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
context: { ...apiSnapshot.context, reference_date: '2026-02-31' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
context: { ...apiSnapshot.context, reference_date: '2024-02-29' },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
indicative_total: null,
|
||||
result: {
|
||||
...apiSnapshot.result,
|
||||
status: 'indeterminate',
|
||||
value: null,
|
||||
missing_inputs: ['approved_rule'],
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
indicative_total: '0.000001',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
result: { ...apiSnapshot.result, value: '0' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
result: {
|
||||
...apiSnapshot.result,
|
||||
status: 'indeterminate',
|
||||
missing_inputs: [],
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('simulation creation and polling responses require a valid execution view', () => {
|
||||
const queuedExecution = { ...apiExecution };
|
||||
delete queuedExecution.result_snapshot;
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: queuedExecution,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(isApiSimulationReadResponseV1({ data: apiExecution }), true);
|
||||
const completedExecution = {
|
||||
...apiExecution,
|
||||
status: 'completed',
|
||||
version_no: 2,
|
||||
result_snapshot: apiSnapshot,
|
||||
};
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({ data: completedExecution }),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...completedExecution, result_snapshot: { broken: true } },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...completedExecution, result_snapshot: null },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: {
|
||||
...apiExecution,
|
||||
result_snapshot: {
|
||||
contract_version: 1,
|
||||
indicative_total: '12',
|
||||
},
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: {
|
||||
...completedExecution,
|
||||
result_snapshot: { indicative_total: '12.50' },
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: true,
|
||||
access_token: 'x'.repeat(48),
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...apiExecution, status: 'unknown' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { id: apiExecution.id, status: 'completed', version_no: 2 },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: 'false',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('history and encrypted-draft endpoints reject malformed envelopes', () => {
|
||||
assert.equal(isApiSimulationHistoryResponseV1(apiHistory), true);
|
||||
assert.equal(
|
||||
isApiSimulationHistoryResponseV1({
|
||||
...apiHistory,
|
||||
data: [{ ...apiHistory.data[0], status: 'unrecognized' }],
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationHistoryResponseV1({ ...apiHistory, meta: {} }),
|
||||
false,
|
||||
);
|
||||
|
||||
assert.equal(isApiSimulationDraftReadResponseV1({ data: apiDraft }), true);
|
||||
assert.equal(isApiSimulationDraftReadResponseV1({ data: null }), true);
|
||||
assert.equal(
|
||||
isApiSimulationDraftReadResponseV1({
|
||||
data: { ...apiDraft, personal_snapshot: ['private'] },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftWriteResponseV1({
|
||||
data: { id: apiDraft.id, version_no: 3 },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftWriteResponseV1({
|
||||
data: { id: 'bad', version_no: 0 },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftAttachResponseV1({
|
||||
data: apiDraft,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftAttachResponseV1({
|
||||
data: apiDraft,
|
||||
replayed: 'false',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('questionnaire, report, job and error envelopes match their server contracts', () => {
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
code: 'user-entered-arithmetic',
|
||||
version_no: 1,
|
||||
locale: 'pt-MZ',
|
||||
schema_snapshot: { inputs: {} },
|
||||
status: 'published',
|
||||
valid_from: '2026-10-01',
|
||||
valid_to: null,
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
code: 'user-entered-arithmetic',
|
||||
version_no: 1,
|
||||
locale: 'pt-MZ',
|
||||
schema_snapshot: { inputs: {} },
|
||||
status: 'published',
|
||||
valid_from: '2026-02-31',
|
||||
valid_to: null,
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({ data: { locale: 'en' } }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: apiSnapshot,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: [],
|
||||
report_sha256: 'invalid',
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'queued',
|
||||
report_snapshot: apiSnapshot,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: null,
|
||||
report_sha256: null,
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(isApiSimulationJobsReadResponseV1({ data: [apiJob] }), true);
|
||||
assert.equal(
|
||||
isApiSimulationJobsReadResponseV1({
|
||||
data: [{ ...apiJob, attempts: 4 }],
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiErrorV1({
|
||||
message: 'Validation failed',
|
||||
errors: { base: ['Invalid'] },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(isApiErrorV1({ message: 42 }), false);
|
||||
assert.equal(isApiErrorV1({ errors: { base: 'Invalid' } }), false);
|
||||
});
|
||||
|
||||
test('wire contract guards survive a real JSON encode/decode round trip', () => {
|
||||
const wirePayloads = [
|
||||
[isApiSimulationReadResponseV1, { data: apiExecution }],
|
||||
[
|
||||
isApiSimulationCreateResponseV1,
|
||||
{
|
||||
data: apiExecution,
|
||||
replayed: false,
|
||||
access_token: 'x'.repeat(48),
|
||||
},
|
||||
],
|
||||
[isApiSimulationHistoryResponseV1, apiHistory],
|
||||
[isApiSimulationDraftReadResponseV1, { data: apiDraft }],
|
||||
[
|
||||
isApiSimulationDraftAttachResponseV1,
|
||||
{ data: apiDraft, replayed: false },
|
||||
],
|
||||
[isApiSimulationJobsReadResponseV1, { data: [apiJob] }],
|
||||
[
|
||||
isApiSimulationResultSnapshotV1,
|
||||
{ ...apiSnapshot, result: { ...apiSnapshot.result } },
|
||||
],
|
||||
];
|
||||
|
||||
for (const [guard, payload] of wirePayloads) {
|
||||
const decoded = JSON.parse(JSON.stringify(payload));
|
||||
assert.equal(guard(decoded), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'indeterminate',
|
||||
value: null,
|
||||
unit: null,
|
||||
explanation: 'Falta a classificação.',
|
||||
missingInputs: ['tariff_code'],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'indeterminate',
|
||||
value: '0',
|
||||
unit: 'MZN',
|
||||
explanation: 'Sem dados.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
['indeterminate_inputs'],
|
||||
);
|
||||
});
|
||||
|
||||
test('estimated and not-applicable states must be explicit', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'estimated',
|
||||
value: '12.30',
|
||||
unit: 'MZN',
|
||||
explanation: 'Estimativa incompleta.',
|
||||
missingInputs: ['tariff_code'],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'not_applicable',
|
||||
value: null,
|
||||
unit: null,
|
||||
explanation: 'Fora do cenário.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'not_applicable',
|
||||
value: '0',
|
||||
unit: 'MZN',
|
||||
explanation: 'Fora do cenário.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
['not_applicable_value'],
|
||||
);
|
||||
});
|
||||
|
||||
test('every tax component remains indeterminate until an approved effective rule exists', () => {
|
||||
assert.deepEqual(fiscalComponentCodes, [
|
||||
'IRPS',
|
||||
'INSS',
|
||||
'IVA',
|
||||
'IRPC',
|
||||
'ISPC',
|
||||
'RETENCOES',
|
||||
]);
|
||||
for (const code of fiscalComponentCodes) {
|
||||
const result = indeterminateFiscalComponent(code, '2026-10-02');
|
||||
assert.deepEqual(validateSimulationResult(result), []);
|
||||
assert.equal(result.value, null);
|
||||
assert.ok(result.missingInputs.includes('approved_rule'));
|
||||
assert.deepEqual(result.sourceIds, []);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const openapi = JSON.parse(
|
||||
readFileSync(
|
||||
new URL(
|
||||
'../../docs/investmoz/simulations/openapi.json',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
|
||||
test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
|
||||
const operation =
|
||||
openapi.paths['/simulation-drafts/{id}/conversions']?.post;
|
||||
assert.ok(operation);
|
||||
assert.deepEqual(
|
||||
operation.parameters.map((parameter) => parameter.$ref),
|
||||
[
|
||||
'#/components/parameters/Id',
|
||||
'#/components/parameters/IfMatch',
|
||||
'#/components/parameters/SimulationToken',
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
operation.requestBody.content['application/json'].schema.$ref,
|
||||
'#/components/schemas/AttachSimulationToDraftInput',
|
||||
);
|
||||
for (const response of ['200', '404', '409', '412', '422', '428', '429'])
|
||||
assert.ok(
|
||||
operation.responses[response],
|
||||
`missing response ${response}`,
|
||||
);
|
||||
assert.match(
|
||||
operation.description,
|
||||
/does not submit a project or create a CRM record/i,
|
||||
);
|
||||
|
||||
const schema = openapi.components.schemas.AttachSimulationToDraftInput;
|
||||
assert.deepEqual(schema.required, ['simulation_id', 'consent_reuse']);
|
||||
assert.equal(schema.additionalProperties, false);
|
||||
assert.equal(schema.properties.simulation_id.format, 'uuid');
|
||||
assert.equal(schema.properties.consent_reuse.const, true);
|
||||
});
|
||||
@@ -1,67 +1,832 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
getSimulationSections,
|
||||
simulationFieldGroups,
|
||||
getAutosaveSnapshot,
|
||||
advancedSimulationFields,
|
||||
partitionSimulationDraft,
|
||||
replaceSimulationValue,
|
||||
restoreSimulationDraft,
|
||||
simulationOptions,
|
||||
validateCustomFiscalPlanning,
|
||||
simulationDraftFingerprint,
|
||||
validateSimulationDraft,
|
||||
} from "../../resources/js/lib/simulation-form.ts";
|
||||
exportCompletedArithmeticCsv,
|
||||
readArithmeticSnapshot,
|
||||
readVersionedArithmeticReportReference,
|
||||
moveSearchChoiceIndex,
|
||||
getFiscalPeriodRange,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
test("changing territorial or sector parents clears every dependent value", () => {
|
||||
test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue({
|
||||
province_id: "p1", district_id: "d1", admin_post_id: "a1", locality_id: "l1",
|
||||
}, "province_id", "p2"),
|
||||
{ province_id: "p2" },
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2024',
|
||||
fiscal_periodicity: 'annual',
|
||||
}),
|
||||
{ start: '2024-01-01', end: '2024-12-31' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue({ sector_id: "s1", activity_id: "a1", activity_id_label: "A" }, "sector_id", "s2"),
|
||||
{ sector_id: "s2" },
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2024',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_month: '02',
|
||||
}),
|
||||
{ start: '2024-02-01', end: '2024-02-29' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'quarterly',
|
||||
fiscal_quarter: 'Q4',
|
||||
}),
|
||||
{ start: '2026-10-01', end: '2026-12-31' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_reference_date: '2026-06-15',
|
||||
}),
|
||||
{ start: '2026-06-15', end: '2026-06-15' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_reference_date: '2025-06-15',
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("switching to anonymous simulation clears formal identity and project data", () => {
|
||||
const next = replaceSimulationValue({
|
||||
purpose: "own_investment", legal_name: "Empresa", email: "a@b.co", project_title: "Projecto",
|
||||
total_investment: "10", total_investment_label: "10",
|
||||
}, "purpose", "simulate_only");
|
||||
assert.deepEqual(next, { purpose: "simulate_only" });
|
||||
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);
|
||||
assert.equal(moveSearchChoiceIndex(2, 1, 3), 2);
|
||||
assert.equal(moveSearchChoiceIndex(0, 1, 0), -1);
|
||||
assert.equal(moveSearchChoiceIndex(0, -1, -1), -1);
|
||||
});
|
||||
|
||||
test("client validation rejects absent arithmetic inputs and out-of-range rates", () => {
|
||||
assert.deepEqual(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes" }, "tax"), {
|
||||
base: "Este campo é obrigatório.",
|
||||
rate: "Este campo é obrigatório.",
|
||||
reduction: "Este campo é obrigatório.",
|
||||
test('anonymous arithmetic journey skips formal investor and project sections', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({ purpose: 'simulate_only' }).map(
|
||||
(section) => section.id,
|
||||
),
|
||||
['purpose', 'tax', 'review'],
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections({ purpose: 'own_investment' }).length,
|
||||
11,
|
||||
);
|
||||
});
|
||||
|
||||
test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
|
||||
const draft = {
|
||||
journey_type: 'small_business',
|
||||
purpose: 'simulate_only',
|
||||
detail_level: 'simple',
|
||||
};
|
||||
assert.deepEqual(
|
||||
getSimulationSections(draft).map((section) => section.id),
|
||||
[
|
||||
'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);
|
||||
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}`);
|
||||
assert.equal(
|
||||
ideaFields.some((field) =>
|
||||
typeof field.required === 'function'
|
||||
? field.required(draft)
|
||||
: Boolean(field.required),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections(draft).some((section) =>
|
||||
['identity', 'documents', 'tax'].includes(section.id),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'location'), {});
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
|
||||
});
|
||||
|
||||
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);
|
||||
assert.deepEqual(sections, [
|
||||
'purpose', 'project', 'location', 'financial', 'tax', 'scenarios', 'procedures', 'review',
|
||||
]);
|
||||
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'));
|
||||
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', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'personal',
|
||||
purpose: 'own_investment',
|
||||
}).map((section) => section.id),
|
||||
['purpose', 'financial', 'tax', 'review'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'small_business',
|
||||
purpose: 'own_investment',
|
||||
}).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'promoter',
|
||||
'project',
|
||||
'financial',
|
||||
'impact',
|
||||
'tax',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections({
|
||||
journey_type: 'company',
|
||||
purpose: 'own_investment',
|
||||
}).length,
|
||||
11,
|
||||
);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'investor',
|
||||
purpose: 'seek_investor',
|
||||
}).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'promoter',
|
||||
'identity',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'opportunity',
|
||||
'documents',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
assert.equal(advancedSimulationFields.has('deductible_costs'), true);
|
||||
});
|
||||
|
||||
test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
journey_type: 'personal',
|
||||
detail_level: 'advanced',
|
||||
legal_name: 'Nome',
|
||||
email: 'a@b.co',
|
||||
},
|
||||
'purpose',
|
||||
'simulate_only',
|
||||
),
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
journey_type: 'personal',
|
||||
detail_level: 'advanced',
|
||||
legal_name: 'Nome',
|
||||
email: 'a@b.co',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('changing territorial or sector parents clears every dependent value', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
province_id: 'p1',
|
||||
district_id: 'd1',
|
||||
admin_post_id: 'a1',
|
||||
locality_id: 'l1',
|
||||
},
|
||||
'province_id',
|
||||
'p2',
|
||||
),
|
||||
{ province_id: 'p2' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{ sector_id: 's1', activity_id: 'a1', activity_id_label: 'A' },
|
||||
'sector_id',
|
||||
's2',
|
||||
),
|
||||
{ sector_id: 's2' },
|
||||
);
|
||||
});
|
||||
|
||||
test('changing the purpose preserves private and project answers for later correction', () => {
|
||||
const next = replaceSimulationValue(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
legal_name: 'Empresa',
|
||||
email: 'a@b.co',
|
||||
project_title: 'Projecto',
|
||||
total_investment: '10',
|
||||
total_investment_label: '10',
|
||||
},
|
||||
'purpose',
|
||||
'simulate_only',
|
||||
);
|
||||
assert.deepEqual(next, {
|
||||
purpose: 'simulate_only',
|
||||
legal_name: 'Empresa',
|
||||
email: 'a@b.co',
|
||||
project_title: 'Projecto',
|
||||
total_investment: '10',
|
||||
total_investment_label: '10',
|
||||
});
|
||||
assert.equal(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes", base: "0", rate: "101", reduction: "0" }, "tax").rate,
|
||||
"O valor não pode exceder 100.");
|
||||
});
|
||||
|
||||
test("financial reconciliation reports a mismatch without inventing a fiscal value", () => {
|
||||
const errors = validateSimulationDraft({
|
||||
currency: "USD", total_investment: "100", own_capital: "20", domestic_debt: "20", foreign_debt: "20", grants: "20",
|
||||
}, "financial");
|
||||
test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_month: '04',
|
||||
fiscal_component: 'iva',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_operation: 'domestic',
|
||||
fiscal_establishments: '1',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
|
||||
});
|
||||
|
||||
test('custom planning mode requires user assumptions and validates percentage limits', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_component: 'iva',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_operation: 'domestic',
|
||||
fiscal_establishments: '1',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'custom_planning',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
|
||||
assert.deepEqual(validateCustomFiscalPlanning(base), {
|
||||
base: 'Este pressuposto é necessário para executar este cenário.',
|
||||
rate: 'Este pressuposto é necessário para executar este cenário.',
|
||||
reduction: 'Este pressuposto é necessário para executar este cenário.',
|
||||
});
|
||||
assert.deepEqual(
|
||||
validateSimulationDraft(
|
||||
{ ...base, fiscal_documentation: 'unknown' },
|
||||
'tax',
|
||||
),
|
||||
{},
|
||||
);
|
||||
const overLimit = {
|
||||
...base,
|
||||
fiscal_documentation: 'unknown',
|
||||
base: '0',
|
||||
rate: '101',
|
||||
reduction: '0',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(overLimit, 'tax'), {});
|
||||
assert.equal(
|
||||
validateCustomFiscalPlanning(overLimit).rate,
|
||||
'O valor não pode exceder 100.',
|
||||
);
|
||||
});
|
||||
|
||||
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),
|
||||
),
|
||||
true,
|
||||
);
|
||||
const ispcErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'quarterly',
|
||||
fiscal_component: 'ispc',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(ispcErrors.fiscal_activity, 'Este campo é obrigatório.');
|
||||
assert.equal(ispcErrors.fiscal_establishments, 'Este campo é obrigatório.');
|
||||
assert.equal(ispcErrors.fiscal_residency_assessment, undefined);
|
||||
const irpsErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'annual',
|
||||
fiscal_component: 'irps',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
irpsErrors.fiscal_residency_assessment,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
assert.equal(
|
||||
irpsErrors.fiscal_income_category,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
assert.deepEqual(simulationOptions.irps_salary_view, [
|
||||
'monthly_net_estimate',
|
||||
'monthly_withholding',
|
||||
'annual_assessment',
|
||||
]);
|
||||
const salaryViewErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_component: 'irps',
|
||||
fiscal_income_category: 'employment',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
salaryViewErrors.irps_salary_view,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
const customsErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_component: 'customs_ice',
|
||||
fiscal_operation: 'import',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
customsErrors.fiscal_customs_code,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
});
|
||||
|
||||
test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
|
||||
const errors = validateSimulationDraft(
|
||||
{
|
||||
currency: 'USD',
|
||||
total_investment: '100',
|
||||
own_capital: '20',
|
||||
domestic_debt: '20',
|
||||
foreign_debt: '20',
|
||||
grants: '20',
|
||||
},
|
||||
'financial',
|
||||
);
|
||||
assert.match(errors.total_investment, /corresponder ao investimento total/);
|
||||
assert.equal(validateSimulationDraft({}, "financial").currency, "Este campo é obrigatório.");
|
||||
assert.equal(
|
||||
validateSimulationDraft({}, 'financial').currency,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
});
|
||||
|
||||
test("autosave omits identity and contact fields from browser storage", () => {
|
||||
assert.deepEqual(getAutosaveSnapshot({
|
||||
total_investment: "50", legal_name: "Nome", email: "person@example.com", nuit: "123",
|
||||
project_title: "Projecto", legal_name_label: "Nome",
|
||||
}), { total_investment: "50", project_title: "Projecto" });
|
||||
test('autosave omits identity and contact fields from browser storage', () => {
|
||||
assert.deepEqual(
|
||||
getAutosaveSnapshot({
|
||||
total_investment: '50',
|
||||
legal_name: 'Nome',
|
||||
email: 'person@example.com',
|
||||
nuit: '123',
|
||||
project_title: 'Projecto',
|
||||
legal_name_label: 'Nome',
|
||||
}),
|
||||
{ total_investment: '50', project_title: 'Projecto' },
|
||||
);
|
||||
});
|
||||
|
||||
test("server draft snapshots split private identity from economic values", () => {
|
||||
assert.deepEqual(partitionSimulationDraft({ purpose: "simulate_only", legal_name: "Nome", base: "10", rate: "2", province_id_label: "Tete", person_type: "collective", person_type_label: "Pessoa colectiva" }), {
|
||||
personal_snapshot: { legal_name: "Nome", person_type: "collective", selection_labels: { person_type: "Pessoa colectiva" } },
|
||||
economic_snapshot: { purpose: "simulate_only", base: "10", rate: "2", selection_labels: { province_id: "Tete" } },
|
||||
});
|
||||
assert.deepEqual(restoreSimulationDraft({ activity_id: "uuid", infrastructure_needs: ["energia", "água"], selection_labels: { activity_id: "Energia", infrastructure_needs: ["Energia", "Água"] } }, {}), {
|
||||
activity_id: "uuid", activity_id_label: "Energia", infrastructure_needs: ["energia", "água"], infrastructure_needs_label: ["Energia", "Água"],
|
||||
});
|
||||
assert.equal(simulationDraftFingerprint({ base: "10", purpose: "simulate_only" }), simulationDraftFingerprint({ purpose: "simulate_only", base: "10" }));
|
||||
test('server draft snapshots split private identity from economic values', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft({
|
||||
journey_type: 'personal',
|
||||
detail_level: 'simple',
|
||||
purpose: 'simulate_only',
|
||||
legal_name: 'Nome',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
rate: '2',
|
||||
province_id_label: 'Tete',
|
||||
person_type: 'collective',
|
||||
person_type_label: 'Pessoa colectiva',
|
||||
}),
|
||||
{
|
||||
personal_snapshot: {
|
||||
legal_name: 'Nome',
|
||||
person_type: 'collective',
|
||||
selection_labels: { person_type: 'Pessoa colectiva' },
|
||||
},
|
||||
economic_snapshot: {
|
||||
journey_type: 'personal',
|
||||
detail_level: 'simple',
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
rate: '2',
|
||||
selection_labels: { province_id: 'Tete' },
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft({
|
||||
purpose: 'own_investment',
|
||||
business_plan_snapshot: '{"version":1}',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
}).economic_snapshot,
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
business_plan_snapshot: '{"version":1}',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
restoreSimulationDraft(
|
||||
{
|
||||
activity_id: 'uuid',
|
||||
infrastructure_needs: ['energia', 'água'],
|
||||
selection_labels: {
|
||||
activity_id: 'Energia',
|
||||
infrastructure_needs: ['Energia', 'Água'],
|
||||
},
|
||||
},
|
||||
{},
|
||||
),
|
||||
{
|
||||
activity_id: 'uuid',
|
||||
project_questionnaire_version: 'legacy-unversioned',
|
||||
activity_id_label: 'Energia',
|
||||
infrastructure_needs: ['energia', 'água'],
|
||||
infrastructure_needs_label: ['Energia', 'Água'],
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
simulationDraftFingerprint({ base: '10', purpose: 'simulate_only' }),
|
||||
simulationDraftFingerprint({ purpose: 'simulate_only', base: '10' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('anonymous server snapshots omit personal values and labels before transmission', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft(
|
||||
{
|
||||
legal_name: 'Nome',
|
||||
legal_name_label: 'Nome',
|
||||
email: 'person@example.com',
|
||||
fiscal_residency_country: 'mzn-country',
|
||||
fiscal_residency_country_label: 'Moçambique',
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
false,
|
||||
),
|
||||
{
|
||||
personal_snapshot: {},
|
||||
economic_snapshot: {
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
|
||||
const restored = restoreSimulationDraft(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
simulation_sources: [{ simulation_id: 'abc' }],
|
||||
base: '100',
|
||||
},
|
||||
{},
|
||||
);
|
||||
assert.equal(restored.base, '100');
|
||||
assert.equal('simulation_sources' in restored, false);
|
||||
assert.equal(
|
||||
'simulation_sources' in
|
||||
partitionSimulationDraft(restored).economic_snapshot,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
|
||||
const simulation = {
|
||||
id: '12345678-aaaa-bbbb-cccc-123456789abc',
|
||||
status: 'completed',
|
||||
version_no: 4,
|
||||
updated_at: '2026-10-02T10:00:00Z',
|
||||
legal_name: 'Pessoa Privada',
|
||||
email: 'private@example.com',
|
||||
reports: [
|
||||
{
|
||||
id: 'report-1',
|
||||
version_no: 3,
|
||||
status: 'ready',
|
||||
created_at: '2026-10-02T10:00:00Z',
|
||||
report_sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
result_snapshot: {
|
||||
base: '100000.00',
|
||||
rate_percent: '10',
|
||||
reduction_percent: '5',
|
||||
indicative_total: '9500.000000',
|
||||
currency: null,
|
||||
legal_interpretation: false,
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 3,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '9500.000000',
|
||||
unit: null,
|
||||
explanation: 'Resultado aritmético; sem conclusão fiscal.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
simulation.reports[0].report_snapshot = structuredClone(
|
||||
simulation.result_snapshot,
|
||||
);
|
||||
const csv = exportCompletedArithmeticCsv(
|
||||
simulation,
|
||||
'2026-10-02T11:00:00Z',
|
||||
);
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /Versão da execução,4/);
|
||||
assert.match(csv, /Versão do contrato,1/);
|
||||
assert.match(csv, /Data de referência,2026-10-02/);
|
||||
assert.match(csv, /ID do cenário,87654321-aaaa-bbbb-cccc-123456789abc/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Versão do motor,portal-tax-arithmetic-v1\+simulation-v1/,
|
||||
);
|
||||
assert.match(csv, /Estado do resultado,calculated/);
|
||||
assert.match(csv, /ID do relatório,report-1/);
|
||||
assert.match(csv, /Versão do relatório\/cenário,3/);
|
||||
assert.match(csv, /Hash SHA-256 do relatório,aaaaaaaa/);
|
||||
assert.match(csv, /Período,cenário aritmético pontual/);
|
||||
assert.match(csv, /IDs de fontes,nenhum/);
|
||||
assert.match(csv, /portal-tax-arithmetic-v1/);
|
||||
assert.match(csv, /Base introduzida,100000\.00/);
|
||||
assert.match(csv, /Resultado aritmético indicativo,9500\.000000/);
|
||||
assert.match(csv, /Moeda,não fornecida/);
|
||||
assert.match(csv, /Fontes legais,nenhuma associada/);
|
||||
assert.doesNotMatch(csv, /Pessoa Privada|private@example\.com/);
|
||||
assert.throws(
|
||||
() => exportCompletedArithmeticCsv({ status: 'running' }),
|
||||
/concluída/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: { base: 1 },
|
||||
}),
|
||||
/base/,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
|
||||
const snapshot = {
|
||||
contract_version: 1,
|
||||
context: { scenario_version: 4 },
|
||||
indicative_total: '12.50',
|
||||
};
|
||||
const simulation = {
|
||||
status: 'completed',
|
||||
result_snapshot: snapshot,
|
||||
reports: [
|
||||
{
|
||||
id: 'matching-report',
|
||||
status: 'ready',
|
||||
version_no: 4,
|
||||
report_snapshot: structuredClone(snapshot),
|
||||
report_sha256: 'b'.repeat(64),
|
||||
created_at: '2026-10-03T10:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
assert.deepEqual(readVersionedArithmeticReportReference(simulation), {
|
||||
id: 'matching-report',
|
||||
version_no: 4,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
created_at: '2026-10-03T10:00:00Z',
|
||||
});
|
||||
assert.equal(
|
||||
readVersionedArithmeticReportReference({
|
||||
...simulation,
|
||||
reports: [
|
||||
{
|
||||
...simulation.reports[0],
|
||||
report_snapshot: { ...snapshot, indicative_total: '99' },
|
||||
},
|
||||
],
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
readVersionedArithmeticReportReference({
|
||||
...simulation,
|
||||
reports: [{ ...simulation.reports[0], report_sha256: 'invalid' }],
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: {
|
||||
base: '10',
|
||||
rate_percent: '2',
|
||||
reduction_percent: '0',
|
||||
indicative_total: '0.2',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
engine_version:
|
||||
'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.3',
|
||||
explanation: 'Aritmética apenas.',
|
||||
},
|
||||
},
|
||||
}),
|
||||
/não reconcilia/,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '10.00',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 2,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v2',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '10.00',
|
||||
unit: null,
|
||||
explanation: 'Aritmética apenas.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
};
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: snapshot,
|
||||
reports: [
|
||||
{
|
||||
id: 'stale-report',
|
||||
status: 'ready',
|
||||
version_no: 1,
|
||||
report_sha256: 'a'.repeat(64),
|
||||
report_snapshot: structuredClone(snapshot),
|
||||
},
|
||||
],
|
||||
}),
|
||||
/nao corresponde a versao atual do resultado/,
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '0.20',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 3,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.20',
|
||||
unit: null,
|
||||
explanation: 'Aritmética apenas.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
};
|
||||
assert.equal(readArithmeticSnapshot(snapshot).integrity, 'versioned');
|
||||
assert.equal(readArithmeticSnapshot(snapshot).value, '0.20');
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({ indicative_total: '0.20' }).integrity,
|
||||
'legacy',
|
||||
);
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({
|
||||
...snapshot,
|
||||
result: { ...snapshot.result, value: '0.2' },
|
||||
}).integrity,
|
||||
'invalid',
|
||||
);
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({ ...snapshot, contract_version: 99 }).integrity,
|
||||
'invalid',
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result CSV neutralizes formula-like report metadata', () => {
|
||||
const csv = exportCompletedArithmeticCsv({
|
||||
id: '=HYPERLINK("https://example.invalid")',
|
||||
status: 'completed',
|
||||
version_no: 1,
|
||||
result_snapshot: {
|
||||
base: '10',
|
||||
rate_percent: '2',
|
||||
reduction_percent: '0',
|
||||
indicative_total: '0.2',
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
},
|
||||
});
|
||||
assert.match(
|
||||
csv,
|
||||
/ID da execução,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const homePage = readFileSync(
|
||||
new URL('../../resources/js/pages/PortalInvestidor.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const simulator = readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/simulation-form.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
test('portal home hero exposes a direct public simulator link', () => {
|
||||
const hero = homePage.slice(
|
||||
homePage.indexOf('function Hero('),
|
||||
homePage.indexOf('function SectorGrid('),
|
||||
);
|
||||
assert.match(hero, /href="\/simulador-fiscal"/);
|
||||
assert.match(hero, /Planear finanças/);
|
||||
});
|
||||
|
||||
test('completed simulator result keeps public interest submission independent', () => {
|
||||
assert.match(simulator, /href="\/manifestar-interesse"/);
|
||||
assert.match(
|
||||
simulator,
|
||||
/Manifestar interesse sem partilhar\s+esta simulação/,
|
||||
);
|
||||
assert.match(simulator, /sem\s+partilhar os dados desta simulação/);
|
||||
});
|
||||
Reference in New Issue
Block a user