feat(irpc): demonstrate documented international credit in QA
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-27 14:57:18 +02:00
parent 814fe0a9b7
commit 838ad941a2
17 changed files with 734 additions and 16 deletions
@@ -0,0 +1,62 @@
<?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 IrpcInternationalCreditDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_international_credit_delta_round_trips_with_frozen_history_and_unchanged_existing_records(): 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);
$snapshot=static fn(string $table):array=>collect(DB::select('select id::text as id,md5(row_to_json(t)::text) as hash from public."'.$table.'" t order by id'))->pluck('hash','id')->all();
$protected=[];
foreach(['opportunities','documents','opportunity_documents','simulation_form_drafts','users','organizations','audit_events']as$table)$protected[$table]=$snapshot($table);
config(['investor-path.enabled'=>true,'suitecrm.enabled'=>false]);
$this->actingAs(User::findOrFail(1021)); // Existing synthetic QA actor, no new grants.
$base=json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-assessment-preserved.json')),true,flags:JSON_THROW_ON_ERROR);
$fixture=json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-international-preserved.json')),true,flags:JSON_THROW_ON_ERROR);
$this->assertTrue($fixture['synthetic']);$this->assertFalse($fixture['actualConventionData']);
$personal=['person_type'=>$base['person_type']];unset($base['person_type']);
$id=null;$etag=null;$previous=null;
foreach($fixture['cases']as$name=>$book){
$draft=$base;$s=json_decode($draft['modelo_a_snapshot'],true,flags:JSON_THROW_ON_ERROR);
if($previous!==null)$book['history']=[$previous];
$s['irpcAnnual'][$draft['context_opportunity']]=$book;
$draft['modelo_a_snapshot']=json_encode($s,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE);
$payload=['personal_snapshot'=>$personal,'economic_snapshot'=>$draft];
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($draft['modelo_a_snapshot'],$back['modelo_a_snapshot']);$this->assertSame($draft['business_plan_snapshot'],$back['business_plan_snapshot']);
$recovered=json_decode($back['modelo_a_snapshot'],true,flags:JSON_THROW_ON_ERROR);
foreach(['irpcNormal','irpcWithholdings','books','currencyEvents','ispcQuarters']as$map)$this->assertSame($s[$map],$recovered[$map]);
$saved=$recovered['irpcAnnual'][$draft['context_opportunity']];$m=$saved['result']['model'];$credit=$m['internationalCredit'];
$this->assertSame($book,$saved);$this->assertSame('IRPC-international-credit/1',$credit['version']);$this->assertFalse($credit['carryCreated']);$this->assertFalse($credit['officialBalancesConsumed']);$this->assertFalse($credit['countryAllocationCreated']);$this->assertFalse($m['submitted']);
$this->assertSame(['numerator'=>'1408','denominator'=>'1'],$m['assessment']['colecta']);
if(in_array($name,['missing','duplicate'],true)){
$this->assertSame('indeterminate',$m['status']);$this->assertNull($m['arithmeticBalance']);$this->assertNull($credit['deducted']);$this->assertNull($m['pecDeduction']['deducted']);$this->assertNotEmpty($m['pending']);
}else{
$expected=['payable'=>['payable','700','8','1400','200'],'treaty'=>['payable','702','6','1402','200'],'limited-collecta'=>['recoverable','-500','1408','0','0'],'absent'=>['payable','708','0','1408','200'],'prior-use'=>['payable','703','5','1403','200']][$name];
$this->assertSame($expected[0],$m['status']);$this->assertEmpty($m['pending']);
$this->assertSame(['numerator'=>$expected[1],'denominator'=>'1'],$m['arithmeticBalance']);
$this->assertSame(['numerator'=>$expected[2],'denominator'=>'1'],$credit['deducted']);
$this->assertSame(['numerator'=>$expected[3],'denominator'=>'1'],$credit['afterCredit']);
$this->assertSame(['numerator'=>$expected[4],'denominator'=>'1'],$m['pecDeduction']['deducted']);
if($name==='limited-collecta'){$this->assertSame(['numerator'=>'592','denominator'=>'1'],$credit['insufficientCollecta']);$this->assertSame(['numerator'=>'200','denominator'=>'1'],$m['pecDeduction']['remaining']);}
}
if($previous!==null)$this->assertSame($previous,$saved['history'][0]);$previous=$saved['result'];
if(getenv('INVESTMOZ_INTERNATIONAL_QA_OUTPUT')==='1')file_put_contents(base_path('outputs/irpc-l8-international-20261027/recovered-'.$name.'.json'),json_encode($back,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE));
}
$preserved=[];
foreach($protected as$table=>$before){$this->assertSame($before,array_intersect_key($snapshot($table),$before),'Existing records changed: '.$table);$preserved[$table]=['existing_rows'=>count($before),'unchanged'=>true];}
if(getenv('INVESTMOZ_INTERNATIONAL_QA_OUTPUT')==='1')file_put_contents(base_path('outputs/irpc-l8-international-20261027/existing-records-preservation.json'),json_encode(['database'=>$target->name,'tables'=>$preserved,'transaction_rollback'=>true],JSON_THROW_ON_ERROR|JSON_PRETTY_PRINT));
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,9 @@
import {pecCase} from './irpc-pec-case.mjs';
import {prepareInternationalBook,newInternationalProof} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newInternationalPosition} from '../../../resources/js/lib/irpc-international-credit.ts';
export function internationalCase(tax='10',national='8',pec='200',ppc='500',rf='0') {
const c=pecCase(pec,ppc,rf);c.b=prepareInternationalBook(c.b);
const p={...newInternationalPosition('country-za'),country:'ZA',qualificationCountry:'ZA',subjectNuit:c.b.subjectNuit,year:c.b.year,assessmentKey:c.b.assessmentKey,incomeAmount:'100',incomeIncluded:'yes',incomeReference:'SYNTHETIC QA: foreign income included in valid 2026 base',nationalLimit:national,nationalLimitReference:'SYNTHETIC QA: documented national fraction, no automatic derivation',treaty:'no',treatyReference:'SYNTHETIC QA assumption only; not an assertion about actual ZA convention applicability',previousUse:{state:'known',amount:'0',reference:'SYNTHETIC QA: actual previous credit use known zero'},payments:[{...newInternationalProof('foreign-tax'),document:'SYNTHETIC-FOREIGN-TAX-2026',issuer:'SYNTHETIC QA foreign authority',date:'2026-09-30',subjectNuit:c.b.subjectNuit,year:c.b.year,proofAmount:tax,amount:tax,effective:'yes',incomeTax:'yes',reference:'SYNTHETIC QA paid MZN tax amount, no real receipt',taxReference:'SYNTHETIC QA income tax nature and entitlement'}]};
Object.assign(c.b.internationalCredits,{state:'known',reference:'SYNTHETIC QA complete inventory for entity/year',positions:[p]});
return c;
}
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import crypto from 'node:crypto';
import {countryIsoCodes} from '../../resources/js/lib/country-iso-codes.ts';
import {internationalCase} from './helpers/irpc-international-case.mjs';
import {calculateAnnual,annualBook,recordAnnual,saveAnnualBook,annualCurrent,annualHtml,annualReportRows,prepareInternationalBook} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const value=v=>v?Number(v.numerator)/Number(v.denominator):null;
const now='2026-10-27T17:00:00+02:00';
const calc=({d,b})=>calculateAnnual(d,b);
const pending=c=>{const m=calc(c);assert.equal(m.status,'indeterminate',JSON.stringify(m.pending));assert.equal(m.arithmeticBalance,null);assert.equal(m.internationalCredit.deducted,null);assert.equal(m.pecDeduction.deducted,null);return m;};
const position=c=>c.b.internationalCredits.positions[0];
const proof=c=>position(c).payments[0];
test('country code projection exactly reuses the existing master and its source hash',()=>{
const raw=Buffer.from(fs.readFileSync(new URL('../../resources/data/iso3166.tab',import.meta.url),'utf8').replace(/\r\n/g,'\n'));
const codes=raw.toString('utf8').split(/\r?\n/).filter(l=>l&&!l.startsWith('#')).map(l=>l.split('\t')[0]);
assert.deepEqual(countryIsoCodes,codes);const source=fs.readFileSync(new URL('../../resources/js/lib/country-iso-codes.ts',import.meta.url),'utf8');assert.ok(source.includes(crypto.createHash('sha256').update(raw).digest('hex')));
});
test('10 paid capped at documented national8 precedes PEC200/PPC500:1408-8-200-500=700',()=>{
const m=calc(internationalCase());assert.deepEqual(m.pending,[]);const p=m.internationalCredit.positions[0];
assert.equal(value(p.paid),10);assert.equal(value(p.eligible),8);assert.equal(value(p.aboveLimit),2);assert.equal(value(m.internationalCredit.deducted),8);assert.equal(value(m.internationalCredit.afterCredit),1400);assert.equal(value(m.pecDeduction.deducted),200);assert.equal(value(m.payable),700);assert.equal(m.internationalCredit.carryCreated,false);assert.equal(m.officialBalancesConsumed,false);
});
test('documented treaty limit6 caps credit without country-based automatic entitlement',()=>{
const c=internationalCase();Object.assign(position(c),{treaty:'yes',treatyLimit:'6',treatyReference:'SYNTHETIC QA convention/article/exercise/limit, not real treaty data'});
const m=calc(c);assert.equal(value(m.internationalCredit.deducted),6);assert.equal(value(m.payable),702);assert.equal(value(m.internationalCredit.positions[0].aboveLimit),4);
position(c).treatyLimit='';pending(c);position(c).treatyLimit='6';position(c).treatyReference='';pending(c);
});
test('multiple actual receipts share one country limit;two countries keep separate limits',()=>{
const c=internationalCase();proof(c).amount='6';proof(c).proofAmount='6';position(c).payments.push({...proof(c),id:'foreign-second',document:'OTHER-RECEIPT',amount:'4',proofAmount:'4'});assert.equal(value(calc(c).internationalCredit.deducted),8);
const other=structuredClone(position(c));other.id='country-pt';other.country='PT';other.qualificationCountry='PT';other.nationalLimit='4';other.payments=[{...other.payments[0],id:'pt-tax',document:'PT-OTHER-RECEIPT',proofAmount:'5',amount:'5'}];c.b.internationalCredits.positions.push(other);assert.equal(value(calc(c).internationalCredit.deducted),12);assert.equal(value(calc(c).payable),696);
});
test('same country cannot multiply the national fraction across positions or other context maps',()=>{
const a=internationalCase(),copy=structuredClone(position(a));copy.id='duplicate-country';copy.payments[0].id='other-proof';copy.payments[0].document='OTHER';a.b.internationalCredits.positions.push(copy);assert.match(pending(a).pending.join(' '),/país\/exercício/);
const b=internationalCase(),other=structuredClone(b.b);other.internationalCredits.positions[0].payments[0].id='elsewhere';other.internationalCredits.positions[0].payments[0].document='ELSEWHERE-RECEIPT';const s=JSON.parse(b.d.modelo_a_snapshot);s.irpcAnnual={'opportunity:other':other};b.d.modelo_a_snapshot=JSON.stringify(s);assert.match(pending(b).pending.join(' '),/noutro mapa/);
});
test('actual previous credit use reduces eligible credit,not gross tax or simulated history',()=>{
const c=internationalCase();position(c).previousUse.amount='3';let m=calc(c);assert.equal(value(m.internationalCredit.positions[0].eligible),8);assert.equal(value(m.internationalCredit.positions[0].available),5);assert.equal(value(m.payable),703);
position(c).previousUse.amount='9';assert.match(pending(c).pending.join(' '),/excede/);position(c).previousUse={state:'absent',amount:'',reference:'QA no actual previous use'};assert.equal(value(calc(c).payable),700);
});
test('lack of collecta is separated from tax above eligibility limits and never refunds credit or PEC',()=>{
const c=internationalCase('2000','2000','200','0'),m=calc(c);assert.equal(m.status,'balanced');assert.equal(value(m.internationalCredit.deducted),1408);assert.equal(value(m.internationalCredit.insufficientCollecta),592);assert.equal(value(m.internationalCredit.positions[0].aboveLimit),0);assert.equal(value(m.pecDeduction.deducted),0);assert.equal(value(m.pecDeduction.remaining),200);assert.equal(value(m.recoverable),0);assert.equal(m.internationalCredit.countryAllocationCreated,false);
c.b.ppc={...internationalCase().b.ppc};const recovered=calc(c);assert.equal(value(recovered.recoverable),500);assert.equal(value(recovered.internationalCredit.insufficientCollecta),592);assert.equal(recovered.internationalCredit.carryCreated,false);
});
test('known zero,declared absence and missing retain distinct inputs and outcomes',()=>{
const zero=internationalCase('0');assert.equal(value(calc(zero).internationalCredit.deducted),0);assert.equal(value(calc(zero).payable),708);
const a=internationalCase();a.b.internationalCredits.state='absent';a.b.internationalCredits.positions=[];assert.equal(value(calc(a).payable),708);
a.b.internationalCredits.state='';pending(a);a.b.internationalCredits.state='known';pending(a);
const b=internationalCase();b.b.internationalCredits.state='absent';pending(b);position(b).previousUse={state:'absent',amount:'0',reference:'QA contradiction'};pending(b);
});
test('country,entity,year,inclusion,current assessment,domestic fraction and convention require support',()=>{
for(const patch of [{country:'MZ'},{country:'ZZ'},{country:''},{country:'PT'},{qualificationCountry:''},{subjectNuit:'999999999'},{year:'2025'},{incomeIncluded:''},{incomeIncluded:'no'},{incomeAmount:''},{incomeAmount:'0'},{incomeReference:''},{nationalLimit:''},{nationalLimitReference:''},{assessmentKey:'stale'},{treaty:''},{treaty:'no',treatyLimit:'0'},{treatyReference:''}]){const c=internationalCase();Object.assign(position(c),patch);pending(c);}
for(const patch of [{state:''},{amount:''},{reference:''}]){const c=internationalCase();Object.assign(position(c).previousUse,patch);pending(c);}
});
test('actual foreign income tax proof is required,not projections,other taxes,wrong exercise or unsupported currency',()=>{
for(const patch of [{effective:''},{effective:'no'},{incomeTax:''},{incomeTax:'no'},{taxReference:''},{document:''},{issuer:''},{reference:''},{subjectNuit:'999999999'},{year:'2025'},{date:'2026-02-30'},{date:'2025-09-30'},{currency:'USD'},{amount:'10.01'},{amount:'0.001'}]){const c=internationalCase();Object.assign(proof(c),patch);pending(c);}
const c=internationalCase();position(c).payments=[];pending(c);
});
test('payment date differs from income exercise only with explicit correspondence,never an automatic carry',()=>{
const c=internationalCase();proof(c).date='2027-01-15';pending(c);proof(c).exerciseReference='SYNTHETIC QA own-exercise2026 assessment and payment relation';const m=calc(c);assert.equal(value(m.payable),700);assert.equal(m.internationalCredit.carryCreated,false);
});
test('same physical foreign receipt cannot be duplicated,re-dated or used as PPC/PEC/RF',()=>{
const a=internationalCase();position(a).payments.push({...proof(a),id:'other-date',date:'2026-10-01'});pending(a);
for(const kind of ['ppc','pec','rf']){const c=internationalCase('10','8','200','500',kind==='rf'?'300':'0');const physical=kind==='ppc'?c.b.ppc.rows[0]:kind==='pec'?c.b.pecPayments.rows[0]:{issuer:'QA AT',document:'QA-RF-PEC-2026',proofAmount:'300'};Object.assign(proof(c),{issuer:physical.issuer,document:physical.document,proofAmount:physical.proofAmount});assert.match(pending(c).pending.join(' '),/naturez|comprovativo/i);}
});
test('a foreign receipt cannot move country/entity across context maps;external changes invalidate current result',()=>{
const c=internationalCase(),other=structuredClone(c.b);other.ppc.rows=[];other.ppc.state='absent';other.pecPayments.rows=[];other.pecPayments.state='absent';other.internationalCredits.positions[0].country='PT';const s=JSON.parse(c.d.modelo_a_snapshot);s.irpcAnnual={'opportunity:other':other};c.d.modelo_a_snapshot=JSON.stringify(s);pending(c);
other.internationalCredits.positions[0].payments[0].document='OTHER-PT';c.d.modelo_a_snapshot=JSON.stringify(s);assert.equal(value(calc(c).payable),700);c.d.modelo_a_snapshot=saveAnnualBook(c.d,recordAnnual(c.d,c.b,now));const saved=annualBook(c.d);assert.equal(annualCurrent(c.d,saved),true);
const edit=JSON.parse(c.d.modelo_a_snapshot);edit.irpcAnnual['opportunity:other'].internationalCredits.positions[0].country='ZA';c.d.modelo_a_snapshot=JSON.stringify(edit);assert.equal(annualCurrent(c.d,saved),false);pending({...c,b:saved});
});
test('economic/benefit positive or missing states block only the dependent annual balance,not known eligibility',()=>{
for(const kind of ['economic','benefits'])for(const patch of [{state:''},{state:'known',amount:'1'},{reference:''}]){const c=internationalCase();Object.assign(c.b.internationalCredits[kind],patch);const m=pending(c);assert.equal(value(m.internationalCredit.positions[0].eligible),8);assert.equal(value(m.assessment.colecta),1408);}
});
test('exact decimals and withholding are included once after credit and PEC',()=>{
const c=internationalCase('10.25','8.15','200','500','300');position(c).previousUse.amount='3.01';const m=calc(c);assert.deepEqual(m.internationalCredit.deducted,{numerator:'257',denominator:'50'});assert.equal(value(m.payable),402.86);assert.equal(value(m.knownWithholdings),300);
});
test('documented fractional ceilings retain exact arithmetic without assumed tax rounding',()=>{
const c=internationalCase('10','1/3');const m=calc(c);assert.deepEqual(m.internationalCredit.deducted,{numerator:'1',denominator:'3'});assert.deepEqual(m.payable,{numerator:'2123',denominator:'3'});
position(c).nationalLimit='1/0';pending(c);
});
test('prepare preserves deliberate prior summary and history;save/recover/report appends frozen records',()=>{
const c=internationalCase(),detail=structuredClone(c.b.internationalCredits);delete c.b.internationalCredits;const original=JSON.parse(c.d.modelo_a_snapshot),plan=c.d.business_plan_snapshot;c.d.modelo_a_snapshot=saveAnnualBook(c.d,recordAnnual(c.d,c.b,now));const prior=structuredClone(annualBook(c.d).result);assert.equal(value(prior.model.payable),708);
let next=prepareInternationalBook(annualBook(c.d));next.internationalCredits=detail;c.d.modelo_a_snapshot=saveAnnualBook(c.d,recordAnnual(c.d,next,now));const back=annualBook(JSON.parse(JSON.stringify(c.d)));assert.deepEqual(back.history,[prior]);assert.equal(annualCurrent(c.d,back),true);assert.equal(value(back.result.model.payable),700);assert.deepEqual(back.credits,{state:'known',amount:'0',reference:'QA créditos precedentes conhecidos zero'});
const after=JSON.parse(c.d.modelo_a_snapshot);delete after.irpcAnnual;assert.deepEqual(after,original);assert.equal(c.d.business_plan_snapshot,plan);
const html=annualHtml(c.d);assert.match(html,/Crédito internacional — antes do PEC/);assert.match(html,/700.00/);assert.match(html,/1400.00/);assert.match(JSON.stringify(createProjectDossierReport(c.d,{selectedSections:new Set(['finance'])})),/Crédito internacional — ZA/);
const frozen=structuredClone(back.result);back.internationalCredits.positions[0].nationalLimit='7';c.d.modelo_a_snapshot=saveAnnualBook(c.d,back);assert.equal(annualCurrent(c.d,back),false);assert.deepEqual(back.result,frozen);assert.match(annualReportRows(c.d).flat().join(' '),/Histórico/);assert.throws(()=>annualHtml(c.d),/fontes actuais/);
});
test('malformed optional international detail never resets existing snapshots',()=>{
const c=internationalCase(),snapshot=c.d.modelo_a_snapshot;proof(c).incomeTax=null;assert.throws(()=>saveAnnualBook(c.d,c.b),/não recuperável/);assert.equal(c.d.modelo_a_snapshot,snapshot);
});