import { inputText } from './input-text.ts'; import { ivaTreatmentForCae } from './iva-activity.ts'; import type { IntegralVat } from './integral-financial-report.ts'; import { monthlyProjectedSales, restoreBusinessPlanSnapshot, } from './business-financial-plan.ts'; import { cashflowCurrency, restoreCashflowDraftSnapshot, } from './monthly-cashflow.ts'; import { isApiSimulationReadResponseV1, type ApiSimulationExecutionV1, } from './simulation-contract.ts'; export type MonthlyIvaInput = { scenario_kind: 'fiscal_rule_published'; monthly_sales: Array<{ date: string; amount: string | null }>; sales_vat_basis: 'net' | 'included' | 'unknown'; currency: string; scope_declared: boolean; /** Present only for the reduced rate of artigo 17-A; absent means the general rate. */ operation?: 'internal_reduced_17a_net'; }; export type MonthlyIvaSettings = { start: string; 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; execution: ApiSimulationExecutionV1; }; export function readMonthlyIvaSettings(raw?: string): MonthlyIvaSettings { try { const value = JSON.parse(raw ?? ''); if ( typeof value.start === 'string' && ['net', 'included', 'unknown'].includes(value.basis) && typeof value.declared === 'boolean' && typeof value.auto === 'boolean' ) 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. */ } return { start: '', basis: 'unknown', declared: false, auto: false }; } export function monthlySalesFromDraft(draft: Record): { amounts: Array; source: string; } { if (draft.business_plan_snapshot) { const plan = restoreBusinessPlanSnapshot( inputText(draft.business_plan_snapshot), ); if (!plan) throw new Error( 'Não foi possível recuperar a projecção de vendas. Os dados guardados não foram substituídos.', ); if (draft.currency && plan.currency && draft.currency !== plan.currency) throw new Error( `A projecção de vendas está em ${plan.currency}, mas o projecto está em ${inputText(draft.currency)}. Reveja a moeda da projecção; os valores não foram convertidos nem reclassificados.`, ); return { amounts: monthlyProjectedSales(plan), source: 'Vendas por produto e mês do plano empresarial; mesmos pressupostos e representação monetária da projecção de vendas.', }; } if (draft.cashflow_snapshot) { const saved = restoreCashflowDraftSnapshot( inputText(draft.cashflow_snapshot), ); if (!saved) throw new Error('Não foi possível recuperar a receita projectada.'); const origin = cashflowCurrency(saved, inputText(draft.currency ?? '')); if (!origin.matchesProject) throw new Error(origin.notice); return { amounts: Array.from({ length: 12 }, () => saved.inputs.monthlyRevenue.trim() === '' ? null : saved.inputs.monthlyRevenue, ), source: 'Receita mensal constante já declarada na projecção de tesouraria; confirme que corresponde a vendas tributáveis.', }; } return { amounts: Array.from({ length: 12 }, () => null), source: 'Sem projecção de vendas guardada. Prepare as vendas no plano empresarial; não é necessário voltar a introduzi-las aqui.', }; } export function monthlyIvaInput( draft: Record, settings: MonthlyIvaSettings, ): MonthlyIvaInput { if ( draft.fiscal_period && inputText(draft.fiscal_period) !== settings.start.slice(0, 4) ) throw new Error( 'O ano escolhido no enquadramento fiscal difere do primeiro mês da projecção. Confira o período; nenhum ano foi alterado automaticamente.', ); const sales = monthlySalesFromDraft(draft); if (!/^2026-(0[1-9]|1[0-2])$/.test(settings.start)) throw new Error( 'Indique o primeiro mês real da projecção. Este cálculo dispõe de cobertura apenas para 2026.', ); const start = Number(settings.start.slice(5)); if (sales.amounts.length > 12 || start + sales.amounts.length > 13) throw new Error( 'O horizonte ultrapassa a cobertura de 2026. Esta versão não calcula os meses fora desse período.', ); return { scenario_kind: 'fiscal_rule_published', monthly_sales: sales.amounts.map((amount, index) => ({ date: `2026-${String(start + index).padStart(2, '0')}-01`, amount, })), sales_vat_basis: settings.basis, currency: inputText(draft.currency ?? ''), scope_declared: settings.declared, ...(monthlyIvaTreatment(draft).operation === 'internal_reduced_17a_net' ? { operation: 'internal_reduced_17a_net' as const } : {}), }; } /** The IVA of the plan's sales follows the activity declared in the plan (CAE). */ export function monthlyIvaTreatment(draft: Record) { const plan = draft.business_plan_snapshot ? restoreBusinessPlanSnapshot(inputText(draft.business_plan_snapshot)) : null; return ivaTreatmentForCae(plan?.economicClassification?.code); } export function monthlyIvaKey( input: Omit, ): string { return JSON.stringify([ input.currency, input.sales_vat_basis, input.scope_declared, input.monthly_sales.map((row) => [row.date, row.amount]), // General-rate keys stay as before, so earlier results remain current. ...(input.operation ? [input.operation] : []), ]); } export function readMonthlyIvaRecord(raw?: string): MonthlyIvaRecord | null { try { const value = JSON.parse(raw ?? ''); if ( value?.input?.scenario_kind === 'fiscal_rule_published' && Array.isArray(value.input.monthly_sales) && isApiSimulationReadResponseV1({ data: value.execution }) ) return value; } catch { /* Keep the stored value intact; no fallback fiscal result. */ } return null; } /** Read an admitted execution through the existing ownership-protected endpoint; never create one. */ export async function recoverMonthlyIvaRecord( record: MonthlyIvaRecord, request: typeof fetch = fetch, ): Promise { const response = await request( `/api/v1/simulations/${encodeURIComponent(record.execution.id)}`, { credentials: 'same-origin', headers: { Accept: 'application/json' } }, ); const value: unknown = await response.json(); if ( !response.ok || !isApiSimulationReadResponseV1(value) || value.data.id !== record.execution.id ) throw new Error( 'Não foi possível recuperar a execução mensal guardada. Os dados foram preservados e não foi criada uma execução alternativa.', ); return { input: record.input, execution: value.data }; } export const monthlyIvaCashTreatment = '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); 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', }; } /** 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; }