feat: qualify treaty interest under governmental financing agreements
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-10 14:18:47 +02:00
parent b10b35f308
commit 7c8d4726e9
10 changed files with 464 additions and 64 deletions
@@ -0,0 +1,36 @@
<?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 IrpcPtMzAgreementDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_agreement_pt_mz_credit_uses_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));
$d = json_decode(file_get_contents(base_path('outputs/irpc-pt-mz-agreement-20261110/fixture.json')), true, flags: JSON_THROW_ON_ERROR);
$personal = ['person_type' => $d['person_type']];
unset($d['person_type']);
$id = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => $personal, 'economic_snapshot' => $d], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$back = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->json('data.economic_snapshot');
$this->assertSame($d['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($d['business_plan_snapshot'], $back['business_plan_snapshot']);
$b = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR)['irpcAnnual'][$d['context_opportunity']];
$this->assertSame('ptMzInterest', $b['internationalCredits']['positions'][0]['treatyMethod']);
$this->assertSame(['numerator' => '0', 'denominator' => '1'], $b['result']['model']['internationalCredit']['positions'][0]['treatyLimit']);
$this->assertSame(['numerator' => '708', 'denominator' => '1'], $b['result']['model']['arithmeticBalance']);
$this->assertSame('agreement', $b['result']['model']['internationalCredit']['positions'][0]['treatyDerivation']['governmentExemption']['basis']);
file_put_contents(base_path('outputs/irpc-pt-mz-agreement-20261110/recovered.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
@@ -0,0 +1,127 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { internationalCase } from './helpers/irpc-international-case.mjs';
import { newPtMzRoyaltyPreparation } from '../../resources/js/lib/irpc-international-credit.ts';
import {
calculateAnnual,
recordAnnual,
saveAnnualBook,
annualBook,
annualCurrent,
annualHtml,
} from '../../resources/js/lib/irpc-annual-settlement.ts';
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
function agreementCase() {
const c = internationalCase();
Object.assign(c.b.internationalCredits.positions[0], {
country: 'PT',
qualificationCountry: 'PT',
incomeAmount: '40',
treaty: 'yes',
treatyMethod: 'ptMzInterest',
treatyReference: 'SYNTHETIC QA explicit PT-MZ11(3)b/23(3)a scope',
treatyPreparation: {
...newPtMzRoyaltyPreparation(),
gross: '60',
from: '2026-01-01',
to: '2026-12-31',
reference: 'SYNTHETIC residence and interest contract conditions',
residentMz: 'yes',
beneficialOwner: 'yes',
sourcePortugal: 'yes',
payerResidentPt: 'yes',
noLinkedEstablishment: 'yes',
armLength: 'yes',
capitalDefinition: 'yes',
governmentInterestExemption: 'yes',
governmentBasis: 'agreement',
institutionRecipient: 'yes',
financingGranted: 'yes',
bilateralAgreement: 'yes',
institutionReference:
'SYNTHETIC current subject123456789 is qualifying institution',
financingReference:
'SYNTHETIC financing granted by this institution and linked to interest',
agreementReference:
'SYNTHETIC PT-MZ intergovernmental agreement and applicable financing clause',
},
});
return c;
}
void test('qualified institution financing under a PT-MZ governmental agreement gives zero source tax cap without altering L6', () => {
const c = agreementCase(),
before = c.d.modelo_a_snapshot,
m = calculateAnnual(c.d, c.b),
p = m.internationalCredit.positions[0];
assert.deepEqual(m.pending, []);
assert.deepEqual(p.treatyLimit, { numerator: '0', denominator: '1' });
assert.equal(p.treatyDerivation.governmentExemption.basis, 'agreement');
assert.deepEqual(p.aboveLimit, { numerator: '10', denominator: '1' });
assert.deepEqual(m.arithmeticBalance, {
numerator: '708',
denominator: '1',
});
assert.equal(m.internationalCredit.officialBalancesConsumed, false);
assert.equal(c.d.modelo_a_snapshot, before);
});
void test('institution identity alone does not prove a qualifying financing or governmental agreement', () => {
for (const patch of [
{ institutionRecipient: '' },
{ financingGranted: '' },
{ bilateralAgreement: 'no' },
{ institutionReference: '' },
{ financingReference: '' },
{ agreementReference: '' },
{ governmentBasis: '' },
]) {
const c = agreementCase();
Object.assign(
c.b.internationalCredits.positions[0].treatyPreparation,
patch,
);
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
}
});
void test('changing or clearing the basis preserves the old result but cannot reuse the former exemption', () => {
const c = agreementCase(),
book = recordAnnual(c.d, c.b, '2026-11-10T18:20:00+02:00'),
old = structuredClone(book.result);
Object.assign(book.internationalCredits.positions[0].treatyPreparation, {
governmentBasis: '',
governmentPayer: 'state',
governmentPayerReference:
'SYNTHETIC previous public-payer classification',
});
assert.equal(annualCurrent(c.d, book), false);
assert.equal(calculateAnnual(c.d, book).arithmeticBalance, null);
assert.deepEqual(book.result, old);
});
void test('agreement qualification and both documentary links survive recovery and reach both report consumers', () => {
const c = agreementCase(),
book = recordAnnual(c.d, c.b, '2026-11-10T18:20:00+02:00'),
d = JSON.parse(
JSON.stringify({
...c.d,
modelo_a_snapshot: saveAnnualBook(c.d, book),
}),
),
back = annualBook(d);
assert.equal(annualCurrent(d, back), true);
assert.deepEqual(
calculateAnnual(d, back).internationalCredit,
back.result.model.internationalCredit,
);
const html = annualHtml(d);
assert.match(html, /IRPC-PT-MZ-agreement-interest\/1/);
assert.match(html, /SYNTHETIC financing granted/);
assert.match(html, /SYNTHETIC PT-MZ intergovernmental agreement/);
assert.match(
JSON.stringify(
createProjectDossierReport(d, {
selectedSections: new Set(['finance']),
generatedAt: '2026-11-10T18:20:00+02:00',
}),
),
/IRPC-PT-MZ-agreement-interest\/1/,
);
});