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
@@ -0,0 +1,53 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class IrpcInvestmentCarryDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_derived_national_fraction_round_trips_through_the_existing_private_draft_writer(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('proactive_investment_20261027_test', $target->name);
$this->assertSame(55441, (int) $target->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::findOrFail(1021));
$id = null;
$etag = null;
foreach (['carry', 'expired'] as $name) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-cbf15-carry-20261110/'.$name.'.json')), true, flags: JSON_THROW_ON_ERROR);
$personal = ['person_type' => $snapshot['person_type']];
unset($snapshot['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $snapshot];
if ($id === null) {
$id = $this->postJson('/api/v1/simulation-drafts', $payload, ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
} else {
$this->putJson('/api/v1/simulation-drafts/'.$id, $payload, ['If-Match' => $etag])->assertOk();
}
$response = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk();
$etag = $response->headers->get('ETag');
$back = $response->json('data.economic_snapshot');
$this->assertSame($snapshot['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($snapshot['business_plan_snapshot'], $back['business_plan_snapshot']);
$book = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR)['irpcAnnual'][$snapshot['context_opportunity']];
$this->assertSame(3, $book['version']);
$this->assertCount(array_search($name, ['carry', 'expired'], true) + 6, $book['history']);
$model = $book['result']['model'];
$this->assertSame($name === 'carry' ? 'active' : 'expired', $model['investmentCredit']['window']['status']);
$this->assertSame(2, $book['investmentCredit']['version']);
$this->assertSame(['numerator' => $name === 'carry' ? '3000' : '0', 'denominator' => '1'], $model['investmentCredit']['available']);
$this->assertSame(['numerator' => $name === 'carry' ? '0' : '3000', 'denominator' => '1'], $model['investmentCredit']['expired']);
$this->assertSame('IRPC-CBF15/3', $model['investmentCredit']['version']);
$this->assertSame(['numerator' => $name === 'carry' ? '200' : '0', 'denominator' => '1'], $model['investmentCredit']['deducted']);
$this->assertSame(['numerator' => $name === 'carry' ? '500' : '700', 'denominator' => '1'], $model['arithmeticBalance']);
file_put_contents(base_path('outputs/irpc-cbf15-carry-20261110/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
@@ -0,0 +1,34 @@
import { investmentCase } from './irpc-investment-case.mjs';
import { prepareInvestmentCarry } from '../../../resources/js/lib/irpc-annual-settlement.ts';
export function investmentCarryCase() {
const c = investmentCase();
c.b = prepareInvestmentCarry(c.d, c.b);
const t = c.b.investmentCredit;
t.startDate = '2022-01-01';
t.carryForward = {
reference:
'SYNTHETIC historical investment/credit record,same project,qualification and rate',
useReconciled: 'yes',
currentState: 'absent',
currentReference: 'SYNTHETIC no realised2026 investment',
};
t.assets = [
{
...t.assets[0],
date: '2025-05-01',
originYear: '2025',
originNuit: t.subjectNuit,
originProject: t.projectReference,
originRate: '5',
originReference:
'SYNTHETIC 2025 CBF15 qualifying credit,same approved project and Maputo city; original value and tax origin',
},
];
t.previousUse = {
state: 'known',
amount: '100',
reference:
'SYNTHETIC actual tax credit use100,all origins reconciled; not simulation history',
};
return c;
}
@@ -0,0 +1,121 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import * as annual from '../../resources/js/lib/irpc-annual-settlement.ts';
import * as investment from '../../resources/js/lib/irpc-investment-credit.ts';
import { investmentCase } from './helpers/irpc-investment-case.mjs';
import { investmentCarryCase } from './helpers/irpc-investment-carry-case.mjs';
const require = createRequire(import.meta.url),
module = { exports: {} };
const source = fs.readFileSync(
new URL(
'../../resources/js/components/simulation-irpc-investment.tsx',
import.meta.url,
),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === '@/lib/irpc-annual-settlement'
? annual
: name === '@/lib/irpc-investment-credit'
? investment
: name === './simulation-irpc-special'
? { QualificationFields: () => null }
: name === './fiscal-proof-parcel'
? { FiscalProofParcelFields: () => null }
: require(name),
module,
module.exports,
);
const Component = module.exports.SimulationIrpcInvestment;
const text = (node) =>
typeof node === 'string' || typeof node === 'number'
? String(node)
: React.isValidElement(node)
? React.Children.toArray(node.props.children).map(text).join('')
: '';
const all = (node) =>
React.isValidElement(node)
? [node, ...React.Children.toArray(node.props.children).flatMap(all)]
: [];
function harness(c) {
let b = c.b;
return {
book: () => b,
render: () =>
Component({
draft: c.d,
book: b,
save: (next) => {
b = next;
},
}),
click(label) {
const button = all(this.render()).find(
(n) => n.type === 'button' && text(n) === label,
);
assert.ok(button, label);
button.props.onClick();
},
change(label, value) {
const input = all(this.render()).find(
(n) => n.props['aria-label'] === label,
);
assert.ok(input, label);
input.props.onChange({ target: { value } });
},
};
}
void test('actual form prepares carry without inventing qualification or erasing current assets', () => {
const c = investmentCase(),
before = structuredClone(c.b.investmentCredit.assets),
h = harness(c);
h.click('Preparar transporte de crédito de anos anteriores');
assert.equal(h.book().version, 3);
assert.equal(h.book().investmentCredit.version, 2);
assert.deepEqual(h.book().investmentCredit.assets, before);
assert.equal(h.book().investmentCredit.carryForward.useReconciled, '');
h.click('Acrescentar activo de origem anterior');
assert.equal(h.book().investmentCredit.assets.length, 2);
assert.equal(h.book().investmentCredit.assets[1].originYear, '');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
});
void test('actual origin and use controls invalidate inconsistent credit and recover when reconciled', () => {
const c = investmentCarryCase(),
h = harness(c);
assert.deepEqual(annual.calculateAnnual(c.d, h.book()).pending, []);
h.change('CBF15 origem 1 — NUIT do contribuinte de origem', '999999999');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
h.change(
'CBF15 origem 1 — NUIT do contribuinte de origem',
c.b.subjectNuit,
);
h.change('CBF15 origem 1 — Referência do projecto de origem', 'OTHER');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
h.change(
'CBF15 origem 1 — Referência do projecto de origem',
c.b.investmentCredit.projectReference,
);
h.change('CBF15 origem 1 — Taxa original documentada — 5 ou 10', '10');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
h.change('CBF15 origem 1 — Taxa original documentada — 5 ou 10', '5');
h.change('CBF15 — Montante de uso anterior', '600');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
h.change('CBF15 — Montante de uso anterior', '100');
assert.deepEqual(annual.calculateAnnual(c.d, h.book()).pending, []);
h.change('CBF15 transporte — Reconciliação do uso', '');
assert.equal(annual.calculateAnnual(c.d, h.book()).arithmeticBalance, null);
assert.equal(h.book().investmentCredit.assets[0].originYear, '2025');
});
@@ -0,0 +1,160 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { investmentCase } from './helpers/irpc-investment-case.mjs';
import { investmentCarryCase } from './helpers/irpc-investment-carry-case.mjs';
import {
calculateAnnual,
recordAnnual,
saveAnnualBook,
annualBook,
annualCurrent,
annualHtml,
validateAnnual,
} from '../../resources/js/lib/irpc-annual-settlement.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
const f = (n) => ({ numerator: String(n), denominator: '1' });
void test('CBF15 carries only actual unused original credit:500 less100 used,without requiring a new investment', () => {
const c = investmentCarryCase(),
m = calculateAnnual(c.d, c.b);
assert.deepEqual(m.pending, []);
assert.deepEqual(m.investmentCredit.carryNominal, f(500));
assert.deepEqual(m.investmentCredit.currentNominal, f(0));
assert.deepEqual(m.investmentCredit.available, f(400));
assert.deepEqual(m.investmentCredit.deducted, f(400));
assert.deepEqual(m.arithmeticBalance, f(300));
assert.equal(m.investmentCredit.officialBalancesConsumed, false);
assert.equal(m.investmentCredit.carryCreated, false);
assert.deepEqual(
calculateAnnual(c.d, c.b).investmentCredit,
m.investmentCredit,
);
});
void test('CBF15 combines distinct current and original assets once,with project quota and actual prior use', () => {
const c = investmentCarryCase(),
t = c.b.investmentCredit;
t.carryForward.currentState = 'known';
t.assets.push({
...investmentCase().b.investmentCredit.assets[0],
id: 'current',
document: 'CURRENT2026',
});
let m = calculateAnnual(c.d, c.b);
assert.deepEqual(m.pending, []);
assert.deepEqual(m.investmentCredit.nominal, f(1000));
assert.deepEqual(m.investmentCredit.available, f(900));
assert.deepEqual(m.arithmeticBalance, f(-200));
t.soleProject = 'no';
t.projectQuota = {
amount: '200',
reference: 'SYNTHETIC residual project collecta200',
};
m = calculateAnnual(c.d, c.b);
assert.deepEqual(m.pending, []);
assert.deepEqual(m.investmentCredit.deducted, f(200));
assert.deepEqual(m.investmentCredit.unused, f(700));
});
void test('CBF15 carry expires with the original project window; prior use and source investment remain visible', () => {
const c = investmentCarryCase();
c.b.investmentCredit.startDate = '2021-01-01';
const m = calculateAnnual(c.d, c.b);
assert.deepEqual(m.pending, []);
assert.deepEqual(m.investmentCredit.carryNominal, f(500));
assert.deepEqual(m.investmentCredit.priorUse, f(100));
assert.deepEqual(m.investmentCredit.expired, f(400));
assert.deepEqual(m.investmentCredit.available, f(0));
assert.deepEqual(m.arithmeticBalance, f(700));
assert.equal(m.investmentCredit.input.assets[0].amount, '10000');
});
void test('CBF15 carry requires original exercise,rate,qualification and actual-use reconciliation', () => {
for (const patch of [
{ originNuit: '999999999' },
{ originProject: 'OTHER-PROJECT' },
{ originYear: '' },
{ originYear: '2026' },
{ originYear: '2021' },
{ originYear: '2024' },
{ originRate: '10' },
{ originReference: '' },
]) {
const c = investmentCarryCase();
Object.assign(c.b.investmentCredit.assets[0], patch);
assert.equal(
calculateAnnual(c.d, c.b).arithmeticBalance,
null,
JSON.stringify(patch),
);
}
for (const patch of [
{ useReconciled: '' },
{ reference: '' },
{ currentState: '' },
{ currentState: 'known' },
{ currentReference: '' },
]) {
const c = investmentCarryCase();
Object.assign(c.b.investmentCredit.carryForward, patch);
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
}
const c = investmentCarryCase();
c.b.investmentCredit.previousUse.amount = '501';
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
c.b.investmentCredit.previousUse.amount = '500';
assert.deepEqual(calculateAnnual(c.d, c.b).investmentCredit.deducted, f(0));
});
void test('CBF15 cannot duplicate historical investment through another id/date,another current row or another scope', () => {
const c = investmentCarryCase(),
t = c.b.investmentCredit;
t.assets.push({ ...t.assets[0], id: 'other', date: '2025-06-01' });
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
const d = investmentCarryCase(),
a = d.b.investmentCredit.assets[0];
d.b.investmentCredit.carryForward.currentState = 'known';
const current = { ...a, id: 'fake-current', date: '2026-01-01' };
delete current.originYear;
delete current.originNuit;
delete current.originProject;
delete current.originRate;
delete current.originReference;
d.b.investmentCredit.assets.push(current);
assert.equal(calculateAnnual(d.d, d.b).arithmeticBalance, null);
const e = investmentCarryCase(),
root = JSON.parse(e.d.modelo_a_snapshot);
root.irpcAnnual = { ...root.irpcAnnual, other: structuredClone(e.b) };
assert.equal(
calculateAnnual(
{ ...e.d, modelo_a_snapshot: JSON.stringify(root) },
e.b,
).arithmeticBalance,
null,
);
});
void test('version3 protects carry from older code; legacy books and prior result history are preserved', () => {
const c = investmentCarryCase();
assert.equal(c.b.version, 3);
assert.equal(c.b.investmentCredit.version, 2);
const broken = structuredClone(c.b);
broken.version = 2;
assert.throws(() => validateAnnual(broken));
const b = recordAnnual(c.d, c.b, '2026-11-10T16:00:00Z');
b.investmentCredit.previousUse.amount = '200';
const next = recordAnnual(c.d, b, '2026-11-10T16:01:00Z'),
d = { ...c.d, modelo_a_snapshot: saveAnnualBook(c.d, next) },
back = annualBook(d);
assert.equal(annualCurrent(d, back), true);
assert.deepEqual(back.history[0].model.investmentCredit.deducted, f(400));
assert.deepEqual(
calculateAnnual(d, back).investmentCredit,
back.result.model.investmentCredit,
);
assert.match(annualHtml(d), /TransporteCBF15/);
assert.match(annualHtml(d), /2025/);
assert.match(
JSON.stringify(
createProjectDossierReport(d, {
selectedSections: new Set(['finance']),
generatedAt: '2026-11-10T16:01:00Z',
}),
),
/TransporteCBF15/,
);
});
@@ -188,7 +188,7 @@ void test('CBF15 calculation-save-recovery-HTML and dossier reports retain sourc
numerator: '200',
denominator: '1',
});
assert.match(annualHtml(d), /IRPC-CBF15\/2/);
assert.match(annualHtml(d), /IRPC-CBF15\/3/);
assert.match(
JSON.stringify(
createProjectDossierReport(d, {
@@ -196,7 +196,7 @@ void test('CBF15 calculation-save-recovery-HTML and dossier reports retain sourc
generatedAt: '2026-11-10T19:00:00+02:00',
}),
),
/IRPC-CBF15\/2/,
/IRPC-CBF15\/3/,
);
const old = internationalCase();
assert.equal(calculateAnnual(old.d, old.b).investmentCredit, undefined);