feat: derive qualified Portugal treaty credit limits
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-10 13:38:56 +02:00
parent ac67f9c13a
commit 60b52fc8c7
13 changed files with 684 additions and 15 deletions
@@ -1,3 +1,4 @@
import { SimulationIrpcPtCdt } from './simulation-irpc-pt-cdt';
import { FiscalProofParcelFields } from './fiscal-proof-parcel';
import CountrySelect, { type Country } from '@/components/country-select';
import { countryIsoCodes } from '@/lib/country-iso-codes';
@@ -387,23 +388,65 @@ export function SimulationIrpcInternational({
</option>
</select>
</label>
{(p.treaty === 'yes' || p.treatyLimit) && (
{p.treaty === 'yes' && (
<label className="block">
Imposto pago elegível nos termos da convenção —
limite MZN
<input
Determinar limite da convenção
<select
aria-label={
'Internacional ' +
(index + 1) +
' — Limite CDT'
' — Método CDT'
}
value={p.treatyLimit}
value={p.treatyMethod ?? 'documented'}
onChange={(e) =>
patch({ treatyLimit: e.target.value })
patch({
treatyMethod: e.target
.value as InternationalPosition['treatyMethod'],
})
}
/>
>
<option value="documented">
Limite documentado
</option>
<option value="ptMzRoyalty">
Portugal — royalties ordinárias,
art.12/23(3)a
</option>
<option value="ptMzDividend">
Portugal — dividendos, art.10/23(3)a
</option>
<option value="ptMzInterest">
Portugal — juros ordinários,
art.11/23(3)a
</option>
</select>
</label>
)}
<SimulationIrpcPtCdt
position={p}
patch={patch}
prefix={'Internacional ' + (index + 1) + ' — '}
/>
{(p.treatyMethod ?? 'documented') === 'documented' &&
(p.treaty === 'yes' || p.treatyLimit) && (
<label className="block">
Imposto pago elegível nos termos da
convenção — limite MZN
<input
aria-label={
'Internacional ' +
(index + 1) +
' — Limite CDT'
}
value={p.treatyLimit}
onChange={(e) =>
patch({
treatyLimit: e.target.value,
})
}
/>
</label>
)}
<label className="block">
Suporte da convenção ou da não aplicação
<input
@@ -0,0 +1,103 @@
import {
newPtMzRoyaltyPreparation,
type InternationalPosition,
type PtMzRoyaltyPreparation,
} from '@/lib/irpc-international-credit';
export function SimulationIrpcPtCdt({
position: p,
patch,
prefix,
}: {
position: InternationalPosition;
patch: (v: Partial<InternationalPosition>) => void;
prefix: string;
}) {
if (!p.treatyMethod || p.treatyMethod === 'documented') return null;
const change = (key: keyof PtMzRoyaltyPreparation, value: string) =>
patch({
treatyPreparation: {
...newPtMzRoyaltyPreparation(),
...p.treatyPreparation,
[key]: value,
},
});
const facts: [keyof PtMzRoyaltyPreparation, string][] = [
['residentMz', 'Beneficiário residente convencional em Moçambique'],
['beneficialOwner', 'Beneficiário efectivo do rendimento'],
[
'payerResidentPt',
'Devedor/sociedade distribuidora residente em Portugal',
],
[
'sourcePortugal',
'Fonte portuguesa, incluindo correspondência de quem suporta o encargo',
],
['noLinkedEstablishment', 'Sem EP/instalação fixa ligada em Portugal'],
];
if (p.treatyMethod !== 'ptMzDividend')
facts.push(['armLength', 'Sem excesso por relações especiais']);
if (p.treatyMethod === 'ptMzRoyalty')
facts.push(
[
'royaltyDefinition',
'Definição convencional de royalties documentada',
],
['nonDigital', 'Caso ordinário não digital'],
);
else
facts.push([
'capitalDefinition',
'Definição convencional de dividendos/juros documentada',
]);
if (p.treatyMethod === 'ptMzInterest')
facts.push([
'governmentInterestExemption',
'Juros abrangidos pela isenção governamental do art.11(3) (o cálculo ordinário exige Não)',
]);
return (
<fieldset className="space-y-2 rounded border p-3">
<legend>Portugal — correspondência CDT</legend>
<p>
Confirme rendimento bruto em MZN, residência convencional,
natureza e período coberto pelos documentos. A taxa de 10%
limita o imposto estrangeiro elegível; não altera a parcela
líquida nacional nem prova pagamento. O limite manual anterior
fica conservado.
</p>
{(
[
['gross', 'Rendimento bruto — MZN'],
['from', 'Início do período documentado — AAAA-MM-DD'],
['to', 'Fim do período documentado — AAAA-MM-DD'],
[
'reference',
'Suporte da residência, contrato e condições convencionais',
],
] as const
).map(([key, label]) => (
<label key={key} className="block">
{label}
<input
aria-label={prefix + label}
value={p.treatyPreparation?.[key] ?? ''}
onChange={(e) => change(key, e.target.value)}
/>
</label>
))}
{facts.map(([key, label]) => (
<label key={key} className="block">
{label}
<select
aria-label={prefix + label}
value={p.treatyPreparation?.[key] ?? ''}
onChange={(e) => change(key, e.target.value)}
>
<option value="">Informação em falta</option>
<option value="yes">Sim — documentado</option>
<option value="no">Não — documentado</option>
</select>
</label>
))}
</fieldset>
);
}
@@ -1740,6 +1740,22 @@ export function annualReportRows(
(p.input.treaty === 'no'
? 'Não aplicável documentado'
: show(p.treatyLimit)) +
(p.treatyDerivation
? '; ' +
p.treatyDerivation.version +
'; bruto ' +
show(p.treatyDerivation.gross) +
' × ' +
p.treatyDerivation.rate +
'%; período ' +
p.treatyDerivation.from +
' a ' +
p.treatyDerivation.to +
'; ' +
p.treatyDerivation.reference +
'; ' +
p.treatyDerivation.source
: '') +
'; elegível: ' +
show(p.eligible) +
'; utilização anterior: ' +
+191 -1
View File
@@ -26,6 +26,36 @@ export type InternationalTaxProof = AnnualPpc & {
taxReference: string;
exerciseReference: string;
};
export type PtMzRoyaltyPreparation = {
capitalDefinition?: '' | 'yes' | 'no';
governmentInterestExemption?: '' | 'yes' | 'no';
gross: string;
from: string;
to: string;
reference: string;
residentMz: '' | 'yes' | 'no';
beneficialOwner: '' | 'yes' | 'no';
sourcePortugal: '' | 'yes' | 'no';
payerResidentPt: '' | 'yes' | 'no';
noLinkedEstablishment: '' | 'yes' | 'no';
armLength: '' | 'yes' | 'no';
royaltyDefinition: '' | 'yes' | 'no';
nonDigital: '' | 'yes' | 'no';
};
export const newPtMzRoyaltyPreparation = (): PtMzRoyaltyPreparation => ({
gross: '',
from: '',
to: '',
reference: '',
residentMz: '',
beneficialOwner: '',
sourcePortugal: '',
payerResidentPt: '',
noLinkedEstablishment: '',
armLength: '',
royaltyDefinition: '',
nonDigital: '',
});
export type InternationalPosition = {
id: string;
country: string;
@@ -40,6 +70,12 @@ export type InternationalPosition = {
nationalLimitReference: string;
nationalMethod?: 'documented' | 'proportional';
nationalBasisReference?: string;
treatyMethod?:
| 'documented'
| 'ptMzRoyalty'
| 'ptMzDividend'
| 'ptMzInterest';
treatyPreparation?: PtMzRoyaltyPreparation;
treaty: '' | 'yes' | 'no';
treatyLimit: string;
treatyReference: string;
@@ -151,10 +187,63 @@ export function validateInternational(c: InternationalCredits) {
) ||
!yesNo.includes(p.incomeIncluded) ||
!yesNo.includes(p.treaty) ||
(p.treatyMethod !== undefined &&
![
'documented',
'ptMzRoyalty',
'ptMzDividend',
'ptMzInterest',
].includes(p.treatyMethod)) ||
(p.treatyPreparation !== undefined &&
(!p.treatyPreparation ||
Object.keys(newPtMzRoyaltyPreparation()).some(
(k) =>
typeof (
p.treatyPreparation as unknown as Record<
string,
unknown
>
)[k] !== 'string',
) ||
[
'residentMz',
'beneficialOwner',
'sourcePortugal',
'payerResidentPt',
'noLinkedEstablishment',
'armLength',
'royaltyDefinition',
'nonDigital',
].some(
(k) =>
!yesNo.includes(
(
p.treatyPreparation as unknown as Record<
string,
string
>
)[k],
),
))) ||
(p.nationalMethod !== undefined &&
!['documented', 'proportional'].includes(p.nationalMethod)) ||
(p.nationalBasisReference !== undefined &&
typeof p.nationalBasisReference !== 'string') ||
(p.treatyPreparation &&
['capitalDefinition', 'governmentInterestExemption'].some(
(k) => {
const v = (
p.treatyPreparation as unknown as Record<
string,
unknown
>
)[k];
return (
v !== undefined &&
(typeof v !== 'string' || !yesNo.includes(v))
);
},
)) ||
!evidenceValid(p.previousUse) ||
!Array.isArray(p.payments)
)
@@ -277,6 +366,102 @@ export function internationalGroupPending(
}
return pending;
}
const validDate = (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 ptMzTreatyLimit(p: InternationalPosition) {
const q = p.treatyPreparation;
if (
p.treaty !== 'yes' ||
p.country !== 'PT' ||
p.qualificationCountry !== 'PT' ||
p.year !== '2026' ||
!q?.reference.trim()
)
throw Error(
'CDT PT–MZ12/23(3)a: royalties de fonte portuguesa de residente em Moçambique, exercício2026 e suporte por corresponder.',
);
for (const key of [
'residentMz',
'beneficialOwner',
'sourcePortugal',
'payerResidentPt',
'noLinkedEstablishment',
] as const)
if (q[key] !== 'yes')
throw Error(
'CDT PT–MZ royalties: condição por documentar — ' + key + '.',
);
if (p.treatyMethod !== 'ptMzDividend' && q.armLength !== 'yes')
throw Error(
'Excesso por relações especiais em juros/royalties por corresponder.',
);
if (
p.treatyMethod === 'ptMzRoyalty' &&
(q.royaltyDefinition !== 'yes' || q.nonDigital !== 'yes')
)
throw Error(
'Royalties ordinárias não digitais e definição convencional por documentar.',
);
if (p.treatyMethod !== 'ptMzRoyalty' && q.capitalDefinition !== 'yes')
throw Error(
'Definição convencional de dividendos/juros por documentar.',
);
if (
p.treatyMethod === 'ptMzInterest' &&
q.governmentInterestExemption !== 'no'
)
throw Error(
'Juros abrangidos ou por corresponder à isenção governamental11(3) exigem tratamento próprio; não presumir limite ordinário.',
);
if (
!validDate(q.from) ||
!validDate(q.to) ||
q.from > q.to ||
!p.payments.length ||
p.payments.some(
(r) => !validDate(r.date) || r.date < q.from || r.date > q.to,
)
)
throw Error(
'Comprovativos fora do período documentado da CDT/residência; não presumir cobertura.',
);
const gross = creditMoney(q.gross);
if (creditCompare(gross, creditMoney(p.incomeAmount)) < 0n)
throw Error(
'Rendimento bruto inferior à parcela líquida incluída; reconcilie custos/perdas e base.',
);
return {
version:
p.treatyMethod === 'ptMzRoyalty'
? 'IRPC-PT-MZ-royalty-credit/1'
: 'IRPC-PT-MZ-capital-credit/1',
...(p.treatyMethod !== 'ptMzRoyalty' ? { nature: p.treatyMethod } : {}),
gross,
rate: '10',
limit: fraction(
BigInt(gross.numerator),
BigInt(gross.denominator) * 10n,
),
from: q.from,
to: q.to,
reference: q.reference,
source:
p.treatyMethod === 'ptMzRoyalty'
? 'CDT PT–MZ, RAR36/1992 art12(2/4–6),PDF13–14 e23(3)a,PDF21; Protocolo RAR36/2009 arts1/7,PDF1–2; CIRPC65(2). Royalties ordinárias não digitais, sem EP/instalação fixa ligada nem excesso por relações especiais. Não confundir com retenção L5 paga por devedor moçambicano; sem isenção ou tax sparing presumidos.'
: 'CDT PT–MZ, RAR36/1992 art23(3)a,PDF21; CIRPC65(2). ' +
(p.treatyMethod === 'ptMzDividend'
? 'Dividendos10(2–4),PDF10; taxa10% actualizada pelo Protocolo RAR36/2009 art6,PDF2; IRPC/art2 actualizado pelo art1.'
: p.treatyMethod === 'ptMzInterest'
? 'Juros11(2–7),PDF11–12, excluída a isenção11(3); IRPC/art2 actualizado pelo Protocolo RAR36/2009 art1.'
: 'Royalties12(2/4–6),PDF13–14; definição actualizada pelo Protocolo RAR36/2009 art7,PDF2; IRPC/art2 actualizado pelo art1. Recorte ordinário não digital.') +
(p.treatyMethod === 'ptMzDividend'
? ' Sem EP/instalação fixa ligada.'
: ' Sem EP/instalação fixa ligada ou excesso convencional por relações especiais.') +
' Não confundir com retenção L5 de devedor moçambicano; sem isenção ou tax sparing presumidos.',
};
}
export function internationalPosition(
p: InternationalPosition,
paid: FiscalFraction,
@@ -297,6 +482,7 @@ export function internationalPosition(
eligible: FiscalFraction | null = null,
available: FiscalFraction | null = null,
aboveLimit: FiscalFraction | null = null;
let treatyDerivation: ReturnType<typeof ptMzTreatyLimit> | null = null;
let nationalDerivation: {
version: string;
income: FiscalFraction;
@@ -381,7 +567,10 @@ export function internationalPosition(
);
if (!p.treaty || !p.treatyReference.trim())
throw Error('Aplicabilidade da convenção e suporte em falta.');
if (p.treaty === 'yes') treatyLimit = creditLimit(p.treatyLimit);
if (p.treatyMethod && p.treatyMethod !== 'documented') {
treatyDerivation = ptMzTreatyLimit(p);
treatyLimit = treatyDerivation.limit;
} else 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())
@@ -421,6 +610,7 @@ export function internationalPosition(
nationalLimit,
...(nationalDerivation ? { nationalDerivation } : {}),
treatyLimit,
...(treatyDerivation ? { treatyDerivation } : {}),
previousUse,
eligible,
available,