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
This commit is contained in:
Claude
2026-12-05 07:19:56 +02:00
committed by nala
parent 1f1a6bf8ba
commit 3c7f6089d5
5 changed files with 267 additions and 10 deletions
@@ -253,6 +253,51 @@ export function SimulationMonthlyIva({
e o servidor usa a versão publicada correspondente.
</p>
</div>
<fieldset className="rounded border p-3 text-sm">
<legend className="px-1 font-medium">
Compras com factura de IVA à taxa geral (16%)
</legend>
<p>
Marque só as categorias em que os fornecedores facturam IVA.
Os valores do plano são sem IVA; o IVA pago entra no fluxo
de caixa.{' '}
{treatment.operation === 'internal_general_net'
? 'É deduzido ao IVA das vendas (CIVA, artigo 17(1)).'
: 'Nas actividades à taxa de 5% não é dedutível (CIVA, artigo 20(2)) e conta como custo.'}
</p>
{(
[
['purchases', 'Mercadorias e custos variáveis'],
['operating', 'Despesas operacionais'],
['assets', 'Aquisição de activos'],
] as const
).map(([key, label]) => (
<label key={key} className="mr-4 inline-flex gap-1">
<input
type="checkbox"
checked={settings.deductible?.[key] ?? false}
onChange={(event) =>
saveSettings({
deductible: {
purchases: false,
operating: false,
assets: false,
...settings.deductible,
[key]: event.target.checked,
},
})
}
/>
{label}
</label>
))}
<p className="text-slate-600">
Cada categoria é marcada por inteiro. Os salários não têm
IVA e há despesas isentas (por exemplo, seguros): marque
«Despesas operacionais» só se todas as despesas desse grupo
forem facturadas com IVA.
</p>
</fieldset>
<p>
Declare se os preços projectados são sem IVA ou com IVA
incluído.
+71 -8
View File
@@ -151,8 +151,20 @@ export type IntegralVat = {
ratePercent: string;
billedByMonth: bigint[];
source: string;
/**
* Purchase categories the investor declares as invoiced with IVA at the
* general rate (16%, CIVA artigo 17(1)). The IVA is paid to the supplier
* with each payment and deducted in the same month; for activities at the
* reduced rate of artigo 17-A it is not deductible (artigo 20(2), Lei
* 22/2022) and is a cost.
*/
purchases?: { purchases: boolean; operating: boolean; assets: boolean };
deductionAllowed?: boolean;
};
/** General rate charged by suppliers (CIVA artigo 17(1)), in hundredths of a percent. */
const supplierVatRate = 1600n;
export function buildIntegralFinancialTables(
plan: BusinessFinancialPlanInput,
vat: IntegralVat | null = null,
@@ -539,6 +551,10 @@ export function buildIntegralFinancialTables(
const vatRate = vat ? vatRateHundredths(vat.ratePercent) : 0n;
const vatReceived: bigint[] = [];
const vatDelivered: bigint[] = [];
const vatOnPurchases: bigint[] = [];
const vatNotDeductible: bigint[] = [];
let vatOwedForMonth = 0n,
vatCredit = 0n;
let depreciation = 0n,
cumulativeProfit = -startup,
principal = 0n;
@@ -581,7 +597,7 @@ export function buildIntegralFinancialTables(
a.manualCollectionsKind === 'other_income'
? cents(plan.monthlyCollections)
: 0n;
const profit =
let profit =
cents(row.profitBeforeTax) + otherIncome - taxExpenses[i];
// IVA: billed with each sale, received in proportion to the sales collected
// (opening receivables, refunds and other income excluded), delivered the next month.
@@ -594,13 +610,38 @@ export function buildIntegralFinancialTables(
otherIncome;
const received = vat ? percentOf(salesCash, vatRate) : 0n;
const billed = vat ? (vat.billedByMonth[i] ?? 0n) : 0n;
const delivered =
vat && i > 0 ? (vat.billedByMonth[i - 1] ?? 0n) : 0n;
// IVA paid to suppliers with the payments of the declared categories (invoice in the payment month).
const taxedPurchases =
(vat?.purchases?.purchases
? cents(row.variableCostPayments)
: 0n) +
(vat?.purchases?.operating
? cents(row.operatingPayments)
: 0n) +
(vat?.purchases?.assets
? cents(row.assetAcquisitions ?? '0') +
(i === 0 ? cents(plan.assetInvestment) : 0n)
: 0n);
const paidToSuppliers = percentOf(taxedPurchases, supplierVatRate);
const deductible = vat?.deductionAllowed ? paidToSuppliers : 0n;
const notDeductible = paidToSuppliers - deductible;
profit -= notDeductible;
// The declaration of month m is delivered in month m+1; a credit is carried to later months.
const delivered = vatOwedForMonth;
const owed = billed - deductible - vatCredit;
vatOwedForMonth = owed > 0n ? owed : 0n;
vatCredit = owed < 0n ? -owed : 0n;
vatReceived.push(received);
vatDelivered.push(delivered);
vatDue += billed - delivered;
vatOnPurchases.push(paidToSuppliers);
vatNotDeductible.push(notDeductible);
vatDue += billed - deductible - delivered;
const netCash =
cents(row.netCashFlow) - taxPayments[i] + received - delivered;
cents(row.netCashFlow) -
taxPayments[i] +
received -
delivered -
paidToSuppliers;
const opening = cash;
cash += netCash;
receivables +=
@@ -681,13 +722,14 @@ export function buildIntegralFinancialTables(
positive(-tradeObligations) +
interestAssets +
advance +
positive(-taxDue);
positive(-taxDue) +
positive(-vatDue);
const liabilities =
positive(-receivables) +
positive(tradeObligations) +
interestLiabilities +
positive(taxDue) +
vatDue +
positive(vatDue) +
loans +
subsequentBorrowings -
principal +
@@ -753,6 +795,12 @@ export function buildIntegralFinancialTables(
]
: []),
);
if (vatNotDeductible.some((value) => value !== 0n))
flows(
'profit-loss',
'IVA não dedutível nas compras',
vatNotDeductible,
);
flows('profit-loss', 'Imposto estimado', taxExpenses);
flows(
'profit-loss',
@@ -811,7 +859,15 @@ export function buildIntegralFinancialTables(
flows('cashflow', 'Pagamento fiscal estimado', taxPayments);
if (vat) {
flows('cashflow', 'IVA recebido dos clientes', vatReceived);
if (vatOnPurchases.some((value) => value !== 0n))
flows('cashflow', 'IVA pago nas compras', vatOnPurchases);
flows('cashflow', 'IVA entregue ao Estado', vatDelivered);
if (vatOnPurchases.some((value) => value !== 0n))
table('cashflow').notes.push(
vat.deductionAllowed
? 'IVA das compras declaradas com factura à taxa geral de 16% (CIVA, artigo 17(1)): pago ao fornecedor com cada pagamento e deduzido na declaração desse mês; quando a dedução excede o IVA facturado, o crédito passa para os meses seguintes, sem reembolso presumido.'
: 'IVA das compras à taxa geral de 16%: as actividades à taxa reduzida do artigo 17-A não o podem deduzir (CIVA, artigo 20(2), Lei 22/2022), pelo que é um custo do negócio, apresentado em Lucros e Perdas.',
);
table('cashflow').notes.push(
`IVA das vendas à taxa de ${vat.ratePercent.replace('.', ',')}% (${vat.source}): recebido com as cobranças das vendas e entregue ao Estado no mês seguinte ao da facturação, com a declaração periódica (CIVA, artigos 23(1) e 32(1)(b): até ao último dia do mês seguinte). Não inclui IVA dedutível nas compras; o IVA não é receita nem custo do negócio. O IVA facturado no último mês fica por entregar no balanço.`,
);
@@ -838,7 +894,14 @@ export function buildIntegralFinancialTables(
: 'Obrigações operacionais líquidas',
],
['taxDue', 'Saldo fiscal estimado'],
...(vat ? ([['vatDue', 'IVA a entregar ao Estado']] as const) : []),
...(vat
? ([
[
'vatDue',
'IVA a entregar ao Estado (crédito, se negativo)',
],
] as const)
: []),
['fixed', 'Activos fixos líquidos'],
['loans', 'Empréstimos e suprimentos por reembolsar'],
['paidCapital', 'Capital declarado e anterior'],
+31 -1
View File
@@ -28,6 +28,8 @@ export type MonthlyIvaSettings = {
basis: MonthlyIvaInput['sales_vat_basis'];
declared: boolean;
auto: boolean;
/** Purchase categories the investor declares as invoiced with IVA at the general rate. Absent: none. */
deductible?: { purchases: boolean; operating: boolean; assets: boolean };
};
export type MonthlyIvaRecord = {
input: MonthlyIvaInput;
@@ -42,7 +44,25 @@ export function readMonthlyIvaSettings(raw?: string): MonthlyIvaSettings {
typeof value.declared === 'boolean' &&
typeof value.auto === 'boolean'
)
return value;
return {
start: value.start,
basis: value.basis,
declared: value.declared,
auto: value.auto,
...(value.deductible &&
typeof value.deductible === 'object' &&
['purchases', 'operating', 'assets'].every(
(key) => typeof value.deductible[key] === 'boolean',
)
? {
deductible: {
purchases: value.deductible.purchases,
operating: value.deductible.operating,
assets: value.deductible.assets,
},
}
: {}),
};
} catch {
/* An invalid setting is not an invented business assumption. */
}
@@ -215,10 +235,20 @@ export function integralVatFromDraft(
const rate = rows[0].rate!;
if (rows.some((row) => row.rate !== rate)) return null;
const treatment = monthlyIvaTreatment(draft);
const settings = readMonthlyIvaSettings(
inputText(draft.monthly_iva_settings ?? ''),
);
return {
ratePercent: rate,
billedByMonth: rows.map((row) => centsHalfUp(row.vat!)),
source: `${treatment.label}, ${treatment.article}; versão publicada aplicada pelo servidor`,
purchases: settings.deductible ?? {
purchases: false,
operating: false,
assets: false,
},
// CIVA artigo 20(2), Lei 22/2022: no deduction for operations at the reduced rate of artigo 17-A.
deductionAllowed: treatment.operation === 'internal_general_net',
};
}
@@ -601,6 +601,9 @@ function makeSections(
'Pagamento de obrigações iniciais',
'Pagamento fiscal estimado',
...(vat ? ['IVA entregue ao Estado'] : []),
...(cell('cashflow', 'IVA pago nas compras')
? ['IVA pago nas compras']
: []),
]),
// With IVA in the treasury, collections include the IVA received from clients.
...(vat
+117 -1
View File
@@ -52,7 +52,11 @@ test('IVA enters the treasury: received with the sales collections, delivered th
`month ${i}`,
);
}
const due = row(withVat, 'balance', 'IVA a entregar ao Estado');
const due = row(
withVat,
'balance',
'IVA a entregar ao Estado (crédito, se negativo)',
);
assert.equal(
money(due[periods]),
billed[periods - 1],
@@ -187,3 +191,115 @@ test('the treasury uses only a completed IVA result that still matches the sales
'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,
);
});