Integrate authorised editorial package with current homologation changes

This commit is contained in:
2026-11-14 09:11:55 +02:00
30 changed files with 1787 additions and 65 deletions
@@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Models\InvestmentZone;
use App\Models\User;
use App\Services\InvestmentMapIndicators;
use App\Services\InvestmentZoneIntegralDetails;
use App\Services\InvestmentZoneOperationalDetails;
use App\Services\InvestmentZoneOperationalProfile;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
class InvestmentObservationNatureTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
Http::preventStrayRequests();
}
private function observation(?string $kind): array
{
$item = ['id' => (string) Str::uuid(), 'label' => 'SYNTHETIC nature QA', 'description' => 'Synthetic source only.',
'indicator' => 'employment', 'value' => '0', 'unit' => 'pessoas', 'period_start' => '2025-01-01', 'period_end' => '2025-12-31',
'scope' => 'Synthetic zone', 'population' => 'Synthetic establishments', 'methodology' => 'Synthetic register',
'source_reference' => 'SYNTHETIC source; not real statistics', 'source_date' => '2026-01-15', 'knowledge' => 'documented', 'disclosure' => true];
return $kind === null ? $item : [...$item, 'measure_kind' => $kind];
}
private function zone(): InvestmentZone
{
$actor = User::factory()->create(['email' => 'measure-'.Str::uuid().'@example.test']);
return InvestmentZone::create(['code' => 'MEASURE-QA-'.Str::uuid(), 'category' => 'industrial_park', 'name' => 'SYNTHETIC nature QA',
'editor_id' => $actor->id, 'publication_status' => 'draft', 'validation_status' => 'pending']);
}
public function test_explicit_natures_persist_recover_and_project_without_inference_or_private_disclosure(): void
{
$zone = $this->zone();
$service = app(InvestmentZoneIntegralDetails::class);
$ops = app(InvestmentZoneOperationalDetails::class);
$rows = array_map(fn ($kind) => $this->observation($kind), ['observed', 'planned', 'projected', null]);
$hidden = [...$this->observation('observed'), 'disclosure' => false, 'source_reference' => 'PRIVATE-NATURE-SOURCE'];
$merged = $service->merge($zone, [], ['observations' => [...$rows, $hidden]]);
$zone->forceFill(['operational_details' => $ops->pack(['integral' => $merged])])->save();
$saved = $zone->fresh();
$before = $saved->getRawOriginal('operational_details');
$recovered = $ops->recover($saved)['integral']['observations'];
$this->assertSame(['observed', 'planned', 'projected'], array_column(array_slice($recovered, 0, 3), 'measure_kind'));
$this->assertArrayNotHasKey('measure_kind', $recovered[3]);
$this->assertSame('0', $recovered[0]['value']);
$view = app(InvestmentMapIndicators::class)->forZones(collect([$saved]));
$this->assertSame(['observed', 'planned', 'projected', 'unknown'], array_column($view['records'], 'measure_kind'));
$this->assertSame(['0', '0', '0', '0'], array_column($view['records'], 'value'));
$this->assertStringNotContainsString('PRIVATE-NATURE-SOURCE', json_encode($view, JSON_THROW_ON_ERROR));
$this->assertSame($before, $zone->fresh()->getRawOriginal('operational_details'));
$this->assertSame(1, $zone->fresh()->version_no);
}
public function test_invalid_nature_is_rejected_and_an_omitted_nature_does_not_erase_an_explicit_choice(): void
{
$zone = $this->zone();
$service = app(InvestmentZoneIntegralDetails::class);
$row = $this->observation('observed');
$before = $service->merge($zone, [], ['observations' => [$row]]);
$withoutKind = $row;
unset($withoutKind['measure_kind']);
$recovered = $service->merge($zone, $before, ['observations' => [$withoutKind]]);
$this->assertSame('observed', $recovered['observations'][0]['measure_kind']);
$changed = $service->merge($zone, $before, ['observations' => [[...$row, 'measure_kind' => 'planned']]]);
$this->assertSame('planned', $changed['observations'][0]['measure_kind']);
$this->assertSame('observed', $before['observations'][0]['measure_kind']);
try {
$service->merge($zone, $before, ['observations' => [[...$row, 'measure_kind' => 'inferred_from_description']]]);
$this->fail('Invalid nature accepted');
} catch (ValidationException $error) {
$this->assertArrayHasKey('observations.0.measure_kind', $error->errors());
}
}
public function test_nature_change_stays_in_private_preparation_with_history_until_existing_editorial_review(): void
{
$zone = $this->zone();
$ops = app(InvestmentZoneOperationalDetails::class);
$row = $this->observation('observed');
$fields = app(InvestmentZoneIntegralDetails::class)->merge($zone, [], ['observations' => [$row]]);
// Synthetic public snapshot only, inside the rolled-back QA transaction.
$zone->forceFill(['publication_status' => 'published', 'validation_status' => 'validated',
'reviewer_id' => User::factory()->create(['email' => 'nature-review-'.Str::uuid().'@example.test'])->id,
'published_at' => now(), 'physical_category' => 'industrial_park',
'source_evidence' => [['source_type' => 'promoter', 'title' => 'SYNTHETIC QA only', 'url' => 'https://example.invalid/qa', 'supports' => 'Synthetic test fixture']],
'operational_details' => $ops->pack(['integral' => $fields])])->save();
$original = $zone->fresh()->getRawOriginal('operational_details');
$profile = app(InvestmentZoneOperationalProfile::class);
$prepared = $profile->prepare($zone->fresh(), ['version_no' => 1,
'operational_details' => ['integral' => ['observations' => [[...$row, 'measure_kind' => 'planned']]]]], $zone->editor_id);
$this->assertSame($original, $prepared->getRawOriginal('operational_details'));
$this->assertSame('observed', $ops->publicData($prepared)['integral']['observations'][0]['measure_kind']);
$this->assertSame('planned', $profile->draft($prepared)['fields']['operational_details']['integral']['observations'][0]['measure_kind']);
$this->assertSame(1, $prepared->version_no);
$this->assertSame(1, DB::table('investment_zone_revisions')->where('zone_id', $zone->id)->where('action', 'profile_prepared')->count());
$this->assertSame(1, DB::table('audit_events')->where('entity_id', $zone->id)->where('action', 'profile_prepared')->count());
}
}
@@ -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 IrpcAdvanceCashflowDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_pec_obligation_and_calendar_survive_native_draft_without_new_paid_deductions(): 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 (['overlap' => 138, 'distributed' => 138, 'partial' => 138, 'zero' => 138] as $name => $balance) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-cashflow-group-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->assertSame(['numerator' => '138', 'denominator' => '1'], $book['history'][0]['model']['arithmeticBalance']);
$this->assertSame($balance === null ? null : ['numerator' => (string) $balance, 'denominator' => '1'], $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-cashflow-group-20261113/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
@@ -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,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 IrpcPecLastAmountDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_pec_obligation_and_calendar_survive_native_draft_without_new_paid_deductions(): 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 (['documented' => 138, 'missing' => 138, 'positive' => 138, 'excess' => 138] as $name => $balance) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-pec-last-amount-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->assertSame(['numerator' => '138', 'denominator' => '1'], $book['history'][0]['model']['arithmeticBalance']);
$this->assertSame($balance === null ? null : ['numerator' => (string) $balance, 'denominator' => '1'], $book['result']['model']['arithmeticBalance']);
$this->assertSame($book['pecObligation'], $book['result']['model']['input']['pecObligation']);
$this->assertSame('42500.25', $book['pecObligation']['lastAmount']['amount']);
$this->assertSame('2024', $book['pecObligation']['lastAmount']['year']);
$this->assertSame('SYNTHETIC effective activity'.($name === 'start' ? '2026' : '2020'), $book['pecObligation']['activityReference']);
file_put_contents(base_path('outputs/irpc-pec-last-amount-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};
}
@@ -29,6 +29,8 @@ compileFunction(compiled, ['require', 'module', 'exports'])(
);
const Component = module.exports.default;
const filterIndicators = module.exports.filterMapIndicators;
const compareObservations = module.exports.compareMapObservations;
const Comparison = module.exports.MapObservationComparison;
const row = {
id: '1',
zone_id: 'park-a',
@@ -219,3 +221,170 @@ test('quantitative filters are labelled, scoped and explain source date and cove
assert.match(html, /não alteram oportunidades ou limites de cobertura/);
assert.match(html, /Limpar filtros dos indicadores/);
});
test('comparison delta: metadata alignment never manufactures a trend or changes exact source values', () => {
const first = {
...row,
description: 'Emprego observado na fonte sintética.',
measure_kind: 'observed',
value: '1234567890123.456789',
};
const second = {
...first,
id: 'next-period',
period_start: '2026-01-01',
period_end: '2026-12-31',
value: '0',
};
const before = JSON.stringify([first, second]);
assert.equal(compareObservations(first, second).state, 'metadata_aligned');
const html = renderToStaticMarkup(
React.createElement(Comparison, { first, second }),
);
assert.match(html, /1234567890123\.456789/);
assert.match(html, />0</);
assert.match(html, /confirme nas fontes/);
assert.match(html, /não calcula evolução/);
assert.ok(!html.includes('<script>synthetic source</script>'));
assert.match(html, /&lt;script&gt;synthetic source/);
assert.equal(JSON.stringify([first, second]), before);
});
test('comparison delta: differences, missing evidence, unknown values and disputed information require review', () => {
const documented = {
...row,
description: 'Emprego observado na fonte sintética.',
measure_kind: 'observed',
};
const second = { ...documented, id: 'different' };
assert.equal(
compareObservations(documented, second).state,
'metadata_aligned',
);
for (const change of [
{ zone_id: 'other' },
{ indicator: 'exports' },
{ unit: 'USD' },
{ scope: 'other base' },
{ population: 'other population' },
{ methodology: 'other method' },
{ knowledge: 'disputed' },
{ knowledge: 'unknown', value: null },
{ value: 'NaN' },
{ source_reference: '' },
{ description: '' },
{ source_date: '2026-02-30' },
{ period_end: '2024-01-01' },
]) {
const result = compareObservations(documented, {
...second,
...change,
});
assert.equal(result.state, 'review_required', JSON.stringify(change));
assert.ok(result.issues.length);
}
assert.equal(compareObservations(row, row).state, 'review_required');
const html = renderToStaticMarkup(
React.createElement(Comparison, {
first: row,
second: { ...second, knowledge: 'unknown', value: null },
}),
);
assert.match(html, /Por confirmar/);
assert.match(html, /lacunas a conferir/);
});
test('measure kind delta: legacy nature stays unknown and observed quantities cannot align with plans or projections', () => {
const observed = {
...row,
description: 'Fonte sintética',
measure_kind: 'observed',
};
const same = { ...observed, id: 'second' };
assert.equal(compareObservations(observed, same).state, 'metadata_aligned');
for (const kind of ['planned', 'projected', 'unknown', null, undefined]) {
const other = { ...same, measure_kind: kind };
const before = JSON.stringify(other);
const result = compareObservations(observed, other);
assert.equal(result.state, 'review_required');
assert.ok(
result.issues.some((issue) =>
issue.includes('Natureza do valor diferente'),
),
);
assert.equal(JSON.stringify(other), before);
}
const legacy = compareObservations(
{ ...observed, measure_kind: undefined },
{ ...same, measure_kind: undefined },
);
assert.equal(legacy.state, 'review_required');
assert.ok(
legacy.issues.every((issue) =>
issue.includes('natureza do valor por confirmar'),
),
);
});
test('measure kind delta: public comparison labels nature independently of documentary confidence and retains zero', () => {
const first = {
...row,
description: 'Fonte sintética',
measure_kind: 'observed',
};
const second = { ...first, id: 'plan', measure_kind: 'planned' };
const html = renderToStaticMarkup(
React.createElement(Comparison, { first, second }),
);
assert.match(html, /Observado \/ efectivo/);
assert.match(html, /Planeado \/ meta/);
assert.match(html, /Documentada/);
assert.match(html, />0</);
const legacyHtml = renderToStaticMarkup(
React.createElement(Comparison, {
first: { ...first, measure_kind: undefined },
second,
}),
);
assert.match(legacyHtml, /natureza do valor por confirmar/);
assert.match(legacyHtml, /Por confirmar/);
});
test('comparison delta: progressive selection stays inside the received filters and shows an incomplete pair explicitly', () => {
const html = render(context);
assert.match(html, /Comparar duas observações/);
assert.match(html, /Primeira.*observação/);
assert.match(html, /Segunda.*observação/);
assert.match(html, /uma versão nova exige nova selecção/);
assert.match(html, /Seleccione duas observações/);
const single = render({ ...context, records: [row] });
assert.ok(!single.includes('Comparar duas observações'));
});
test('temporal delta: unequal duration and overlapping boundaries require review without annualising values', () => {
const first = {...row, description:'Synthetic source', measure_kind:'observed', period_start:'2024-01-01', period_end:'2024-12-31', value:'123.4500'};
const second = {...first, id:'second', period_start:'2025-01-01', period_end:'2025-12-31', value:'0'};
const before = JSON.stringify([first,second]);
assert.ok(compareObservations(first,second).issues.some(x=>x.includes('Duração dos períodos diferente')));
const boundary = {...second, period_start:'2024-12-31'};
assert.ok(compareObservations(first,boundary).issues.some(x=>x.includes('sobrepõem-se')));
const identical = {...first,id:'same-period'};
assert.equal(compareObservations(first,identical).state,'metadata_aligned');
const html = renderToStaticMarkup(React.createElement(Comparison,{first,second}));
assert.match(html,/Duração do período/);assert.match(html,/>366</);assert.match(html,/>365</);
assert.match(html,/123\.4500/);assert.match(html,/>0</);
assert.equal(JSON.stringify([first,second]),before);
});
test('temporal delta: missing invalid and inverted dates never become a duration', () => {
const first = {...row, description:'Synthetic', measure_kind:'observed'};
for (const change of [{period_start:null},{period_start:'2025'},{period_start:'2025-02-30'},{period_start:'2026-01-01'}]) {
const second = {...first,id:'invalid',...change};
const result = compareObservations(first,second);
assert.ok(result.issues.some(x=>x.includes('período incompleto ou inválido')));
assert.ok(!result.issues.some(x=>x.includes('Duração dos períodos diferente')));
const html = renderToStaticMarkup(React.createElement(Comparison,{first,second}));
assert.match(html,/Por confirmar/);assert.ok(!html.includes('NaN'));
}
});
@@ -0,0 +1,31 @@
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 ts from 'typescript';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import * as annual from '../../resources/js/lib/irpc-annual-settlement.ts';
import {combinedCase} from './helpers/irpc-investment-combination-case.mjs';
import {plan as ppc} from './helpers/irpc-ppc-obligation-case.mjs';
import {plan as pec} from './helpers/irpc-pec-obligation-case.mjs';
import {newPecPlan} from '../../resources/js/lib/irpc-pec-plan.ts';
const require=createRequire(import.meta.url),module={exports:{}};
const source=fs.readFileSync(new URL('../../resources/js/components/simulation-irpc-annual.tsx',import.meta.url),'utf8');
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
compileFunction(code,['require','module','exports'])(name=>name==='@/lib/irpc-annual-settlement'?annual:name.startsWith('./')?new Proxy({},{get:()=>()=>null}):require(name),module,module.exports);
const Summary=module.exports.SimulationIrpcAdvanceCashflow;
const book=()=>({...combinedCase().b,ppcObligation:ppc(),pecObligation:{...pec(),plan:{...newPecPlan(),mode:'single',singleMonth:'2026-05',reference:'SYNTHETIC cash choice'}}});
const render=b=>renderToStaticMarkup(React.createElement(Summary,{book:b}));
test('joint view labels monthly contributions and distinguishes a partial subtotal from a complete forecast',()=>{
const b=book(),html=render(b);assert.match(html,/Saídas previstas PPC\/PEC por mês/);assert.match(html,/112000\.00/);assert.match(html,/64000\.00/);assert.match(html,/não acrescenta outra saída/);assert.match(html,/prazo legal/);
delete b.pecObligation;const partial=render(b);assert.match(partial,/Projecção parcial/);assert.match(partial,/Subtotal conhecido/);assert.match(partial,/Por determinar/);assert.ok(!partial.includes('Total da projecção:'));
});
test('explicit zero has a complete zero forecast and legacy absence does not create a forecast',()=>{
const b=book();b.ppcObligation.previousTax='0';b.ppcObligation.previousWithholdings='0';b.pecObligation.previousPpcPaid='60000';const html=render(b);assert.match(html,/Total da projecção: 0\.00 MZN/);assert.match(html,/Sem saída PPC\/PEC estimada/);
delete b.ppcObligation;delete b.pecObligation;assert.equal(render(b),'');const {d}=combinedCase(),prepared=book();d.modelo_a_snapshot=annual.saveAnnualBook(d,annual.recordAnnual(d,prepared,'2026-11-13T21:45:00Z'));
const full=renderToStaticMarkup(React.createElement(module.exports.SimulationIrpcAnnual,{draft:d,onChange:()=>{}}));
const estimation=full.indexOf('<legend>Estimativas PPC e PEC para a viabilidade</legend>'),paid=full.indexOf('<legend>PPC documentados como pagos</legend>');
assert.ok(estimation>=0 && paid>estimation);const between=full.slice(estimation,paid);assert.match(between,/Saídas previstas PPC\/PEC por mês/);assert.match(between,/<\/fieldset>/);
});
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {plan as ppcPlan} from './helpers/irpc-ppc-obligation-case.mjs';
import {plan as pecPlan} from './helpers/irpc-pec-obligation-case.mjs';
import {newPecPlan} from '../../resources/js/lib/irpc-pec-plan.ts';
import {combinedCase} from './helpers/irpc-investment-combination-case.mjs';
import {annualAdvanceCashflow,annualAdvanceCashflowReport,annualHtml,recordAnnual,saveAnnualBook,annualBook,annualCurrent} from '../../resources/js/lib/irpc-annual-settlement.ts';
const f=n=>({numerator:String(n),denominator:'1'});
const book=()=>({...combinedCase().b,ppcObligation:ppcPlan(),pecObligation:{...pecPlan(),plan:{...newPecPlan(),mode:'single',singleMonth:'2026-05',reference:'SYNTHETIC cash hypothesis'}}});
test('joint cash projection groups the same month once using existing exact PPC and PEC estimates',()=>{
const b=book(),before=JSON.stringify(b),m=annualAdvanceCashflow(b);
assert.equal(m.pending.length,0);assert.deepEqual(m.total,f(112000));assert.equal(m.rows.length,3);assert.deepEqual(m.rows[0],{month:'2026-05',ppc:f(24000),pec:f(40000),knownSubtotal:f(64000)});
assert.equal(JSON.stringify(b),before);
const report=annualAdvanceCashflowReport(b);assert.ok(report[0][3].includes('SYNTHETIC'));assert.ok(report.slice(1).every(r=>r[3]===''));
});
test('missing or unreconciled component stays unknown; known rows never become a complete total',()=>{
const b=book();delete b.pecObligation;let m=annualAdvanceCashflow(b);assert.equal(m.total,null);assert.equal(m.pecKnown,false);assert.deepEqual(m.knownSubtotal,f(72000));
const c=book();c.pecObligation.plan={...c.pecObligation.plan,mode:'three',june:'1',august:'1',october:'1'};m=annualAdvanceCashflow(c);assert.equal(m.total,null);assert.equal(m.pecKnown,false);assert.ok(m.pending.length);assert.equal(m.rows.length,3);
delete c.ppcObligation;m=annualAdvanceCashflow(c);assert.equal(m.total,null);assert.equal(m.rows.length,0);
});
test('confirmed zero PEC and zero PPC differ from unavailable estimates and preserve deliberate dates',()=>{
const b=book();b.pecObligation.previousPpcPaid='60000';let m=annualAdvanceCashflow(b);assert.equal(m.pecKnown,true);assert.deepEqual(m.total,f(72000));
b.ppcObligation.previousTax='0';b.ppcObligation.previousWithholdings='0';m=annualAdvanceCashflow(b);assert.deepEqual(m.total,f(0));assert.equal(m.ppcKnown,true);assert.equal(m.rows.length,0);
const c=book();c.pecObligation.plan.singleMonth='2026-04';m=annualAdvanceCashflow(c);assert.equal(m.rows[0].month,'2026-04');assert.deepEqual(m.rows[0].pec,f(40000));
});
test('monthly decimal allocation retains source precision and sums only the accepted cash hypotheses',()=>{
const b=book();b.pecObligation.plan={...newPecPlan(),mode:'three',june:'10000.01',august:'14999.99',october:'15000',reference:'SYNTHETIC three explicit amounts'};
const m=annualAdvanceCashflow(b);assert.deepEqual(m.total,f(112000));assert.equal(m.rows.length,6);assert.deepEqual(m.rows.find(r=>r.month==='2026-06').pec,{numerator:'1000001',denominator:'100'});
});
test('recovery and frozen report use the same cash projection without adding to the annual balance or rewriting history',()=>{
const {d}=combinedCase(),b=book();const prior=recordAnnual(d,b,'2026-11-13T21:30:00Z');d.modelo_a_snapshot=saveAnnualBook(d,prior);const recovered=annualBook(d);
assert.equal(annualCurrent(d,recovered),true);assert.deepEqual(recovered.result.model.arithmeticBalance,f(138));assert.match(annualHtml(d),/Projecção mensal conjunta PPC\/PEC/);assert.match(annualHtml(d),/64000\.00/);
const changed={...recovered,pecObligation:{...recovered.pecObligation,plan:{...recovered.pecObligation.plan,singleMonth:'2026-06'}}};assert.equal(annualCurrent(d,changed),false);
assert.deepEqual(annualAdvanceCashflow(changed).total,f(112000));assert.match(annualHtml(d),/PPC\/PEC — 2026-05/);assert.equal(annualAdvanceCashflowReport({...b,ppcObligation:undefined,pecObligation:undefined}).length,0);
});
@@ -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/);
});
@@ -0,0 +1,55 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {plan} from './helpers/irpc-pec-obligation-case.mjs';
import {combinedCase} from './helpers/irpc-investment-combination-case.mjs';
import {calculatePecObligation,validatePecObligation} from '../../resources/js/lib/irpc-pec-obligation.ts';
import {recordAnnual,saveAnnualBook,annualBook,annualCurrent,annualHtml} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {calculatePecPlan,newPecPlan} from '../../resources/js/lib/irpc-pec-plan.ts';
const f=n=>({numerator:String(n),denominator:'1'});
const sample=()=>{const p={...plan(),previousTurnover:'0.00'};return {...p,lastAmount:{version:1,subjectNuit:p.subjectNuit,year:'2024',amount:'42500.25',reference:'SYNTHETIC final PEC amount; latest applicable annual ordinary MZN reference',confirmed:'yes'}}};
const calc=p=>calculatePecObligation(p,p.subjectNuit,p.year,'normal');
test('documented latest PEC amount is retained without percentage, caps or a second PPC deduction',()=>{
const p=sample(),before=JSON.stringify(p),m=calc(p);
assert.deepEqual(m.total,{numerator:'170001',denominator:'4'});assert.equal(m.percentage,null);assert.equal(m.limited,null);assert.equal(m.lastAmountApplied,true);assert.equal(m.requiresLastAmount,true);
assert.equal(m.paymentExecuted,false);assert.equal(m.annualDeductionCreated,false);assert.equal(JSON.stringify(p),before);
p.lastAmount.amount='0';assert.deepEqual(calc(p).total,f(0));
});
test('absent stale unconfirmed unsupported or malformed historical references never determine the estimate',()=>{
for(const changes of [{confirmed:''},{reference:''},{subjectNuit:'999999999'},{year:'2026'},{year:'2019'},{amount:''},{amount:'-1'},{amount:'NaN'}]){const p=sample();Object.assign(p.lastAmount,changes);assert.equal(calc(p).total,null,JSON.stringify(changes));}
const p=sample();delete p.lastAmount;assert.equal(calc(p).total,null);
assert.throws(()=>validatePecObligation({...sample(),lastAmount:{...sample().lastAmount,amount:null}}));
});
test('ordinary positive turnover and activity start do not use or erase a saved historical reference',()=>{
const p=sample();p.previousTurnover='10000000';assert.deepEqual(calc(p).total,f(40000));assert.equal(calc(p).lastAmountApplied,false);assert.equal(p.lastAmount.amount,'42500.25');
p.activityStartYear='2026';assert.deepEqual(calc(p).total,f(0));assert.equal(calc(p).lastAmountApplied,false);
});
test('native annual recovery and report retain history and require reconfirming cash assumptions after the estimate changes',()=>{
const {d,b}=combinedCase();b.pecObligation={...sample(),subjectNuit:b.subjectNuit,lastAmount:{...sample().lastAmount,subjectNuit:b.subjectNuit}};
const prior=recordAnnual(d,b,'2026-11-13T21:00:00Z');
const changed={...prior,pecObligation:{...prior.pecObligation,lastAmount:{...prior.pecObligation.lastAmount,amount:'50000'}}};
assert.equal(annualCurrent(d,changed),false);
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,changed,'2026-11-13T21:01:00Z'));
const recovered=annualBook(d);assert.equal(annualCurrent(d,recovered),true);assert.equal(recovered.history.length,1);assert.deepEqual(recovered.result.model.arithmeticBalance,f(138));
assert.match(annualHtml(d),/PEC — último montante documentado/);assert.match(annualHtml(d),/50000/);
const cash={...newPecPlan(),mode:'three',june:'42500.25',august:'0',october:'0',reference:'SYNTHETIC prior cash hypothesis'};
const cm=calculatePecPlan(cash,calc(recovered.pecObligation).total,false,'2026');assert.ok(cm.pending.length);
});
test('unknown turnover cannot be bypassed and a documented correction to zero reuses the historical reference once',()=>{
const p=sample();p.previousTurnover='';assert.equal(calc(p).total,null);
p.previousTurnover='10000000';p.correction={version:1,apply:'yes',originalTurnover:p.previousTurnover,revisedTurnover:'0.00',subjectNuit:p.subjectNuit,turnoverYear:'2025',reference:'SYNTHETIC corrected sales to zero'};
assert.equal(calc(p).requiresLastAmount,true);assert.equal(calc(p).lastAmountApplied,true);assert.deepEqual(calc(p).total,{numerator:'170001',denominator:'4'});
p.correction.reference='';assert.equal(calc(p).total,null);
p.correction.apply='no';assert.deepEqual(calc(p).total,f(40000));assert.equal(calc(p).lastAmountApplied,false);
});
test('excess documented PPC covers the PEC estimate without refund credit or duplicate annual deduction',()=>{
for(const [paid,expected] of [['50000','0'],['60000','10000'],['50000.01','0.01']]){
const p={...plan(),previousPpcPaid:paid};const m=calc(p);assert.deepEqual(m.total,f(0));assert.equal(m.pending.length,0);
if(expected==='0')assert.equal(m.ppcExcess,null);else assert.ok(m.ppcExcess);
assert.equal(m.paymentExecuted,false);assert.equal(m.annualDeductionCreated,false);
}
const {d,b}=combinedCase();b.pecObligation={...plan(),subjectNuit:b.subjectNuit,previousPpcPaid:'60000'};
d.modelo_a_snapshot=saveAnnualBook(d,recordAnnual(d,b,'2026-11-13T21:20:00Z'));
const recovered=annualBook(d);assert.equal(annualCurrent(d,recovered),true);assert.deepEqual(recovered.result.model.arithmeticBalance,f(138));assert.match(annualHtml(d),/PEC — PPC acima da base limitada/);assert.match(annualHtml(d),/não cria reembolso/);
});
@@ -53,7 +53,6 @@ test('unknown turnover is distinct from zero; no turnover requires29(5),excess P
{ previousTurnover: '' },
{ previousTurnover: '0' },
{ previousPpcPaid: '' },
{ previousPpcPaid: '60000' },
{ scope: 'other' },
{ subjectNuit: '999999999' },
{ previousYear: '2024' },