412 lines
14 KiB
TypeScript
412 lines
14 KiB
TypeScript
import type { AnnualPpc } from './irpc-annual-settlement.ts';
|
||
import {
|
||
validateProofParcel,
|
||
requireProofParcel,
|
||
} from './fiscal-proof-parcel.ts';
|
||
import { countryIsoCodes } from './country-iso-codes.ts';
|
||
import {
|
||
addFractions,
|
||
subtractFractions,
|
||
decimalFraction,
|
||
fraction,
|
||
type FiscalFraction,
|
||
} from './fiscal-rational.ts';
|
||
|
||
export const internationalCreditVersion = 'IRPC-international-credit/1';
|
||
export const internationalCreditSource =
|
||
'CIRPC art. 65(1–2), Lei 34/2007, PDF18/p.768-(72); ordem face ao PEC: art.66 e RIRPC21. Recorte: próprio exercício 2026, residente geral, ano civil, valores comprovados em MZN. Menor entre imposto sobre o rendimento pago no estrangeiro, fracção nacional documentada e limite da convenção quando aplicável; depois utilizações anteriores comprovadas e limite da colecta. Não determina a fracção nacional, a aplicabilidade da convenção ou a conversão cambial por presunção. Sem transporte, reembolso do excedente ou consumo de saldos oficiais.';
|
||
export type CreditState = '' | 'known' | 'absent';
|
||
export type CreditEvidence = {
|
||
state: CreditState;
|
||
amount: string;
|
||
reference: string;
|
||
};
|
||
export type InternationalTaxProof = AnnualPpc & {
|
||
incomeTax: '' | 'yes' | 'no';
|
||
taxReference: string;
|
||
exerciseReference: string;
|
||
};
|
||
export type InternationalPosition = {
|
||
id: string;
|
||
country: string;
|
||
subjectNuit: string;
|
||
year: string;
|
||
assessmentKey: string;
|
||
qualificationCountry: string;
|
||
incomeAmount: string;
|
||
incomeIncluded: '' | 'yes' | 'no';
|
||
incomeReference: string;
|
||
nationalLimit: string;
|
||
nationalLimitReference: string;
|
||
treaty: '' | 'yes' | 'no';
|
||
treatyLimit: string;
|
||
treatyReference: string;
|
||
previousUse: CreditEvidence;
|
||
payments: InternationalTaxProof[];
|
||
};
|
||
export type InternationalCredits = {
|
||
version: 1;
|
||
state: CreditState;
|
||
reference: string;
|
||
positions: InternationalPosition[];
|
||
economic: CreditEvidence;
|
||
benefits: CreditEvidence;
|
||
};
|
||
const emptyEvidence = (): CreditEvidence => ({
|
||
state: '',
|
||
amount: '',
|
||
reference: '',
|
||
});
|
||
export const newInternationalCredits = (): InternationalCredits => ({
|
||
version: 1,
|
||
state: '',
|
||
reference: '',
|
||
positions: [],
|
||
economic: emptyEvidence(),
|
||
benefits: emptyEvidence(),
|
||
});
|
||
export const newInternationalPosition = (
|
||
id: string,
|
||
): InternationalPosition => ({
|
||
id,
|
||
country: '',
|
||
subjectNuit: '',
|
||
year: '',
|
||
assessmentKey: '',
|
||
qualificationCountry: '',
|
||
incomeAmount: '',
|
||
incomeIncluded: '',
|
||
incomeReference: '',
|
||
nationalLimit: '',
|
||
nationalLimitReference: '',
|
||
treaty: '',
|
||
treatyLimit: '',
|
||
treatyReference: '',
|
||
previousUse: emptyEvidence(),
|
||
payments: [],
|
||
});
|
||
const states = ['', 'known', 'absent'];
|
||
const yesNo = ['', 'yes', 'no'];
|
||
const evidenceValid = (e: CreditEvidence) =>
|
||
e &&
|
||
states.includes(e.state) &&
|
||
typeof e.amount === 'string' &&
|
||
typeof e.reference === 'string';
|
||
const proofKeys = [
|
||
'id',
|
||
'document',
|
||
'issuer',
|
||
'date',
|
||
'subjectNuit',
|
||
'year',
|
||
'currency',
|
||
'proofAmount',
|
||
'amount',
|
||
'effective',
|
||
'reference',
|
||
'incomeTax',
|
||
'taxReference',
|
||
'exerciseReference',
|
||
];
|
||
const positionKeys = [
|
||
'id',
|
||
'country',
|
||
'subjectNuit',
|
||
'year',
|
||
'assessmentKey',
|
||
'qualificationCountry',
|
||
'incomeAmount',
|
||
'incomeIncluded',
|
||
'incomeReference',
|
||
'nationalLimit',
|
||
'nationalLimitReference',
|
||
'treaty',
|
||
'treatyLimit',
|
||
'treatyReference',
|
||
];
|
||
export function validateInternational(c: InternationalCredits) {
|
||
if (
|
||
!c ||
|
||
c.version !== 1 ||
|
||
!states.includes(c.state) ||
|
||
typeof c.reference !== 'string' ||
|
||
!evidenceValid(c.economic) ||
|
||
!evidenceValid(c.benefits) ||
|
||
!Array.isArray(c.positions) ||
|
||
new Set(c.positions.map((p) => p?.id)).size !== c.positions.length
|
||
)
|
||
throw Error(
|
||
'Créditos internacionais não recuperáveis; originais conservados.',
|
||
);
|
||
const proofIds: string[] = [];
|
||
for (const p of c.positions) {
|
||
if (
|
||
!p ||
|
||
positionKeys.some(
|
||
(k) =>
|
||
typeof (p as unknown as Record<string, unknown>)[k] !==
|
||
'string',
|
||
) ||
|
||
!yesNo.includes(p.incomeIncluded) ||
|
||
!yesNo.includes(p.treaty) ||
|
||
!evidenceValid(p.previousUse) ||
|
||
!Array.isArray(p.payments)
|
||
)
|
||
throw Error(
|
||
'Posição internacional não recuperável; originais conservados.',
|
||
);
|
||
for (const r of p.payments) {
|
||
validateProofParcel(r);
|
||
if (
|
||
!r ||
|
||
proofKeys.some(
|
||
(k) =>
|
||
typeof (r as unknown as Record<string, unknown>)[k] !==
|
||
'string',
|
||
) ||
|
||
!yesNo.includes(r.effective) ||
|
||
!yesNo.includes(r.incomeTax)
|
||
)
|
||
throw Error('Comprovativo internacional não recuperável.');
|
||
proofIds.push(r.id);
|
||
}
|
||
}
|
||
if (new Set(proofIds).size !== proofIds.length)
|
||
throw Error('Identificador de comprovativo internacional repetido.');
|
||
}
|
||
export const creditMoney = (raw: string) => {
|
||
if (!/^\d{1,18}(\.\d{1,2})?$/.test(raw))
|
||
throw Error(
|
||
'Montante MZN em falta/inválido; zero exige declaração própria.',
|
||
);
|
||
return decimalFraction(raw);
|
||
};
|
||
export const creditCompare = (a: FiscalFraction, b: FiscalFraction) =>
|
||
BigInt(a.numerator) * BigInt(b.denominator) -
|
||
BigInt(b.numerator) * BigInt(a.denominator);
|
||
export const creditLimit = (raw: string) => {
|
||
const rational = /^(\d{1,18})\/(\d{1,18})$/.exec(raw);
|
||
if (rational) return fraction(BigInt(rational[1]), BigInt(rational[2]));
|
||
if (!/^\d{1,18}(\.\d{1,6})?$/.test(raw))
|
||
throw Error(
|
||
'Limite documentado em falta/inválido; use decimal ou fracção exacta n/d, sem arredondamento presumido.',
|
||
);
|
||
return decimalFraction(raw);
|
||
};
|
||
const zero = () => fraction(0n);
|
||
const minimum = (...values: FiscalFraction[]) =>
|
||
values.reduce((a, b) => (creditCompare(a, b) < 0n ? a : b));
|
||
const isDate = (s: string) =>
|
||
/^20\d{2}-\d{2}-\d{2}$/.test(s) &&
|
||
Number.isFinite(Date.parse(s)) &&
|
||
new Date(s).toISOString().slice(0, 10) === s;
|
||
export function internationalProofValue(
|
||
r: InternationalTaxProof,
|
||
subjectNuit: string,
|
||
year: string,
|
||
) {
|
||
requireProofParcel(r);
|
||
if (
|
||
!r.id.trim() ||
|
||
!r.document.trim() ||
|
||
!r.issuer.trim() ||
|
||
!r.reference.trim() ||
|
||
!r.taxReference.trim() ||
|
||
r.incomeTax !== 'yes' ||
|
||
r.effective !== 'yes' ||
|
||
r.currency !== 'MZN' ||
|
||
!isDate(r.date) ||
|
||
r.subjectNuit !== subjectNuit ||
|
||
r.year !== year ||
|
||
year !== '2026'
|
||
)
|
||
throw Error(
|
||
'Crédito internacional: exige imposto sobre o rendimento efectivamente pago, prova/titular/exercício 2026 e MZN; previsões, outras naturezas e conversões não correspondidas ficam separados.',
|
||
);
|
||
if (!r.date.startsWith(year + '-') && !r.exerciseReference.trim())
|
||
throw Error(
|
||
'Data de pagamento fora do exercício: falta correspondência documental com o rendimento e imposto deste exercício; não é transporte presumido.',
|
||
);
|
||
const value = creditMoney(r.amount),
|
||
proofAmount = creditMoney(r.proofAmount);
|
||
if (creditCompare(value, proofAmount) > 0n)
|
||
throw Error('Parcela estrangeira ultrapassa o montante comprovado.');
|
||
return { value, proofAmount };
|
||
}
|
||
export function internationalGroupPending(
|
||
c: InternationalCredits,
|
||
economicDetailed = false,
|
||
) {
|
||
const pending: string[] = [];
|
||
if (!c.state || !c.reference.trim())
|
||
pending.push(
|
||
'Crédito internacional: declare pagamentos conhecidos, ausência ou informação em falta, com suporte.',
|
||
);
|
||
if (c.state === 'absent' && c.positions.length)
|
||
pending.push(
|
||
'Ausência de crédito internacional contradiz posições presentes; conserve e reconcilie.',
|
||
);
|
||
if (c.state === 'known' && !c.positions.length)
|
||
pending.push(
|
||
'Crédito internacional conhecido sem posição/comprovativo; zero não é ausência presumida.',
|
||
);
|
||
for (const [label, e] of [
|
||
...(economicDetailed
|
||
? []
|
||
: [['Dupla tributação económica', c.economic] as const]),
|
||
['Benefícios/créditos próprios', c.benefits] as const,
|
||
]) {
|
||
try {
|
||
if (!e.state || !e.reference.trim())
|
||
throw Error('estado e suporte em falta');
|
||
if (e.state === 'absent') {
|
||
if (e.amount.trim()) throw Error('ausência contradiz montante');
|
||
} else if (creditCompare(creditMoney(e.amount), zero()) !== 0n)
|
||
throw Error(
|
||
'valor positivo exige regra própria; não é deduzido nem ignorado',
|
||
);
|
||
} catch (e) {
|
||
pending.push(label + ': ' + String(e));
|
||
}
|
||
}
|
||
return pending;
|
||
}
|
||
export function internationalPosition(
|
||
p: InternationalPosition,
|
||
paid: FiscalFraction,
|
||
proofIssues: string[],
|
||
subjectNuit: string,
|
||
year: string,
|
||
assessmentKey: string,
|
||
) {
|
||
const pending = [...proofIssues];
|
||
let nationalLimit: FiscalFraction | null = null,
|
||
treatyLimit: FiscalFraction | null = null,
|
||
previousUse: FiscalFraction | null = null,
|
||
eligible: FiscalFraction | null = null,
|
||
available: FiscalFraction | null = null,
|
||
aboveLimit: FiscalFraction | null = null;
|
||
try {
|
||
if (
|
||
!p.id.trim() ||
|
||
!countryIsoCodes.includes(p.country) ||
|
||
p.country === 'MZ' ||
|
||
p.subjectNuit !== subjectNuit ||
|
||
p.year !== year ||
|
||
year !== '2026'
|
||
)
|
||
throw Error(
|
||
'País estrangeiro do catálogo, titular e exercício não correspondem.',
|
||
);
|
||
if (p.qualificationCountry !== p.country)
|
||
throw Error(
|
||
'O país mudou; confirme a inclusão e os limites documentados para o país seleccionado.',
|
||
);
|
||
if (p.assessmentKey !== assessmentKey || !p.assessmentKey)
|
||
throw Error(
|
||
'Confirme a inclusão e a fracção nacional na colecta corrente; a origem mudou.',
|
||
);
|
||
if (p.incomeIncluded !== 'yes' || !p.incomeReference.trim())
|
||
throw Error(
|
||
'Falta inclusão documentada do rendimento estrangeiro na matéria colectável.',
|
||
);
|
||
const income = creditMoney(p.incomeAmount);
|
||
nationalLimit = creditLimit(p.nationalLimit);
|
||
if (!p.nationalLimitReference.trim())
|
||
throw Error(
|
||
'Fracção nacional exige suporte próprio; não é calculada nem presumida pelo portal.',
|
||
);
|
||
if (
|
||
creditCompare(income, zero()) === 0n &&
|
||
creditCompare(nationalLimit, zero()) !== 0n
|
||
)
|
||
throw Error(
|
||
'Rendimento incluído zero contradiz fracção nacional positiva.',
|
||
);
|
||
if (!p.treaty || !p.treatyReference.trim())
|
||
throw Error('Aplicabilidade da convenção e suporte em falta.');
|
||
if (p.treaty === 'yes') treatyLimit = creditLimit(p.treatyLimit);
|
||
else if (p.treatyLimit.trim())
|
||
throw Error('Ausência de convenção contradiz limite preenchido.');
|
||
if (!p.previousUse.state || !p.previousUse.reference.trim())
|
||
throw Error(
|
||
'Utilizações anteriores do crédito em falta; histórico de simulação não é consumo oficial.',
|
||
);
|
||
if (p.previousUse.state === 'absent') {
|
||
if (p.previousUse.amount.trim())
|
||
throw Error('Ausência de uso anterior contradiz montante');
|
||
previousUse = zero();
|
||
} else previousUse = creditMoney(p.previousUse.amount);
|
||
if (!p.payments.length)
|
||
throw Error(
|
||
'Sem comprovativos de imposto estrangeiro nesta posição.',
|
||
);
|
||
if (!pending.length) {
|
||
eligible = minimum(
|
||
paid,
|
||
nationalLimit,
|
||
...(treatyLimit ? [treatyLimit] : []),
|
||
);
|
||
aboveLimit = subtractFractions(paid, eligible);
|
||
if (creditCompare(previousUse, eligible) > 0n)
|
||
throw Error(
|
||
'Utilização anterior excede o crédito elegível; reconcilie o saldo.',
|
||
);
|
||
available = subtractFractions(eligible, previousUse);
|
||
}
|
||
} catch (e) {
|
||
pending.push(String(e));
|
||
available = null;
|
||
}
|
||
return {
|
||
id: p.id,
|
||
country: p.country,
|
||
paid,
|
||
nationalLimit,
|
||
treatyLimit,
|
||
previousUse,
|
||
eligible,
|
||
available,
|
||
aboveLimit,
|
||
pending,
|
||
input: structuredClone(p),
|
||
};
|
||
}
|
||
export function internationalDeduction(
|
||
positions: ReturnType<typeof internationalPosition>[],
|
||
colecta: FiscalFraction | null,
|
||
ready: boolean,
|
||
selected?: FiscalFraction | null,
|
||
) {
|
||
const available = addFractions(
|
||
positions.flatMap((p) =>
|
||
p.available && !p.pending.length ? [p.available] : [],
|
||
),
|
||
);
|
||
const deducted =
|
||
ready && colecta ? (selected ?? minimum(available, colecta)) : null;
|
||
return {
|
||
version: internationalCreditVersion,
|
||
positions,
|
||
available,
|
||
deducted,
|
||
afterCredit:
|
||
deducted && colecta ? subtractFractions(colecta, deducted) : null,
|
||
insufficientCollecta:
|
||
selected === undefined && deducted
|
||
? subtractFractions(available, deducted)
|
||
: null,
|
||
...(selected !== undefined
|
||
? {
|
||
notSelected: deducted
|
||
? subtractFractions(available, deducted)
|
||
: null,
|
||
}
|
||
: {}),
|
||
source: internationalCreditSource,
|
||
countryAllocationCreated: false,
|
||
carryCreated: false,
|
||
officialBalancesConsumed: false,
|
||
};
|
||
}
|