Clarify viability simulation purpose and preserve PEC cash-flow hypotheses
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-11 10:37:33 +02:00
parent aae79c712d
commit a708f079b3
24 changed files with 754 additions and 42 deletions
+48
View File
@@ -0,0 +1,48 @@
<?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 IrpcPecPlanDraftTest 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('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 (['three' => 138, 'single' => 138, 'mismatch' => 138, 'changed_total' => 138] as $name => $balance) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-pec-plan-20261111/'.$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('SYNTHETIC cash-flow hypothesis for viability', $book['pecObligation']['plan']['reference']);
$this->assertSame('SYNTHETIC effective activity'.($name === 'start' ? '2026' : '2020'), $book['pecObligation']['activityReference']);
file_put_contents(base_path('outputs/irpc-pec-plan-20261111/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
@@ -30,7 +30,9 @@ const output = ts.transpileModule(source, {
}).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === '@/lib/irpc-annual-settlement'
name === './simulation-irpc-pec-plan'
? {SimulationIrpcPecPlan:()=>null}
: name === '@/lib/irpc-annual-settlement'
? annual
: name === '@/lib/irpc-pec-obligation'
? investment
@@ -86,7 +88,7 @@ function harness(c) {
test('actual PEC form reuses context, preserves hidden edits and explains first-year exception', () => {
const c = investmentCase(),
h = harness(c);
h.click('Preparar obrigação PEC');
h.click('Simular PEC');
assert.equal(h.book().pecObligation.subjectNuit, c.b.subjectNuit);
assert.equal(h.book().pecObligation.previousTurnover, '');
h.change('Enquadramento PEC', 'ordinary_resident');
+1 -1
View File
@@ -91,7 +91,7 @@ test('existing private book and annual history retain PEC preparation without ch
before.arithmeticBalance,
);
assert.deepEqual(back.pecPayments, b.pecPayments);
assert.match(annualHtml(d), /PEC — obrigação preparada/);
assert.match(annualHtml(d), /PEC — estimativa fiscal/);
assert.match(annualHtml(d), /2026-06/);
});
+100
View File
@@ -0,0 +1,100 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import * as annual from '../../resources/js/lib/irpc-annual-settlement.ts';
import * as investment from '../../resources/js/lib/irpc-pec-plan.ts';
import * as rational from '../../resources/js/lib/fiscal-rational.ts';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url),
module = { exports: {} };
const source = fs.readFileSync(
new URL(
'../../resources/js/components/simulation-irpc-pec-plan.tsx',
import.meta.url,
),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === './simulation-irpc-pec-plan'
? { SimulationIrpcPecPlan: () => null }
: name === '@/lib/irpc-annual-settlement'
? annual
: name === '@/lib/irpc-pec-plan'
? investment
: name === '@/lib/fiscal-rational'
? rational
: name === './simulation-irpc-special'
? { QualificationFields: () => null }
: name === './fiscal-proof-parcel'
? { FiscalProofParcelFields: () => null }
: require(name),
module,
module.exports,
);
const Component = module.exports.SimulationIrpcPecPlan;
const text = (node) =>
typeof node === 'string' || typeof node === 'number'
? String(node)
: React.isValidElement(node)
? React.Children.toArray(node.props.children).map(text).join('')
: '';
const all = (node) =>
React.isValidElement(node)
? [node, ...React.Children.toArray(node.props.children).flatMap(all)]
: [];
test('actual plan form retains deliberate amounts across mode changes and explains legal deadline limitation', () => {
let p;
const total = { numerator: '40000', denominator: '1' };
const render = () =>
Component({
plan: p,
total,
notApplicable: false,
year: '2026',
onChange: (next) => (p = next),
});
const click = (label) => {
const n = all(render()).find(
(x) => x.type === 'button' && text(x) === label,
);
assert.ok(n, label);
n.props.onClick();
};
const change = (label, value) => {
const n = all(render()).find((x) => x.props['aria-label'] === label);
assert.ok(n, label);
n.props.onChange({ target: { value } });
};
click('Simular tesouraria PEC');
assert.equal(p.june, '');
change('Opção de preparação PEC', 'three');
change('Fundamento do projecção PEC', 'SYNTHETIC allocation');
change('PEC Junho — MZN', '10000');
change('PEC Agosto — MZN', '15000');
change('PEC Outubro — MZN', '15000');
assert.match(text(render()), /Soma reconciliada/);
assert.match(text(render()), /Prazo legal não validado/);
change('Opção de preparação PEC', 'single');
change('Mês previsto do PEC único', '2026-06');
assert.equal(p.june, '10000');
assert.match(text(render()), /40000/);
change('Opção de preparação PEC', 'three');
assert.equal(p.singleMonth, '2026-06');
assert.match(text(render()), /15000/);
const html = renderToStaticMarkup(render());
assert.match(html, /Alterar projecção PEC/);
assert.match(html, /guia/);
});
+99
View File
@@ -0,0 +1,99 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
newPecPlan,
calculatePecPlan,
validatePecPlan,
} from '../../resources/js/lib/irpc-pec-plan.ts';
import { calculatePecObligation } from '../../resources/js/lib/irpc-pec-obligation.ts';
import { plan as obligation } from './helpers/irpc-pec-obligation-case.mjs';
import { combinedCase } from './helpers/irpc-investment-combination-case.mjs';
import {
recordAnnual,
annualCurrent,
annualBook,
saveAnnualBook,
annualHtml,
} from '../../resources/js/lib/irpc-annual-settlement.ts';
const f = (n) => ({ numerator: String(n), denominator: '1' }),
three = () => ({
...newPecPlan(),
mode: 'three',
reference: 'SYNTHETIC proposed allocation29(1)',
june: '10000',
august: '15000',
october: '15000',
}),
calc = (p, total = f(40000), na = false) =>
calculatePecPlan(p, total, na, '2026');
test('three explicit positive instalments reconcile exact total without inventing equal allocation', () => {
const m = calc(three());
assert.deepEqual(m.pending, []);
assert.deepEqual(
m.rows.map((r) => r.month),
['2026-06', '2026-08', '2026-10'],
);
assert.deepEqual(
m.rows.map((r) => r.amount),
[f(10000), f(15000), f(15000)],
);
assert.equal(m.legalDeadlineValidated, false);
assert.equal(m.paymentExecuted, false);
assert.equal(m.annualDeductionCreated, false);
});
test('single option records chosen month and entire obligation but does not certify deadline', () => {
const m = calc({ ...three(), mode: 'single', singleMonth: '2026-06' });
assert.deepEqual(m.pending, []);
assert.deepEqual(m.rows, [{ month: '2026-06', amount: f(40000) }]);
assert.equal(m.legalDeadlineValidated, false);
});
test('unknown,total changed,zero,not applicable,invalid month and mismatched cents never release a reconciled schedule', () => {
for (const p of [
{ ...three(), june: '' },
{ ...three(), june: '9999.99' },
{ ...three(), june: '10000.01' },
{ ...three(), june: '0' },
{ ...three(), reference: '' },
{ ...three(), mode: 'single', singleMonth: '2025-06' },
]) {
const m = calc(p);
assert.ok(m.pending.length);
assert.equal(m.allocationReconciled, false);
assert.deepEqual(m.rows, []);
}
for (const t of [null, f(0), f(50000)])
assert.ok(calc(three(), t).pending.length);
assert.ok(calc(three(), f(40000), true).pending.length);
assert.throws(() => validatePecPlan({ ...three(), june: null }));
});
test('schedule preserves explicit option in native book and invalidates annual snapshot on edits without new paid deductions', () => {
const { d, b } = combinedCase();
b.pecObligation = { ...obligation(), subjectNuit: b.subjectNuit };
let current = recordAnnual(d, b, '2026-11-11T11:00:00Z');
current.pecObligation.plan = three();
assert.equal(annualCurrent(d, current), false);
current = recordAnnual(d, current, '2026-11-11T11:01:00Z');
d.modelo_a_snapshot = saveAnnualBook(d, current);
const back = annualBook(d);
assert.equal(annualCurrent(d, back), true);
assert.deepEqual(back.result.model.arithmeticBalance, f(138));
assert.deepEqual(back.pecPayments, b.pecPayments);
assert.equal(back.history.length, 1);
assert.match(annualHtml(d), /PEC — projecção de tesouraria/);
back.pecObligation.previousTurnover = '20000000';
assert.ok(
calculatePecPlan(
back.pecObligation.plan,
calculatePecObligation(
back.pecObligation,
back.subjectNuit,
back.year,
back.assessment,
).total,
false,
'2026',
).pending.length,
);
assert.equal(annualCurrent(d, back), false);
});
@@ -84,7 +84,7 @@ function harness(c) {
};
}
test('actual progressive PPC form reuses subject, retains deliberate edits and exposes calendar separately from paid proofs',()=>{
const c=investmentCase(),h=harness(c);h.click('Preparar obrigação PPC');assert.equal(h.book().ppcObligation.subjectNuit,c.b.subjectNuit);assert.equal(h.book().ppcObligation.previousTax,'');
const c=investmentCase(),h=harness(c);h.click('Simular PPC');assert.equal(h.book().ppcObligation.subjectNuit,c.b.subjectNuit);assert.equal(h.book().ppcObligation.previousTax,'');
h.change('Enquadramento PPC','ordinary_resident');h.change('Exercício anterior — PPC','2025');h.change('Exercício anterior civil completo','yes');h.change('Imposto liquidado anterior21(1) — MZN','100001');h.change('Retenções na fonte anteriores — MZN','10000');h.change('Fonte da liquidação anterior — PPC','SYNTHETIC tax');h.change('Fonte das retenções anteriores — PPC','SYNTHETIC RF');
assert.match(text(h.render()),/75000/);assert.match(text(h.render()),/2026-05/);assert.deepEqual(h.book().ppc,c.b.ppc);
h.change('Enquadramento PPC','other');assert.equal(h.book().ppcObligation.previousTax,'100001');assert.match(text(h.render()),/Outros períodos/);h.change('Enquadramento PPC','ordinary_resident');assert.match(text(h.render()),/75000/);
+1 -1
View File
@@ -82,6 +82,6 @@ test('preparation survives existing book, versions/history/report; obligation ne
assert.deepEqual(recovered.ppc, b.ppc);
assert.equal(annualCurrent(d, recovered), true);
assert.equal(recovered.history.length, 1);
assert.match(annualHtml(d), /PPC — obrigação preparada/);
assert.match(annualHtml(d), /PPC — estimativa fiscal/);
assert.match(annualHtml(d), /2026-05/);
});