Prepare PEC obligation total and calendar with private recovery and reports
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-11 09:59:54 +02:00
parent e549003e5d
commit bcbbe51c2f
14 changed files with 797 additions and 8 deletions
@@ -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 IrpcPecObligationDraftTest 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 (['ordinary' => 138, 'minimum' => 138, 'maximum' => 138, 'start' => 138, 'zero_turnover' => 138, 'unknown' => 138] as $name => $balance) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-pec-obligation-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('2025', $book['pecObligation']['previousYear']);
$this->assertSame('SYNTHETIC effective activity'.($name === 'start' ? '2026' : '2020'), $book['pecObligation']['activityReference']);
file_put_contents(base_path('outputs/irpc-pec-obligation-20261111/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
}
@@ -0,0 +1,12 @@
import { newPecObligation } from '../../../resources/js/lib/irpc-pec-obligation.ts';
export const plan = () => ({
...newPecObligation('123456789', '2026'),
scope: 'ordinary_resident',
activityStartYear: '2020',
activityReference: 'SYNTHETIC effective activity2020',
previousYear: '2025',
previousTurnover: '10000000',
turnoverReference: 'SYNTHETIC sales2025',
previousPpcPaid: '10000',
ppcReference: 'SYNTHETIC effective PPC2025',
});
@@ -0,0 +1,119 @@
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-obligation.ts';
import * as rational from '../../resources/js/lib/fiscal-rational.ts';
import { renderToStaticMarkup } from 'react-dom/server';
import { plan } from './helpers/irpc-pec-obligation-case.mjs';
import { investmentCase } from './helpers/irpc-investment-case.mjs';
const require = createRequire(import.meta.url),
module = { exports: {} };
const source = fs.readFileSync(
new URL(
'../../resources/js/components/simulation-irpc-pec-obligation.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 === '@/lib/irpc-annual-settlement'
? annual
: name === '@/lib/irpc-pec-obligation'
? 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.SimulationIrpcPecObligation;
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)]
: [];
function harness(c) {
let b = c.b;
return {
book: () => b,
render: () =>
Component({
draft: c.d,
book: b,
onChange: (next) => {
b = { ...b, pecObligation: next };
},
}),
click(label) {
const button = all(this.render()).find(
(n) => n.type === 'button' && text(n) === label,
);
assert.ok(button, label);
button.props.onClick();
},
change(label, value) {
const input = all(this.render()).find(
(n) => n.props['aria-label'] === label,
);
assert.ok(input, label);
input.props.onChange({ target: { value } });
},
};
}
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');
assert.equal(h.book().pecObligation.subjectNuit, c.b.subjectNuit);
assert.equal(h.book().pecObligation.previousTurnover, '');
h.change('Enquadramento PEC', 'ordinary_resident');
h.change('Ano de início efectivo da actividade — PEC', '2020');
h.change('Fonte do início de actividade — PEC', 'SYNTHETIC activity');
h.change('Exercício anterior — PEC', '2025');
h.change('Volume de negócios anterior — MZN', '10000000');
h.change('Fonte do volume de negócios — PEC', 'SYNTHETIC volume');
h.change('PPC efectivamente pagos no ano anterior — MZN', '10000');
h.change('Fonte dos PPC anteriores — PEC', 'SYNTHETIC actual PPC');
assert.match(text(h.render()), /40000/);
assert.match(text(h.render()), /2026-06/);
assert.deepEqual(h.book().pecPayments, c.b.pecPayments);
h.change('Ano de início efectivo da actividade — PEC', '2026');
assert.match(text(h.render()), /Não aplicável/);
assert.equal(h.book().pecObligation.previousTurnover, '10000000');
h.change('Ano de início efectivo da actividade — PEC', '2020');
assert.match(text(h.render()), /40000/);
const html = renderToStaticMarkup(
Component({
book: {
...c.b,
pecObligation: { ...plan(), subjectNuit: c.b.subjectNuit },
},
onChange: () => {},
}),
);
assert.match(html, /2026-10/);
assert.match(html, /Fonte e limites PEC/);
});
@@ -0,0 +1,98 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
calculatePecObligation,
validatePecObligation,
} from '../../resources/js/lib/irpc-pec-obligation.ts';
import { plan } from './helpers/irpc-pec-obligation-case.mjs';
import { combinedCase } from './helpers/irpc-investment-combination-case.mjs';
import {
calculateAnnual,
recordAnnual,
annualCurrent,
annualBook,
saveAnnualBook,
annualHtml,
} from '../../resources/js/lib/irpc-annual-settlement.ts';
const f = (n) => ({ numerator: String(n), denominator: '1' }),
calc = (p) => calculatePecObligation(p, '123456789', '2026', 'normal');
test('PEC caps percentage before subtracting actual previous PPC; no PPC instalment rounding reused', () => {
let m = calc(plan());
assert.deepEqual(m.percentage, f(50000));
assert.deepEqual(m.total, f(40000));
assert.deepEqual(m.months, ['2026-06', '2026-08', '2026-10']);
assert.equal(m.paymentExecuted, false);
assert.equal(m.annualDeductionCreated, false);
assert.equal(m.instalmentAmountsDetermined, false);
assert.deepEqual(
calc({ ...plan(), previousTurnover: '1000000' }).total,
f(20000),
);
assert.deepEqual(
calc({ ...plan(), previousTurnover: '50000000' }).total,
f(90000),
);
assert.deepEqual(calc({ ...plan(), previousPpcPaid: '50000' }).total, f(0));
});
test('documented first activity year is not applicable without fabricating previous business figures', () => {
const m = calc({
...plan(),
activityStartYear: '2026',
previousTurnover: '',
previousPpcPaid: '',
turnoverReference: '',
ppcReference: '',
});
assert.deepEqual(m.pending, []);
assert.equal(m.notApplicable, true);
assert.deepEqual(m.total, f(0));
assert.deepEqual(m.months, []);
});
test('unknown turnover is distinct from zero; no turnover requires29(5),excess PPC never becomes refund', () => {
for (const change of [
{ previousTurnover: '' },
{ previousTurnover: '0' },
{ previousPpcPaid: '' },
{ previousPpcPaid: '60000' },
{ scope: 'other' },
{ subjectNuit: '999999999' },
{ previousYear: '2024' },
{ activityStartYear: '2027' },
{ activityReference: '' },
{ turnoverReference: '' },
{ ppcReference: '' },
]) {
const m = calc({ ...plan(), ...change });
assert.ok(m.pending.length);
assert.equal(m.total, null);
}
assert.match(
calc({ ...plan(), previousTurnover: '0' }).pending.join(' '),
/29\(5\)/,
);
assert.throws(() =>
validatePecObligation({ ...plan(), previousTurnover: null }),
);
});
test('existing private book and annual history retain PEC preparation without changing paid deductions or balance', () => {
const { d, b } = combinedCase(),
before = calculateAnnual(d, b);
const prior = recordAnnual(d, b, '2026-11-11T10:30:00Z');
prior.pecObligation = { ...plan(), subjectNuit: b.subjectNuit };
assert.equal(annualCurrent(d, prior), false);
const next = recordAnnual(d, prior, '2026-11-11T10:31:00Z');
d.modelo_a_snapshot = saveAnnualBook(d, next);
const back = annualBook(d);
assert.equal(back.history.length, 1);
assert.equal(annualCurrent(d, back), true);
assert.deepEqual(back.pecObligation, next.pecObligation);
assert.deepEqual(
back.result.model.arithmeticBalance,
before.arithmeticBalance,
);
assert.deepEqual(back.pecPayments, b.pecPayments);
assert.match(annualHtml(d), /PEC — obrigação preparada/);
assert.match(annualHtml(d), /2026-06/);
});
test('documented old activity is not excluded by an invented1900 cut-off',()=>{assert.deepEqual(calc({...plan(),activityStartYear:'1899'}).total,f(40000));});