diff --git a/resources/js/components/integral-financial-plan.tsx b/resources/js/components/integral-financial-plan.tsx index f85ff7b1..3bb56899 100644 --- a/resources/js/components/integral-financial-plan.tsx +++ b/resources/js/components/integral-financial-plan.tsx @@ -7,6 +7,7 @@ import { import type { BusinessFinancialPlanInput } from '@/lib/business-financial-plan'; import { buildIntegralFinancialTables, + type IntegralVat, newReportAssumptions, isReportAssumptions, } from '@/lib/integral-financial-report'; @@ -24,9 +25,12 @@ import { useState } from 'react'; export function IntegralFinancialPlan({ plan, onChange, + vat = null, }: { plan: BusinessFinancialPlanInput; onChange: (plan: BusinessFinancialPlanInput) => void; + /** IVA of the sales from the published version, when current; included in the treasury. */ + vat?: IntegralVat | null; }) { if (plan.reportSource === 'annual_example') { return ( @@ -324,13 +328,18 @@ export function IntegralFinancialPlan({ ))} +

+ {vat + ? `O fluxo de caixa inclui o IVA das vendas à taxa de ${vat.ratePercent.replace('.', ',')}% da actividade: recebido com as cobranças e entregue ao Estado no mês seguinte.` + : 'O IVA ainda não está incluído no fluxo de caixa: calcule o «IVA mensal das vendas projectadas» com as vendas actuais (preços sem IVA).'} +

diff --git a/resources/js/components/simulation-business-plan.tsx b/resources/js/components/simulation-business-plan.tsx index a2256330..d7a1fb26 100644 --- a/resources/js/components/simulation-business-plan.tsx +++ b/resources/js/components/simulation-business-plan.tsx @@ -1,6 +1,7 @@ import { DecimalInput } from '@/components/decimal-input'; import { presentDecimal } from '@/lib/decimal-input'; import { productUnitMargin } from '@/lib/product-margin'; +import type { IntegralVat } from '@/lib/integral-financial-report'; import { WarningLimitsEditor } from './warning-limits-editor'; import { SupplierAdvancesEditor } from '@/components/supplier-advances'; import { PeriodInvestmentsEditor } from '@/components/period-investments'; @@ -168,11 +169,13 @@ export function SimulationBusinessPlan({ snapshot, onCurrencyChange, onSnapshotChange, + vat = null, }: { currency: string; snapshot?: string; onCurrencyChange: (value: string) => void; onSnapshotChange: (snapshot: string) => void; + vat?: IntegralVat | null; }) { const hasOversizedStoredSnapshot = typeof snapshot === 'string' && @@ -969,7 +972,7 @@ export function SimulationBusinessPlan({ !forecastErrorShownInReport(plan, startupErrorMessage(plan)) } /> - +
diff --git a/resources/js/components/simulation-form.tsx b/resources/js/components/simulation-form.tsx index a7833de8..7ca36410 100644 --- a/resources/js/components/simulation-form.tsx +++ b/resources/js/components/simulation-form.tsx @@ -1,6 +1,7 @@ import { DecimalInput } from '@/components/decimal-input'; import { focusCorrectionId } from '@/lib/field-corrections'; import { adoptTeamPayroll } from '@/lib/complementary-report'; +import { integralVatFromDraft } from '@/lib/monthly-iva'; import FiscalOperationPicker from './fiscal-operation-picker'; import { SimulationIrpcAnnual } from '@/components/simulation-irpc-annual'; import DemographicContext from '@/components/demographic-context'; @@ -3958,6 +3959,7 @@ export function SimulationForm() { onSnapshotChange={(value) => change('business_plan_snapshot', value) } + vat={integralVatFromDraft(draft)} /> )} @@ -4303,6 +4305,7 @@ export function SimulationForm() { onSnapshotChange={(value) => change('business_plan_snapshot', value) } + vat={integralVatFromDraft(draft)} /> )} {current.id === 'review' && @@ -4547,6 +4550,7 @@ export function SimulationForm() { onSnapshotChange={(value) => change('business_plan_snapshot', value) } + vat={integralVatFromDraft(draft)} /> )} diff --git a/resources/js/lib/integral-financial-report.ts b/resources/js/lib/integral-financial-report.ts index 7eb4eba8..c2268bbb 100644 --- a/resources/js/lib/integral-financial-report.ts +++ b/resources/js/lib/integral-financial-report.ts @@ -71,6 +71,20 @@ export const displayReportMoney = (value: string) => { return `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')},${fraction}`; }; const positive = (value: bigint) => (value > 0n ? value : 0n); +/** «16» or «5» as hundredths of a percent. */ +const vatRateHundredths = (rate: string) => { + const [whole, fraction = ''] = rate.trim().split('.'); + if (!/^\d+$/.test(whole) || !/^\d{0,2}$/.test(fraction)) + throw new Error('Taxa de IVA inválida no resultado publicado.'); + return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0')); +}; +/** amount × rate, half up to the cent (amount in cents, rate in hundredths of a percent). */ +const percentOf = (amount: bigint, rate: bigint) => { + const scaled = amount * rate; + const sign = scaled < 0n ? -1n : 1n; + const abs = scaled * sign; + return (sign * (abs + 5000n)) / 10000n; +}; export function newReportAssumptions( periods: number, ): NonNullable { @@ -127,8 +141,21 @@ export function isReportAssumptions( } /** Read only declared investor inputs. The synthetic annual example is never used. */ +/** + * IVA of the plan's sales, as calculated by the published IVA version for the + * plan's activity (16% or 5%): billed per month, in cents. When present it is + * included in the treasury: received with the sales collections and delivered + * to the State in the following month (CIVA, arts. 23(1) and 32(1)(b)). + */ +export type IntegralVat = { + ratePercent: string; + billedByMonth: bigint[]; + source: string; +}; + export function buildIntegralFinancialTables( plan: BusinessFinancialPlanInput, + vat: IntegralVat | null = null, ): InvestmentReportTable[] { const titles = [ ['startup', 'Start-up / arranque'], @@ -507,7 +534,11 @@ export function buildIntegralFinancialTables( let cash = cents(result.openingCashAfterInitialUses) - startup; let receivables = cents(plan.receivables), obligations = cents(plan.payables), - taxDue = 0n; + taxDue = 0n, + vatDue = 0n; + const vatRate = vat ? vatRateHundredths(vat.ratePercent) : 0n; + const vatReceived: bigint[] = []; + const vatDelivered: bigint[] = []; let depreciation = 0n, cumulativeProfit = -startup, principal = 0n; @@ -552,13 +583,32 @@ export function buildIntegralFinancialTables( : 0n; const profit = cents(row.profitBeforeTax) + otherIncome - taxExpenses[i]; - const netCash = cents(row.netCashFlow) - taxPayments[i]; + // IVA: billed with each sale, received in proportion to the sales collected + // (opening receivables, refunds and other income excluded), delivered the next month. + const salesCash = + cents(row.cashCollections) - + cents(row.openingReceivablesCollections ?? '0') - + cents( + result.supplierAdvanceLedger?.monthly[i].refunded ?? '0', + ) - + 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; + vatReceived.push(received); + vatDelivered.push(delivered); + vatDue += billed - delivered; + const netCash = + cents(row.netCashFlow) - taxPayments[i] + received - delivered; const opening = cash; cash += netCash; receivables += cents(row.revenue) - cents(row.cashCollections) + otherIncome + + billed - + received + cents(result.supplierAdvanceLedger?.monthly[i].refunded ?? '0'); const purchases = row.inventoryReceipts === null @@ -637,6 +687,7 @@ export function buildIntegralFinancialTables( positive(tradeObligations) + interestLiabilities + positive(taxDue) + + vatDue + loans + subsequentBorrowings - principal + @@ -650,6 +701,7 @@ export function buildIntegralFinancialTables( obligations: obligationsKnown ? tradeObligations : null, advance, taxDue, + vatDue, profit, netCash, assets: inventory === null || !obligationsKnown ? null : assets, @@ -757,6 +809,13 @@ export function buildIntegralFinancialTables( ] as const) flows('cashflow', label, data(key)); flows('cashflow', 'Pagamento fiscal estimado', taxPayments); + if (vat) { + flows('cashflow', 'IVA recebido dos clientes', vatReceived); + flows('cashflow', 'IVA entregue ao Estado', vatDelivered); + 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.`, + ); + } if (plan.dividendsByPeriod) flows('cashflow', 'Dividendos distribuídos', data('dividends')); flows( @@ -779,6 +838,7 @@ export function buildIntegralFinancialTables( : 'Obrigações operacionais líquidas', ], ['taxDue', 'Saldo fiscal estimado'], + ...(vat ? ([['vatDue', 'IVA a entregar ao Estado']] as const) : []), ['fixed', 'Activos fixos líquidos'], ['loans', 'Empréstimos e suprimentos por reembolsar'], ['paidCapital', 'Capital declarado e anterior'], diff --git a/resources/js/lib/monthly-iva.ts b/resources/js/lib/monthly-iva.ts index b5120d37..9e67fbf7 100644 --- a/resources/js/lib/monthly-iva.ts +++ b/resources/js/lib/monthly-iva.ts @@ -1,5 +1,6 @@ import { inputText } from './input-text.ts'; import { ivaTreatmentForCae } from './iva-activity.ts'; +import type { IntegralVat } from './integral-financial-report.ts'; import { monthlyProjectedSales, restoreBusinessPlanSnapshot, @@ -180,4 +181,50 @@ export async function recoverMonthlyIvaRecord( return { input: record.input, execution: value.data }; } export const monthlyIvaCashTreatment = - 'IVA apresentado separadamente: não é somado novamente aos recebimentos declarados nem deduzido como custo ou imposto final a pagar. A tesouraria conserva os recebimentos e pagamentos introduzidos, antes de uma liquidação fiscal não apurada; não se presume cobrança integral das vendas no mesmo mês.'; + 'IVA apresentado em linhas próprias: não é somado novamente aos recebimentos declarados nem deduzido como custo. No relatório financeiro integral, o IVA recebido com as cobranças das vendas e o IVA entregue ao Estado no mês seguinte (CIVA, artigos 23(1) e 32(1)(b)) entram na tesouraria; não se presume cobrança integral das vendas no mesmo mês.'; + +/** + * The IVA of the plan's sales for the treasury: only from a completed result + * that still matches the current sales, activity and basis, with every month + * determined. Otherwise null, and the treasury says the IVA is not included. + */ +export function integralVatFromDraft( + draft: Record, +): IntegralVat | null { + const record = readMonthlyIvaRecord( + inputText(draft.monthly_iva_snapshot ?? ''), + ); + if (!record || record.execution.status !== 'completed') return null; + let input: MonthlyIvaInput; + try { + input = monthlyIvaInput( + draft, + readMonthlyIvaSettings(inputText(draft.monthly_iva_settings ?? '')), + ); + } catch { + return null; + } + if (monthlyIvaKey(record.input) !== monthlyIvaKey(input)) return null; + const rows = ( + record.execution.result_snapshot?.monthly_projection as + | { rows?: { vat: string | null; rate: string | null }[] } + | undefined + )?.rows; + if (!rows?.length || rows.some((row) => row.vat === null || !row.rate)) + return null; + const rate = rows[0].rate!; + if (rows.some((row) => row.rate !== rate)) return null; + const treatment = monthlyIvaTreatment(draft); + return { + ratePercent: rate, + billedByMonth: rows.map((row) => centsHalfUp(row.vat!)), + source: `${treatment.label}, ${treatment.article}; versão publicada aplicada pelo servidor`, + }; +} + +/** A non-negative decimal with up to 4 places, rounded half up to cents. */ +function centsHalfUp(value: string): bigint { + const [whole, fraction = ''] = value.split('.'); + const digits = BigInt(whole + fraction.padEnd(4, '0').slice(0, 4)); + return (digits + 50n) / 100n; +} diff --git a/resources/js/lib/project-dossier-report.ts b/resources/js/lib/project-dossier-report.ts index 4ddc8e76..f0dc9a93 100644 --- a/resources/js/lib/project-dossier-report.ts +++ b/resources/js/lib/project-dossier-report.ts @@ -10,6 +10,7 @@ import { } from './integral-financial-report.ts'; import { restoreBusinessPlanSnapshot } from './business-financial-plan.ts'; import { fiscalQaRows } from './fiscal-qa-preview.ts'; +import { integralVatFromDraft } from './monthly-iva.ts'; import { financialPlanWarnings } from './financial-plan-warnings.ts'; import { pathStates } from './investor-path.ts'; import { financialIssuesForDisplay } from './financial-issue-presentation.ts'; @@ -546,12 +547,13 @@ function makeSections( const section = sections.get(id as DossierReportSectionId); if (section) section.tables = [complementaryTables[i]]; } + const vat = integralVatFromDraft(draft); if ( finance && financialPlan?.reportAssumptions && financialPlan.reportSource !== 'annual_example' ) { - finance.tables = buildIntegralFinancialTables(financialPlan); + finance.tables = buildIntegralFinancialTables(financialPlan, vat); finance.paragraphs.push( ...financialPlanWarnings(financialPlan, finance.tables).map( (w) => `Aviso não bloqueante — ${w.message}`, @@ -598,7 +600,17 @@ function makeSections( : []), 'Pagamento de obrigações iniciais', 'Pagamento fiscal estimado', + ...(vat ? ['IVA entregue ao Estado'] : []), ]), + // With IVA in the treasury, collections include the IVA received from clients. + ...(vat + ? { + 'Cobranças no horizonte': sumRows('cashflow', [ + 'Recebimentos', + 'IVA recebido dos clientes', + ]), + } + : {}), 'Resultado antes de impostos': sumRows('profit-loss', [ 'Lucro líquido', 'Imposto estimado', @@ -1011,12 +1023,16 @@ export function createInvestorDecisionReport( keep: (header: string, index: number) => boolean, ): InvestmentReportTable => { const kept = table.headers - .map((header, index) => (index === 0 || keep(header, index) ? index : -1)) + .map((header, index) => + index === 0 || keep(header, index) ? index : -1, + ) .filter((index) => index >= 0); return { ...table, headers: kept.map((index) => table.headers[index]), - rows: table.rows.map((row) => kept.map((index) => row[index] ?? '')), + rows: table.rows.map((row) => + kept.map((index) => row[index] ?? ''), + ), }; }; const yearly = (table: InvestmentReportTable) => @@ -1093,7 +1109,10 @@ export function createInvestorDecisionReport( ...(said('project_summary') ? [said('project_summary')] : []), ...labelled('Objectivos', investorReportFields.objectives), ...labelled('Missão', investorReportFields.mission), - ...labelled('Chaves para o sucesso', investorReportFields.successKeys), + ...labelled( + 'Chaves para o sucesso', + investorReportFields.successKeys, + ), ]), chapter( '2. Resumo da Startup', diff --git a/tests/frontend/integral-vat-treasury.test.mjs b/tests/frontend/integral-vat-treasury.test.mjs new file mode 100644 index 00000000..bbc18fcc --- /dev/null +++ b/tests/frontend/integral-vat-treasury.test.mjs @@ -0,0 +1,189 @@ +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'); + 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', + ); +});