import type { BusinessFinancialPlanInput } from './business-financial-plan.ts'; const money = (value: string | undefined, label: string) => { if (!value || !/^\d+(?:\.\d{1,2})?$/.test(value)) throw Error( `Indique ${label}, com até duas casas decimais; use zero apenas quando conhecido.`, ); const [a, b = ''] = value.split('.'); return BigInt(a) * 100n + BigInt(b.padEnd(2, '0')); }; const positive = (n: bigint) => (n > 0n ? n : 0n); export const startupAmount = (n: bigint) => `${n / 100n}.${String(n % 100n).padStart(2, '0')}`; /** Requirements are targets; the existing cash equation still uses available opening balances and declared financing. */ export function calculateStartupAssetRequirements( plan: BusinessFinancialPlanInput, ) { const target = plan.startupAssetRequirements; if (!target) throw Error('Indique as necessidades de caixa e activos do arranque.'); const cashRequired = money(target.cashRequired, 'a caixa requerida'); const currentRequired = money( target.otherCurrentAssetsRequired, 'os activos correntes requeridos', ); const fixedRequired = money( target.longTermAssetsRequired, 'os activos de longo prazo requeridos', ); const cashAvailable = money( plan.openingCash, 'a caixa disponível antes do financiamento', ); const currentAvailable = money( plan.reportAssumptions?.openingOtherAssets, 'os outros activos correntes disponíveis', ); const fixedAvailable = money( plan.reportAssumptions?.openingFixedAssets, 'os activos de longo prazo disponíveis', ); // Inventory and receivables are already initial uses in the approved engine, not acquisitions to count twice. const currentAlreadyPlanned = money(plan.inventory, 'as existências iniciais planeadas') + money(plan.receivables, 'os recebíveis iniciais planeados'); const currentAcquisition = positive( currentRequired - currentAvailable - currentAlreadyPlanned, ); const fixedAcquisition = positive(fixedRequired - fixedAvailable); const startupExpenses = ( plan.reportAssumptions?.startupExpenses ?? [] ).reduce((sum, r) => sum + money(r.amount, r.label), 0n); return { cashRequired, currentRequired, fixedRequired, cashAvailable, currentAvailable, fixedAvailable, currentAlreadyPlanned, currentAcquisition, fixedAcquisition, assetInvestment: currentAcquisition + fixedAcquisition, totalRequiredAssets: cashRequired + currentRequired + fixedRequired, grossRequirements: startupExpenses + cashRequired + currentRequired + fixedRequired, startupExpenses, }; } /** Usual start-up expenses of a new company (mapa de erros, ponto 4), offered as a starting list. */ export const startupExpenseCategories = [ 'Constituição da empresa e despesas legais', 'Mobiliário', 'Seguros', 'Rendas', 'Computadores e equipamento informático', 'Outras despesas de início de actividade', ] as const; /** Adds the usual categories that are still missing; existing rows and amounts are kept. */ export function withStartupExpenseCategories( rows: { label: string; amount: string }[], ): { label: string; amount: string }[] { const present = new Set(rows.map((row) => row.label.trim().toLowerCase())); return [ ...rows, ...startupExpenseCategories .filter((label) => !present.has(label.toLowerCase())) .map((label) => ({ label, amount: '' })), ]; } /** Total of the start-up expenses, or null while an amount is missing or invalid. */ export function startupExpensesTotal( rows: { label: string; amount: string }[], ): string | null { try { return startupAmount( rows.reduce( (sum, row) => sum + money(row.amount, 'o montante'), 0n, ), ); } catch { return null; } }