feat: add bounded current-year PEC deduction to annual IRPC QA

This commit is contained in:
2026-10-27 13:15:18 +02:00
parent dc14f01e14
commit 7fdb6b424b
15 changed files with 874 additions and 18 deletions
+65
View File
@@ -0,0 +1,65 @@
<?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 IrpcPecDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_pec_delta_round_trips_without_consuming_balances_or_changing_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 function(string $table): array {
return 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 operator; 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-pec-preserved.json')),true,flags:JSON_THROW_ON_ERROR);
$personal=['person_type'=>$base['person_type']];unset($base['person_type']);
$id=null;$etag=null;$previous=null;
foreach($fixture['cases']as$name=>$book){
$draft=$base;$store=json_decode($draft['modelo_a_snapshot'],true,flags:JSON_THROW_ON_ERROR);
if($previous!==null)$book['history']=[$previous];
$store['irpcAnnual'][$draft['context_opportunity']]=$book;
$draft['modelo_a_snapshot']=json_encode($store,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($store[$map],$recovered[$map]);
$saved=$recovered['irpcAnnual'][$draft['context_opportunity']];$m=$saved['result']['model'];
$this->assertSame($book,$saved);$this->assertSame('IRPC-PEC/1',$m['pecDeduction']['version']);
$this->assertFalse($m['officialBalancesConsumed']);$this->assertFalse($m['pecDeduction']['carryCreated']);
$this->assertSame(['numerator'=>'1408','denominator'=>'1'],$m['assessment']['colecta']);
if($name==='missing'){$this->assertSame('indeterminate',$m['status']);$this->assertNull($m['arithmeticBalance']);$this->assertNull($m['pecDeduction']['deducted']);}
else{
$expected=['payable'=>['payable','708','200','0'],'capped'=>['balanced','0','1408','592'],'recoverable'=>['recoverable','-500','1408','592'],'prior-use'=>['payable','1208','200','0']][$name];
$this->assertSame($expected[0],$m['status']);
foreach(['arithmeticBalance'=>1,'deducted'=>2,'remaining'=>3]as$field=>$index)$this->assertSame(['numerator'=>$expected[$index],'denominator'=>'1'],$field==='arithmeticBalance'?$m[$field]:$m['pecDeduction'][$field]);
}
if($previous!==null)$this->assertSame($previous,$saved['history'][0]);
$previous=$saved['result'];
if(getenv('INVESTMOZ_PEC_QA_OUTPUT')==='1')file_put_contents(base_path('outputs/irpc-l8-pec-20261027/recovered-'.$name.'.json'),json_encode($back,JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE));
}
$preserved=[];
foreach($protected as$table=>$before){
$after=$snapshot($table);
$this->assertSame($before,array_intersect_key($after,$before),'Existing records changed: '.$table);
$preserved[$table]=['existing_rows'=>count($before),'unchanged'=>true];
}
if(getenv('INVESTMOZ_PEC_QA_OUTPUT')==='1')file_put_contents(base_path('outputs/irpc-l8-pec-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
+25
View File
@@ -0,0 +1,25 @@
import {irpcBook,newIrpcRow,saveIrpcBook,recordIrpc} from '../../../resources/js/lib/irpc-withholdings.ts';
import fs from 'node:fs';
import {newPecPayment} from '../../../resources/js/lib/irpc-pec.ts';
import {newAnnualBook,newAnnualPpc,reuseAnnualAssessment,reuseAnnualWithholding} from '../../../resources/js/lib/irpc-annual-settlement.ts';
export function pecCase(amount='200',ppc='500',rf='0') {
const d=JSON.parse(fs.readFileSync(new URL('../fixtures/irpc-assessment-preserved.json',import.meta.url),'utf8'));
if(rf!=='0'){
const l5=irpcBook(d);
l5.rows.push({...newIrpcRow('pec-rf'),direction:'received',origin:'effective',counterparty:'QA AT',documentRef:'QA rendimento próprio 2026',base:String(Number(rf)*5),currency:'MZN',kind:'royalty',recipientIrpc:'yes',payerIrpc:'yes',residence:'resident',mozambique:'yes',qualificationRef:'QA royalties próprios incluídos no resultado anual',specialRelief:'none',eventsComplete:'yes',events:[{kind:'payment',date:'2026-10-02',reference:'QA rendimento primeiro evento'}],settlement:'complete',settlementRef:'QA retenção sofrida reconciliada',allocations:[{paymentId:'pec-rf-proof',amount:rf}],ordinary:{nonDigital:'yes',capitalType:'',rentOwnPropertyManagement:'',specialFacts:'no',capitalSeatAndManagement:'',reference:'QA royalties não digitais de residente'}});
l5.payments.push({id:'pec-rf-proof',kind:'withholding_proof',reference:'QA-RF-PEC-2026',date:'2026-10-02',amount:rf,currency:'MZN'});
d.modelo_a_snapshot=saveIrpcBook(d,recordIrpc(d,l5,'2026-10-27T15:00:00+02:00'));
}
let b=reuseAnnualAssessment(d,newAnnualBook());
b.reference='QA PEC: inventário completo da entidade/exercício';b.assessmentReference='QA colecta válida já demonstrada';
b.withholdings={state:'absent',reference:'QA sem retenções próprias neste caso',rows:[]};
b.ppc={state:ppc==='0'?'absent':'known',reference:'QA inventário de PPC efectivo',rows:ppc==='0'?[]:[{...newAnnualPpc('ppc'),document:'QA-PPC-PEC-2026',issuer:'QA AT',date:'2026-06-30',subjectNuit:b.subjectNuit,year:b.year,proofAmount:ppc,amount:ppc,effective:'yes',reference:'QA prova efectiva de natureza PPC'}]};
b.pec={state:'absent',amount:'',reference:'QA resumo anterior preservado'};
b.credits={state:'known',amount:'0',reference:'QA créditos precedentes conhecidos zero'};
b.pecPayments={version:1,state:'known',reference:'QA inventário de pagamentos PEC 2026',rows:[{...newPecPayment('pec'),document:'QA-PEC-2026',issuer:'QA AT',date:'2026-08-31',subjectNuit:b.subjectNuit,year:b.year,proofAmount:amount,amount,effective:'yes',previouslyUsed:'0',priorUseReference:'QA reconciliação: zero utilizações fora destas parcelas',reference:'QA comprovativo pago de natureza PEC'}]};
if(rf!=='0'){
b.withholdings.state='known';b=reuseAnnualWithholding(d,b,'pec-rf','pec-rf-proof','rf-claim');
Object.assign(b.withholdings.rows[0],{incomeIncluded:'yes',reference:'QA titular e rendimento incluído no exercício'});
}
return {d,b};
}
+67
View File
@@ -0,0 +1,67 @@
import {pecCase} from './helpers/irpc-pec-case.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import {annualBook,newAnnualBook,newAnnualPpc,reuseAnnualAssessment,calculateAnnual,recordAnnual,saveAnnualBook,annualCurrent,annualReportRows,annualHtml} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const value=x=>x?Number(x.numerator)/Number(x.denominator):null;
const now='2026-10-27T15:00:00+02:00';
const model=({d,b})=>calculateAnnual(d,b);
const indeterminate=c=>{const m=model(c);assert.equal(m.status,'indeterminate',JSON.stringify(m.pending));assert.equal(m.arithmeticBalance,null);assert.equal(m.pecDeduction.deducted,null);assert.equal(m.pecDeduction.remaining,null);return m;};
test('PEC precedes PPC; 1408 - 200 - 500 = 708, no official consumption',()=>{
const m=model(pecCase());assert.deepEqual(m.pending,[]);assert.equal(value(m.pecDeduction.deducted),200);assert.equal(value(m.pecDeduction.afterPec),1208);assert.equal(value(m.payable),708);assert.equal(m.pecDeduction.carryCreated,false);assert.equal(m.officialBalancesConsumed,false);
});
test('existing received L5 proof is reused after PEC and cannot become another PEC receipt',()=>{
const c=pecCase('200','500','300');assert.equal(value(model(c).payable),408);
Object.assign(c.b.pecPayments.rows[0],{document:'QA-RF-PEC-2026',proofAmount:'300'});
assert.match(indeterminate(c).pending.join(' '),/natureza/);
});
test('PEC cap never generates refund; PPC can still generate recoverable balance',()=>{
const a=model(pecCase('2000','0'));assert.equal(value(a.pecDeduction.deducted),1408);assert.equal(value(a.pecDeduction.remaining),592);assert.equal(value(a.arithmeticBalance),0);assert.equal(value(a.recoverable),0);
const b=model(pecCase('2000','500'));assert.equal(value(b.recoverable),500);assert.equal(value(b.pecDeduction.remaining),592);assert.equal(value(b.pecDeduction.afterPec),0);
});
test('previous use explicit, precise decimals and available portion are respected',()=>{
const c=pecCase('200.25','0');Object.assign(c.b.pecPayments.rows[0],{proofAmount:'300.75',previouslyUsed:'100.50'});assert.equal(value(model(c).payable),1207.75);
c.b.pecPayments.rows[0].amount='200.26';indeterminate(c);
});
test('absence, known zero and missing PEC are distinct; contradictory rows block',()=>{
const c=pecCase();c.b.pecPayments.rows=[];c.b.pecPayments.state='absent';assert.equal(value(model(c).payable),908);
c.b.pecPayments.state='';indeterminate(c);c.b.pecPayments.state='known';indeterminate(c);
const z=pecCase('0');assert.equal(value(model(z).payable),908);z.b.pecPayments.rows[0].previouslyUsed='';indeterminate(z);
z.b.pecPayments.state='absent';indeterminate(z);
});
test('payment proof, unused balance, entity, year and currency cannot be presumed',()=>{
for(const change of[{effective:''},{effective:'no'},{document:''},{reference:''},{priorUseReference:''},{previouslyUsed:''},{previouslyUsed:'201'},{amount:'201'},{amount:'1.001'},{subjectNuit:'999999999'},{year:'2025'},{date:'2025-08-31'},{date:'2026-02-30'},{currency:'USD'}]){const c=pecCase();Object.assign(c.b.pecPayments.rows[0],change);indeterminate(c);}
});
test('same physical proof cannot be duplicated, re-dated or relabelled PPC',()=>{
const a=pecCase();a.b.pecPayments.rows.push({...a.b.pecPayments.rows[0],id:'copy',date:'2026-09-01'});assert.match(indeterminate(a).pending.join(' '),/repetido|saldo disponível/);
const b=pecCase();Object.assign(b.b.pecPayments.rows[0],{document:b.b.ppc.rows[0].document,proofAmount:'500'});assert.match(indeterminate(b).pending.join(' '),/naturezas|natureza incompatível/);
});
test('cross-context allocations respect prior use and changing external claims invalidates current result',()=>{
const c=pecCase('100','0'),r=c.b.pecPayments.rows[0];r.proofAmount='500';r.previouslyUsed='100';
const other=structuredClone(c.b);other.pecPayments.rows[0].amount='300';
const s=JSON.parse(c.d.modelo_a_snapshot);s.irpcAnnual={'opportunity:other':other};c.d.modelo_a_snapshot=JSON.stringify(s);
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);assert.equal(value(saved.result.model.payable),1308);
const edit=JSON.parse(c.d.modelo_a_snapshot);edit.irpcAnnual['opportunity:other'].pecPayments.rows[0].amount='301';c.d.modelo_a_snapshot=JSON.stringify(edit);assert.equal(annualCurrent(c.d,saved),false);assert.match(indeterminate({...c,b:saved}).pending.join(' '),/saldo disponível/);
edit.irpcAnnual['opportunity:other'].pecPayments.rows[0].amount='100';edit.irpcAnnual['opportunity:other'].pecPayments.rows[0].previouslyUsed='0';c.d.modelo_a_snapshot=JSON.stringify(edit);indeterminate({...c,b:saved});
});
test('other contexts cannot change PEC titular, origin or payment nature',()=>{
for(const change of[{subjectNuit:'999999999'},{year:'2025'}]){const c=pecCase('100','0'),other=structuredClone(c.b);other.pecPayments.rows[0].proofAmount='500';Object.assign(other.pecPayments.rows[0],change);const s=JSON.parse(c.d.modelo_a_snapshot);s.irpcAnnual={'opportunity:other':other};c.d.modelo_a_snapshot=JSON.stringify(s);indeterminate(c);}
const c=pecCase('100','0'),other=structuredClone(c.b);other.ppc.rows=[{...c.b.pecPayments.rows[0],amount:'50',proofAmount:'100'}];other.ppc.state='known';other.pecPayments.rows=[];other.pecPayments.state='absent';const s=JSON.parse(c.d.modelo_a_snapshot);s.irpcAnnual={'opportunity:other':other};c.d.modelo_a_snapshot=JSON.stringify(s);indeterminate(c);
});
test('positive special credits remain scoped and cannot be silently skipped before PEC',()=>{
const c=pecCase();c.b.credits.amount='10';assert.match(indeterminate(c).pending.join(' '),/Créditos/);assert.equal(value(model(c).pecDeduction.available),200);
});
test('save/recover/recalculate preserves old annual results and all other fiscal books, plan and reports',()=>{
const c=pecCase(),before=JSON.parse(c.d.modelo_a_snapshot),plan=c.d.business_plan_snapshot;
const legacy=structuredClone(c.b);delete legacy.pecPayments;c.d.modelo_a_snapshot=saveAnnualBook(c.d,recordAnnual(c.d,legacy,now));const old=structuredClone(annualBook(c.d).result);
c.b={...annualBook(c.d),pecPayments:c.b.pecPayments};c.d.modelo_a_snapshot=saveAnnualBook(c.d,recordAnnual(c.d,c.b,now));const back=annualBook(JSON.parse(JSON.stringify(c.d)));
assert.deepEqual(back.history,[old]);assert.equal(value(back.result.model.payable),708);assert.equal(annualCurrent(c.d,back),true);const after=JSON.parse(c.d.modelo_a_snapshot);delete after.irpcAnnual;assert.deepEqual(after,before);assert.equal(c.d.business_plan_snapshot,plan);
const html=annualHtml(c.d);assert.match(html,/PEC — dedução limitada/);assert.match(html,/708.00/);assert.match(html,/sem reembolso PEC/);
const dossier=createProjectDossierReport(c.d,{selectedSections:new Set(['finance'])});assert.match(JSON.stringify(dossier),/PEC — dedução limitada/);
const frozen=structuredClone(back.result);back.pecPayments.rows[0].amount='100';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 PEC extension never replaces legacy snapshots',()=>{
const c=pecCase(),original=c.d.modelo_a_snapshot;c.b.pecPayments.rows[0].previouslyUsed=null;assert.throws(()=>saveAnnualBook(c.d,c.b),/não recuperáveis/);assert.equal(c.d.modelo_a_snapshot,original);
});