import { newQualification, qualifySpecialTreatment, type Qualification, } from './irpc-special.ts'; import type { NormalBook, NormalModel } from './irpc-normal.ts'; import { creditMoney, creditCompare, creditLimit, type CreditEvidence, } from './irpc-international-credit.ts'; import { canonicalParcel, requireProofParcel, overlappingProofParcels, } from './fiscal-proof-parcel.ts'; import { addFractions, subtractFractions, fraction, type FiscalFraction, } from './fiscal-rational.ts'; export const investmentCreditVersion = 'IRPC-CBF15/3'; export const investmentCreditSource = 'CBF,Lei4/2009,arts3/4/9/10/12/13/15; compilação oficial APIEX2025,PDF66–72,art15PDF71–72. Liquidação2026,regime normal residente,ano civil/MZN,colecta integral ou quota residual documentada do projecto. Janela de cinco exercícios desde o início aplicável15(4/7),incluindo o primeiro; activos efectivos de2026,com transporte apenas no detalhe preparado das origens históricas. Activo corpóreo novo afecto à exploração nacional,sem exclusões15(6). Cidade de Maputo5%,restantes províncias10%. Menor entre crédito disponível e colecta remanescente depois dos créditos económicos/internacionais,antesPEC/RF/PPC (RIRPC21). Sem criação automática de transporte,reembolso ou consumo de saldo oficial;outros exercícios,regimes e cumulações separados.'; type Choice = '' | 'yes' | 'no'; export type InvestmentAsset = { originYear?: string; originNuit?: string; originProject?: string; originReference?: string; originRate?: string; id: string; issuer: string; document: string; parcel: string; parcelReference: string; date: string; proofAmount: string; amount: string; currency: string; realised: Choice; newTangible: Choice; domesticUse: Choice; directProductive: Choice; excluded15_6: Choice; reference: string; }; export const newInvestmentAsset = (id: string): InvestmentAsset => ({ id, issuer: '', document: '', parcel: '', parcelReference: '', date: '', proofAmount: '', amount: '', currency: 'MZN', realised: '', newTangible: '', domesticUse: '', directProductive: '', excluded15_6: '', reference: '', }); export type InvestmentCredit = { projectQuota?: { amount: string; reference: string }; version: 1 | 2; carryForward?: { reference: string; useReconciled: Choice; currentState: '' | 'known' | 'absent'; currentReference: string; }; qualification: Qualification; subjectNuit: string; year: string; assessmentKey: string; projectReference: string; location: '' | 'maputo_city' | 'other'; locationReference: string; startKind: '' | 'new' | 'existing'; startDate: string; startReference: string; cbfRequirements: Choice; recognition: '' | 'documented' | 'not_required'; recognitionReference: string; genericOnly: Choice; noOtherBenefits: Choice; noOtherBenefitsReference: string; soleProject: Choice; soleProjectReference: string; assets: InvestmentAsset[]; previousUse: CreditEvidence; }; export const newInvestmentCredit = (): InvestmentCredit => ({ version: 1, qualification: newQualification(), subjectNuit: '', year: '', assessmentKey: '', projectReference: '', location: '', locationReference: '', startKind: '', startDate: '', startReference: '', cbfRequirements: '', recognition: '', recognitionReference: '', genericOnly: '', noOtherBenefits: '', noOtherBenefitsReference: '', soleProject: '', soleProjectReference: '', assets: [], previousUse: { state: '', amount: '', reference: '' }, }); export function validateInvestmentCredit(c: InvestmentCredit) { const template = newInvestmentCredit(); if ( !c || ![1, 2].includes(c.version) || Object.keys(template) .filter( (k) => ![ 'version', 'qualification', 'assets', 'previousUse', ].includes(k), ) .some( (k) => typeof (c as unknown as Record)[k] !== 'string', ) || !c.qualification || !c.previousUse || !Array.isArray(c.assets) || new Set(c.assets.map((r) => r?.id)).size !== c.assets.length ) throw Error('CréditoCBF15 não recuperável; original conservado.'); if ( c.projectQuota !== undefined && (!c.projectQuota || typeof c.projectQuota.amount !== 'string' || typeof c.projectQuota.reference !== 'string') ) throw Error('QuotaCBF15 não recuperável; original conservado.'); if ((c.version === 2) !== (c.carryForward !== undefined)) throw Error( 'Formato do transporteCBF15 não recuperável; original conservado.', ); if ( c.carryForward && (!c.carryForward || typeof c.carryForward.reference !== 'string' || typeof c.carryForward.currentReference !== 'string' || !['', 'known', 'absent'].includes(c.carryForward.currentState) || !['', 'yes', 'no'].includes(c.carryForward.useReconciled)) ) throw Error('TransporteCBF15 não recuperável; original conservado.'); const q = c.qualification; if ( !['', 'known', 'absent', 'not_applicable'].includes(q.state) || !['', 'yes', 'no'].includes(q.eligible) || ['from', 'to', 'reference', 'periodReference'].some( (k) => typeof (q as unknown as Record)[k] !== 'string', ) || !['', 'maputo_city', 'other'].includes(c.location) || !['', 'new', 'existing'].includes(c.startKind) || !['', 'documented', 'not_required'].includes(c.recognition) || [ 'cbfRequirements', 'genericOnly', 'noOtherBenefits', 'soleProject', ].some( (k) => !['', 'yes', 'no'].includes( (c as unknown as Record)[k], ), ) || !['', 'known', 'absent'].includes(c.previousUse.state) || typeof c.previousUse.amount !== 'string' || typeof c.previousUse.reference !== 'string' ) throw Error('QualificaçãoCBF15 não recuperável; original conservado.'); for (const r of c.assets) { if ( !r || [ 'originYear', 'originReference', 'originRate', 'originNuit', 'originProject', ].some( (k) => (r as unknown as Record)[k] !== undefined && (c.version !== 2 || typeof (r as unknown as Record)[k] !== 'string'), ) || Object.keys(newInvestmentAsset('')).some( (k) => typeof (r as unknown as Record)[k] !== 'string', ) || [ 'realised', 'newTangible', 'domesticUse', 'directProductive', 'excluded15_6', ].some( (k) => !['', 'yes', 'no'].includes( (r as unknown as Record)[k], ), ) ) throw Error( 'InvestimentoCBF15 não recuperável; original conservado.', ); } } const zero = () => fraction(0n); const minimum = (a: FiscalFraction, b: FiscalFraction) => creditCompare(a, b) < 0n ? a : b; const iso = (s: string) => /^\d{4}-\d{2}-\d{2}$/.test(s) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString().slice(0, 10) === s; export const investmentAssetIdentity = (r: InvestmentAsset) => JSON.stringify([canonicalParcel(r.issuer), canonicalParcel(r.document)]); export function calculateInvestmentCredit( c: InvestmentCredit, b: NormalBook, m: NormalModel, currentKey: string, current: boolean, ) { validateInvestmentCredit(c); const decision = qualifySpecialTreatment(c.qualification, b, m), pending = [...decision.pending]; if (c.noOtherBenefits !== 'yes' || !c.noOtherBenefitsReference.trim()) pending.push( 'Restantes benefícios próprios por reconciliar; o detalheCBF15 não os deduz nem ignora por presunção.', ); let investment: FiscalFraction | null = null, nominal: FiscalFraction | null = null, priorUse: FiscalFraction | null = null, available: FiscalFraction | null = null, rate: number | null = null; let currentNominal: FiscalFraction | undefined, carryNominal: FiscalFraction | undefined, expired: FiscalFraction | undefined; let projectCeiling: FiscalFraction | undefined; let window: | { firstYear: number; lastYear: number; currentYear: number; exercise: number; status: 'active' | 'expired'; } | undefined; const rows: { input: InvestmentAsset; value: FiscalFraction | null; reason: string; pending: string[]; }[] = []; if (decision.status === 'calculated') { try { if ( !current || b.special || b.periodsFx || b.scope !== 'resident_general' || b.year !== '2026' || c.year !== b.year || c.subjectNuit !== b.base?.subjectNuit || !c.assessmentKey || c.assessmentKey !== currentKey || !m.colecta ) throw Error( 'CBF15 exige colecta L6 normal corrente,residente/ano civil2026/MZN; outros âmbitos separados.', ); if ( !c.projectReference.trim() || c.cbfRequirements !== 'yes' || !c.recognition || !c.recognitionReference.trim() || c.genericOnly !== 'yes' || c.noOtherBenefits !== 'yes' || !c.noOtherBenefitsReference.trim() ) throw Error( 'CondiçõesCBF3/9/10,regime genérico13,reconhecimento/excepção documentada e ausência de outros benefícios por corresponder.', ); if (c.soleProject === 'yes') { if (!c.soleProjectReference.trim()) throw Error( 'Correspondência da colecta integral do projecto por documentar.', ); } else if (c.soleProject === 'no') { if (!c.projectQuota?.reference.trim()) throw Error( 'Quota residual da colecta do projecto após créditos económicos/internacionais exige suporte próprio.', ); projectCeiling = creditLimit(c.projectQuota.amount); if (creditCompare(projectCeiling, m.colecta) > 0n) throw Error( 'Quota do projecto excede a colecta L6; reconcilie.', ); } else throw Error( 'Correspondência da colecta ao projecto por documentar.', ); if ( !c.location || !c.locationReference.trim() || !c.startKind || !iso(c.startDate) || !c.startReference.trim() ) throw Error( 'Local efectivo do investimento e início aplicável por documentar: início de exploração para projecto novo,procedimentos após aprovação para projecto em funcionamento.', ); const firstYear = Number(c.startDate.slice(0, 4)); if (firstYear < 1 || firstYear > Number(b.year)) throw Error( 'Ano inicial inválido ou posterior à liquidação2026; não antecipar o crédito.', ); window = { firstYear, lastYear: firstYear + 4, currentYear: Number(b.year), exercise: Number(b.year) - firstYear + 1, status: Number(b.year) > firstYear + 4 ? 'expired' : 'active', }; if (c.carryForward) { const t = c.carryForward, prior = c.assets.filter((r) => r.originYear !== undefined), own = c.assets.filter((r) => r.originYear === undefined); if (!t.reference.trim() || t.useReconciled !== 'yes') throw Error( 'Transporte exige correspondência histórica e reconciliação do uso efectivo de todo o crédito, separado do histórico de simulações.', ); if ( !t.currentReference.trim() || !t.currentState || (t.currentState === 'absent' ? own.length !== 0 : own.length === 0) ) throw Error( 'Investimento corrente conhecido/ausente deve corresponder aos activos e ter suporte próprio; dados conservados.', ); if (!prior.length) throw Error( 'Transporte exige activo/documento e exercício de origem; não importar saldo agregado sem origem.', ); } if (!c.assets.length) throw Error( 'Investimento conhecido exige activo/documento; zero não se presume.', ); rate = c.location === 'maputo_city' ? 5 : 10; } catch (e) { pending.push(String(e)); } for (const r of c.assets) { const issues: string[] = []; let value: FiscalFraction | null = null; try { const excluded = r.realised === 'no' || r.newTangible === 'no' || r.domesticUse === 'no' || r.directProductive === 'no' || r.excluded15_6 === 'yes'; if (excluded && r.reference.trim()) { rows.push({ input: structuredClone(r), value: zero(), reason: 'Condição negativa/exclusão15(5–6) documentada; valor conservado,crédito zero para este activo.', pending: [], }); continue; } requireProofParcel(r); if ( r.currency !== 'MZN' || r.realised !== 'yes' || !r.id.trim() || !r.issuer.trim() || !r.document.trim() || !iso(r.date) || (r.originYear === undefined && !r.date.startsWith(b.year + '-')) || !r.reference.trim() || r.newTangible !== 'yes' || r.domesticUse !== 'yes' || r.directProductive !== 'yes' || r.excluded15_6 !== 'no' ) throw Error( 'Activo/documento2026,corpóreo novo,afectação nacional produtiva e exclusões15(6) por corresponder.', ); if (r.originYear !== undefined) { const origin = Number(r.originYear), first = Number(c.startDate.slice(0, 4)); if ( !c.carryForward || !/^\d{4}$/.test(r.originYear) || origin < first || origin >= Number(b.year) || origin > first + 4 || Number(r.date.slice(0, 4)) > origin || r.originNuit !== c.subjectNuit || !r.originProject?.trim() || canonicalParcel(r.originProject) !== canonicalParcel(c.projectReference) || !r.originReference?.trim() || r.originRate !== String(rate) ) throw Error( 'OrigemCBF15 anterior à liquidação, dentro do prazo original, taxa e qualificação histórica do mesmo projecto por corresponder; não renovar/revalorizar o crédito.', ); } if (c.startKind === 'existing' && r.date < c.startDate) throw Error( 'Investimento anterior ao início documentado deste recorte; correspondência própria necessária.', ); value = creditMoney(r.amount); if (creditCompare(value, creditMoney(r.proofAmount)) > 0n) throw Error( 'Investimento atribuído excede o documento efectivo.', ); if ( c.assets.some( (other) => other !== r && investmentAssetClaimed(other) && overlappingProofParcels( { ...r, identity: investmentAssetIdentity(r) }, { ...other, identity: investmentAssetIdentity(other), }, ), ) ) throw Error( 'Documento/parcela de investimento repetido; não duplicar activos por mudar id/data.', ); } catch (e) { issues.push(String(e)); value = null; } rows.push({ input: structuredClone(r), value: value && window?.status === 'expired' && r.originYear === undefined ? zero() : value, reason: issues.length ? issues.join(' ') : r.originYear !== undefined ? 'Activo de origem histórica documentada; saldo depende do uso efectivo e prazo original.' : window?.status === 'expired' ? 'Prazo15(4) terminado no quinto exercício; investimento2026 conservado,sem crédito.' : 'Activo elegível documentado.', pending: issues, }); pending.push(...issues); } const pools = new Map< string, { amount: FiscalFraction; proof: FiscalFraction } >(); for (const row of rows) { if ( !row.value || creditCompare(row.value, zero()) === 0n || row.pending.length ) continue; const id = investmentAssetIdentity(row.input), proof = creditMoney(row.input.proofAmount), existing = pools.get(id); if (existing && creditCompare(existing.proof, proof) !== 0n) pending.push( 'Montante total do mesmo documento difere entre parcelas; reconcilie a prova.', ); const amount = addFractions([ existing?.amount ?? zero(), row.value, ]); pools.set(id, { amount, proof }); if (creditCompare(amount, proof) > 0n) pending.push( 'Soma das parcelas elegíveis ultrapassa o documento efectivo; não duplicar investimento.', ); } if (!pending.length) { investment = addFractions( rows.flatMap((r) => (r.value ? [r.value] : [])), ); nominal = fraction( BigInt(investment.numerator) * BigInt(rate!), BigInt(investment.denominator) * 100n, ); if (c.carryForward) { const value = (prior: boolean) => { const total = addFractions( rows .filter( (r) => (r.input.originYear !== undefined) === prior, ) .flatMap((r) => (r.value ? [r.value] : [])), ); return fraction( BigInt(total.numerator) * BigInt(rate!), BigInt(total.denominator) * 100n, ); }; currentNominal = value(false); carryNominal = value(true); } try { if (!c.previousUse.state || !c.previousUse.reference.trim()) throw Error( 'Uso anterior efectivo do crédito por documentar; histórico de simulações não é uso fiscal.', ); if (c.previousUse.state === 'absent') { if (c.previousUse.amount.trim()) throw Error('Ausência de uso contradiz montante'); priorUse = zero(); } else priorUse = creditLimit(c.previousUse.amount); if (creditCompare(priorUse, nominal) > 0n) throw Error('Uso anterior excede o crédito nominal.'); available = subtractFractions(nominal, priorUse); if (c.carryForward) { expired = window?.status === 'expired' ? available : zero(); if (window?.status === 'expired') available = zero(); } } catch (e) { pending.push(String(e)); } } } else if ( ['absent', 'not_applicable'].includes(decision.status) && !pending.length ) { investment = nominal = priorUse = available = zero(); } return { version: investmentCreditVersion, input: structuredClone(c), decision, rows, investment, ...(projectCeiling === undefined ? {} : { projectCeiling }), rate, ...(window ? { window } : {}), nominal, ...(c.carryForward ? { currentNominal, carryNominal, expired } : {}), priorUse, available: pending.length ? null : available, pending, source: (c.carryForward ? ' TransporteCBF15/1: activos de origem anterior identificados,qualificação/taxa histórica documentadas,uso efectivo agregado reconciliado,sem renovação do prazo15(4/7),consumo oficial ou reembolso automático. ' : '') + (c.soleProject === 'no' ? investmentCreditSource.replace( 'colecta inteiramente do projecto documentada', 'quota residual documental da colecta do projecto após créditos económicos/internacionais', ) + ' QuotaCBF15-project/1: limite documental não superior ao saldo global corrente, com atribuição dos créditos anteriores ao projecto expressamente reconciliada; não é repartição automática de custos/perdas ou rendimentos.' : investmentCreditSource), }; } export function deductInvestmentCredit( model: ReturnType, collecta: FiscalFraction | null, ready: boolean, ) { const deducted = ready && collecta && model.available ? minimum( model.available, model.projectCeiling === undefined ? collecta : minimum(collecta, model.projectCeiling), ) : null; return { ...model, deducted, afterCredit: deducted && collecta ? subtractFractions(collecta, deducted) : null, unused: deducted && model.available ? subtractFractions(model.available, deducted) : null, officialBalancesConsumed: false, carryCreated: false, }; } export function investmentAssetClaimed(r: InvestmentAsset) { try { return ( r.realised === 'yes' && r.newTangible === 'yes' && r.domesticUse === 'yes' && r.directProductive === 'yes' && r.excluded15_6 === 'no' && r.currency === 'MZN' && creditCompare(creditMoney(r.amount), zero()) > 0n ); } catch { return false; } }