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:
@@ -1,3 +1,13 @@
|
||||
import {
|
||||
newInvestmentCredit,
|
||||
validateInvestmentCredit,
|
||||
calculateInvestmentCredit,
|
||||
deductInvestmentCredit,
|
||||
investmentCreditSource,
|
||||
investmentAssetIdentity,
|
||||
investmentAssetClaimed,
|
||||
type InvestmentCredit,
|
||||
} from './irpc-investment-credit.ts';
|
||||
import { inputText } from './input-text.ts';
|
||||
import {
|
||||
carryPlan,
|
||||
@@ -23,6 +33,7 @@ import {
|
||||
requireProofParcel,
|
||||
parcelProjection,
|
||||
overlappingProofParcels,
|
||||
canonicalParcel,
|
||||
type FiscalProofParcel,
|
||||
} from './fiscal-proof-parcel.ts';
|
||||
import {
|
||||
@@ -32,6 +43,8 @@ import {
|
||||
internationalPosition,
|
||||
internationalDeduction,
|
||||
internationalCreditSource,
|
||||
creditMoney,
|
||||
creditCompare,
|
||||
newInternationalCredits,
|
||||
type InternationalCredits,
|
||||
type InternationalTaxProof,
|
||||
@@ -93,7 +106,7 @@ type AnnualRecord = {
|
||||
model: AnnualModel;
|
||||
};
|
||||
export type AnnualBook = {
|
||||
version: 1;
|
||||
version: 1 | 2;
|
||||
subjectNuit: string;
|
||||
year: string;
|
||||
reference: string;
|
||||
@@ -108,6 +121,7 @@ export type AnnualBook = {
|
||||
internationalCredits?: InternationalCredits;
|
||||
creditCarry?: CreditCarry;
|
||||
economicCredits?: EconomicCredits;
|
||||
investmentCredit?: InvestmentCredit;
|
||||
result?: AnnualRecord;
|
||||
history: AnnualRecord[];
|
||||
};
|
||||
@@ -131,9 +145,25 @@ export const annualSource = (b: AnnualBook) => {
|
||||
(b.pecPayments ? ' ' + pecSource : '') +
|
||||
(b.internationalCredits ? ' ' + internationalCreditSource : '') +
|
||||
(b.creditCarry ? ' ' + carrySource : '') +
|
||||
(b.economicCredits ? ' ' + economicSource : '')
|
||||
(b.economicCredits ? ' ' + economicSource : '') +
|
||||
(b.investmentCredit ? ' ' + investmentCreditSource : '')
|
||||
);
|
||||
};
|
||||
export function prepareInvestmentCredit(
|
||||
d: Record<string, unknown>,
|
||||
b: AnnualBook,
|
||||
): AnnualBook {
|
||||
if (b.investmentCredit) return b;
|
||||
const next = prepareInternationalBook(b),
|
||||
c = newInvestmentCredit(),
|
||||
a = annualAssessment(d);
|
||||
c.subjectNuit = b.subjectNuit;
|
||||
c.year = b.year;
|
||||
c.assessmentKey = b.assessmentKey;
|
||||
c.qualification.from = a.period?.from ?? '';
|
||||
c.qualification.to = a.period?.to ?? '';
|
||||
return { ...next, version: 2, investmentCredit: c };
|
||||
}
|
||||
export function prepareEconomicBook(b: AnnualBook): AnnualBook {
|
||||
if (b.economicCredits) return b;
|
||||
const next = prepareInternationalBook(b),
|
||||
@@ -240,6 +270,8 @@ function books(d: Record<string, unknown>): Record<string, AnnualBook> {
|
||||
return m;
|
||||
}
|
||||
export function validateAnnual(b: AnnualBook) {
|
||||
if (b?.investmentCredit !== undefined)
|
||||
validateInvestmentCredit(b.investmentCredit);
|
||||
if (b?.economicCredits !== undefined) validateEconomic(b.economicCredits);
|
||||
if (b?.creditCarry !== undefined) validateCreditCarry(b.creditCarry);
|
||||
if (b?.pecPayments !== undefined) validatePec(b.pecPayments);
|
||||
@@ -247,7 +279,9 @@ export function validateAnnual(b: AnnualBook) {
|
||||
validateInternational(b.internationalCredits);
|
||||
if (
|
||||
!b ||
|
||||
b.version !== 1 ||
|
||||
![1, 2].includes(b.version) ||
|
||||
(b.version === 2 && b.investmentCredit === undefined) ||
|
||||
(b.investmentCredit !== undefined && b.version !== 2) ||
|
||||
[
|
||||
'subjectNuit',
|
||||
'year',
|
||||
@@ -467,7 +501,7 @@ export function reuseAnnualWithholding(
|
||||
},
|
||||
};
|
||||
}
|
||||
function dependencies(d: Record<string, unknown>) {
|
||||
function dependencies(d: Record<string, unknown>, includeInvestment = false) {
|
||||
let normal: unknown, L5: unknown;
|
||||
try {
|
||||
const a = annualAssessment(d);
|
||||
@@ -496,6 +530,9 @@ function dependencies(d: Record<string, unknown>) {
|
||||
...(b.internationalCredits ? [b.internationalCredits] : []),
|
||||
...(b.creditCarry ? [b.creditCarry] : []),
|
||||
...(b.economicCredits ? [b.economicCredits] : []),
|
||||
...(includeInvestment && b.investmentCredit
|
||||
? [b.investmentCredit]
|
||||
: []),
|
||||
]),
|
||||
];
|
||||
}
|
||||
@@ -505,7 +542,7 @@ function key(d: Record<string, unknown>, b: AnnualBook) {
|
||||
annualSettlementVersion,
|
||||
acquisitionScope(d),
|
||||
input,
|
||||
dependencies(d),
|
||||
dependencies(d, !!b.investmentCredit),
|
||||
]);
|
||||
}
|
||||
export function annualCurrent(d: Record<string, unknown>, b: AnnualBook) {
|
||||
@@ -809,6 +846,7 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
...internationalGroupPending(
|
||||
b.internationalCredits,
|
||||
!!b.economicCredits,
|
||||
!!b.investmentCredit,
|
||||
),
|
||||
);
|
||||
const countries = b.internationalCredits.positions.map(
|
||||
@@ -1230,6 +1268,122 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
'Crédito económico delimitado à colecta normal corrente;efeitos L7 exigem correspondência própria.',
|
||||
);
|
||||
}
|
||||
const investmentPreview =
|
||||
b.investmentCredit && assessment?.record
|
||||
? calculateInvestmentCredit(
|
||||
b.investmentCredit,
|
||||
assessment.book,
|
||||
assessment.record.model,
|
||||
assessment.key,
|
||||
assessment.current,
|
||||
)
|
||||
: null;
|
||||
if (b.investmentCredit && !investmentPreview)
|
||||
pending.push('CréditoCBF15 exige colecta L6 recuperável.');
|
||||
if (investmentPreview) pending.push(...investmentPreview.pending);
|
||||
if (
|
||||
investmentPreview?.available &&
|
||||
cmp(investmentPreview.available, zero()) > 0n &&
|
||||
(!investmentPreview.projectCeiling ||
|
||||
cmp(investmentPreview.projectCeiling, zero()) > 0n) &&
|
||||
b.creditCarry?.lots.length
|
||||
)
|
||||
pending.push(
|
||||
'CombinaçãoCBF15 com saldos anteriores exige correspondência própria; transportes anteriores preservados.',
|
||||
);
|
||||
if (
|
||||
b.investmentCredit?.qualification.state === 'known' &&
|
||||
b.investmentCredit.qualification.eligible === 'yes' &&
|
||||
investmentPreview?.nominal &&
|
||||
cmp(investmentPreview.nominal, zero()) > 0n
|
||||
) {
|
||||
for (const [scope, other] of Object.entries(books(d))) {
|
||||
if (
|
||||
scope === acquisitionScope(d) ||
|
||||
other.subjectNuit !== b.subjectNuit ||
|
||||
other.year !== b.year ||
|
||||
!other.investmentCredit
|
||||
)
|
||||
continue;
|
||||
try {
|
||||
validateInvestmentCredit(other.investmentCredit);
|
||||
const c = other.investmentCredit;
|
||||
if (
|
||||
c.qualification.state !== 'known' ||
|
||||
c.qualification.eligible !== 'yes'
|
||||
)
|
||||
continue;
|
||||
if (!c.assets.some(investmentAssetClaimed)) continue;
|
||||
for (const r of b.investmentCredit.assets.filter(
|
||||
investmentAssetClaimed,
|
||||
)) {
|
||||
const id = investmentAssetIdentity(r),
|
||||
others = c.assets.filter(
|
||||
(x) =>
|
||||
investmentAssetClaimed(x) &&
|
||||
investmentAssetIdentity(x) === id,
|
||||
);
|
||||
if (!others.length) continue;
|
||||
const proof = creditMoney(r.proofAmount);
|
||||
if (
|
||||
others.some(
|
||||
(x) =>
|
||||
creditCompare(
|
||||
creditMoney(x.proofAmount),
|
||||
proof,
|
||||
) !== 0n,
|
||||
)
|
||||
)
|
||||
pending.push(
|
||||
'Montante documentalCBF15 contraditório entre mapas; reconcilie a prova.',
|
||||
);
|
||||
const own = b.investmentCredit.assets.filter(
|
||||
(x) =>
|
||||
investmentAssetClaimed(x) &&
|
||||
investmentAssetIdentity(x) === id,
|
||||
);
|
||||
if (
|
||||
creditCompare(
|
||||
addFractions(
|
||||
[...own, ...others].map((x) =>
|
||||
creditMoney(x.amount),
|
||||
),
|
||||
),
|
||||
proof,
|
||||
) > 0n
|
||||
)
|
||||
pending.push(
|
||||
'InvestimentoCBF15 atribuído entre mapas ultrapassa o documento efectivo; não duplicar capacidade.',
|
||||
);
|
||||
}
|
||||
const sameProject =
|
||||
canonicalParcel(c.projectReference) ===
|
||||
canonicalParcel(b.investmentCredit.projectReference);
|
||||
const sharedAsset = c.assets
|
||||
.filter(investmentAssetClaimed)
|
||||
.some((r) =>
|
||||
b.investmentCredit!.assets.some((p) =>
|
||||
overlappingProofParcels(
|
||||
{ ...r, identity: investmentAssetIdentity(r) },
|
||||
{ ...p, identity: investmentAssetIdentity(p) },
|
||||
),
|
||||
),
|
||||
);
|
||||
if (sameProject || sharedAsset)
|
||||
pending.push(
|
||||
'CBF15 já preparado noutro mapa da entidade; consolide projecto/documentos sem duplicar: ' +
|
||||
scope,
|
||||
);
|
||||
} catch (e) {
|
||||
pending.push(
|
||||
'Outro mapaCBF15 não recuperável para conferir duplicação: ' +
|
||||
scope +
|
||||
'; ' +
|
||||
String(e),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const economicPreview = b.economicCredits
|
||||
? economicDeduction(economicRows, colecta, true)
|
||||
: null;
|
||||
@@ -1286,6 +1440,27 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
)
|
||||
: null;
|
||||
if (carry) pending.push(...carry.pending);
|
||||
if (investmentPreview?.projectCeiling && !pending.length) {
|
||||
const beforeInternational = economicPreview?.afterCredit ?? colecta;
|
||||
const preview = b.internationalCredits
|
||||
? internationalDeduction(
|
||||
positions,
|
||||
beforeInternational,
|
||||
true,
|
||||
carry?.international ?? undefined,
|
||||
)
|
||||
: null;
|
||||
const remaining = carry
|
||||
? subtractFractions(
|
||||
preview?.afterCredit ?? beforeInternational!,
|
||||
carry.priorInternational,
|
||||
)
|
||||
: (preview?.afterCredit ?? beforeInternational);
|
||||
if (!remaining || cmp(investmentPreview.projectCeiling, remaining) > 0n)
|
||||
pending.push(
|
||||
'Quota residualCBF15 do projecto excede a colecta após créditos económicos/internacionais; reconcilie a atribuição antes de deduzir.',
|
||||
);
|
||||
}
|
||||
const ready = pending.length === 0 && colecta !== null,
|
||||
economic = b.economicCredits
|
||||
? economicDeduction(economicRows, colecta, ready)
|
||||
@@ -1306,10 +1481,14 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
carry.priorInternational,
|
||||
)
|
||||
: (international?.afterCredit ?? afterEconomic);
|
||||
const investment = investmentPreview
|
||||
? deductInvestmentCredit(investmentPreview, creditCollecta, ready)
|
||||
: null;
|
||||
const afterInvestment = investment?.afterCredit ?? creditCollecta;
|
||||
const pec = b.pecPayments
|
||||
? pecDeduction(
|
||||
pecAvailable,
|
||||
creditCollecta,
|
||||
afterInvestment,
|
||||
ready,
|
||||
carry?.pec ?? undefined,
|
||||
)
|
||||
@@ -1317,10 +1496,10 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
const afterPec =
|
||||
ready && carry
|
||||
? subtractFractions(
|
||||
pec?.afterPec ?? creditCollecta!,
|
||||
pec?.afterPec ?? afterInvestment!,
|
||||
carry.priorPec,
|
||||
)
|
||||
: (pec?.afterPec ?? creditCollecta);
|
||||
: (pec?.afterPec ?? afterInvestment);
|
||||
const arithmeticBalance = ready
|
||||
? subtractFractions(
|
||||
subtractFractions(afterPec!, knownWithholdings),
|
||||
@@ -1387,6 +1566,7 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
claims,
|
||||
...(economic ? { economicCredit: economic } : {}),
|
||||
internationalCredit: international,
|
||||
...(investment ? { investmentCredit: investment } : {}),
|
||||
pecDeduction: pec,
|
||||
...(carry
|
||||
? {
|
||||
@@ -1427,8 +1607,12 @@ export function calculateAnnual(d: Record<string, unknown>, b: AnnualBook) {
|
||||
? 'Crédito internacional do próprio exercício:fracção nacional derivada no caso L6 ordinário com parcela líquida correspondida;CDT e montantes MZN documentados;sem repartição presumida de custos/perdas,transporte ou consumo oficial. '
|
||||
: 'Crédito internacional do próprio exercício:fracção nacional,convenção e montantes MZN são documentados;sem cálculo presumido,transporte ou consumo oficial. ') +
|
||||
(b.economicCredits
|
||||
? 'Benefícios positivos ficam separados;crédito económico no detalhe próprio.'
|
||||
: 'Créditos económicos/benefícios positivos ficam separados.'),
|
||||
? b.investmentCredit
|
||||
? 'CBF15 do primeiro exercício no detalhe próprio;restantes benefícios positivos separados;crédito económico no detalhe próprio.'
|
||||
: 'Benefícios positivos ficam separados;crédito económico no detalhe próprio.'
|
||||
: b.investmentCredit
|
||||
? 'CBF15 do primeiro exercício no detalhe próprio;restantes créditos económicos/benefícios positivos separados.'
|
||||
: 'Créditos económicos/benefícios positivos ficam separados.'),
|
||||
]
|
||||
: []),
|
||||
b.economicCredits
|
||||
@@ -1815,7 +1999,9 @@ export function annualReportRows(
|
||||
m.input.internationalCredits?.benefits
|
||||
.state ?? '',
|
||||
) +
|
||||
'.',
|
||||
(m.investmentCredit
|
||||
? '. Resumo anterior dos benefícios conservado, não reaplicado; CBF15 no detalhe próprio.'
|
||||
: '.'),
|
||||
m.internationalCredit.source +
|
||||
'; ' +
|
||||
(m.input.internationalCredits?.reference ?? '') +
|
||||
@@ -1904,6 +2090,99 @@ export function annualReportRows(
|
||||
] as [string, string, string, string],
|
||||
]
|
||||
: []),
|
||||
...(m.investmentCredit
|
||||
? [
|
||||
...m.investmentCredit.rows.map(
|
||||
(r) =>
|
||||
[
|
||||
'IRPC — L8',
|
||||
'CBF15 — ' +
|
||||
r.input.issuer +
|
||||
' / ' +
|
||||
r.input.document +
|
||||
' / ' +
|
||||
r.input.parcel +
|
||||
'; data ' +
|
||||
r.input.date,
|
||||
'Valor declarado: ' +
|
||||
r.input.amount +
|
||||
' ' +
|
||||
r.input.currency +
|
||||
'; investimento elegível: ' +
|
||||
show(r.value),
|
||||
r.input.reference +
|
||||
'; ' +
|
||||
r.reason +
|
||||
'; parcela: ' +
|
||||
r.input.parcelReference +
|
||||
'; ' +
|
||||
r.pending.join(' | '),
|
||||
] as [string, string, string, string],
|
||||
),
|
||||
[
|
||||
'IRPC — L8',
|
||||
'CBF15 — crédito fiscal por investimento',
|
||||
'Investimento: ' +
|
||||
show(m.investmentCredit.investment) +
|
||||
'; taxa ' +
|
||||
(m.investmentCredit.rate === null
|
||||
? 'não aplicável'
|
||||
: m.investmentCredit.rate + '%') +
|
||||
'; nominal ' +
|
||||
show(m.investmentCredit.nominal) +
|
||||
'; uso anterior ' +
|
||||
show(m.investmentCredit.priorUse) +
|
||||
'; disponível ' +
|
||||
show(m.investmentCredit.available) +
|
||||
'; dedução ' +
|
||||
show(m.investmentCredit.deducted) +
|
||||
'; sem colecta neste exercício ' +
|
||||
show(m.investmentCredit.unused) +
|
||||
(m.investmentCredit.projectCeiling
|
||||
? '; quota documental do projecto ' +
|
||||
show(m.investmentCredit.projectCeiling)
|
||||
: '') +
|
||||
'; colecta após benefício ' +
|
||||
show(m.investmentCredit.afterCredit),
|
||||
m.investmentCredit.version +
|
||||
'; ' +
|
||||
m.investmentCredit.source +
|
||||
'; projecto ' +
|
||||
m.investmentCredit.input.projectReference +
|
||||
'; ' +
|
||||
m.investmentCredit.input.qualification.reference +
|
||||
'; período ' +
|
||||
m.investmentCredit.input.qualification.from +
|
||||
' a ' +
|
||||
m.investmentCredit.input.qualification.to +
|
||||
'; ' +
|
||||
m.investmentCredit.input.qualification
|
||||
.periodReference +
|
||||
'; ' +
|
||||
m.investmentCredit.input.locationReference +
|
||||
'; ' +
|
||||
'início ' +
|
||||
m.investmentCredit.input.startDate +
|
||||
'; ' +
|
||||
m.investmentCredit.input.startReference +
|
||||
'; reconhecimento ' +
|
||||
m.investmentCredit.input.recognitionReference +
|
||||
'; exclusividade ' +
|
||||
(m.investmentCredit.input.soleProject === 'no'
|
||||
? m.investmentCredit.input.projectQuota
|
||||
?.reference
|
||||
: m.investmentCredit.input
|
||||
.soleProjectReference) +
|
||||
'; outros benefícios: ' +
|
||||
m.investmentCredit.input
|
||||
.noOtherBenefitsReference +
|
||||
'; uso anterior: ' +
|
||||
m.investmentCredit.input.previousUse.reference +
|
||||
'; ' +
|
||||
m.investmentCredit.pending.join(' | '),
|
||||
] as [string, string, string, string],
|
||||
]
|
||||
: []),
|
||||
...(m.pecDeduction
|
||||
? [
|
||||
[
|
||||
|
||||
@@ -383,6 +383,7 @@ export function internationalProofValue(
|
||||
export function internationalGroupPending(
|
||||
c: InternationalCredits,
|
||||
economicDetailed = false,
|
||||
benefitsDetailed = false,
|
||||
) {
|
||||
const pending: string[] = [];
|
||||
if (!c.state || !c.reference.trim())
|
||||
@@ -401,7 +402,9 @@ export function internationalGroupPending(
|
||||
...(economicDetailed
|
||||
? []
|
||||
: [['Dupla tributação económica', c.economic] as const]),
|
||||
['Benefícios/créditos próprios', c.benefits] as const,
|
||||
...(benefitsDetailed
|
||||
? []
|
||||
: [['Benefícios/créditos próprios', c.benefits] as const]),
|
||||
]) {
|
||||
try {
|
||||
if (!e.state || !e.reference.trim())
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1400,3 +1400,5 @@ function specialCombinationsReport(
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
export { qualify as qualifySpecialTreatment };
|
||||
|
||||
Reference in New Issue
Block a user