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
@@ -0,0 +1,46 @@
<?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 IrpcPtMzCapitalDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_derived_pt_mz_capital_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));
$id = null;
$etag = null;
foreach (['dividend', 'interest'] as $kind) {
$d = json_decode(file_get_contents(base_path('outputs/irpc-pt-mz-'.$kind.'-20261110/fixture.json')), true, flags: JSON_THROW_ON_ERROR);
$personal = ['person_type' => $d['person_type']];
unset($d['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $d];
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($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($kind === 'dividend' ? 'ptMzDividend' : 'ptMzInterest', $b['internationalCredits']['positions'][0]['treatyMethod']);
$this->assertSame(['numerator' => '6', 'denominator' => '1'], $b['result']['model']['internationalCredit']['positions'][0]['treatyLimit']);
$this->assertSame(['numerator' => '702', 'denominator' => '1'], $b['result']['model']['arithmeticBalance']);
file_put_contents(base_path('outputs/irpc-pt-mz-'.$kind.'-20261110/recovered.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
+35
View File
@@ -0,0 +1,35 @@
<?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 IrpcPtMzCreditDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_derived_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-credit-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('ptMzRoyalty', $b['internationalCredits']['positions'][0]['treatyMethod']);
$this->assertSame(['numerator' => '6', 'denominator' => '1'], $b['result']['model']['internationalCredit']['positions'][0]['treatyLimit']);
$this->assertSame(['numerator' => '702', 'denominator' => '1'], $b['result']['model']['arithmeticBalance']);
file_put_contents(base_path('outputs/irpc-pt-mz-credit-20261110/recovered.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
+175
View File
@@ -0,0 +1,175 @@
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 treatyCase() {
const c = internationalCase();
Object.assign(c.b.internationalCredits.positions[0], {
country: 'PT',
qualificationCountry: 'PT',
incomeAmount: '40',
treaty: 'yes',
treatyMethod: 'ptMzRoyalty',
treatyReference:
'SYNTHETIC QA PT-MZ12/23(3)a actual royalty qualification, no real treaty decision',
treatyPreparation: {
...newPtMzRoyaltyPreparation(),
gross: '60',
from: '2026-01-01',
to: '2026-12-31',
reference:
'SYNTHETIC QA residence certificate, royalty contract and all conditions documented',
residentMz: 'yes',
beneficialOwner: 'yes',
sourcePortugal: 'yes',
payerResidentPt: 'yes',
noLinkedEstablishment: 'yes',
armLength: 'yes',
royaltyDefinition: 'yes',
nonDigital: 'yes',
},
});
return c;
}
void test('PT royalty credit derives a6 treaty ceiling from gross60 and leaves national fraction,paid tax and L6 separate', () => {
const c = treatyCase(),
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: '6', denominator: '1' });
assert.deepEqual(p.eligible, { numerator: '6', denominator: '1' });
assert.deepEqual(m.arithmeticBalance, {
numerator: '702',
denominator: '1',
});
assert.equal(c.d.modelo_a_snapshot, before);
});
void test('PT royalty matching rejects wrong country,unknown facts,expired coverage and contradictory gross without silently using the manual limit', () => {
for (const patch of [
{ country: 'ZA' },
{ treaty: 'no' },
{ treatyPreparation: { beneficialOwner: '' } },
{ treatyPreparation: { sourcePortugal: 'no' } },
{ treatyPreparation: { to: '2026-09-01' } },
{ treatyPreparation: { gross: '30' } },
{ treatyPreparation: { from: '2026-02-30' } },
]) {
const c = treatyCase(),
p = c.b.internationalCredits.positions[0];
const q = patch.treatyPreparation;
if (q) Object.assign(p.treatyPreparation, q);
else Object.assign(p, patch);
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
}
});
void test('PT royalty ceiling is exact and can be lower than paid tax without creating official use or refund', () => {
const c = treatyCase();
c.b.internationalCredits.positions[0].treatyPreparation.gross = '60.01';
const m = calculateAnnual(c.d, c.b);
assert.deepEqual(m.internationalCredit.positions[0].treatyLimit, {
numerator: '6001',
denominator: '1000',
});
assert.equal(m.internationalCredit.officialBalancesConsumed, false);
});
void test('PT royalty limit survives save,recovery and both report consumers; previous documented mode stays unchanged', () => {
const c = treatyCase(),
b = recordAnnual(c.d, c.b, '2026-11-10T17:00:00+02:00'),
d = JSON.parse(
JSON.stringify({
...c.d,
modelo_a_snapshot: saveAnnualBook(c.d, b),
}),
),
back = annualBook(d);
assert.equal(annualCurrent(d, back), true);
assert.deepEqual(
calculateAnnual(d, back).internationalCredit,
back.result.model.internationalCredit,
);
assert.match(annualHtml(d), /IRPC-PT-MZ-royalty-credit\/1/);
assert.match(
JSON.stringify(
createProjectDossierReport(d, {
selectedSections: new Set(['finance']),
generatedAt: '2026-11-10T17:00:00+02:00',
}),
),
/IRPC-PT-MZ-royalty-credit\/1/,
);
const old = internationalCase();
assert.equal(
calculateAnnual(old.d, old.b).internationalCredit.positions[0]
.treatyDerivation,
undefined,
);
});
void test('PT dividends use the2009 treaty10percent ceiling and interest uses ordinary11 conditions, preserving royalty evidence', () => {
for (const method of ['ptMzDividend', 'ptMzInterest']) {
const c = treatyCase(),
p = c.b.internationalCredits.positions[0];
p.treatyMethod = method;
Object.assign(p.treatyPreparation, {
capitalDefinition: 'yes',
governmentInterestExemption: 'no',
royaltyDefinition: '',
nonDigital: '',
...(method === 'ptMzDividend' ? { armLength: '' } : {}),
});
const m = calculateAnnual(c.d, c.b),
r = m.internationalCredit.positions[0];
assert.deepEqual(m.pending, []);
assert.deepEqual(r.treatyLimit, { numerator: '6', denominator: '1' });
assert.equal(r.treatyDerivation.nature, method);
assert.match(
r.treatyDerivation.source,
method === 'ptMzDividend' ? /art6/ : /11/,
);
const d = {
...c.d,
modelo_a_snapshot: saveAnnualBook(
c.d,
recordAnnual(c.d, c.b, '2026-11-10T17:10:00+02:00'),
),
};
assert.match(annualHtml(d), /IRPC-PT-MZ-capital-credit\/1/);
assert.match(
JSON.stringify(
createProjectDossierReport(d, {
selectedSections: new Set(['finance']),
generatedAt: '2026-11-10T17:10:00+02:00',
}),
),
/IRPC-PT-MZ-capital-credit\/1/,
);
}
});
void test('PT capital matching does not presume article11 governmental exemption or classification', () => {
for (const patch of [
{ capitalDefinition: '' },
{ governmentInterestExemption: '' },
{ governmentInterestExemption: 'yes' },
{ armLength: '' },
]) {
const c = treatyCase(),
p = c.b.internationalCredits.positions[0];
p.treatyMethod = 'ptMzInterest';
Object.assign(
p.treatyPreparation,
{ capitalDefinition: 'yes', governmentInterestExemption: 'no' },
patch,
);
assert.equal(calculateAnnual(c.d, c.b).arithmeticBalance, null);
}
});