Files
Investidor-V2/tests/frontend/integral-vat-treasury.test.mjs
T
Claude 3c7f6089d5 Fluxo de caixa: IVA das compras declaradas, deduzido na taxa geral e custo nas actividades a 5%
O investidor marca no IVA mensal quais categorias de compras têm factura
com IVA à taxa geral (mercadorias e custos variáveis, despesas
operacionais, aquisição de activos); por omissão nenhuma. O IVA pago aos
fornecedores entra no fluxo de caixa com cada pagamento.

Nas actividades à taxa geral é deduzido ao IVA das vendas na declaração
desse mês (CIVA, artigo 17(1)); se a dedução exceder o IVA facturado, o
crédito passa para os meses seguintes, sem reembolso presumido, e o
balanço mostra-o como crédito. Nas actividades à taxa reduzida do artigo
17-A não é dedutível (CIVA, artigo 20(2), Lei 22/2022, texto arquivado no
portal) e aparece como custo em Lucros e Perdas. O balanço continua
reconciliado e o resumo do dossier soma o IVA pago nas compras.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-05 07:19:56 +02:00

306 lines
11 KiB
JavaScript

import { financialReportFixture as plan } from './fixtures/integral-financial-plan.mjs';
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildIntegralFinancialTables } from '../../resources/js/lib/integral-financial-report.ts';
import { forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
const row = (tables, id, label) =>
tables.find((t) => t.id === id).rows.find((r) => r[0] === label);
const money = (value) => BigInt(value.replace('.', ''));
test('IVA enters the treasury: received with the sales collections, delivered the following month, balance still reconciled (decisão 04/12)', () => {
const input = plan(13);
const periods = 13;
const forecast = forecastBusinessPlan(input);
const billed = forecast.rows.map((r) => (money(r.revenue) * 16n) / 100n);
const vat = {
ratePercent: '16',
billedByMonth: billed,
source: 'Operação interna geral, CIVA art. 17',
};
const without = buildIntegralFinancialTables(input);
const withVat = buildIntegralFinancialTables(input, vat);
const received = row(withVat, 'cashflow', 'IVA recebido dos clientes');
const delivered = row(withVat, 'cashflow', 'IVA entregue ao Estado');
assert.ok(received && delivered);
assert.equal(
delivered[1],
'0.00',
'nothing is delivered in the first month',
);
assert.equal(
money(delivered[2]),
billed[0],
'month 1 IVA delivered in month 2',
);
// Received follows the sales actually collected, never the billing alone.
forecast.rows.forEach((r, i) => {
const salesCash =
money(r.cashCollections) - money(r.openingReceivablesCollections);
assert.equal(money(received[i + 1]), (salesCash * 16n + 50n) / 100n);
});
const cashWithout = row(without, 'cashflow', 'Caixa final');
const cashWith = row(withVat, 'cashflow', 'Caixa final');
let effect = 0n;
for (let i = 1; i <= periods; i++) {
effect += money(received[i]) - money(delivered[i]);
assert.equal(
money(cashWith[i]),
money(cashWithout[i]) + effect,
`month ${i}`,
);
}
const due = row(
withVat,
'balance',
'IVA a entregar ao Estado (crédito, se negativo)',
);
assert.equal(
money(due[periods]),
billed[periods - 1],
'the last month stays to deliver',
);
assert.deepEqual(
row(withVat, 'balance', 'Diferença do balanço'),
row(without, 'balance', 'Diferença do balanço'),
'the balance reconciles exactly as before',
);
assert.deepEqual(
row(withVat, 'profit-loss', 'Lucro líquido'),
row(without, 'profit-loss', 'Lucro líquido'),
'IVA is neither revenue nor cost',
);
assert.match(
withVat.find((t) => t.id === 'cashflow').notes.join(' '),
/32\(1\)\(b\)/,
);
assert.equal(
row(without, 'cashflow', 'IVA recebido dos clientes'),
undefined,
);
});
test('the treasury uses only a completed IVA result that still matches the sales; a stale or partial one is left out', async () => {
const { serializeBusinessPlanSnapshot } =
await import('../../resources/js/lib/business-financial-plan.ts');
const { monthlyIvaInput, integralVatFromDraft } =
await import('../../resources/js/lib/monthly-iva.ts');
const settings = {
start: '2026-01',
basis: 'net',
declared: true,
auto: true,
};
const value = plan(3);
const draft = {
currency: 'MZN',
business_plan_snapshot: serializeBusinessPlanSnapshot(value),
monthly_iva_settings: JSON.stringify(settings),
};
const input = monthlyIvaInput(draft, settings);
const record = (rows) =>
JSON.stringify({
input,
execution: {
id: '61000100-0000-4000-8000-000000000078',
status: 'completed',
version_no: 1,
result_snapshot: {
contract_version: 1,
scenario_kind: 'fiscal_rule_published',
base: null,
currency: 'MZN',
indicative_total: null,
legal_interpretation: false,
formula_version: 'investmoz.tax.v1',
context: {
reference_date: '2026-01-01',
currency: 'MZN',
currency_fraction_digits: 2,
scenario_id: '61000100-0000-4000-8000-000000000099',
scenario_version: 1,
engine_version: 'fiscal-published-v1',
ruleset_version: 'IVA-GERAL-BASE-LIQUIDA:1',
},
result: {
status: 'indeterminate',
value: null,
unit: 'MZN',
explanation: 'IVA mensal; não é imposto a pagar.',
missing_inputs: ['monthly_sales'],
source_ids: ['qa-source'],
},
presentation: { value: null, rounding_applied: false },
fiscal_provenance: {
rule: {
rule_code: 'IVA-GERAL-BASE-LIQUIDA',
rule_version: 1,
valid_from: '2023-01-01',
valid_until: null,
source: {
diploma: 'Fonte sintética QA',
article: 'Teste',
},
},
scope_status: 'user_declared',
},
monthly_projection: { input, rows },
},
},
});
const rows = input.monthly_sales.map((sale) => ({
date: sale.date,
sales_declared: sale.amount,
net_sales: sale.amount,
rate: '16',
vat: '160.0048',
gross_sales: null,
status: 'calculated',
}));
const vat = integralVatFromDraft({
...draft,
monthly_iva_snapshot: record(rows),
});
assert.equal(vat.ratePercent, '16');
assert.deepEqual(
vat.billedByMonth,
[16000n, 16000n, 16000n],
'rounded half up to the cent',
);
assert.equal(
integralVatFromDraft({
...draft,
monthly_iva_snapshot: record([
...rows.slice(0, 2),
{ ...rows[2], vat: null, rate: null },
]),
}),
null,
);
const changed = plan(3);
changed.products[0].unitPrice = '120';
assert.equal(
integralVatFromDraft({
...draft,
business_plan_snapshot: serializeBusinessPlanSnapshot(changed),
monthly_iva_snapshot: record(rows),
}),
null,
'a result for other sales is not used',
);
});
test('IVA on declared purchases: deducted for the general rate, a cost for activities at 5% (CIVA arts. 17(1) and 20(2)); the balance still reconciles', () => {
const input = plan(13);
input.monthlyVariableCostPayments = '200';
input.monthlyOperatingPayments = '100';
input.monthlyOperatingExpenses = '100';
const forecast = forecastBusinessPlan(input);
const billed = forecast.rows.map((r) => (money(r.revenue) * 16n) / 100n);
const base = {
ratePercent: '16',
billedByMonth: billed,
source: 'Operação interna geral',
purchases: { purchases: true, operating: false, assets: false },
};
const without = buildIntegralFinancialTables(input);
const general = buildIntegralFinancialTables(input, {
...base,
deductionAllowed: true,
});
const paid = row(general, 'cashflow', 'IVA pago nas compras');
forecast.rows.forEach((r, i) =>
assert.equal(
money(paid[i + 1]),
(money(r.variableCostPayments) * 16n + 50n) / 100n,
'only the declared category',
),
);
const delivered = row(general, 'cashflow', 'IVA entregue ao Estado');
assert.equal(
money(delivered[2]),
billed[0] - money(paid[1]),
'month 1 delivers sales IVA less the purchase IVA deducted',
);
assert.deepEqual(
row(general, 'profit-loss', 'Lucro líquido'),
row(without, 'profit-loss', 'Lucro líquido'),
'deductible IVA is neither revenue nor cost',
);
assert.deepEqual(
row(general, 'balance', 'Diferença do balanço'),
row(without, 'balance', 'Diferença do balanço'),
);
const reduced = buildIntegralFinancialTables(input, {
...base,
ratePercent: '5',
billedByMonth: forecast.rows.map((r) => (money(r.revenue) * 5n) / 100n),
deductionAllowed: false,
});
const notDeductible = row(
reduced,
'profit-loss',
'IVA não dedutível nas compras',
);
assert.ok(notDeductible, 'a cost for the 17-A activity');
const profitWith = row(reduced, 'profit-loss', 'Lucro líquido');
const profitWithout = row(without, 'profit-loss', 'Lucro líquido');
for (let i = 1; i <= 13; i++)
assert.equal(
money(profitWith[i]),
money(profitWithout[i]) - money(notDeductible[i]),
);
assert.equal(
money(row(reduced, 'cashflow', 'IVA entregue ao Estado')[2]),
(money(forecast.rows[0].revenue) * 5n) / 100n,
'nothing is deducted at the reduced rate',
);
assert.deepEqual(
row(reduced, 'balance', 'Diferença do balanço'),
row(without, 'balance', 'Diferença do balanço'),
);
assert.match(
reduced.find((t) => t.id === 'cashflow').notes.join(' '),
/20\(2\)/,
);
});
test('a deduction larger than the sales IVA becomes a credit carried forward, never a refund', () => {
const input = plan(13);
input.assetInvestment = '600';
const forecast = forecastBusinessPlan(input);
const billed = forecast.rows.map((r) => (money(r.revenue) * 16n) / 100n);
billed[0] = 0n;
const tables = buildIntegralFinancialTables(input, {
ratePercent: '16',
billedByMonth: billed,
source: 'Operação interna geral',
purchases: { purchases: false, operating: false, assets: true },
deductionAllowed: true,
});
const delivered = row(tables, 'cashflow', 'IVA entregue ao Estado');
assert.equal(
delivered[2],
'0.00',
'month 1 ends in credit: nothing delivered',
);
assert.equal(
money(delivered[3]),
billed[1] - (600n * 100n * 16n) / 100n,
'the credit reduces the next declaration',
);
assert.equal(
money(
row(
tables,
'balance',
'IVA a entregar ao Estado (crédito, se negativo)',
)[1],
),
-9600n,
);
});