commit correcoes

This commit is contained in:
2026-11-21 20:58:19 +02:00
parent 4ca54e7655
commit 9d7a14459b
581 changed files with 151192 additions and 1620 deletions
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace Tests\Feature;
use App\Models\DevelopmentCorridor;
use App\Models\InvestmentDossier;
use App\Models\Project;
use App\Models\Sector;
use App\Models\User;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
final class GlobalSearchCountTest extends TestCase
{
use DatabaseTransactions;
public function test_licensing_question_opens_existing_guidance_without_mixing_catalogue_matches(): void
{
$this->withoutVite();
$this->get('/pesquisa?'.http_build_query(['q' => 'como licenciar uma empresa']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'guide')->where('results.total', 2)
->where('results.data.0.url', '/como-investir#planeamento')
->where('results.data.1.url', '/investimentos/iniciar?step=S08'));
}
public function test_physical_product_search_keeps_the_product_and_documented_location_in_its_link(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
config(['portal.legacy_content_enabled' => false, 'portal.legacy_content_qa_enabled' => false]);
$sector = Sector::firstOrCreate(['slug' => 'mineracao'], ['name' => 'Mineração']);
$sector->forceFill(['is_active' => true, 'published_at' => now()->subMinute()])->save();
$this->get('/pesquisa?'.http_build_query(['q' => 'onde encontrar grafite em Cabo Delgado']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
->where('results.data.0.title', 'Grafite')->where('results.data.0.category', 'Produtos e localizações')
->where('results.data.0.location', fn ($text) => str_contains($text, 'Cabo Delgado'))
->where('results.data.0.url', fn ($url) => str_contains($url, 'resource_group=') && str_contains($url, 'resource_location=Cabo+Delgado')));
$this->get('/pesquisa?'.http_build_query(['q' => 'grafite Cabo Delgado', 'category' => 'physical']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.category', 'physical')->where('results.total', 1)
->where('results.data.0.category', 'Produtos e localizações'));
$this->get('/pesquisa?category=invalid')->assertRedirect();
}
public function test_financial_product_search_excludes_drafts_and_future_publications_and_distinguishes_coverage(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
if (! Schema::hasTable('funding_programmes')) {
// Only this transaction in the isolated QA database; no active schema changes.
(require database_path('migrations/2026_11_02_210000_funding_programme_catalogue.php'))->up();
}
$actor = User::factory()->create();
$marker = 'SYNTHFIN'.Str::random(8);
foreach (['published', 'draft', 'future', 'historical', 'merged'] as $state) {
$id = (string) Str::uuid();
$version = (string) Str::uuid();
$payload = json_encode(['title' => $marker.' '.$state, 'kind' => 'institution', 'summary' => 'Nota de preparação: ficha e documento gerador.',
'institution_nature' => 'bank', 'institution_services' => ['investment'],
'institution_status' => in_array($state, ['historical', 'merged'], true) ? $state : 'reported',
'locations' => [['location_text' => 'Nampula']], 'products' => [['title' => 'Crédito PME', 'coverage' => 'national', 'needs' => ['investment']]]], JSON_THROW_ON_ERROR);
DB::table('funding_programmes')->insert(['id' => $id, 'code' => $marker.$state, 'draft' => $payload, 'created_by' => $actor->id]);
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => 1, 'payload' => $payload,
'reason' => 'Synthetic QA only', 'actor_id' => $actor->id, 'published_at' => $state === 'future' ? now()->addDay() : now()->subMinute()]);
if ($state !== 'draft') {
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version]);
}
}
$this->get('/pesquisa?'.http_build_query(['q' => 'produtos financeiros '.$marker.' em Nampula']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
->where('results.data.0.category', 'Produtos financeiros')->where('results.data.0.description', 'Crédito PME')
->where('results.data.0.location', 'Presença física: Nampula')
->where('results.data.0.coverage', fn ($text) => str_contains($text, 'nacional')));
}
public function test_corridor_count_excludes_other_types_drafts_and_deleted_entities(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
$marker = 'SYNTHCOUNT'.Str::random(10);
foreach (range(1, 4) as $n) {
$corridor = DevelopmentCorridor::create(['code' => $marker.$n, 'name' => $marker.$n, 'status' => 'active', 'data_classification' => 'public']);
InvestmentDossier::create(['corridor_id' => $corridor->id, 'title' => $marker.' '.$n,
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => $n === 3 ? 'draft' : 'published',
'published_at' => now()->subMinute(), 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
if ($n === 4) {
$corridor->delete();
}
}
InvestmentDossier::create(['project_id' => Project::factory()->create()->id, 'title' => $marker.' corredor relacionado',
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
$query = 'quantos corredores existem '.$marker;
$this->get('/pesquisa?'.http_build_query(['q' => $query]))->assertOk()->assertInertia(fn (Assert $page) => $page
->component('portal/search')->where('query', $query)->where('answer.count', 2)->where('answer.label', 'corredores')
->where('results.total', 2)->has('results.data', 2)->where('results.unavailable', []));
$this->get('/pesquisa?'.http_build_query(['q' => 'quantos corredores existem '.$marker.' inexistente']))
->assertOk()->assertInertia(fn (Assert $page) => $page->where('answer.count', 0)->where('results.total', 0));
$this->get('/pesquisa?q=quantos+corredores+existem')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.label', 'corredores')->where('answer.count', fn ($count) => $count >= 2)
->where('results.unavailable', []));
}
}
+13
View File
@@ -7,6 +7,7 @@ use App\Services\FederatedSearch;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class GlobalSearchTest extends TestCase
@@ -35,6 +36,18 @@ final class GlobalSearchTest extends TestCase
$this->assertSame('Como investir', $result['data'][0]['title']);
}
public function test_unavailable_public_reference_does_not_hide_other_sources_or_swallow_forbidden_access(): void
{
$result = app(FederatedSearch::class)->page([
'Referências' => fn () => throw new HttpException(503),
'Páginas' => fn () => ['count' => 1, 'fetch' => fn () => [['title' => 'Como investir', 'url' => '/como-investir']]],
], 1);
$this->assertSame(1, $result['total']);
$this->assertSame(['Referências'], $result['unavailable']);
$this->expectException(HttpException::class);
app(FederatedSearch::class)->page(['Restrito' => fn () => throw new HttpException(403)], 1);
}
public function test_public_search_uses_the_existing_portfolio_visibility_scope(): void
{
if (getenv('GLOBAL_SEARCH_QA') !== '1') {
@@ -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());
}
}
@@ -71,6 +71,62 @@ class InvestmentPreparationWorkspaceTest extends TestCase
return $this->postJson('/investimentos/'.$this->caseId.'/preparacao', ['version' => $view['version'], 'operation_key' => (string) Str::uuid(), 'reason' => 'SYNTHETIC explicit review, not real external action', 'action' => $action, ...$data])->assertOk()->json();
}
public function test_dossier_reports_recover_preserved_exports_and_keep_financial_sources_private(): void
{
$view = $this->workspace();
$view = $this->action($view, 'apiex_review', ['fingerprint' => $view['api_fingerprint']]);
$view = $this->action($view, 'apiex_export');
$export = $view['apiex']['exports'][0]['id'];
$draft = (string) Str::uuid(); $report = (string) Str::uuid(); $simulation = (string) Str::uuid();
$source = ['simulation_id' => $simulation, 'report_id' => $report, 'report_version_no' => 2, 'report_sha256' => str_repeat('a', 64), 'report_snapshot' => ['private' => 'SYNTHETIC NEVER EXPOSED'], 'consented_at' => now()->toIso8601String()];
$otherReport = (string) Str::uuid();
$otherSource = [...$source, 'report_id' => $otherReport, 'association_opportunity' => 'other-opportunity'];
\App\Models\SimulationFormDraft::create(['id' => $draft, 'owner_user_id' => $this->owner->id,
'create_key_hash' => hash('sha256', $draft), 'create_payload_hash' => hash('sha256', $draft), 'snapshot_sha256' => hash('sha256', $draft),
'personal_snapshot' => \App\Models\SimulationFormDraft::encryptSnapshot([]),
'economic_snapshot' => \App\Models\SimulationFormDraft::encryptSnapshot(['purpose' => 'request_support', 'simulation_sources' => [$source, $otherSource]])]);
DB::table('desk_cases')->where('id', $this->caseId)->update(['simulation_id' => $draft]);
$land = \App\Models\LandAssistanceCase::create(['user_id' => $this->owner->id, 'reference' => 'QA-'.Str::uuid(), 'crm_submission_key' => (string) Str::uuid(),
'version' => 3, 'payload' => ['investor_path_case_id' => $this->caseId]]);
$before = DB::table('simulation_form_drafts')->where('id', $draft)->first();
$data = $this->getJson('/investimentos/'.$this->caseId)->assertOk()->json();
$this->assertSame($this->caseId, $data['preparation_report']['case_id']);
$this->assertSame($export, $data['preparation_report']['exports'][0]['id']);
$this->assertStringContainsString('/investimentos/'.$this->caseId.'/preparacao/exportar/'.$export, $data['preparation_report']['exports'][0]['href']);
$this->assertSame($report, $data['fiscal_reports'][0]['report_id']);
$this->assertCount(1, $data['fiscal_reports']);
$this->assertSame('/investidor/terra-duat/'.$land->id.'/imprimir', $data['land_report']['href']);
$this->assertStringNotContainsString('SYNTHETIC NEVER EXPOSED', json_encode($data, JSON_THROW_ON_ERROR));
$download = $this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.$report)->assertOk()
->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('case_id', $this->caseId)->assertJsonPath('report_snapshot.private', 'SYNTHETIC NEVER EXPOSED')->assertJsonPath('scope_state', 'unconfirmed');
$this->assertSame($download->getContent(), $this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.$report)->assertOk()->getContent());
$this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.Str::uuid())->assertNotFound();
$this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.$otherReport)->assertNotFound();
$this->assertEquals($before, DB::table('simulation_form_drafts')->where('id', $draft)->first());
$this->getJson('/investimentos/'.$this->caseId.'?opportunity=other-opportunity')->assertUnprocessable();
$this->getJson('/investimentos/'.$this->caseId)->assertOk()->assertJsonPath('preparation_report.exports.0.id', $export)->assertJsonPath('fiscal_reports.0.report_id', $report);
$drafts = app(\App\Services\SimulationFormDrafts::class);
$current = \App\Models\SimulationFormDraft::findOrFail($draft);
$request = \Illuminate\Http\Request::create('/api/v1/simulation-drafts/'.$draft.'/simulations', 'POST');
$request->setUserResolver(fn () => $this->owner);
$request->headers->set('If-Match', $drafts->etag($current));
$newSource = [...$source, 'simulation_id' => (string) Str::uuid(), 'report_id' => (string) Str::uuid()];
\App\Models\Simulation::create(['id' => $newSource['simulation_id'], 'owner_user_id' => $this->owner->id, 'status' => 'completed', 'input_snapshot' => ['synthetic' => true]]);
$attached = $drafts->attachSimulation($draft, $newSource, $request);
$saved = \App\Models\SimulationFormDraft::decryptSnapshot($attached['draft']->economic_snapshot)['simulation_sources'];
$this->assertSame($source, $saved[0]);
$this->assertArrayHasKey('association_opportunity', $saved[2]);
$this->assertNull($saved[2]['association_opportunity']);
$this->assertTrue($drafts->attachSimulation($draft, $newSource, $request)['replayed']);
config(['investor-path.enabled' => false]);
$this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.$report)->assertNotFound();
config(['investor-path.enabled' => true]);
$manager = User::factory()->create(); config(['portal.managers' => [$manager->email]]);
$this->actingAs($manager)->getJson('/investimentos/'.$this->caseId)->assertOk()->assertJsonPath('fiscal_reports', [])->assertJsonPath('results', [])->assertJsonPath('land_report', null);
$this->get('/investimentos/'.$this->caseId.'/relatorios/fiscais/'.$report)->assertForbidden();
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$this->caseId)->assertForbidden();
}
public function test_apiex_existing_dossier_requirements_review_zip_and_external_delivery_without_submission_or_approval(): void
{
$before = DB::table('journey_steps')->orderBy('id')->get()->toJson();
@@ -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,51 @@
<?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 IrpcAnnualNoncivilDraftTest 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 (['three', 'single', 'missing', 'changed'] as $name) {
$snapshot = json_decode(file_get_contents(base_path('outputs/irpc-noncivil-20261114/'.$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($book['advancePeriodDeclaration'], $book['result']['model']['input']['advancePeriodDeclaration']);
$this->assertSame('SYNTHETIC effective activity2020', $book['pecObligation']['activityReference']);
file_put_contents(base_path('outputs/irpc-noncivil-20261114/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));
}
}
}
+52
View File
@@ -9,6 +9,33 @@ use PHPUnit\Framework\TestCase;
final class SearchTermsTest extends TestCase
{
public function test_count_questions_select_a_category_instead_of_searching_question_words(): void
{
$search = new SearchTerms;
$intent = $search->countIntent('Quantos corredores existem?');
$this->assertSame('corridor', $intent['kind']);
$this->assertSame('', $intent['filter']);
$this->assertSame('corredores', $intent['label']);
$this->assertSame('Oportunidades', $search->countIntent('Quantas oportunidades existem no portal?')['category']);
$this->assertSame('em nampula', $search->countIntent('Quantos corredores existem em Nampula?')['filter']);
$this->assertSame('cluster', $search->countIntent('Qual é o número de clusters disponíveis?')['kind']);
$this->assertNull($search->countIntent('oportunidades nos corredores'));
$this->assertNull($search->countIntent('documentos sobre quantos corredores existem'));
}
public function test_investor_requests_distinguish_products_guidance_and_lists(): void
{
$search = new SearchTerms;
$this->assertSame('guide', $search->requestIntent('como licenciar uma empresa')['type']);
$this->assertSame('guide', $search->requestIntent('como faço para licenciar a empresa em Nampula?')['type']);
$this->assertNull($search->requestIntent('como licenciar software'));
$this->assertSame('list', $search->requestIntent('quais são os corredores existentes')['type']);
$this->assertSame('Produtos financeiros', $search->requestIntent('produtos financeiros em Nampula')['category']);
$this->assertNull($search->requestIntent('tipo de produtos e sua localização')['category']);
$this->assertSame('', $search->requestIntent('tipo de produtos e sua localização')['filter']);
$this->assertSame('grafite em cabo delgado', $search->requestIntent('onde encontrar grafite em Cabo Delgado?')['filter']);
}
public function test_matches_all_words_in_any_order_without_case_or_accents(): void
{
$search = new SearchTerms;
@@ -56,4 +83,29 @@ final class SearchTermsTest extends TestCase
$this->assertGreaterThan($search->score('Como investir', 'investir', ['investir']), $search->score('Investir', 'investir', ['investir']));
$this->assertSame(['de'], $search->tokens('de'));
}
public function test_direct_titles_precede_titles_and_descriptions_that_reference_the_query(): void
{
$search = new SearchTerms;
$phrase = 'corredor da beira';
$tokens = $search->tokens($phrase);
$titles = ['Açúcar no Corredor da Beira', 'Corredor da Beira e investimentos', 'Corredor da Beira', 'Produção de açúcar'];
usort($titles, fn ($a, $b) => $search->score($b, $phrase, $tokens) <=> $search->score($a, $phrase, $tokens));
$this->assertSame(['Corredor da Beira', 'Corredor da Beira e investimentos', 'Açúcar no Corredor da Beira', 'Produção de açúcar'], $titles);
$this->assertSame($search->score('Corredor da Beira', $phrase, $tokens), $search->score('CORREDOR DA BEIRA', $phrase, $tokens));
}
public function test_database_relevance_uses_the_same_levels_and_escaped_prefix(): void
{
$connection = new PostgresConnection(fn () => throw new \LogicException('A database must not be opened.'));
$query = $connection->table('records');
$search = new SearchTerms;
$search->orderByRelevance($query, 'title', '100% açúcar', $search->tokens('100% açúcar'), 'id');
$this->assertStringContainsString('THEN 1000', $query->toSql());
$this->assertStringContainsString('THEN 600', $query->toSql());
$this->assertStringContainsString('THEN 400', $query->toSql());
$this->assertSame(['100% acucar', '100!% acucar%', '%100!% acucar%'], array_slice($query->getBindings(), 0, 3));
}
}
+192
View File
@@ -0,0 +1,192 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
formFieldGuidance,
formHelpPlacement,
normaliseHelpLabel,
readFormHelpAutomatic,
simulationStepGuidance,
} from '../../resources/js/lib/form-help.ts';
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
test('guidance explains actual fiscal/financial inputs without inventing rates or replacing periods', () => {
for (const [label, expected] of [
['Volume de negócios anterior', /período pedido/],
['Imposto liquidado', /documento correspondente/],
['Retenções na fonte', /documentado/],
['Receita mensal', /previsão/],
['Custo unitário', /unitário, mensal, anual ou total/],
['Moeda do projecto', /moeda/],
['Residência fiscal', /enquadramento/],
['NUIT', /documento/],
['Fonte documental', /recuperar e conferir/],
]) {
const result = formFieldGuidance({
label,
type: 'text',
required: false,
value: 'PRIVATE-INPUT-123',
});
assert.match(result.instruction, expected);
assert.doesNotMatch(JSON.stringify(result), /PRIVATE-INPUT|\d+%/);
}
});
test('native and accessible custom field types receive useful instructions', () => {
for (const type of [
'text',
'number',
'range',
'select',
'combobox',
'checkbox',
'radio',
'date',
'month',
'email',
'tel',
'url',
'password',
'file',
'textarea',
]) {
const result = formFieldGuidance({
label: 'Campo de ensaio',
type,
required: true,
});
assert.ok(result.instruction.length > 30, type);
}
assert.match(
formFieldGuidance({
label: 'Autorização',
type: 'checkbox',
required: false,
}).instruction,
/apenas se/,
);
assert.match(
formFieldGuidance({ label: 'Documento', type: 'file', required: false })
.instruction,
/formatos indicados/,
);
assert.equal(
normaliseHelpLabel('RETENÇÕES — MOÇAMBIQUE'),
'retencoes — mocambique',
);
});
test('all adaptive simulator sections have specific step guidance', () => {
const seen = new Set();
for (const draft of [
{},
{ purpose: 'simulate_only' },
{ journey_type: 'company' },
{ journey_type: 'personal' },
{ journey_type: 'investor' },
{ journey_type: 'small_business' },
{ purpose: 'prepare_investment', journey_type: 'investor' },
]) {
for (const step of getSimulationSections(draft)) {
seen.add(step.id);
assert.notEqual(
simulationStepGuidance(step.id),
simulationStepGuidance('unknown-section'),
step.id,
);
}
}
for (const code of [
'purpose',
'market',
'investment',
'financial',
'operating',
'cashflow',
'tax',
'review',
'team',
'scenarios',
'procedures',
]) {
assert.ok(simulationStepGuidance(code).length > 40);
}
assert.ok(seen.size >= 11);
});
test('browser help preference is optional and does not store field contents', () => {
assert.equal(readFormHelpAutomatic(null), true);
assert.equal(readFormHelpAutomatic('off'), false);
assert.equal(readFormHelpAutomatic('on'), true);
assert.equal(readFormHelpAutomatic('corrupt'), true);
for (const file of [
'components/form-field-help.tsx',
'lib/form-help-dom.ts',
]) {
const source = readFileSync(
new URL('../../resources/js/' + file, import.meta.url),
'utf8',
);
assert.doesNotMatch(
source,
/\.value\b|FormData|fetch\(|router\.|\.submit\(|\.requestSubmit\(/,
);
}
});
test('help is placed above or below the focused mobile field without covering it', () => {
for (const rect of [
{ left: 24, top: 180, bottom: 224 },
{ left: 24, top: 440, bottom: 484 },
{ left: 24, top: 700, bottom: 744 },
]) {
const layout = formHelpPlacement(rect, 390, 844);
assert.ok(layout.maxHeight >= 96 && layout.maxHeight <= 844 * 0.45);
if (layout.vertical === 'top')
assert.ok(80 + layout.maxHeight + 60 < rect.top);
else assert.ok(844 - 12 - layout.maxHeight - 60 > rect.bottom);
}
});
test('help mounts once across portal pages and the simulator publishes its current adaptive step', () => {
const app = readFileSync(
new URL('../../resources/js/app.tsx', import.meta.url),
'utf8',
);
assert.equal((app.match(/<FormFieldHelp\s*\/>/g) ?? []).length, 1);
const simulator = readFileSync(
new URL(
'../../resources/js/components/simulation-form.tsx',
import.meta.url,
),
'utf8',
);
assert.match(simulator, /data-form-help-step=\{current.id\}/);
assert.match(simulator, /data-form-help-title=\{current.title\}/);
assert.match(
simulator,
/<button[^>]*type="button"[^>]*data-form-help-open/s,
);
});
test('modal assistance remains inside the dialog focus scope and leaves form controls mounted', () => {
const component = readFileSync(
new URL(
'../../resources/js/components/form-field-help.tsx',
import.meta.url,
),
'utf8',
);
assert.match(component, /createPortal\(content, dialog\)/);
assert.doesNotMatch(
component,
/innerHTML|replaceChildren|appendChild|removeChild/,
);
const dom = readFileSync(
new URL('../../resources/js/lib/form-help-dom.ts', import.meta.url),
'utf8',
);
assert.match(dom, /dialog\[open\]/);
assert.doesNotMatch(dom, /cloneNode|\.value\b/);
});
+47
View File
@@ -35,6 +35,53 @@ new Function('require', 'module', 'exports', compiled)(
);
const Search = module.exports.default;
test('product categories preserve the location filter and pagination even without a query', () => {
const results = { data: [{ title: 'Grafite', description: '', category: 'Produtos e localizações', url: '/sectores/mineracao' }], total: 6, current_page: 1, last_page: 2, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'Nampula', results,
answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: 'Nampula', category: 'physical' },
}));
assert.match(html, /q=Nampula&amp;category=financial/);
assert.match(html, /q=Nampula&amp;page=2&amp;category=physical/);
assert.match(html, /name="category" value="physical"/);
const all = renderToStaticMarkup(React.createElement(Search, {
query: '', results, answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: '', category: 'all' },
}));
assert.match(all, /href="\/sectores\/mineracao"/);
});
test('count answer is explicit and zero is distinct from an unavailable count', () => {
const results = { data: [], total: 0, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'quantos corredores existem', results,
answer: { type: 'count', label: 'corredores', count: 0, filter: '' },
}));
assert.match(html, /0 corredores/);
assert.match(html, /registos publicados/);
const failed = renderToStaticMarkup(React.createElement(Search, {
query: 'quantos corredores existem', results,
answer: { type: 'count', label: 'corredores', count: null, filter: '' },
}));
assert.match(failed, /Contagem indisponível/);
assert.doesNotMatch(failed, /0 corredores/);
});
test('products show their location separately from financial coverage and guidance has no invented count', () => {
const results = { data: [{ title: 'Banco de ensaio', description: 'Crédito PME', location: 'Presença física: Maputo', coverage: 'Cobertura nacional', category: 'Produtos financeiros', url: '/fundos/qa' }], total: 1, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'produtos financeiros', results, answer: { type: 'products', label: 'Produtos e localização', count: 1, filter: '' },
}));
assert.match(html, /Produtos financeiros/);
assert.match(html, /Presença física: Maputo/);
assert.match(html, /Cobertura nacional/);
assert.match(html, /não determina a cobertura/);
const guide = renderToStaticMarkup(React.createElement(Search, {
query: 'como licenciar empresa', results: { ...results, data: [] }, answer: { type: 'guide', label: 'Licenciamento da empresa', count: 2, filter: 'licenciamento' },
}));
assert.match(guide, /Licenciamento da empresa/);
assert.doesNotMatch(guide, /2 Licenciamento/);
});
test('shows five results in one sequence with numbered pagination and the query preserved', () => {
const results = {
data: [
@@ -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,11 @@
import {periodAdvanceCase} from './irpc-advance-period-case.mjs';
import {newAdvancePeriodDeclaration,advancePeriodBasis,annualAdvancePeriod} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newPecPlan} from '../../../resources/js/lib/irpc-pec-plan.ts';
export function noncivilCase(){
const c=periodAdvanceCase('noncivil');c.b.ppcObligation.previousFullCalendarYear='no';
c.b.advancePeriodDeclaration={...newAdvancePeriodDeclaration(c.b.subjectNuit,c.b.year,c.period),currentReference:'SYNTHETIC documented authorised annual period CIRPC7(2), continued activity',previousReference:'SYNTHETIC prior annual period and amount/source correspondence',confirmed:'yes'};
c.b.advancePeriodDeclaration.ppcBasisKey=advancePeriodBasis(c.b,'ppc');c.b.advancePeriodDeclaration.pecBasisKey=advancePeriodBasis(c.b,'pec');
c.period=annualAdvancePeriod(c.d,c.b);
c.b.pecObligation.plan={...newPecPlan(c.period),mode:'three',june:'10000',august:'15000',october:'15000',reference:'SYNTHETIC reviewed noncivil cash distribution'};
return c;
}
@@ -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,228 @@
import React from 'react';
import ts from 'typescript';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
investmentStageHelp,
preparationHelp,
helpPreferenceKey,
readHelpPreference,
} from '../../resources/js/lib/investment-step-help.ts';
test('each of the 19 existing stages has specific orientation, an example and a purpose', () => {
const instructions = new Set();
for (let i = 1; i <= 19; i++) {
const code = `S${String(i).padStart(2, '0')}`;
const help = investmentStageHelp(code, `Título ${i}`);
assert.equal(help.code, code);
assert.equal(help.title, `Título ${i}`);
assert.ok(help.instruction.length > 30);
assert.ok(help.example.length > 25);
assert.ok(help.purpose.length > 25);
instructions.add(help.instruction);
}
assert.equal(instructions.size, 19);
assert.equal(
investmentStageHelp('future-stage', 'Nova etapa').title,
'Nova etapa',
);
});
test('preparation guidance preserves the review before confirmation sequence', () => {
assert.deepEqual(
preparationHelp.map((step) => step.code),
['help-choices', 'help-declarations', 'help-review'],
);
assert.match(preparationHelp[2].instruction, /Compare.*confirme/);
});
test('preferences default safely, survive malformed storage and remain separate per user and flow', () => {
assert.deepEqual(readHelpPreference(null), {
automatic: true,
seen: false,
});
assert.deepEqual(readHelpPreference('{bad'), {
automatic: true,
seen: false,
});
assert.deepEqual(readHelpPreference('{"automatic":false,"seen":true}'), {
automatic: false,
seen: true,
});
assert.deepEqual(readHelpPreference('{"automatic":true,"seen":true}'), {
automatic: true,
seen: true,
});
assert.notEqual(helpPreferenceKey(1, 'path'), helpPreferenceKey(2, 'path'));
assert.notEqual(
helpPreferenceKey(1, 'path'),
helpPreferenceKey(1, 'preparation'),
);
assert.notEqual(
helpPreferenceKey('a:b', 'c'),
helpPreferenceKey('a', 'b:c'),
);
});
test('dossier help follows only the steps already permitted by the adaptive path', () => {
const page = readFileSync(
new URL(
'../../resources/js/pages/investor-path/show.tsx',
import.meta.url,
),
'utf8',
);
assert.match(
page,
/steps=\{path\.steps\s*\.filter\(\(step\) => step\.preparation_allowed\)/,
);
assert.match(page, /<HelpAtStep code=\{step.code\}/);
const component = readFileSync(
new URL(
'../../resources/js/components/investment-step-help.tsx',
import.meta.url,
),
'utf8',
);
assert.doesNotMatch(component, /router\.|fetch\(|\.submit\(|\.post\(/);
assert.doesNotMatch(component, /location\.(assign|reload)|window\.history/);
});
test('summary focus and click wait for the native open toggle; closing a stage does not reopen it', () => {
const require = createRequire(import.meta.url);
const memory = [];
let cursor = 0;
let refCursor = 0;
const refs = [];
const effects = [];
const listeners = {};
const rootNode = {
querySelectorAll: () => [],
addEventListener: (name, listener) => {
listeners[name] = listener;
},
removeEventListener() {},
};
const hooks = {
...React,
useEffect(effect) {
effects.push(effect);
},
useRef: (initial) => {
const index = refCursor++;
return (refs[index] ??= { current: initial });
},
useState(initial) {
const index = cursor++;
if (!(index in memory)) memory[index] = initial;
return [
memory[index],
(value) => {
memory[index] = value;
},
];
},
};
const source = readFileSync(
new URL(
'../../resources/js/components/investment-step-help.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
name === 'react'
? hooks
: name === 'lucide-react'
? { CircleHelp: () => null }
: name === '@/lib/investment-step-help'
? { helpPreferenceKey, readHelpPreference }
: require(name),
module,
module.exports,
);
class Target {
constructor(summary, open) {
this.summary = summary;
this.open = open;
this.dataset = { investmentStep: 'S02' };
}
closest(selector) {
return selector === 'summary'
? this.summary
? this
: null
: selector === '[data-investment-step]'
? this
: null;
}
}
class Disclosure extends Target {}
const originalElement = globalThis.Element;
const originalDetails = globalThis.HTMLDetailsElement;
globalThis.Element = Target;
globalThis.HTMLDetailsElement = Disclosure;
const render = () => {
cursor = 0;
refCursor = 0;
effects.length = 0;
const tree = module.exports.InvestmentHelpGuide({
user: 1,
flow: 'regression',
steps: [investmentStageHelp('S02', 'Análise')],
});
refs[0].current = rootNode;
effects.at(-1)();
return tree;
};
try {
let tree = render();
const summary = new Target(true);
tree.props.children.props.onFocusCapture({ target: summary });
tree.props.children.props.onClickCapture({ target: summary });
assert.equal(
render().props.value.active,
null,
'summary events must not open details before their native click',
);
listeners.toggle({
target: new Disclosure(false, false),
});
assert.equal(render().props.value.active, null);
listeners.toggle({
target: new Disclosure(false, true),
});
tree = render();
assert.equal(
tree.props.value.active,
'S02',
'opening a stage selects its automatic help',
);
tree.props.value.choose(null);
tree = render();
listeners.toggle({
target: new Disclosure(false, true),
});
assert.equal(
render().props.value.active,
null,
'closing the guide keeps automatic help paused',
);
} finally {
if (originalElement === undefined) delete globalThis.Element;
else globalThis.Element = originalElement;
if (originalDetails === undefined) delete globalThis.HTMLDetailsElement;
else globalThis.HTMLDetailsElement = originalDetails;
}
});
@@ -0,0 +1,311 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import JSZip from 'jszip';
import {
createInvestorDossierReport,
investorDossierReportIndex,
} from '../../resources/js/lib/investor-dossier-report.ts';
import {
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
function fixture() {
return {
case: {
id: 'case-a',
title: 'Investimento QA <script>alert(1)</script>',
version: 9,
},
context_opportunity: 'op-a',
opportunity_options: ['op-a', 'op-b'],
investment_context: {
revision: 3,
fields: { project_title: 'Projecto QA', province: 'Manica' },
},
phases: { 1: 'Viabilidade', 2: 'Preparação' },
steps: [
{
code: 'S03',
title: 'Viabilidade',
phase: 1,
version: 2,
state: 'preparing',
reason: 'Conferir pressupostos',
detail: {},
},
{
code: 'S08',
title: 'Licenciamento prévio',
phase: 2,
version: 4,
state: 'not_started',
reason: '',
detail: { document_id: 'doc-a' },
},
],
results: [],
land_report: {
id: 'land-a',
version: 3,
updated_at: '2026-11-13',
href: '/investidor/terra-duat/land-a/imprimir',
},
documents: [
{
id: 'link-a',
document_id: 'doc-a',
file_name: 'Estudo QA',
status: 'active',
malware_scan_status: 'clean',
version_no: 2,
sha256: 'a'.repeat(64),
},
],
preparation_report: {
case_id: 'case-a',
opportunity: 'op-a',
version: 7,
context_revision: 3,
href: '/investimentos/case-a/preparacao?opportunity=op-a',
api_state: 'delivery_recorded',
api_issues: [],
exports: [
{
id: 'export-old',
at: '2026-11-12',
context_revision: 2,
historical: true,
fingerprint: 'old',
href: '/investimentos/case-a/preparacao/exportar/export-old?opportunity=op-a',
},
{
id: 'export-new',
at: '2026-11-13',
context_revision: 3,
historical: false,
fingerprint: 'new',
href: '/investimentos/case-a/preparacao/exportar/export-new?opportunity=op-a',
},
],
external: [
{
kind: 'delivery',
date: '2026-11-13',
reference: 'QA-ENTREGA',
export_id: 'export-new',
},
],
swot_review_required: true,
swot: {
object_key: 'investment:case-a',
scope: 'Produção QA',
rows: [
{
id: 's1',
dimension: 'strength',
text: 'Equipa experiente',
reference: 'Fonte QA',
date: '2026-11-12',
classification: 'hypothesis',
},
],
review: null,
actions: [],
},
},
fiscal_reports: [
{
simulation_id: 'simulation-a',
report_id: 'report-a',
report_version_no: 2,
report_sha256: 'b'.repeat(64),
consented_at: '2026-11-13',
},
],
company_reports: {
comparison: { revision: 2, at: '2026-11-12' },
guides: {
energy: {
slug: 'energia',
title: 'Guia de energia',
revision: 1,
at: '2026-11-12',
},
},
},
};
}
void test('one dossier groups stage evidence, SWOT, fiscal and all preserved APIEX versions without modifying sources', () => {
const input = fixture();
input.documents.push({ ...input.documents[0], id: 'second-link' });
const before = JSON.stringify(input);
const index = investorDossierReportIndex(input);
assert.equal(
index.filter((entry) => entry.id.startsWith('apiex:')).length,
2,
);
assert.equal(
index.find((entry) => entry.id === 'document:link-a').stage,
'S08',
);
assert.equal(
index.filter((entry) => entry.id.startsWith('document:')).length,
1,
);
assert.match(
index.find((entry) => entry.id === 'apiex:export-old').state,
/histórica/,
);
assert.equal(
index.find((entry) => entry.id === 'swot').state,
'Revisão necessária',
);
assert.match(
index.find((entry) => entry.id === 'land:land-a').state,
/não é título DUAT/,
);
const report = createInvestorDossierReport(input, '2026-11-13T12:00:00Z');
assert.match(report.version, /case-a.*v9.*contexto v3.*op-a/);
assert.match(
report.sections.find((s) => s.id === 'execution').rows[1].value,
/Por iniciar.*versão 4/,
);
assert.match(
report.sections.find((s) => s.id === 'market').rows[0].value,
/Hipótese/,
);
assert.match(
report.sections.find((s) => s.id === 'sources').paragraphs.join(' '),
/Entrega externa registada.*não equivale a aprovação/,
);
assert.equal(JSON.stringify(input), before);
});
void test('cross-dossier or cross-opportunity preparation is rejected and an ambiguous scope requires selection', () => {
const input = fixture();
input.preparation_report.case_id = 'case-b';
assert.throws(() => createInvestorDossierReport(input), /outro dossier/);
input.preparation_report.case_id = 'case-a';
input.preparation_report.opportunity = 'op-b';
assert.throws(() => createInvestorDossierReport(input), /oportunidade/);
input.context_opportunity = null;
assert.throws(() => investorDossierReportIndex(input), /Seleccione/);
});
void test('financial results from a different opportunity do not enter the consolidated report or its index', () => {
const input = fixture();
input.results = [
{
id: 'other',
context_opportunity: 'op-b',
financial_snapshot: 'OTHER-PRIVATE-INPUTS',
draft_id: 'other-draft',
draft_version: 8,
recorded_at: '2026-11-13',
engine: 'unknown',
currency: 'MZN',
},
];
assert.ok(
!JSON.stringify(createInvestorDossierReport(input)).includes(
'OTHER-PRIVATE-INPUTS',
),
);
assert.ok(
!investorDossierReportIndex(input).some(
(entry) => entry.id === 'finance:other',
),
);
assert.match(
createInvestorDossierReport(input).sections.find(
(s) => s.id === 'finance',
).paragraphs[0],
/Nenhum resultado/,
);
});
void test('the consolidated report reuses loan, break-even, financing and budget outputs with currency and historical state', () => {
const input = fixture();
const financial_snapshot = serializeFinancialToolsSnapshot({
budgetPeriod: 'Mensal',
loan: {
principal: '100000',
rate: '0',
months: '12',
rateType: 'nominal',
periodMonths: '1',
gracePeriods: '0',
upfrontFee: '0',
recurringFee: '0',
},
breakEven: { fixed: '1000', price: '100', variable: '50' },
funding: { total: '100000', secured: '30000' },
incomes: [{ label: 'Receita QA', amount: '100' }],
expenses: [{ label: 'Custo QA', amount: '50' }],
});
input.results = [
{
id: 'finance-a',
context_opportunity: 'op-a',
context_revision: 2,
context_state: 'review_required',
financial_snapshot,
draft_id: 'draft-a',
draft_version: 5,
recorded_at: '2026-11-12',
engine: 'financial-calculators:v1',
currency: 'MZN',
},
];
const report = createInvestorDossierReport(input);
const rows = report.sections.find(
(section) => section.id === 'finance',
).rows;
assert.equal(
rows.find(
(item) => item.field === 'Financiamento — Diferença por financiar',
).value,
'70000.00 MZN',
);
assert.equal(
rows.find(
(item) => item.field === 'Ponto de equilíbrio — Unidades estimadas',
).value,
'20',
);
assert.equal(
rows.find(
(item) => item.field === 'Orçamento — Saldo operacional estimado',
).value,
'50.00 MZN',
);
assert.ok(
rows.some((item) => item.field.startsWith('Empréstimo educativo')),
);
assert.match(rows[0].classification, /Histórico/);
assert.equal(input.results[0].financial_snapshot, financial_snapshot);
});
void test('the existing Word and print exporters retain dossier identity, pending stages, source and history, escaping active HTML', async () => {
const report = createInvestorDossierReport(
fixture(),
'2026-11-13T12:00:00Z',
);
const html = await createProjectDossierPrintHtml(report, [], false);
assert.ok(!html.includes('<script>alert(1)</script>'));
assert.match(html, /case-a/);
assert.match(html, /Fonte QA/);
assert.match(html, /export-old/);
assert.ok(html.includes('a'.repeat(64)));
const docx = await generateProjectDossierDocx(report, [], false);
const zip = await JSZip.loadAsync(await docx.arrayBuffer());
const xml = await zip.file('word/document.xml').async('string');
assert.match(xml, /case-a/);
assert.match(xml, /Licenciamento prévio/);
assert.match(xml, /Por iniciar/);
assert.match(xml, /Fonte QA/);
assert.match(xml, /export-old/);
});
@@ -0,0 +1,99 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import JSZip from 'jszip';
import { createInvestorStageReport } from '../../resources/js/lib/investor-dossier-report.ts';
import {
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
const input = {
case: {
id: 'synthetic-stage-dossier',
title: 'Ensaio sintético',
version: 3,
},
context_opportunity: null,
opportunity_options: [],
investment_context: {
revision: 1,
fields: { project_title: 'Fábrica sintética', province: 'Sofala' },
},
phases: { 1: 'Preparação sintética' },
results: [],
documents: [],
steps: Array.from({ length: 19 }, (_, i) => ({
code: `S${String(i + 1).padStart(2, '0')}`,
title: `Etapa sintética ${i + 1}`,
phase: 1,
version: i + 2,
state: 'preparing',
reason: `Fundamento sintético exclusivo ${i + 1}.`,
detail: { recorded_at: '2026-11-13' },
})),
};
void test('all 19 stage reports can be consulted and exported without inventing outcomes or changing source data', async () => {
const before = JSON.stringify(input);
for (const step of input.steps) {
const model = createInvestorStageReport(
input,
step.code,
'2026-11-13T15:00:00Z',
);
assert.match(model.title, new RegExp(step.code));
const execution = model.sections.find((s) => s.id === 'execution');
assert.equal(execution.rows.length, 1);
assert.ok(execution.rows[0].value.includes(step.reason));
assert.ok(
model.sections
.find((s) => s.id === 'summary')
.rows.every((r) => r.field.startsWith(step.code)),
);
assert.ok(
!model.sections.some((s) => s.id === 'finance') ||
step.code === 'S03',
);
const html = await createProjectDossierPrintHtml(model, [], true);
assert.ok(html.includes(step.reason));
assert.ok(html.includes('synthetic-stage-dossier'));
const blob = await generateProjectDossierDocx(model, [], true);
const zip = await JSZip.loadAsync(await blob.arrayBuffer());
const xml = await zip.file('word/document.xml').async('string');
assert.ok(xml.includes(step.reason));
assert.ok(xml.includes('não cria documentos'));
}
assert.equal(JSON.stringify(input), before);
assert.throws(
() => createInvestorStageReport(input, 'S99'),
/não encontrada/,
);
assert.throws(
() =>
createInvestorStageReport(
{ ...input, opportunity_options: ['a', 'b'] },
'S01',
),
/Seleccione/,
);
});
void test('exported limitations retain literal text and cannot inject active HTML', async () => {
const model = createInvestorStageReport(input, 'S08');
model.limitations.push('Limite <script>alert(1)</script> & origem');
const html = await createProjectDossierPrintHtml(model, [], true);
assert.ok(
html.includes(
'Limite &lt;script&gt;alert(1)&lt;/script&gt; &amp; origem',
),
);
assert.ok(!html.includes('<script>alert(1)</script>'));
const zip = await JSZip.loadAsync(
await (await generateProjectDossierDocx(model, [], true)).arrayBuffer(),
);
assert.ok(
(await zip.file('word/document.xml').async('string')).includes(
'Limite &lt;script&gt;alert(1)&lt;/script&gt; &amp; origem',
),
);
});
@@ -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,42 @@
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 planLib from '../../resources/js/lib/irpc-pec-plan.ts';
import * as rational from '../../resources/js/lib/fiscal-rational.ts';
import {noncivilCase} from './helpers/irpc-annual-noncivil-case.mjs';
const require=createRequire(import.meta.url);
function load(name,resolver){const module={exports:{}};const code=ts.transpileModule(fs.readFileSync(new URL('../../resources/js/components/'+name,import.meta.url),'utf8'),{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;}
function all(tree){if(!tree||typeof tree!=='object')return [];return [tree,...React.Children.toArray(tree.props?.children).flatMap(all)];}
const annualUi=()=>load('simulation-irpc-annual.tsx',n=>n==='@/lib/irpc-annual-settlement'?annual:n.startsWith('./')?new Proxy({},{get:()=>()=>null}):require(n));
test('period preparation suggests dates without evidence or silent confirmation; editing retains deliberate inputs',()=>{
const {d,b}=noncivilCase();delete b.advancePeriodDeclaration;let changed;
const C=annualUi().SimulationIrpcAdvancePeriodDeclaration;
let tree=C({draft:d,book:b,onChange:v=>changed=v});all(tree).find(e=>e.type==='button').props.onClick();
assert.equal(changed.currentFrom,'2025-07-01');assert.equal(changed.previousFrom,'2024-07-01');assert.equal(changed.confirmed,'');assert.equal(changed.previousReference,'');
b.advancePeriodDeclaration={...changed,currentReference:'SYNTHETIC chosen reference',previousReference:'SYNTHETIC prior reference',confirmed:'yes'};
tree=C({draft:d,book:b,onChange:v=>changed=v});
all(tree).find(e=>e.props?.['aria-label']==='Fonte e correspondência do período anterior').props.onChange({target:{value:'SYNTHETIC corrected source'}});
assert.equal(changed.confirmed,'');assert.equal(changed.currentReference,'SYNTHETIC chosen reference');assert.equal(changed.previousReference,'SYNTHETIC corrected source');
});
test('reconfirmation retains periods and deliberate references while binding changed financial amounts',()=>{
const {d,b}=noncivilCase(),old=structuredClone(b.advancePeriodDeclaration);b.ppcObligation.previousTax='200000';let changed;
const tree=annualUi().SimulationIrpcAdvancePeriodDeclaration({draft:d,book:b,onChange:v=>changed=v});
all(tree).find(e=>e.type==='button'&&String(e.props.children).includes('Reconferi')).props.onClick();
assert.equal(changed.currentReference,old.currentReference);assert.equal(changed.previousFrom,old.previousFrom);assert.equal(changed.confirmed,'yes');assert.notEqual(changed.ppcBasisKey,old.ppcBasisKey);assert.equal(changed.pecBasisKey,old.pecBasisKey);
});
test('PEC explicit period binding preserves cash distribution and renders actual relative months',()=>{
const C=load('simulation-irpc-pec-plan.tsx',n=>n==='@/lib/irpc-pec-plan'?planLib:n==='@/lib/fiscal-rational'?rational:require(n)).SimulationIrpcPecPlan;
const {b,period}=noncivilCase(),plan={...b.pecObligation.plan};delete plan.periodFrom;delete plan.periodTo;let changed;
const props={plan,total:{numerator:'40000',denominator:'1'},notApplicable:false,year:'2026',period,onChange:v=>changed=v};
const tree=C(props);all(tree).find(e=>e.type==='button'&&String(e.props.children).includes('Conferi')).props.onClick();
assert.equal(changed.june,'10000');assert.equal(changed.august,'15000');assert.equal(changed.reference,plan.reference);assert.equal(changed.periodFrom,'2025-07-01');
const html=renderToStaticMarkup(React.createElement(C,{...props,plan:changed}));
for(const month of ['2025-12','2026-02','2026-04'])assert.match(html,new RegExp(month));
assert.ok(!html.includes('Conferi a distribuição para'));
});
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {noncivilCase} from './helpers/irpc-annual-noncivil-case.mjs';
import {advanceCalendar,newAdvancePeriodDeclaration} from '../../resources/js/lib/irpc-advance-calendar.ts';
import {calculatePpcObligation} from '../../resources/js/lib/irpc-ppc-obligation.ts';
import {calculatePecObligation} from '../../resources/js/lib/irpc-pec-obligation.ts';
import {calculatePecPlan} from '../../resources/js/lib/irpc-pec-plan.ts';
import {annualAdvancePeriod,advancePeriodBasis,annualAdvanceCashflow,recordAnnual,saveAnnualBook,annualBook,annualCurrent,annualHtml} from '../../resources/js/lib/irpc-annual-settlement.ts';
const f=n=>({numerator:String(n),denominator:'1'});
test('documented annual noncivil periods reuse exact estimates and relative PPC PEC months',()=>{
const {b,period}=noncivilCase(),before=JSON.stringify(b);const ppc=calculatePpcObligation(b.ppcObligation,b.subjectNuit,b.year,b.assessment,period),pec=calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,period);
assert.deepEqual(ppc.total,f(72000));assert.deepEqual(ppc.schedule.map(r=>r.month),['2025-11','2026-01','2026-03']);assert.deepEqual(pec.total,f(40000));assert.deepEqual(pec.months,['2025-12','2026-02','2026-04']);
const joint=annualAdvanceCashflow(b,period);assert.deepEqual(joint.total,f(112000));assert.deepEqual(joint.rows.map(r=>r.month),['2025-11','2025-12','2026-01','2026-02','2026-03','2026-04']);assert.equal(JSON.stringify(b),before);
});
test('missing evidence, identity mismatch, nonadjacent and short previous periods cannot qualify the annual recorte',()=>{
for(const changes of [{confirmed:''},{currentReference:''},{previousReference:''},{subjectNuit:'999999999'},{currentFrom:'2025-08-01'},{previousFrom:'2025-01-01'},{previousTo:'2025-05-31'}]){
const {d,b}=noncivilCase();Object.assign(b.advancePeriodDeclaration,changes);assert.equal(annualAdvanceCashflow(b,annualAdvancePeriod(d,b)).total,null,JSON.stringify(changes));
}
const missing=noncivilCase();missing.b.advancePeriodDeclaration.previousReference='';const result=calculatePpcObligation(missing.b.ppcObligation,missing.b.subjectNuit,missing.b.year,missing.b.assessment,annualAdvancePeriod(missing.d,missing.b));assert.ok(result.pending.length);assert.ok(!result.pending.join(' ').includes('exercício civil completo2025'));
assert.equal(advanceCalendar(null,'').mode,'unavailable');
});
test('editing one component invalidates only its confirmed amount correspondence',()=>{
const {d,b}=noncivilCase();b.ppcObligation.previousTax='200000';let m=annualAdvanceCashflow(b,annualAdvancePeriod(d,b));assert.equal(m.ppcKnown,false);assert.equal(m.pecKnown,true);assert.equal(m.total,null);
b.advancePeriodDeclaration.ppcBasisKey=advancePeriodBasis(b,'ppc');m=annualAdvanceCashflow(b,annualAdvancePeriod(d,b));assert.equal(m.ppcKnown,true);assert.deepEqual(m.total,f(193000));
});
test('civil cash choices are retained without automatic displacement and require explicit noncivil binding',()=>{
const {b,period}=noncivilCase();delete b.pecObligation.plan.periodFrom;delete b.pecObligation.plan.periodTo;let m=annualAdvanceCashflow(b,period);assert.equal(m.pecKnown,false);assert.equal(b.pecObligation.plan.june,'10000');
b.pecObligation.plan.periodFrom=period.from;b.pecObligation.plan.periodTo=period.to;m=annualAdvanceCashflow(b,period);assert.deepEqual(m.total,f(112000));
const p={...b.pecObligation.plan,mode:'single',singleMonth:'2026-01'};assert.deepEqual(calculatePecPlan(p,f(40000),false,'2026',period).rows,[{month:'2026-01',amount:f(40000)}]);p.singleMonth='2026-07';assert.equal(calculatePecPlan(p,f(40000),false,'2026',period).rows.length,0);
});
test('source changes preserve the declaration but require reconfirmation; excluded historical and start cases stay separate',()=>{
const {d,b}=noncivilCase();const old=JSON.stringify(b.advancePeriodDeclaration);const period={...annualAdvancePeriod(d,b),from:'2025-08-01',to:'2026-07-31'};assert.equal(annualAdvanceCashflow(b,period).total,null);assert.equal(JSON.stringify(b.advancePeriodDeclaration),old);
b.pecObligation.previousTurnover='0';b.advancePeriodDeclaration.pecBasisKey=advancePeriodBasis(b,'pec');assert.equal(calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,annualAdvancePeriod(d,b)).total,null);
b.pecObligation.activityStartYear='2026';b.advancePeriodDeclaration.pecBasisKey=advancePeriodBasis(b,'pec');assert.equal(calculatePecObligation(b.pecObligation,b.subjectNuit,b.year,b.assessment,annualAdvancePeriod(d,b)).total,null);
});
test('annual recovery freezes qualified periods and keeps the independent settlement and history unchanged',()=>{
const {d,b}=noncivilCase();const prior=recordAnnual(d,{...b,ppcObligation:undefined,pecObligation:undefined},'2026-11-14T07:00:00Z');const next=recordAnnual(d,{...prior,ppcObligation:b.ppcObligation,pecObligation:b.pecObligation},'2026-11-14T07:01:00Z');assert.deepEqual(next.result.model.arithmeticBalance,prior.result.model.arithmeticBalance);
d.modelo_a_snapshot=saveAnnualBook(d,next);const back=annualBook(d);assert.equal(annualCurrent(d,back),true);assert.equal(back.history.length,1);assert.deepEqual(annualAdvanceCashflow(back,back.result.model.advancePeriod).total,f(112000));assert.match(annualHtml(d),/2025-11/);
const frozen=JSON.stringify(back.result.model.advancePeriod);back.advancePeriodDeclaration.previousReference='SYNTHETIC revised reference';assert.equal(JSON.stringify(back.result.model.advancePeriod),frozen);assert.equal(annualCurrent(d,back),false);
});
@@ -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' },
+2
View File
@@ -6,6 +6,7 @@ import { createRequire } from "node:module";
import ts from "typescript";
import React from "react";
import { revealPathStage } from "../../resources/js/lib/investor-path-stage.ts";
import { investmentStageHelp } from "../../resources/js/lib/investment-step-help.ts";
const require = createRequire(import.meta.url);
const flatten = (node) =>
Array.isArray(node)
@@ -62,6 +63,7 @@ function harness(overrides = {}, react = React) {
? { pathStates: { preparing: "Em preparação" } }
: name === "@/lib/operation-key" ? { createOperationKey: () => 'qa-key' }
: name === "@/lib/investor-path-stage" ? { revealPathStage }
: name === "@/lib/investment-step-help" ? { investmentStageHelp }
: name === "@/components/proactive-investment" ? { proactiveView: () => null }
: name.startsWith("@/")
? {}
@@ -18,6 +18,7 @@ function load(file, page) {
const module = { exports: {} };
const aliases = new Proxy({ default: Empty }, { get: (target, name) => name in target ? target[name] : Empty });
compileFunction(code, ['require', 'module', 'exports'])((name) => {
if (name.endsWith('.css')) return {};
if (name === 'lucide-react') return aliases;
if (name === '@inertiajs/react') return {
Link: 'a', Head: Empty, usePage: () => page,