feat: carry documented investment credits within original project window
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-10 16:17:48 +02:00
parent d216830b06
commit 7476dc3430
14 changed files with 827 additions and 30 deletions
@@ -2,6 +2,7 @@ import { QualificationFields } from './simulation-irpc-special';
import { FiscalProofParcelFields } from './fiscal-proof-parcel';
import {
prepareInvestmentCredit,
prepareInvestmentCarry,
type AnnualBook,
} from '@/lib/irpc-annual-settlement';
import {
@@ -302,6 +303,127 @@ export function SimulationIrpcInvestment({
</button>
</>
)}
{!c.carryForward ? (
<button
type="button"
onClick={() => save(prepareInvestmentCarry(draft, book))}
>
Preparar transporte de crédito de anos anteriores
</button>
) : (
<fieldset className="space-y-2 rounded border p-3">
<legend>Transporte CBF15 do mesmo projecto</legend>
<p>
Declare activos de origem anterior, taxa e qualificação
históricas. Não copie saldos de simulações como uso
fiscal. O prazo original de cinco exercícios mantém-se;
investimentos correntes ficam separados.
</p>
<label className="block">
Correspondência histórica do crédito transportado
<input
aria-label="CBF15 transporte — Correspondência"
value={c.carryForward.reference}
onChange={(e) =>
patch({
carryForward: {
...c.carryForward!,
reference: e.target.value,
},
})
}
/>
</label>
<label className="block">
Investimento efectivo de 2026
<select
aria-label="CBF15 transporte — Investimento corrente"
value={c.carryForward.currentState}
onChange={(e) =>
patch({
carryForward: {
...c.carryForward!,
currentState: e.target.value as
| 'known'
| 'absent'
| '',
},
})
}
>
<option value="">Por documentar</option>
<option value="known">
Conhecido — activos correntes discriminados
</option>
<option value="absent">
Ausência documentada — apenas origens anteriores
</option>
</select>
</label>
<label className="block">
Suporte do investimento corrente/ausência
<input
aria-label="CBF15 transporte — Suporte corrente"
value={c.carryForward.currentReference}
onChange={(e) =>
patch({
carryForward: {
...c.carryForward!,
currentReference: e.target.value,
},
})
}
/>
</label>
<label className="block">
Uso efectivo de todo o crédito reconciliado
<select
aria-label="CBF15 transporte — Reconciliação do uso"
value={c.carryForward.useReconciled}
onChange={(e) =>
patch({
carryForward: {
...c.carryForward!,
useReconciled: e.target.value as
| ''
| 'yes'
| 'no',
},
})
}
>
<option value="">Por documentar</option>
<option value="yes">
Sim — inclui as origens anteriores e o crédito
corrente
</option>
<option value="no">Não reconciliado</option>
</select>
</label>
<button
type="button"
onClick={() =>
patch({
assets: [
...c.assets,
{
...newInvestmentAsset(
crypto.randomUUID(),
),
originYear: '',
originNuit: '',
originProject: '',
originReference: '',
originRate: '',
},
],
})
}
>
Acrescentar activo de origem anterior
</button>
</fieldset>
)}
{c.assets.map((r, index) => {
const change = (v: Partial<InvestmentAsset>) =>
patch({
@@ -315,6 +437,57 @@ export function SimulationIrpcInvestment({
className="space-y-2 rounded border p-3"
>
<legend>Investimento {index + 1}</legend>
{r.originYear !== undefined && (
<>
<p>
Origem anterior — mantém a data real de
aquisição e o prazo original do projecto.
</p>
{(
[
[
'originYear',
'Exercício que originou o crédito',
],
[
'originNuit',
'NUIT do contribuinte de origem',
],
[
'originProject',
'Referência do projecto de origem',
],
[
'originRate',
'Taxa original documentada — 5 ou 10',
],
[
'originReference',
'Suporte da qualificação e crédito de origem,mesmo projecto/local/regime',
],
] as const
).map(([key, label]) => (
<label key={key} className="block">
{label}
<input
aria-label={
'CBF15 origem ' +
(index + 1) +
' — ' +
label
}
value={r[key] ?? ''}
onChange={(e) =>
change({
[key]: e.target.value,
})
}
/>
</label>
))}
</>
)}
{(
[
['issuer', 'Fornecedor/emitente'],
@@ -444,7 +617,8 @@ export function SimulationIrpcInvestment({
<option value="absent">Ausência documentada</option>
</select>
<label className="block">
Montante anteriormente utilizado
Montante anteriormente utilizado em todo o crédito
discriminado
<input
aria-label="CBF15 — Montante de uso anterior"
value={c.previousUse.amount}
+74 -4
View File
@@ -106,7 +106,7 @@ type AnnualRecord = {
model: AnnualModel;
};
export type AnnualBook = {
version: 1 | 2;
version: 1 | 2 | 3;
subjectNuit: string;
year: string;
reference: string;
@@ -164,6 +164,27 @@ export function prepareInvestmentCredit(
c.qualification.to = a.period?.to ?? '';
return { ...next, version: 2, investmentCredit: c };
}
export function prepareInvestmentCarry(
d: Record<string, unknown>,
b: AnnualBook,
): AnnualBook {
const next = prepareInvestmentCredit(d, b);
if (next.investmentCredit!.carryForward) return next;
return {
...next,
version: 3,
investmentCredit: {
...next.investmentCredit!,
version: 2,
carryForward: {
reference: '',
useReconciled: '',
currentState: '',
currentReference: '',
},
},
};
}
export function prepareEconomicBook(b: AnnualBook): AnnualBook {
if (b.economicCredits) return b;
const next = prepareInternationalBook(b),
@@ -279,9 +300,10 @@ export function validateAnnual(b: AnnualBook) {
validateInternational(b.internationalCredits);
if (
!b ||
![1, 2].includes(b.version) ||
(b.version === 2 && b.investmentCredit === undefined) ||
(b.investmentCredit !== undefined && b.version !== 2) ||
![1, 2, 3].includes(b.version) ||
(b.version >= 2 && b.investmentCredit === undefined) ||
(b.investmentCredit !== undefined &&
b.version !== (b.investmentCredit.carryForward ? 3 : 2)) ||
[
'subjectNuit',
'year',
@@ -2132,6 +2154,28 @@ export function annualReportRows(
show(m.investmentCredit.nominal) +
'; uso anterior ' +
show(m.investmentCredit.priorUse) +
(m.investmentCredit.input.carryForward
? '; TransporteCBF15/1: nominal corrente ' +
show(
m.investmentCredit.currentNominal ??
null,
) +
'; nominal de origem anterior ' +
show(
m.investmentCredit.carryNominal ?? null,
) +
'; parcela expirada ' +
show(m.investmentCredit.expired ?? null) +
'; ' +
m.investmentCredit.input.carryForward
.reference +
'; investimento corrente ' +
m.investmentCredit.input.carryForward
.currentState +
': ' +
m.investmentCredit.input.carryForward
.currentReference
: '') +
'; disponível ' +
show(m.investmentCredit.available) +
'; dedução ' +
@@ -2189,6 +2233,32 @@ export function annualReportRows(
'; outros benefícios: ' +
m.investmentCredit.input
.noOtherBenefitsReference +
(m.investmentCredit.input.carryForward
? '; origens: ' +
m.investmentCredit.input.assets
.filter(
(r) => r.originYear !== undefined,
)
.map(
(r) =>
r.issuer +
'/' +
r.document +
'/' +
r.parcel +
': exercício ' +
r.originYear +
'; NUIT ' +
r.originNuit +
'; projecto ' +
r.originProject +
', taxa ' +
r.originRate +
'%; ' +
r.originReference,
)
.join(' | ')
: '') +
'; uso anterior: ' +
m.investmentCredit.input.previousUse.reference +
'; ' +
+131 -11
View File
@@ -21,11 +21,16 @@ import {
fraction,
type FiscalFraction,
} from './fiscal-rational.ts';
export const investmentCreditVersion = 'IRPC-CBF15/2';
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,sem transporte de activos/créditos anteriores. 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.';
'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;
@@ -61,7 +66,13 @@ export const newInvestmentAsset = (id: string): InvestmentAsset => ({
});
export type InvestmentCredit = {
projectQuota?: { amount: string; reference: string };
version: 1;
version: 1 | 2;
carryForward?: {
reference: string;
useReconciled: Choice;
currentState: '' | 'known' | 'absent';
currentReference: string;
};
qualification: Qualification;
subjectNuit: string;
year: string;
@@ -110,7 +121,7 @@ export function validateInvestmentCredit(c: InvestmentCredit) {
const template = newInvestmentCredit();
if (
!c ||
c.version !== 1 ||
![1, 2].includes(c.version) ||
Object.keys(template)
.filter(
(k) =>
@@ -139,6 +150,19 @@ export function validateInvestmentCredit(c: InvestmentCredit) {
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) ||
@@ -170,6 +194,20 @@ export function validateInvestmentCredit(c: InvestmentCredit) {
for (const r of c.assets) {
if (
!r ||
[
'originYear',
'originReference',
'originRate',
'originNuit',
'originProject',
].some(
(k) =>
(r as unknown as Record<string, unknown>)[k] !==
undefined &&
(c.version !== 2 ||
typeof (r as unknown as Record<string, unknown>)[k] !==
'string'),
) ||
Object.keys(newInvestmentAsset('')).some(
(k) =>
typeof (r as unknown as Record<string, unknown>)[k] !==
@@ -221,6 +259,9 @@ export function calculateInvestmentCredit(
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:
| {
@@ -307,6 +348,29 @@ export function calculateInvestmentCredit(
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.',
@@ -342,7 +406,8 @@ export function calculateInvestmentCredit(
!r.issuer.trim() ||
!r.document.trim() ||
!iso(r.date) ||
!r.date.startsWith(b.year + '-') ||
(r.originYear === undefined &&
!r.date.startsWith(b.year + '-')) ||
!r.reference.trim() ||
r.newTangible !== 'yes' ||
r.domesticUse !== 'yes' ||
@@ -352,6 +417,27 @@ export function calculateInvestmentCredit(
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.',
@@ -384,12 +470,19 @@ export function calculateInvestmentCredit(
}
rows.push({
input: structuredClone(r),
value: value && window?.status === 'expired' ? zero() : value,
value:
value &&
window?.status === 'expired' &&
r.originYear === undefined
? zero()
: value,
reason: issues.length
? issues.join(' ')
: window?.status === 'expired'
? 'Prazo15(4) terminado no quinto exercício; investimento2026 conservado,sem crédito.'
: 'Activo elegível documentado.',
: 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);
@@ -430,6 +523,25 @@ export function calculateInvestmentCredit(
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(
@@ -443,6 +555,10 @@ export function calculateInvestmentCredit(
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));
}
@@ -463,17 +579,21 @@ export function calculateInvestmentCredit(
rate,
...(window ? { window } : {}),
nominal,
...(c.carryForward ? { currentNominal, carryNominal, expired } : {}),
priorUse,
available: pending.length ? null : available,
pending,
source:
c.soleProject === 'no'
(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,
: investmentCreditSource),
};
}
export function deductInvestmentCredit(