import fs from 'node:fs'; import { createHash } from 'node:crypto'; import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; /** Printed Portuguese monetary values, not JavaScript floating-point inputs. */ export function printedCents(value) { const text = value.trim(); if (!/^(?:-?\d+(?:\.\d{3})*(?:,\d{1,2})?|\(\d+(?:\.\d{3})*(?:,\d{1,2})?\))$/.test(text)) throw new Error(`Montante impresso não reconhecido: ${text}`); const negative = text.startsWith('(') || text.startsWith('-'); const [whole, fraction = ''] = text.replace(/[().-]/g, '').split(','); const amount = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0')); return negative ? -amount : amount; } const decimal = value => `${value < 0n ? '-' : ''}${(value < 0n ? -value : value) / 100n}.${String((value < 0n ? -value : value) % 100n).padStart(2, '0')}`; const sum = values => values.reduce((total, value) => total + value, 0n); export function financialTable(text, title, occurrence, width) { const lines = text.normalize('NFC').split(/\r?\n/); const starts = lines.flatMap((line, index) => line.trim() === title ? [index] : []); const start = occurrence === 'last' ? starts.at(-1) : starts[occurrence]; if (start === undefined) throw new Error(`Tabela em falta: ${title}`); let end = lines.findIndex((line, index) => index > start && (line.trim().startsWith('Tabela:') || /^\d+\.\d+\s/.test(line.trim()))); if (end < 0) end = lines.length; const rows = []; for (let index = start + 1; index < end; index++) { const cells = lines[index].split('\t').map(cell => cell.trim()); const numbers = cells.slice(1).filter(cell => /^\(?-?\d[\d.,]*\)?$/.test(cell)); if (numbers.length >= width) rows.push({ label: cells[0], line: index + 1, values: numbers.slice(-width).map(printedCents), printed: numbers.slice(-width), rates: cells.slice(1).filter(cell => cell.endsWith('%')) }); } return rows; } function row(table, label, occurrence = 0) { const record = table.filter(entry => entry.label === label)[occurrence]; if (!record) throw new Error(`Rubrica em falta: ${label}`); return record; } function check(id, reported, calculated, references) { return { id, reported: decimal(reported), calculated: decimal(calculated), difference: decimal(calculated - reported), matches: calculated === reported, references }; } export function financialReferenceTables(text) { return [ { key: 'annualSales', title: 'Tabela: Previsão de Vendas', occurrence: 0, width: 3 }, { key: 'monthlySales', title: 'Tabela: Previsão de Vendas', occurrence: 'last', width: 12 }, { key: 'annualProfit', title: 'Tabela: Lucros e Perdas', occurrence: 0, width: 3 }, { key: 'monthlyProfit', title: 'Tabela: Lucros e Perdas', occurrence: 'last', width: 12 }, { key: 'annualCash', title: 'Tabela: Fluxo de Caixa', occurrence: 0, width: 3 }, { key: 'monthlyCash', title: 'Tabela: Fluxo de Caixa', occurrence: 'last', width: 12 }, { key: 'annualBalance', title: 'Tabela: Balanço', occurrence: 0, width: 3 }, { key: 'monthlyBalance', title: 'Tabela: Balanço', occurrence: 'last', width: 13 }, ].map(specification => ({ ...specification, rows: financialTable(text, specification.title, specification.occurrence, specification.width) })); } export function reconcileFinancialReference(text) { const { annualSales, monthlySales, annualProfit, monthlyProfit, annualCash, monthlyCash, annualBalance, monthlyBalance } = Object.fromEntries(financialReferenceTables(text).map(table => [table.key, table.rows])); const checks = []; const compare = (id, annualTable, annualLabel, monthlyTable, monthlyLabel, occurrence = 0) => { const annual = row(annualTable, annualLabel), monthly = row(monthlyTable, monthlyLabel, occurrence); checks.push(check(id, annual.values[0], sum(monthly.values), [annual.line, monthly.line])); }; compare('sales.months_to_2025', annualProfit, 'Vendas', monthlyProfit, 'Vendas'); compare('direct_costs.months_to_2025', annualProfit, 'Custo Direto das Vendas', monthlyProfit, 'Custo Direto das Vendas'); compare('gross_margin.months_to_2025', annualProfit, 'Margem bruta', monthlyProfit, 'Margem bruta'); compare('payroll.months_to_2025', annualProfit, 'Folha de pagamento', monthlyProfit, 'Folha de pagamento'); compare('payroll_charges.printed_months_to_2025', annualProfit, 'Impostos sobre Folhas de Pagamento', monthlyProfit, 'Impostos sobre Folhas de Pagamento'); compare('operating_expenses.printed_months_to_2025', annualProfit, 'Despesas Operacionais Totais', monthlyProfit, 'Despesas Operacionais Totais'); compare('net_profit.printed_months_to_2025', annualProfit, 'Lucro Líquido', monthlyProfit, 'Lucro Líquido'); for (const [annualLabel, monthlyLabel] of [ ['Vendas em Dinheiro', 'Vendas em Dinheiro'], ['Caixa proveniente de contas a receber', 'Caixa proveniente de contas a receber'], ['Subtotal de Caixa Proveniente das Operações', 'Subtotal de Caixa Proveniente das Operações'], ['Imposto sobre vendas, IVA, HST/GST recebidos', 'Imposto sobre vendas, IVA, HST/GST recebidos'], ['Pagamentos de Contas', 'Pagamentos de Contas'], ['Subtotal gasto em operações', 'Subtotal gasto em operações'], ['Imposto sobre vendas, IVA, HST/GST pagos', 'Imposto sobre vendas, IVA, HST/GST pagos'], ['Subtotal de Dinheiro Gasto', 'Subtotal de Dinheiro Gasto'], ['Fluxo de Caixa Líquido', 'Fluxo de Caixa Líquido'], ]) compare(`cash.${annualLabel}`, annualCash, annualLabel, monthlyCash, monthlyLabel); const labels = ['Publicidade', 'Intermediação Comercial', 'Comercialização de Commodities', 'Formação']; const totals = row(annualSales, 'Vendas Totais'); const directTotals = row(annualSales, 'Subtotal Direct Cost of Sales'); for (let year = 0; year < 3; year++) { checks.push(check(`sales.listed_lines.${2025 + year}`, totals.values[year], sum(labels.map(label => row(annualSales, label).values[year])), [totals.line, ...labels.map(label => row(annualSales, label).line)])); const costRows = labels.map(label => row(annualSales, label, 1)).concat(row(annualSales, 'Marketing')); checks.push(check(`costs.listed_lines.${2025 + year}`, directTotals.values[year], sum(costRows.map(entry => entry.values[year])), [directTotals.line, ...costRows.map(entry => entry.line)])); } for (const label of labels) { compare(`sales.line.${label}`, annualSales, label, monthlySales, label); const annual = row(annualSales, label, 1), monthly = row(monthlySales, label, 1); checks.push(check(`costs.line.${label}`, annual.values[0], sum(monthly.values), [annual.line, monthly.line])); } const cashReceived = row(annualCash, 'Subtotal de Dinheiro Recebido'); const cashSpent = row(annualCash, 'Subtotal de Dinheiro Gasto'); const operatingPaid = row(annualCash, 'Subtotal gasto em operações'); const vatPaid = row(annualCash, 'Imposto sobre vendas, IVA, HST/GST pagos'); const initialCash = row(monthlyBalance, 'Dinheiro').values[0]; const nonCashAssets = row(annualBalance, 'Contas a receber').values[0] + row(annualBalance, 'Outros ativos correntes').values[0] + row(annualBalance, 'Total de Activos a Longo Prazo').values[0]; const capital = row(annualBalance, 'Total Capital').values[0]; const liabilities = row(annualBalance, 'Total de Passivos').values[0]; const assets = row(annualBalance, 'Total de Activos').values[0]; const componentCashSpent = operatingPaid.values[0] + vatPaid.values[0]; checks.push(check('cash.2025_spending_components', cashSpent.values[0], componentCashSpent, [cashSpent.line, operatingPaid.line, vatPaid.line])); checks.push(check('balance.2025_assets_vs_liabilities_capital', liabilities + capital, assets, [row(annualBalance, 'Total de Activos').line, row(annualBalance, 'Total de Passivos').line, row(annualBalance, 'Total Capital').line])); const balanceMonths = []; const cashRow = row(monthlyBalance, 'Dinheiro'), arRow = row(monthlyBalance, 'Contas a receber'), otherRow = row(monthlyBalance, 'Outros Activos correntes'), fixedRow = row(monthlyBalance, 'Total de Activos a Longo Prazo'), liabilityRow = row(monthlyBalance, 'Total de Passivos'), capitalRow = row(monthlyBalance, 'Total Capital'), assetRow = row(monthlyBalance, 'Total de Activos'); for (let month = 1; month <= 12; month++) { const computedAssets = cashRow.values[month] + arRow.values[month] + otherRow.values[month] + fixedRow.values[month]; const computedFunds = liabilityRow.values[month] + capitalRow.values[month]; balanceMonths.push({ month, printedAssets: decimal(assetRow.values[month]), componentAssets: decimal(computedAssets), componentLiabilitiesCapital: decimal(computedFunds), componentDifference: decimal(computedAssets - computedFunds) }); } const payroll = row(monthlyProfit, 'Folha de pagamento'), charges = row(monthlyProfit, 'Impostos sobre Folhas de Pagamento'); if (charges.rates.length !== 1) throw new Error('Taxa de referência da folha não identificada univocamente'); const basisPoints = printedCents(charges.rates[0].slice(0, -1)); const exactCharges = payroll.values.map(value => { const product = value * basisPoints; if (product % 10000n !== 0n) throw new Error('Precisão adicional necessária para os encargos da folha'); return product / 10000n; }); const otherExpenses = ['Marketing/Promoção', 'Depreciação', 'Aluguer', 'Serviços públicos', 'Seguros', 'Outros'].map(label => row(monthlyProfit, label)); const interest = row(monthlyProfit, 'Despesa com juros'), taxes = row(monthlyProfit, 'Impostos Incorridos'); const exactOperating = payroll.values.map((value, index) => value + exactCharges[index] + sum(otherExpenses.map(entry => entry.values[index]))); const gross = row(monthlyProfit, 'Margem bruta').values; const exactNetProfit = gross.map((value, index) => value - exactOperating[index] - interest.values[index] - taxes.values[index]); const payrollRecomposition = { scope: 'reference_arithmetic_only_not_a_fiscal_rule', rate: charges.rates[0], monthlyCharges: exactCharges.map(decimal), monthlyOperating: exactOperating.map(decimal), monthlyNetProfit: exactNetProfit.map(decimal), chargesAnnualCheck: check('payroll_charges.cent_recomposition', row(annualProfit, 'Impostos sobre Folhas de Pagamento').values[0], sum(exactCharges), [charges.line, payroll.line]), operatingAnnualCheck: check('operating_expenses.cent_recomposition', row(annualProfit, 'Despesas Operacionais Totais').values[0], sum(exactOperating), [charges.line, payroll.line]), profitAnnualCheck: check('net_profit.cent_recomposition', row(annualProfit, 'Lucro Líquido').values[0], sum(exactNetProfit), [charges.line, payroll.line, row(monthlyProfit, 'Margem bruta').line]), }; return { status: 'BLOCKED_SOURCE_PRECISION_OR_COMPLETENESS', annualTotalsChanged: false, applicationFormulasChanged: false, checks, balanceMonths, payrollRecomposition, oneUnitTrace: { approvedCashSpent: decimal(cashSpent.values[0]), componentCashSpent: decimal(componentCashSpent), approvedClosingCash: decimal(initialCash + cashReceived.values[0] - cashSpent.values[0]), componentOnlyClosingCash: decimal(initialCash + cashReceived.values[0] - componentCashSpent), approvedAssets: decimal(assets), componentOnlyAssets: decimal(initialCash + cashReceived.values[0] - componentCashSpent + nonCashAssets), liabilitiesAndCapital: decimal(liabilities + capital), componentOnlyIsDiagnosticNotCorrection: true, }, ambiguousCashLabel: monthlyCash.filter(entry => entry.label === 'Novo Investimento Recebido').map(entry => ({ line: entry.line, sum: decimal(sum(entry.values)), printed: entry.printed })), missing: ['Valores monetários de origem sem arredondamento por mês e por rubrica', 'Regras do programa de origem: arredondamento de apresentação versus cálculo e momento do arredondamento', 'Linhas de vendas e custos omitidas ou uma versão completa que explique os subtotais', 'Identificação correcta da segunda linha Novo Investimento Recebido no fluxo mensal'], }; } if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { try { if (!process.argv[2]) throw new Error('Indique o caminho do texto financeiro fornecido.'); const source = fs.readFileSync(process.argv[2]); const report = { sourceSha256: createHash('sha256').update(source).digest('hex'), ...reconcileFinancialReference(source.toString('utf8')) }; const output = JSON.stringify(report, null, 2) + '\n'; if (process.argv[3]) { if (resolve(process.argv[3]) === resolve(process.argv[2])) throw new Error('O diagnóstico não pode sobrescrever a fonte.'); fs.writeFileSync(process.argv[3], output); } else process.stdout.write(output); process.exitCode = 2; } catch (error) { process.stderr.write(`${error.message}\n`); process.exitCode = 1; } }