Keep PPC PEC estimates and reports consistent with the prepared L6 period
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-14 00:23:46 +02:00
parent e9278ee446
commit 078f770dea
14 changed files with 295 additions and 21 deletions
@@ -0,0 +1,50 @@
<?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 IrpcAdvancePeriodDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_period_survives_native_recovery_without_changing_the_independent_annual_result(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('investmoz_demography_test', $target->name);
$this->assertSame(55441, (int) $target->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$actor = User::factory()->create();
$this->actingAs($actor);
$id = null;
$etag = null;
foreach (['ordinary', 'noncivil', 'short', 'start'] as $name) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-period-consistency-20261113/'.$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']);
$book = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR)['irpcAnnual'][$snapshot['context_opportunity']];
$this->assertCount(1, $book['history']);
$this->assertArrayHasKey('advancePeriod', $book['result']['model']);
$this->assertSame($book['history'][0]['model']['arithmeticBalance'], $book['result']['model']['arithmeticBalance']);
$this->assertSame($book['pecObligation'], $book['result']['model']['input']['pecObligation']);
$this->assertSame($book['ppcObligation'], $book['result']['model']['input']['ppcObligation']);
$this->assertSame('2026', $book['ppcObligation']['year']);
$this->assertSame('SYNTHETIC effective activity'.($name === 'start' ? '2026' : '2020'), $book['pecObligation']['activityReference']);
file_put_contents(base_path('outputs/irpc-period-consistency-20261113/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
@@ -0,0 +1,23 @@
import {combinedCase} from './irpc-investment-combination-case.mjs';
import {plan as ppc} from './irpc-ppc-obligation-case.mjs';
import {plan as pec} from './irpc-pec-obligation-case.mjs';
import {newPecPlan} from '../../../resources/js/lib/irpc-pec-plan.ts';
import {normalBook,recordNormal,saveNormalBook} from '../../../resources/js/lib/irpc-normal.ts';
import {newNormalPeriodFx} from '../../../resources/js/lib/irpc-normal-period-fx.ts';
import {annualAssessment,reuseAnnualAssessment} from '../../../resources/js/lib/irpc-annual-settlement.ts';
export function periodAdvanceCase(kind='ordinary'){
const c=combinedCase();
if(kind!=='ordinary'){
const n=normalBook(c.d);
const dates=kind==='noncivil'?['annual','2025-07-01','2026-06-30','2025-07-01']:kind==='start'?['start','2026-07-01','2026-12-31','2026-01-01']:['cessation','2026-01-01','2026-06-30','2026-01-01'];
n.periodsFx={...newNormalPeriodFx(),kind:dates[0],from:dates[1],to:dates[2],planStart:dates[3],reference:'SYNTHETIC documented fiscal period '+kind,mznMapsReference:'SYNTHETIC existing MZN mapping; no real tax filing'};
c.d.modelo_a_snapshot=saveNormalBook(c.d,recordNormal(c.d,n,'2026-11-13T22:00:00Z'));
c.b=reuseAnnualAssessment(c.d,c.b);
}
c.b.ppcObligation={...ppc(),subjectNuit:c.b.subjectNuit};
c.b.pecObligation={...pec(),subjectNuit:c.b.subjectNuit,plan:{...newPecPlan(),mode:'single',singleMonth:'2026-05',reference:'SYNTHETIC cash hypothesis'}};
if(kind==='start'){
c.b.pecObligation.activityStartYear='2026';c.b.pecObligation.activityReference='SYNTHETIC effective activity2026';c.b.ppcObligation.previousTax='0';c.b.ppcObligation.previousWithholdings='0';
}
return {...c,period:annualAssessment(c.d).period};
}
@@ -0,0 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import {compileFunction} from 'node:vm';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
import * as annual from '../../resources/js/lib/irpc-annual-settlement.ts';
import * as pec from '../../resources/js/lib/irpc-pec-obligation.ts';
import * as rational from '../../resources/js/lib/fiscal-rational.ts';
import {periodAdvanceCase} from './helpers/irpc-advance-period-case.mjs';
const require=createRequire(import.meta.url);
function load(name,resolver){const module={exports:{}};const s=fs.readFileSync(new URL('../../resources/js/components/'+name,import.meta.url),'utf8');const code=ts.transpileModule(s,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;compileFunction(code,['require','module','exports'])(resolver,module,module.exports);return module.exports;}
test('L8 supplies the actual prepared L6 period to both estimators and the joint view',()=>{
const seen={};const components=load('simulation-irpc-annual.tsx',name=>name==='@/lib/irpc-annual-settlement'?annual:name==='./simulation-irpc-ppc-obligation'?{SimulationIrpcPpcObligation:p=>(seen.ppc=p.period,null)}:name==='./simulation-irpc-pec-obligation'?{SimulationIrpcPecObligation:p=>(seen.pec=p.period,null)}:name.startsWith('./')?new Proxy({},{get:()=>()=>null}):require(name));
const {d,b,period}=periodAdvanceCase('noncivil');d.modelo_a_snapshot=annual.saveAnnualBook(d,annual.recordAnnual(d,b,'2026-11-13T22:04:00Z'));const html=renderToStaticMarkup(React.createElement(components.SimulationIrpcAnnual,{draft:d,onChange:()=>{}}));
assert.deepEqual(seen.ppc,period);assert.deepEqual(seen.pec,period);assert.match(html,/Período preparado em L6/);assert.match(html,/2025-07-01/);assert.match(html,/Projecção parcial/);assert.ok(!html.includes('Total da projecção: 112000'));
});
test('the existing PEC start-year exclusion remains visible with a short source period',()=>{
const components=load('simulation-irpc-pec-obligation.tsx',name=>name==='@/lib/irpc-pec-obligation'?pec:name==='@/lib/fiscal-rational'?rational:name.startsWith('./')?new Proxy({},{get:()=>()=>null}):require(name));
const {b,period}=periodAdvanceCase('start');const html=renderToStaticMarkup(React.createElement(components.SimulationIrpcPecObligation,{book:b,period,onChange:()=>{}}));assert.match(html,/Não aplicável no ano de início/);assert.ok(!html.includes('não corresponde ao ano civil'));
});
@@ -0,0 +1,39 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {periodAdvanceCase} from './helpers/irpc-advance-period-case.mjs';
import {normalBook,saveNormalBook} from '../../resources/js/lib/irpc-normal.ts';
import {newNormalPeriodFx} from '../../resources/js/lib/irpc-normal-period-fx.ts';
import {calculatePpcObligation} from '../../resources/js/lib/irpc-ppc-obligation.ts';
import {calculatePecObligation} from '../../resources/js/lib/irpc-pec-obligation.ts';
import {annualAdvancePeriod,annualAdvanceCashflow,annualAdvanceCashflowReport,recordAnnual,saveAnnualBook,annualBook,annualCurrent,annualHtml} from '../../resources/js/lib/irpc-annual-settlement.ts';
const f=n=>({numerator:String(n),denominator:'1'});
test('ordinary calendar estimates and legacy independent preparation retain accepted amounts',()=>{
const {b,period}=periodAdvanceCase();assert.deepEqual(annualAdvanceCashflow(b,period).total,f(112000));assert.deepEqual(annualAdvanceCashflow(b).total,f(112000));
});
test('actual L6 noncivil and short periods cannot produce ordinary PPC PEC dates or a complete cash total',()=>{
for(const kind of ['noncivil','short']){
const {b,period}=periodAdvanceCase(kind),before=JSON.stringify(b);assert.ok(period);assert.ok(period.to!=='2026-12-31');
const ppc=calculatePpcObligation(b.ppcObligation,b.subjectNuit,b.year,b.assessment,period),pec=calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,period),joint=annualAdvanceCashflow(b,period);
assert.equal(ppc.total,null);assert.equal(pec.total,null);assert.equal(joint.total,null);assert.deepEqual(joint.rows,[]);assert.match(joint.pending.join(' '),/período L6/);assert.equal(JSON.stringify(b),before);
assert.ok(!JSON.stringify(annualAdvanceCashflowReport(b,period)).includes('112000'));
}
});
test('documented PEC activity-start exclusion survives a short L6 period while unsupported PPC remains separate',()=>{
const {b,period}=periodAdvanceCase('start');const pec=calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,period);assert.equal(pec.notApplicable,true);assert.deepEqual(pec.total,f(0));
const joint=annualAdvanceCashflow(b,period);assert.equal(joint.pecKnown,true);assert.equal(joint.ppcKnown,false);assert.equal(joint.total,null);assert.ok(joint.pending.some(p=>p.startsWith('PPC: o período L6')));assert.ok(!joint.pending.some(p=>p.startsWith('PEC: o período L6')));
for(const outside of [{from:'2025-07-01',to:'2026-06-30'},{from:'2025-01-01',to:'2025-12-31'},{from:'2026-02-30',to:'2026-12-31'}]) assert.equal(calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,outside).total,null);
});
test('recovery and frozen reports use the recorded L6 period without changing the independent annual calculation',()=>{
const {d,b,period}=periodAdvanceCase('noncivil');const without={...b,ppcObligation:undefined,pecObligation:undefined};const prior=recordAnnual(d,without,'2026-11-13T22:01:00Z');
const current=recordAnnual(d,{...prior,ppcObligation:b.ppcObligation,pecObligation:b.pecObligation},'2026-11-13T22:02:00Z');assert.deepEqual(current.result.model.arithmeticBalance,prior.result.model.arithmeticBalance);
d.modelo_a_snapshot=saveAnnualBook(d,current);const recovered=annualBook(d);assert.equal(annualCurrent(d,recovered),true);assert.equal(recovered.history.length,1);assert.deepEqual(recovered.result.model.assessment.period,period);assert.match(annualHtml(d),/período L6/);assert.ok(!annualHtml(d).includes('Total da projecção: 112000'));
});
test('incomplete invalid and contradictory calendar metadata require reconciliation rather than replacing dates',()=>{
const {b}=periodAdvanceCase();for(const period of [{from:'2026-01-01',to:null},{from:'2026-02-30',to:'2026-12-31'},{from:'2025-01-01',to:'2025-12-31'}])assert.equal(annualAdvanceCashflow(b,period).total,null);
});
test('edited L6 period is not silently replaced by the prior calculated period and is frozen on annual recalculation',()=>{
const {d,b}=periodAdvanceCase();const n=normalBook(d);n.periodsFx={...newNormalPeriodFx(),kind:'cessation',from:'2026-01-01',to:'2026-06-30',planStart:'2026-01-01',reference:'SYNTHETIC period edit',mznMapsReference:'SYNTHETIC pending review'};
d.modelo_a_snapshot=saveNormalBook(d,n);const period=annualAdvancePeriod(d);assert.equal(period.to,'2026-06-30');assert.equal(annualAdvanceCashflow(b,period).total,null);
const saved=recordAnnual(d,b,'2026-11-13T22:03:00Z');assert.deepEqual(saved.result.model.advancePeriod,period);d.modelo_a_snapshot=saveAnnualBook(d,saved);assert.match(annualHtml(d),/período L6/);
});