feat: calculate qualified investment credits in annual settlement
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,496 @@
|
||||
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/1';
|
||||
export const investmentCreditSource =
|
||||
'CBF,Lei4/2009,arts3/4/9/10/12/13/15; compilação oficial APIEX2025,PDF66–72,art15PDF71–72. Primeiro exercício2026,regime normal residente,ano civil/MZN,colecta inteiramente do projecto documentada. 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 transporte/reembolso ou consumo de saldo oficial presumidos;outros exercícios,regimes e cumulações separados.';
|
||||
type Choice = '' | 'yes' | 'no';
|
||||
export type InvestmentAsset = {
|
||||
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;
|
||||
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 ||
|
||||
c.version !== 1 ||
|
||||
Object.keys(template)
|
||||
.filter(
|
||||
(k) =>
|
||||
![
|
||||
'version',
|
||||
'qualification',
|
||||
'assets',
|
||||
'previousUse',
|
||||
].includes(k),
|
||||
)
|
||||
.some(
|
||||
(k) =>
|
||||
typeof (c as unknown as Record<string, unknown>)[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.');
|
||||
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<string, unknown>)[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<string, string>)[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 ||
|
||||
Object.keys(newInvestmentAsset('')).some(
|
||||
(k) =>
|
||||
typeof (r as unknown as Record<string, unknown>)[k] !==
|
||||
'string',
|
||||
) ||
|
||||
[
|
||||
'realised',
|
||||
'newTangible',
|
||||
'domesticUse',
|
||||
'directProductive',
|
||||
'excluded15_6',
|
||||
].some(
|
||||
(k) =>
|
||||
!['', 'yes', 'no'].includes(
|
||||
(r as unknown as Record<string, string>)[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) =>
|
||||
/^2026-\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 projectCeiling: FiscalFraction | 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 primeiro exercício2026 por documentar: início de exploração para projecto novo,procedimentos após aprovação para projecto em funcionamento.',
|
||||
);
|
||||
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.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 (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,
|
||||
reason: issues.length
|
||||
? issues.join(' ')
|
||||
: '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,
|
||||
);
|
||||
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);
|
||||
} 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,
|
||||
nominal,
|
||||
priorUse,
|
||||
available: pending.length ? null : available,
|
||||
pending,
|
||||
source:
|
||||
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<typeof calculateInvestmentCredit>,
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user