This commit is contained in:
2026-11-03 15:31:43 +02:00
124 changed files with 10287 additions and 380 deletions
@@ -0,0 +1,126 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentGeography;
use App\Services\CorridorAgribusinessOpportunities;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class CatalogueProvinceCoverageTest extends TestCase
{
use DatabaseTransactions;
private const PROVINCE = 'bfde2651-2b46-5d9c-a500-733fa55a8c5c';
protected function setUp(): void
{
parent::setUp();\Tests\Support\ProactiveInvestmentFixture::guard();$this->withoutVite();
}
public function test_accepted_maputo_source_is_found_in_both_approved_provinces_without_becoming_a_district_site(): void
{
$c=app(InvestmentCatalogue::class);
$expected=Opportunity::published()->where('workflow_context->corridor_agribusiness->source_sha256',CorridorAgribusinessOpportunities::SOURCE_HASH)
->where('workflow_context->corridor_agribusiness->corridor','Corredor de Maputo')->pluck('id')->all();
$this->assertCount(5,$expected);
foreach([self::PROVINCE,'4aa31470-997e-5c63-8fe0-ff2f62586f56']as$province){
foreach(['all','context']as$basis){
$ids=$c->query(['sector'=>'agronegocio','province_id'=>$province,'territory_basis'=>$basis])->pluck('id')->all();
foreach($expected as$id)$this->assertContains($id,$ids);
}
}
foreach($expected as$id)$this->assertNotContains($id,$c->query(['province_id'=>self::PROVINCE,'territory_basis'=>'direct'])->pluck('id')->all());
$district=app(InvestmentGeography::class)->publicReferences()->where('parent_id',self::PROVINCE)->where('location_type','district')->first();
$this->assertNotNull($district);
foreach($expected as$id)$this->assertNotContains($id,$c->query(['province_id'=>self::PROVINCE,'district_id'=>$district->id])->pluck('id')->all());
$label=$c->presentLocation(Opportunity::findOrFail($expected[0]))->territorial_summary;
$this->assertStringContainsString('contexto provincial do corredor',$label);
$this->assertStringContainsString('distrito e posto administrativo não indicados',$label);
foreach($expected as$id)$this->assertContains($id,$c->query(['geo_location_id'=>self::PROVINCE])->pluck('id')->all());
$this->assertSame([],array_intersect($expected,$c->query(['province_id'=>'059b02ca-7095-577a-8705-4d4c46896747'])->pluck('id')->all()));
}
public function test_province_includes_its_descendants_with_full_location_and_excludes_private_and_other_provinces(): void
{
$geo=app(InvestmentGeography::class);$c=app(InvestmentCatalogue::class);
$district=$geo->publicReferences()->where('parent_id',self::PROVINCE)->where('location_type','district')->first();
$post=$geo->publicReferences()->where('parent_id',$district->id)->where('location_type','admin_post')->first();
$this->assertNotNull($post);
$make=fn($territory,$status='published')=>Opportunity::create(['sector_id'=>1,'reference'=>'SYNTHETIC-QA-'.Str::uuid(),'slug'=>'synthetic-'.Str::uuid(),'title'=>'SYNTHETIC QA province coverage','status'=>$status,'published_at'=>now()->subMinute(),'primary_territory_id'=>$territory,'geography_scope'=>'specific']);
$record=$make($post->id);$private=$make($post->id,'draft');$other=$make('059b02ca-7095-577a-8705-4d4c46896747');
$ids=$c->query(['province_id'=>self::PROVINCE,'sector'=>'agronegocio'])->pluck('id')->all();
$this->assertContains($record->id,$ids);$this->assertNotContains($private->id,$ids);$this->assertNotContains($other->id,$ids);
$label=$c->presentLocation($record)->territorial_summary;
foreach(['Maputo Província',$district->name,$post->name]as$name)$this->assertStringContainsString($name,$label);
}
public function test_actual_territory_and_publication_decisions_override_old_corridor_context(): void
{
$c=app(InvestmentCatalogue::class);
$record=Opportunity::published()->where('workflow_context->corridor_agribusiness->corridor','Corredor de Maputo')->firstOrFail();
$record->primary_territory_id='059b02ca-7095-577a-8705-4d4c46896747';$record->save();
$this->assertNotContains($record->id,$c->query(['province_id'=>self::PROVINCE])->pluck('id')->all());
$record->primary_territory_id=null;$record->status='draft';$record->save();
$this->assertNotContains($record->id,$c->query(['province_id'=>self::PROVINCE])->pluck('id')->all());
}
public function test_public_search_and_corridor_view_agree_without_inventing_map_coordinates(): void
{
$filters=['province_id'=>self::PROVINCE,'sector'=>'agronegocio'];
$response=$this->getJson('/api/v1/investment/search?'.http_build_query($filters))->assertOk()->assertJsonPath('total',5);
foreach($response->json('data')as$row)$this->assertStringContainsString('contexto provincial do corredor',$row['territorial_summary']);
$groups=app(\App\Services\OpportunityCorridorExplorer::class)->groups($filters);
$this->assertCount(1,$groups);$this->assertSame(5,$groups[0]['count']);
foreach($groups[0]['opportunities']as$row){$this->assertContains('Maputo Província',$row['provinces']);$this->assertNull($row['district']);}
$map=app(InvestmentCatalogue::class)->map($filters);
$this->assertCount(5,$map['unlocated']);$this->assertSame([],$map['features']);
}
public function test_all_approved_corridors_are_found_in_their_provinces_and_not_in_unrelated_provinces(): void
{
$catalogue=app(InvestmentCatalogue::class);
$provinces=app(InvestmentGeography::class)->publicReferences()->where('location_type','province')->get();
$this->assertCount(11,$provinces);
foreach(config('investment_corridors')as$entry){
$records=Opportunity::published()->whereNull('primary_territory_id')
->where('workflow_context->corridor_agribusiness->source_sha256',CorridorAgribusinessOpportunities::SOURCE_HASH)
->where('workflow_context->corridor_agribusiness->corridor',$entry['name'])->pluck('id')->all();
$this->assertNotEmpty($records,$entry['name']);
foreach($provinces as$province){
$ids=$catalogue->query(['province_id'=>$province->id,'sector'=>'agronegocio'])->pluck('id')->all();
foreach($records as$id){
if(in_array($province->source_code,$entry['provinces'],true))$this->assertContains($id,$ids);
else $this->assertNotContains($id,$ids);
}
}
}
}
public function test_descendant_coverage_is_national_and_shared_by_sectors_and_location_entry_points(): void
{
$geo=app(InvestmentGeography::class);$catalogue=app(InvestmentCatalogue::class);
$provinces=$geo->publicReferences()->where('location_type','province')->get();
$sectors=DB::table('sectors')->where('is_active',true)->whereNotNull('published_at')->whereNull('deleted_at')->orderBy('id')->limit(2)->get();
$this->assertCount(2,$sectors);
foreach($provinces as$province){
$district=$geo->publicReferences()->where('parent_id',$province->id)->where('location_type','district')->first();
$this->assertNotNull($district,$province->name);
$post=$geo->publicReferences()->where('parent_id',$district->id)->where('location_type','admin_post')->first();
$leaf=$post?:$district;
foreach($sectors as$sector){
$record=Opportunity::create(['sector_id'=>$sector->id,'reference'=>'SYNTHETIC-QA-'.Str::uuid(),'slug'=>'synthetic-'.Str::uuid(),
'title'=>'SYNTHETIC QA national coverage','status'=>'published','published_at'=>now()->subMinute(),'primary_territory_id'=>$leaf->id,'geography_scope'=>'specific']);
foreach([['province_id'=>$province->id],['geo_location_id'=>$province->id],['province_id'=>$province->id,'district_id'=>$district->id]]as$entry){
$this->assertContains($record->id,$catalogue->query([...$entry,'sector'=>$sector->slug])->pluck('id')->all());
}
$other=$sectors->firstWhere('id','!=',$sector->id);
$this->assertNotContains($record->id,$catalogue->query(['province_id'=>$province->id,'sector'=>$other->slug])->pluck('id')->all());
$label=$catalogue->presentLocation($record)->territorial_summary;
$this->assertStringContainsString($province->name,$label);$this->assertStringContainsString($district->name,$label);
if($post)$this->assertStringContainsString($post->name,$label);
}
}
}
}
@@ -0,0 +1,175 @@
<?php
namespace Tests\Feature;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\User;
use App\Services\ClusterCompetitiveness;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia;
use Tests\TestCase;
class ClusterCompetitivenessTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
}
private function manager(): User
{
$user = User::factory()->create();
config(['portal.managers' => [$user->email], 'portal.profile_access_enabled' => false]);
$this->actingAs($user);
return $user;
}
private function cluster(): EconomicCluster
{
return EconomicCluster::create(['code' => 'COMP-'.bin2hex(random_bytes(6)), 'name' => 'Cluster de teste de persistência', 'sector' => 'Energia', 'status' => 'planned']);
}
private function draft(EconomicCluster $cluster): array
{
$draft = ['version' => 1, 'clusterId' => $cluster->id, 'sector' => 'Energia', 'region' => 'Distrito de demonstração', 'forces' => []];
foreach (ClusterCompetitiveness::FORCES as $force) {
$draft['forces'][$force] = ['pressure' => 'medium', 'evidence' => 'Observação de teste, não publicável como facto real',
'source' => 'Fonte de demonstração p. 2', 'period' => '2025', 'rationale' => 'Apreciação de teste',
'limitations' => 'Dados sintéticos', 'opportunity' => 'Hipótese de demonstração'];
}
return $draft;
}
private function url(EconomicCluster $cluster): string
{
return '/management/clusters/'.$cluster->id.'/competitiveness';
}
public function test_save_recovers_from_database_across_requests_and_records_encrypted_history(): void
{
$actor = $this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])
->assertOk()->assertJsonPath('version', 1)->assertJsonPath('draft', $draft)->assertJsonPath('approved', null);
$this->getJson($this->url($cluster))->assertOk()->assertHeader('Cache-Control', 'no-store, private')
->assertJsonPath('draft', $draft)->assertJsonPath('history.0.actor', $actor->id)->assertJsonPath('history.0.action', 'saved');
$this->get('/management/clusters/'.$cluster->id.'/edit')->assertInertia(fn (AssertableInertia $page) => $page
->component('structures/editor')->where('competitiveness.version', 1)->where('competitiveness.draft.region', $draft['region']));
$event = DB::table('audit_events')->where('source_system', 'cluster-competitiveness')->where('entity_id', $cluster->id)->first();
$this->assertStringNotContainsString($draft['forces']['rivalry']['evidence'], $event->after_data);
$this->assertSame('restricted', $event->data_classification);
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($cluster->id));
}
public function test_validation_conflict_and_server_error_do_not_overwrite_the_saved_version(): void
{
$this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
$changed = $draft;
$changed['region'] = 'Outra região';
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $changed])->assertConflict();
$changed['forces']['buyers']['pressure'] = 'zero';
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $changed])->assertUnprocessable();
$changed = $draft;
$changed['clusterId'] = $this->cluster()->id;
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $changed])->assertUnprocessable();
$this->getJson($this->url($cluster))->assertJsonPath('version', 1)->assertJsonPath('draft', $draft)->assertJsonCount(1, 'history');
}
public function test_approval_pins_content_and_later_drafts_and_restoration_do_not_publish(): void
{
$this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$url = $this->url($cluster);
$this->postJson($url.'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
$this->postJson($url.'/approved', ['expected_version' => 1, 'reason' => 'Aprovação sintética em QA'])->assertOk()->assertJsonPath('version', 2);
$changed = $draft;
$changed['region'] = 'Rascunho privado posterior';
$this->postJson($url.'/saved', ['expected_version' => 2, 'draft' => $changed])->assertOk();
$public = app(ClusterCompetitiveness::class)->publicData($cluster->id);
$this->assertSame($draft, $public['draft']);
$this->assertSame(['draft', 'version', 'at'], array_keys($public));
$this->postJson($url.'/restored', ['expected_version' => 3, 'revision' => 1])->assertOk()
->assertJsonPath('version', 4)->assertJsonPath('draft', $draft)->assertJsonPath('approved.version', 2);
$this->assertSame($public, app(ClusterCompetitiveness::class)->publicData($cluster->id));
$this->postJson($url.'/withdrawn', ['expected_version' => 4, 'reason' => 'Retirada sintética em QA'])->assertOk()->assertJsonCount(5, 'history');
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($cluster->id));
$this->getJson($url)->assertJsonPath('draft', $draft);
}
public function test_incomplete_drafts_are_saved_but_not_approved_and_unknown_revisions_do_not_write(): void
{
$this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$draft['forces']['buyers']['source'] = '';
$draft['forces']['entrants']['pressure'] = '';
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])->assertOk();
$this->postJson($this->url($cluster).'/approved', ['expected_version' => 1, 'reason' => 'Pedido de aprovação QA'])->assertUnprocessable();
$this->postJson($this->url($cluster).'/restored', ['expected_version' => 1, 'revision' => 99])->assertNotFound();
$this->getJson($this->url($cluster))->assertJsonPath('version', 1)->assertJsonPath('draft.forces.buyers.source', '');
}
public function test_saved_data_keeps_the_portable_file_contract_and_rejects_missing_forces(): void
{
$this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$draft['version'] = '1';
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 0, 'draft' => $draft])
->assertOk()->assertJsonPath('draft.version', 1);
unset($draft['forces']['suppliers']);
$this->postJson($this->url($cluster).'/saved', ['expected_version' => 1, 'draft' => $draft])->assertUnprocessable();
$this->getJson($this->url($cluster))->assertJsonPath('version', 1);
}
public function test_anonymous_and_unauthorised_users_cannot_read_history_or_mutate(): void
{
$cluster = $this->cluster();
$url = $this->url($cluster);
$this->getJson($url)->assertUnauthorized();
$this->postJson($url.'/saved', [])->assertUnauthorized();
$this->actingAs(User::factory()->create());
$this->getJson($url)->assertForbidden();
foreach (['saved', 'approved', 'withdrawn', 'restored'] as $action) {
$this->postJson($url.'/'.$action, [])->assertForbidden();
}
$this->assertSame(0, DB::table('audit_events')->where('source_system', 'cluster-competitiveness')->where('entity_id', $cluster->id)->count());
}
public function test_public_dossier_returns_only_the_approved_projection_and_unpublished_dossiers_remain_hidden(): void
{
$actor = $this->manager();
$cluster = $this->cluster();
$draft = $this->draft($cluster);
$dossier = InvestmentDossier::create(['cluster_id' => $cluster->id, 'title' => 'Ficha sintética QA', 'source' => 'Fonte sintética QA',
'content' => ['sector' => 'Energia'], 'publication_status' => 'published', 'approval_basis' => 'document_owner',
'approval_evidence' => 'Aprovação sintética só na base QA', 'published_at' => now()]);
$service = app(ClusterCompetitiveness::class);
$service->change($cluster, $actor->id, 0, 'saved', ['draft' => $draft]);
$this->app['auth']->forgetGuards();
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page->where('competitiveness', null));
$service->change($cluster, $actor->id, 1, 'approved', ['reason' => 'Aprovação privada de teste']);
$draft['region'] = 'CONTEÚDO PRIVADO NÃO APROVADO';
$service->change($cluster, $actor->id, 2, 'saved', ['draft' => $draft]);
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page
->where('competitiveness.version', 2)->where('competitiveness.draft.region', 'Distrito de demonstração')
->missing('competitiveness.actor')->missing('competitiveness.evidence')->missing('competitiveness.history'));
$dossier->update(['publication_status' => 'draft']);
$this->get('/carteira/'.$dossier->id)->assertNotFound();
$dossier->update(['publication_status' => 'published']);
$service->change($cluster, $actor->id, 3, 'withdrawn', ['reason' => 'Retirada privada de teste']);
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (AssertableInertia $page) => $page->where('competitiveness', null));
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
final class FiscalFormEntryTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
\Tests\Support\ProactiveInvestmentFixture::guard();
$this->withoutVite();
}
public function test_both_fiscal_forms_are_public_and_do_not_redirect_to_legal_documents(): void
{
config(['portal.homologation_only' => false]);
foreach (['iva', 'irpc'] as $tax) {
$this->get('/formularios/fiscais?imposto='.$tax)
->assertOk()
->assertInertia(fn (Assert $page) => $page->component('portal/fiscal-forms')->where('initialTax', $tax));
}
}
}
@@ -0,0 +1,57 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\InvestmentGeography;
use App\Services\InvestmentZones;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class InvestorUsabilityScopeTest extends TestCase
{
use DatabaseTransactions;
protected function setUp():void{parent::setUp();\Tests\Support\ProactiveInvestmentFixture::guard();$this->withoutVite();}
public function test_public_sector_is_consultable_by_guest_and_accounts_without_promoter_grants():void
{
config(['portal.homologation_only'=>false,'portal.legacy_content_enabled'=>false,'portal.legacy_content_qa_enabled'=>false]);
$this->get('/sectores/turismo')->assertOk();
$actor=User::factory()->create();
$this->actingAs($actor)->get('/sectores/turismo')->assertOk();
$this->assertSame(0,DB::table('portal_role_assignments')->where('user_id',$actor->id)->count());
config(['portal.profile_access_enabled'=>true]);
$entry=app(\App\Services\SectorInvestment::class)->publicView(\App\Models\Sector::where('slug','turismo')->firstOrFail());
$this->assertSame('/perfil/promotor',$entry['register_href']);
$this->assertSame('Pedir acesso para cadastrar oportunidades',$entry['register_label']);
}
public function test_zones_all_equals_visible_set_and_province_and_district_never_fall_back_to_all():void
{
$zones=app(InvestmentZones::class);$geo=app(InvestmentGeography::class);
$province='059b02ca-7095-577a-8705-4d4c46896747';
$district=$geo->publicReferences()->where('parent_id',$province)->where('location_type','district')->first();
$template=$zones->visible()->firstOrFail();
$make=function($territory,$published=true)use($template){$zone=$template->replicate();$zone->id=(string)Str::uuid();$zone->code='SYNTHETIC-'.Str::random(12);$zone->name='SYNTHETIC QA zone scope';$zone->primary_territory_id=$territory;$zone->publication_status=$published?'published':'draft';$zone->save();return$zone;};
$inside=$make($district->id);$outside=$make('9e42dac8-fd9b-523f-bf59-71a7d3aa0fb8');$private=$make($district->id,false);
$all=$zones->search([])->orderBy('id')->pluck('id')->all();
$this->assertSame($zones->visible()->orderBy('id')->pluck('id')->all(),$all);
foreach([['province_id'=>$province],['province_id'=>$province,'district_id'=>$district->id]]as$selection){
$ids=$zones->search($selection)->pluck('id')->all();
$this->assertContains($inside->id,$ids);$this->assertNotContains($outside->id,$ids);$this->assertNotContains($private->id,$ids);
}
}
public function test_documented_legal_scope_covers_child_area_but_influence_does_not_become_an_installation():void
{
$zones=app(InvestmentZones::class);$geo=app(InvestmentGeography::class);$province='059b02ca-7095-577a-8705-4d4c46896747';
$district=$geo->publicReferences()->where('parent_id',$province)->where('location_type','district')->first();
$editor=User::factory()->create();$reviewer=User::factory()->create();$template=$zones->visible()->firstOrFail();$ids=[];
foreach(['legal_scope','influence']as$scope){
$zone=$template->replicate();$zone->id=(string)Str::uuid();$zone->code='SYNTHETIC-'.Str::random(12);$zone->name='SYNTHETIC QA legal coverage';$zone->primary_territory_id='9e42dac8-fd9b-523f-bf59-71a7d3aa0fb8';$zone->save();$ids[$scope]=$zone->id;
DB::table('investment_zone_locations')->insert(['id'=>(string)Str::uuid(),'zone_id'=>$zone->id,'geo_location_id'=>$scope==='legal_scope'?$province:$district->id,'scope_type'=>$scope,'source_reference'=>'SYNTHETIC isolated QA scope fixture','validation_status'=>'validated','editor_id'=>$editor->id,'reviewer_id'=>$reviewer->id,'valid_from'=>now()->subDay(),'version_no'=>1,'created_at'=>now(),'updated_at'=>now()]);
}
$matches=$zones->search(['province_id'=>$province,'district_id'=>$district->id])->pluck('id')->all();
$this->assertContains($ids['legal_scope'],$matches);$this->assertNotContains($ids['influence'],$matches);
}
}
@@ -0,0 +1,82 @@
<?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 IrpcCreditCarryDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_prior_credit_details_round_trip_with_frozen_history_and_preserved_records(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('proactive_investment_20261027_test', $target->name);
$this->assertSame(55441, (int) $target->port);
$snapshot = static fn (string $table): array => collect(DB::select('select id::text as id,md5(row_to_json(t)::text) as hash from public."'.$table.'" t order by id'))->pluck('hash', 'id')->all();
$protected = [];
foreach (['opportunities', 'documents', 'opportunity_documents', 'simulation_form_drafts', 'users', 'organizations', 'audit_events'] as $table) {
$protected[$table] = $snapshot($table);
}
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::findOrFail(1021));
$fixture = json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-carry-preserved.json')), true, flags: JSON_THROW_ON_ERROR);
$this->assertTrue($fixture['synthetic']);
$this->assertFalse($fixture['actualBalances']);
$id = null;
$etag = null;
foreach ($fixture['cases'] as $name => $draft) {
$personal = ['person_type' => $draft['person_type']];
unset($draft['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $draft];
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($draft['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($draft['business_plan_snapshot'], $back['business_plan_snapshot']);
$original = json_decode($draft['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$recovered = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
foreach (['irpcNormal', 'irpcWithholdings', 'books', 'currencyEvents', 'ispcQuarters'] as $map) {
$this->assertSame($original[$map], $recovered[$map]);
}
$book = $recovered['irpcAnnual'][$draft['context_opportunity']];
$model = $book['result']['model'];
$this->assertSame($original['irpcAnnual'][$draft['context_opportunity']], $book);
$this->assertCount(1, $book['history']);
$this->assertSame('IRPC-credit-carry/1', $model['creditCarry']['version']);
$this->assertFalse($model['creditCarry']['carryCreated']);
$this->assertFalse($model['creditCarry']['officialBalancesConsumed']);
$this->assertFalse($model['submitted']);
if (in_array($name, ['expired', 'missing-use', 'overallocated'], true)) {
$this->assertSame('indeterminate', $model['status']);
$this->assertNull($model['arithmeticBalance']);
$this->assertNull($model['internationalCredit']['deducted']);
$this->assertNull($model['pecDeduction']['deducted']);
} else {
$expected = ['payable' => ['550', '1'], 'fractional' => ['1822', '3'], 'recoverable' => ['-500', '1']][$name];
$this->assertEmpty($model['pending']);
$this->assertSame(['numerator' => $expected[0], 'denominator' => $expected[1]], $model['arithmeticBalance']);
}
if (getenv('INVESTMOZ_CARRY_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-carry-20261028/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
$preserved = [];
foreach ($protected as $table => $before) {
$this->assertSame($before, array_intersect_key($snapshot($table), $before), 'Existing records changed: '.$table);
$preserved[$table] = ['existing_rows' => count($before), 'unchanged' => true];
}
if (getenv('INVESTMOZ_CARRY_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-carry-20261028/existing-records-preservation.json'), json_encode(['database' => $target->name, 'tables' => $preserved, 'transaction_rollback' => true], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
}
}
@@ -0,0 +1,83 @@
<?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 IrpcEconomicCreditDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_economic_credit_and_compatible_carry_round_trip_without_overwriting_accepted_history(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('proactive_investment_20261027_test', $target->name);
$this->assertSame(55441, (int) $target->port);
$snapshot = static fn (string $table): array => collect(DB::select('select id::text as id,md5(row_to_json(t)::text) as hash from public."'.$table.'" t order by id'))->pluck('hash', 'id')->all();
$protected = [];
foreach (['opportunities', 'documents', 'opportunity_documents', 'simulation_form_drafts', 'users', 'organizations', 'audit_events'] as $table) {
$protected[$table] = $snapshot($table);
}
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::findOrFail(1021));
$fixture = json_decode(file_get_contents(base_path('tests/frontend/fixtures/irpc-economic-preserved.json')), true, flags: JSON_THROW_ON_ERROR);
$this->assertTrue($fixture['synthetic']);
$this->assertFalse($fixture['actualTaxEvidence']);
$id = null;
$etag = null;
foreach ($fixture['cases'] as $name => $draft) {
$personal = ['person_type' => $draft['person_type']];
unset($draft['person_type']);
$payload = ['personal_snapshot' => $personal, 'economic_snapshot' => $draft];
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($draft['modelo_a_snapshot'], $back['modelo_a_snapshot']);
$this->assertSame($draft['business_plan_snapshot'], $back['business_plan_snapshot']);
$original = json_decode($draft['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$recovered = json_decode($back['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
foreach (['irpcNormal', 'irpcWithholdings', 'books', 'currencyEvents', 'ispcQuarters'] as $map) {
$this->assertSame($original[$map], $recovered[$map]);
}
$book = $recovered['irpcAnnual'][$draft['context_opportunity']];
$model = $book['result']['model'];
$this->assertSame($original['irpcAnnual'][$draft['context_opportunity']], $book);
$this->assertCount(1, $book['history']);
$this->assertSame('IRPC-economic-credit/1', $model['economicCredit']['version']);
$this->assertFalse($model['economicCredit']['carryCreated']);
$this->assertFalse($model['economicCredit']['officialBalancesConsumed']);
$this->assertFalse($model['submitted']);
if (in_array($name, ['duplicate', 'missing-gross-up', 'article40', 'partial-parcel'], true)) {
$this->assertSame('indeterminate', $model['status']);
$this->assertNull($model['arithmeticBalance']);
$this->assertNull($model['economicCredit']['deducted']);
$this->assertNull($model['internationalCredit']['deducted']);
$this->assertNull($model['pecDeduction']['deducted']);
} else {
$expected = ['payable' => ['688', '1'], 'combined' => ['538', '1'], 'quota' => ['695', '1'], 'prior-use' => ['691', '1'], 'shared-paper' => ['688', '1'], 'fractional' => ['349997', '500'], 'recoverable' => ['-500', '1']][$name];
$this->assertEmpty($model['pending']);
$this->assertSame(['numerator' => $expected[0], 'denominator' => $expected[1]], $model['arithmeticBalance']);
}
if (getenv('INVESTMOZ_ECONOMIC_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-economic-20261028/recovered-'.$name.'.json'), json_encode($back, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
$preserved = [];
foreach ($protected as $table => $before) {
$this->assertSame($before, array_intersect_key($snapshot($table), $before), 'Existing records changed: '.$table);
$preserved[$table] = ['existing_rows' => count($before), 'unchanged' => true];
}
if (getenv('INVESTMOZ_ECONOMIC_QA_OUTPUT') === '1') {
file_put_contents(base_path('outputs/irpc-l8-economic-20261028/existing-records-preservation.json'), json_encode(['database' => $target->name, 'tables' => $preserved, 'transaction_rollback' => true], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
}
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityManagement;
use App\Services\ProactiveSupply;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Support\ProactiveInvestmentFixture as F;
use Tests\TestCase;
final class ProactiveSupplyTest extends TestCase
{
use DatabaseTransactions;
private User $actor;
private string $territory;
private string $observation;
protected function setUp():void
{
parent::setUp();F::guard();$this->withoutVite();
config(['portal.profile_access_enabled'=>true,'portal.opportunity_specialized_drafts_enabled'=>true,'portal.managers'=>[],'investor-path.enabled'=>true,'suitecrm.enabled'=>false,'investmoz_ai.enabled'=>false]);
$this->actor=F::operator();$this->login($this->actor);
$input=F::input('Gurué');$this->territory=$input['district_id'];
$hash=hash('sha256','SYNTHETIC-QA-SUPPLY-SOURCE');
DB::table('proactive_supply_sources')->insert(['sha256'=>$hash,'name'=>'SYNTHETIC-QA-SUPPLY.xlsx','period'=>'2020','limitations'=>'Synthetic, not a real market source','receipt'=>'{}','imported_at'=>now()]);
$this->observation=hash('sha256','SYNTHETIC-QA-OBSERVATION');
$row=['id'=>$this->observation,'source_hash'=>$hash,'sheet'=>'QA','row_number'=>2,'entity_key'=>hash('sha256','QA-ENTITY'),'name'=>'PRIVATE-UNIQUE-QA-SUPPLIER','province'=>'Zambézia','district'=>'Gurué','cae'=>'33120','activity'=>'SYNTHETIC QA repair','sector'=>'SYNTHETIC QA manufacturing','source_date'=>'2020','fingerprint'=>hash('sha256','QA-FINGERPRINT'),'duplicate_of'=>null,'identity_conflict'=>false,'territory_id'=>$this->territory,'territory_resolution'=>'exact_normalized_province_district'];
DB::table('proactive_supply_observations')->insert($row);
DB::table('proactive_supply_observations')->insert([...$row,'id'=>hash('sha256','QA-REPEATED-OBSERVATION'),'row_number'=>3,'duplicate_of'=>$this->observation]);
}
private function login(User $u):void{$this->actingAs($u)->withSession(['portal.mfa_actor'=>$u->id,'portal.mfa_at'=>time(),'portal.access_revision'=>(int)$u->portal_access_revision]);}
private function url(string $extra=''):string{return '/minhas-oportunidades/oferta-interna?territory_id='.$this->territory.$extra;}
public function test_private_query_filters_supply_and_preserves_source_and_duplicate_count():void
{
$r=$this->getJson($this->url('&activity=SYNTHETIC%20QA%20repair'))->assertOk()->assertJsonPath('total',1)->assertJsonPath('duplicate_sightings',1)->assertJsonPath('rows.0.source_name','SYNTHETIC-QA-SUPPLY.xlsx')->assertJsonPath('rows.0.row_number',2)->assertJsonPath('rows.0.source_date','2020');
$this->assertStringContainsString('no-store',$r->headers->get('Cache-Control'));
$this->assertArrayNotHasKey('contact',$r->json('rows.0'));
$this->assertArrayNotHasKey('nuit',$r->json('rows.0'));
}
public function test_no_match_means_insufficient_information_not_absent_market():void
{
$this->getJson($this->url('&activity=NO-SUCH-SYNTHETIC-ACTIVITY'))->assertOk()->assertJsonPath('total',0)->assertJsonPath('status','Informação insuficiente nesta base e nestes filtros.');
}
public function test_unassigned_user_cannot_read_internal_register():void
{
$this->login(User::factory()->create());$this->getJson($this->url())->assertForbidden();
$this->getJson('/minhas-oportunidades/oferta-interna?territory_id=not-a-uuid')->assertForbidden();
}
public function test_comparison_persists_source_lineage_and_rejects_forgery_and_public_reclassification():void
{
$input=F::input('Gurué');$a=$input['proactive'];$id=(string)\Illuminate\Support\Str::uuid();
$a['evidence'][]=['id'=>$id,'interpretation'=>'SYNTHETIC QA possible complement, not a contract','verified_on'=>'2026-10-28',...app(ProactiveSupply::class)->evidence($this->actor,$this->observation,null)];
$a['supply_comparisons']=[['observation_id'=>$this->observation,'relationship'=>'complementarity','rationale'=>'SYNTHETIC QA compare servicing with tea-chain idea','limitations'=>'No current capacity or demand proved']];
$input['proactive']=$a;
$oid=$this->postJson('/minhas-oportunidades/drafts',$input)->assertCreated()->json('id');$o=Opportunity::findOrFail($oid);
$saved=app(OpportunityManagement::class)->values($o)['proactive'];$this->assertSame($this->observation,$saved['supply_comparisons'][0]['observation_id']);
$this->assertSame('internal',$saved['evidence'][2]['access']);$this->assertStringContainsString('SYNTHETIC-QA-SUPPLY.xlsx',$saved['evidence'][2]['source']);
$a['evidence'][2]['source']='Forged source';$a['evidence'][2]['statement']='Forged supply fact';
$this->putJson('/minhas-oportunidades/'.$oid.'/draft',['etag'=>app(OpportunityManagement::class)->etag($o),'proactive'=>$a,'reason'=>'SYNTHETIC QA canonical source lineage is server-resolved'])->assertOk();
$saved=app(OpportunityManagement::class)->values($o->fresh())['proactive'];$this->assertStringContainsString('PRIVATE-UNIQUE-QA-SUPPLIER',$saved['evidence'][2]['statement']);
$a['evidence'][2]['access']='public';$this->putJson('/minhas-oportunidades/'.$oid.'/draft',['etag'=>app(OpportunityManagement::class)->etag($o),'proactive'=>$a,'reason'=>'SYNTHETIC QA internal list cannot become public'])->assertUnprocessable();
$a['evidence'][2]['access']='internal';$a['supply_comparisons'][0]['observation_id']=str_repeat('f',64);
$this->putJson('/minhas-oportunidades/'.$oid.'/draft',['etag'=>app(OpportunityManagement::class)->etag($o),'proactive'=>$a,'reason'=>'SYNTHETIC QA unknown supply observation rejected'])->assertUnprocessable();
}
public function test_sector_filter_does_not_infer_absence_and_comparison_requires_its_evidence():void
{
$this->getJson($this->url('&sector=NO-SUCH-SECTOR'))->assertOk()->assertJsonPath('total',0);
$input=F::input('Gurué');$input['proactive']['supply_comparisons']=[['observation_id'=>$this->observation,'relationship'=>'partner','rationale'=>'SYNTHETIC QA prospective partner','limitations'=>'Not contacted, no agreement']];
$this->postJson('/minhas-oportunidades/drafts',$input)->assertUnprocessable();
}
public function test_database_policy_hides_internal_rows_without_actor_context():void
{
$role='supply_qa_'.bin2hex(random_bytes(6));
DB::statement('CREATE ROLE '.$role.' NOLOGIN');
DB::statement('GRANT USAGE ON SCHEMA public TO '.$role);
DB::statement('GRANT SELECT ON proactive_supply_sources,proactive_supply_observations TO '.$role);
DB::select("select set_config('app.actor_user_id','',true),set_config('app.proactive_supply_read','',true)");
try{
DB::statement('SET LOCAL ROLE '.$role);
$this->assertSame(0,DB::table('proactive_supply_observations')->count());
$this->assertSame(0,DB::table('proactive_supply_sources')->count());
DB::select("select set_config('app.actor_user_id',?,true),set_config('app.proactive_supply_read','internal',true)",[(string)$this->actor->id]);
$this->assertNotNull(DB::table('proactive_supply_observations')->where('id',$this->observation)->first());
}finally{DB::statement('RESET ROLE');}
}
public function test_preserved_repetitions_cannot_inflate_saved_comparisons():void
{
$this->expectException(\Illuminate\Validation\ValidationException::class);
$this->expectExceptionMessage('Esta observação administrativa é repetida.');
$comparison=['relationship'=>'competition','rationale'=>'SYNTHETIC QA duplicate must not count as another competitor','limitations'=>'Historical observation,not a unique company'];
app(ProactiveSupply::class)->comparisons($this->actor,[
[...$comparison,'observation_id'=>$this->observation],
[...$comparison,'observation_id'=>hash('sha256','QA-REPEATED-OBSERVATION')],
],null);
}
}
@@ -0,0 +1,169 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Services\CorridorAgribusinessOpportunities;
use App\Services\InvestmentGeography;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia;
use Tests\TestCase;
class ProvinceSearchCompatibilityTest extends TestCase
{
use DatabaseTransactions;
public function createApplication(): Application
{
$app = parent::createApplication();
if (! IsolatedQaDatabase::allowsSchemaChanges()) {
throw new \LogicException('Isolated QA required');
}
return $app;
}
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
}
private function createOpportunity(?string $territory, string $prefix, string $status = 'published', ?string $province = null): Opportunity
{
return Opportunity::create(['sector_id' => 1, 'reference' => 'SYNTHETIC-QA-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(),
'title' => $prefix.' synthetic provincial search', 'status' => $status, 'published_at' => now()->subMinute(),
'primary_territory_id' => $territory, 'province' => $province, 'district' => null, 'geography_scope' => 'specific']);
}
private function requests(array $filters): array
{
$query = http_build_query([...$filters, 'per_page' => 50]);
return ['/api/v1/investment/search?'.$query, '/api/v1/opportunities/search?'.$query];
}
public function test_a_single_province_includes_all_lower_levels_and_linked_locations_in_both_apis(): void
{
$geo = app(InvestmentGeography::class);
$locality = $geo->publicReferences()->where('location_type', 'locality')->orderBy('id')->first();
$this->assertNotNull($locality, 'Public locality fixture required');
$path = $geo->path($locality->id);
$this->assertCount(4, $path);
$prefix = 'SYNTHETIC-'.Str::uuid();
$records = array_map(fn ($node) => $this->createOpportunity($node->id, $prefix, 'published', 'Legacy label differs from canonical hierarchy'), $path);
$linked = $this->createOpportunity(null, $prefix);
$linked->additionalTerritories()->attach($locality->id);
$records[] = $linked;
$private = $this->createOpportunity($locality->id, $prefix, 'draft');
$deleted = $this->createOpportunity($locality->id, $prefix);
$deleted->delete();
$otherProvince = $geo->publicReferences()->where('location_type', 'province')->where('id', '<>', $path[0]->id)->first();
$outside = $this->createOpportunity($otherProvince->id, $prefix);
foreach ([['province_id' => $path[0]->id], ['province' => $path[0]->name], ['geo_location_id' => $path[0]->id]] as $entry) {
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
$response = $this->getJson($url)->assertOk()->assertJsonPath('total', 5);
$this->assertEqualsCanonicalizing(array_map(fn ($row) => $row->id, $records), array_column($response->json('data'), 'id'), $url);
foreach ($response->json('data') as $row) {
$this->assertNull($row['district']);
}
foreach ([$private, $deleted, $outside] as $row) {
$this->assertNotContains($row->id, array_column($response->json('data'), 'id'));
}
}
}
foreach ($records as $record) {
$this->assertNull($record->fresh()->district);
$this->assertSame($record->primary_territory_id, $record->fresh()->primary_territory_id);
}
$this->assertSame([$locality->id], $linked->additionalTerritories()->pluck('geo_locations.id')->all());
foreach ($this->requests(['province_id' => $path[0]->id, 'district_id' => $path[1]->id, 'q' => $prefix]) as $url) {
// Province-only records are not silently assigned to a district.
$this->getJson($url)->assertOk()->assertJsonPath('total', 4);
}
foreach ($this->requests(['district_id' => $path[1]->id]) as $url) {
$this->getJson($url)->assertUnprocessable();
}
}
public function test_published_province_declaration_is_found_without_inventing_a_district_or_overriding_an_explicit_other_territory(): void
{
$geo = app(InvestmentGeography::class);
$province = $geo->publicReferences()->where('location_type', 'province')->first();
$other = $geo->publicReferences()->where('location_type', 'province')->where('id', '<>', $province->id)->first();
$district = $geo->publicReferences()->where('parent_id', $province->id)->where('location_type', 'district')->first();
$prefix = 'SYNTHETIC-'.Str::uuid();
$legacy = $this->createOpportunity(null, $prefix, 'published', $province->name);
$contradictory = $this->createOpportunity($other->id, $prefix, 'published', $province->name);
$linkedOutside = $this->createOpportunity(null, $prefix, 'published', $province->name);
$linkedOutside->additionalTerritories()->attach($other->id);
foreach ([['province' => $province->name], ['province_id' => $province->id], ['geo_location_id' => $province->id]] as $entry) {
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
$this->getJson($url)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $legacy->id)->assertJsonPath('data.0.district', null);
}
}
foreach ($this->requests(['province_id' => $province->id, 'district_id' => $district->id, 'q' => $prefix]) as $url) {
$this->getJson($url)->assertOk()->assertJsonPath('total', 0);
}
$this->assertNull($legacy->fresh()->primary_territory_id);
$this->assertNull($legacy->fresh()->district);
$this->assertSame($other->id, $contradictory->fresh()->primary_territory_id);
}
public function test_provincial_only_search_covers_the_eleven_provinces_without_including_neighbouring_provinces(): void
{
$geo = app(InvestmentGeography::class);
$provinces = $geo->publicReferences()->where('location_type', 'province')->get();
$this->assertCount(11, $provinces);
$prefix = 'SYNTHETIC-'.Str::uuid();
$records = [];
foreach ($provinces as $province) {
$district = $geo->publicReferences()->where('parent_id', $province->id)->where('location_type', 'district')->first();
$this->assertNotNull($district, $province->name);
$records[$province->id] = $this->createOpportunity($district->id, $prefix);
}
foreach ($provinces as $province) {
foreach ([['province_id' => $province->id], ['province' => $province->name]] as $entry) {
foreach ($this->requests([...$entry, 'q' => $prefix]) as $url) {
$this->getJson($url)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $records[$province->id]->id);
}
}
}
}
public function test_maputo_names_ids_page_map_and_export_share_the_existing_approved_corridor_coverage(): void
{
$provinceId = 'bfde2651-2b46-5d9c-a500-733fa55a8c5c';
$expected = Opportunity::published()->where('workflow_context->corridor_agribusiness->source_sha256', CorridorAgribusinessOpportunities::SOURCE_HASH)
->where('workflow_context->corridor_agribusiness->corridor', 'Corredor de Maputo')->pluck('id')->all();
$this->assertCount(5, $expected);
foreach ([['province' => 'Maputo Província'], ['province' => ' mApUtO Província '], ['province_id' => $provinceId]] as $entry) {
foreach ($this->requests([...$entry, 'sector' => 'agronegocio']) as $url) {
$response = $this->getJson($url)->assertOk()->assertJsonPath('total', 5);
$this->assertEqualsCanonicalizing($expected, array_column($response->json('data'), 'id'));
foreach ($response->json('data') as $row) {
$this->assertNull($row['district']);
$this->assertStringContainsString('contexto provincial do corredor', $row['territorial_summary']);
}
}
}
$query = http_build_query(['sector' => 'agronegocio', 'province' => 'Maputo Província']);
$this->get('/oportunidades?'.$query)->assertInertia(fn (AssertableInertia $page) => $page
->component('investment/catalogue')->where('filters.province_id', $provinceId)->missing('filters.province')
->has('territorySelection', 1)->where('results.total', 5));
$this->getJson('/api/v1/investment/map?'.$query)->assertOk()->assertJsonCount(0, 'features')->assertJsonCount(5, 'unlocated');
$csv = $this->get('/api/v1/investment/export?'.$query)->assertOk()->streamedContent();
foreach (Opportunity::whereIn('id', $expected)->get() as $row) {
$this->assertStringContainsString($row->title, $csv);
}
foreach ($this->requests(['sector' => 'turismo', 'province_id' => $provinceId]) as $url) {
$response = $this->getJson($url)->assertOk();
foreach ($response->json('data') as $row) {
$this->assertNotContains($row['id'], $expected);
}
}
}
}
@@ -24,6 +24,10 @@ class OpportunityCorridorExplorerTest extends TestCase
$catalogue->shouldReceive('query')->with($filters)->once()->andReturn($query);
$catalogue->shouldReceive('context')->with(101)->once()->andReturn(['corridors' => collect([(object)['id'=>'a','name'=>'Corredor A'],(object)['id'=>'b','name'=>'Corredor B']])]);
$catalogue->shouldReceive('context')->with(102)->once()->andReturn(['corridors'=>collect()]);
$first->setAttribute('territorial_summary','Sofala / Dondo');
$other->setAttribute('territorial_summary','Localização não indicada');
$catalogue->shouldReceive('presentLocation')->with($first)->once()->andReturn($first);
$catalogue->shouldReceive('presentLocation')->with($other)->once()->andReturn($other);
$this->app->instance(InvestmentCatalogue::class, $catalogue);
$groups = app(OpportunityCorridorExplorer::class)->groups($filters);
$this->assertSame(['Corredor A','Corredor B','Outras localizações'], array_column($groups,'name'));
@@ -32,5 +36,6 @@ class OpportunityCorridorExplorerTest extends TestCase
$this->assertSame(['Sofala / Dondo'], $groups[0]['locations']);
$this->assertSame([], $groups[2]['locations']);
$this->assertSame([], $groups[0]['opportunities'][0]['stages']);
$this->assertSame('Sofala / Dondo',$groups[0]['opportunities'][0]['territorial_summary']);
}
}
@@ -0,0 +1,22 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
const require=createRequire(import.meta.url);
const source=fs.readFileSync(new URL('../../resources/js/components/catalogue-guide-links.tsx',import.meta.url),'utf8');
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
const module={exports:{}};
new Function('require','module','exports',compiled)(name=>name==='@inertiajs/react'?{Link:({href,children,...props})=>React.createElement('a',{href,...props},children)}:require(name),module,module.exports);
const render=articles=>renderToStaticMarkup(React.createElement(module.exports.default,{articles}));
test('catalogue guides are closed optional links, not educational bodies or nationwide opportunity shortcuts',()=>{
const html=render([{title:'Turismo',href:'/artigos/turismo',summary:'EDUCATIONAL-BODY-NOT-A-RESULT',image:{href:'/photo.jpg',alt:'ILLUSTRATION'},opportunities_href:'/oportunidades?sector=turismo',opportunities_label:'ALL-NATIONAL-OPPORTUNITIES',has_opportunities:true}]);
assert.match(html,/<details\b/);assert.doesNotMatch(html,/<details[^>]*\bopen\b/);
assert.match(html,/apoio opcional/);assert.match(html,/href="\/artigos\/turismo"/);
for(const forbidden of ['EDUCATIONAL-BODY-NOT-A-RESULT','ALL-NATIONAL-OPPORTUNITIES','/oportunidades?sector=turismo','photo.jpg','<img'])assert.ok(!html.includes(forbidden),forbidden);
});
test('no educational substitute is rendered when no guides are available',()=>{
assert.equal(render([]),'');
});
@@ -0,0 +1,101 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
assessmentReady,
diagnosticReady,
forces,
newCompetitivenessDraft,
readCompetitivenessDraft,
} from '../../resources/js/lib/cluster-competitiveness.ts';
function complete() {
const draft = newCompetitivenessDraft('cluster-a', 'Energia');
draft.region = 'Distrito de demonstração';
for (const force of forces)
Object.assign(draft.forces[force], {
pressure: 'medium',
evidence: 'Observação de demonstração',
source: 'Fonte de demonstração, p. 2',
period: '2025',
rationale: 'Pressão fundamentada na observação',
limitations: 'Amostra parcial',
opportunity: 'Investigar capacidade de armazenamento',
});
return draft;
}
test('ausência de dados permanece indeterminada nas cinco forças independentes', () => {
const draft = newCompetitivenessDraft('cluster-a', 'Energia');
assert.equal(forces.length, 5);
assert.equal(diagnosticReady(draft), false);
draft.forces.buyers.evidence = 'Observação';
assert.equal(draft.forces.suppliers.evidence, '');
assert.ok(forces.every((force) => draft.forces[force].pressure === ''));
});
test('classificação exige todos os fundamentos; âmbito é necessário para o diagnóstico', () => {
const draft = complete();
assert.equal(diagnosticReady(draft), true);
for (const field of [
'evidence',
'source',
'period',
'rationale',
'limitations',
'opportunity',
]) {
const row = { ...draft.forces.buyers, [field]: ' ' };
assert.equal(assessmentReady(row), false, field);
}
draft.region = '';
assert.equal(diagnosticReady(draft), false);
});
test('ficheiro conserva rascunhos, dados e incertezas sem modificar o original', () => {
const draft = complete();
draft.forces.entrants.pressure = '';
const restored = readCompetitivenessDraft(
JSON.stringify(draft),
'cluster-a',
);
assert.deepEqual(restored, draft);
restored.forces.buyers.source = 'Outra fonte';
assert.notEqual(restored.forces.buyers.source, draft.forces.buyers.source);
assert.equal(diagnosticReady(restored), false);
});
test('recuperação rejeita outro cluster, versões, forças ausentes e campos inválidos', () => {
assert.throws(() =>
readCompetitivenessDraft(JSON.stringify(complete()), 'cluster-b'),
);
for (const mutate of [
(d) => {
d.version = 2;
},
(d) => {
delete d.forces.buyers;
},
(d) => {
d.forces.buyers.pressure = 'zero';
},
(d) => {
d.forces.buyers.source = 42;
},
(d) => {
d.forces.buyers.source = 'x'.repeat(5001);
},
(d) => {
d.region = null;
},
]) {
const draft = complete();
mutate(draft);
assert.throws(() =>
readCompetitivenessDraft(JSON.stringify(draft), 'cluster-a'),
);
}
assert.throws(() => readCompetitivenessDraft('null', 'cluster-a'));
assert.throws(() =>
readCompetitivenessDraft('x'.repeat(250001), 'cluster-a'),
);
});
+34
View File
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
import * as forms from '../../resources/js/lib/fiscal-form-preparation.ts';
const require=createRequire(import.meta.url);
const source=fs.readFileSync(new URL('../../resources/js/pages/portal/fiscal-forms.tsx',import.meta.url),'utf8');
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
const module={exports:{}};
new Function('require','module','exports',compiled)(name=>name==='@inertiajs/react'?{Head:()=>null,Link:({href,children,...props})=>React.createElement('a',{href,...props},children),router:{on:()=>()=>{}}}:name==='@/layouts/portal-navigation'?{PortalMenu:()=>null}:name==='@/lib/fiscal-form-preparation'?forms:require(name),module,module.exports);
test('fiscal entry renders labelled editable fields and a guided preparation rather than legislation',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default));
for(const label of ['Identificação e período','Nome ou designação social','NUIT','Período — ano e mês','Conferir e guardar','Guardar ficheiro para continuar','Recuperar ficheiro guardado','Confirmar recuperação']) {
// Confirmation appears only after a compatible file is selected.
if(label !== 'Confirmar recuperação') assert.ok(html.includes(label),label);
}
assert.equal((html.match(/inputMode="decimal"/g)??[]).length,27);
assert.match(html,/sem submissão à Autoridade Tributária/);
assert.match(html,/Não há gravação automática/);
assert.doesNotMatch(html,/value="0"/);
});
test('IRPC entry opens the requested form directly and keeps its partial coverage explicit',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{initialTax:'irpc'}));
assert.match(html,/IRPC — Modelo 22/);
assert.match(html,/L8 permanece parcial/);
assert.match(html,/303 — Dupla tributação económica/);
assert.match(html,/304 — Dupla tributação internacional/);
assert.match(html,/Não utilize a mesma parcela/);
assert.equal((html.match(/inputMode="decimal"/g)??[]).length,24);
assert.doesNotMatch(html,/01 — Base das operações/);
});
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {newFiscalPreparation, readFiscalPreparation, fiscalPreparationIssues, fiscalFormFields} from '../../resources/js/lib/fiscal-form-preparation.ts';
test('IVA and IRPC preparations round trip deliberate entries and unknown amounts without zero defaults', () => {
for (const kind of ['iva', 'irpc']) {
const p = newFiscalPreparation(kind);
p.name = 'Investidor de teste'; p.nuit = '123456789'; p.period = kind === 'iva' ? '2026-10' : '2026';
const [first, second] = fiscalFormFields(kind);
p.values[first.code] = '123456789012345678901234,01';
p.values[second.code] = '';
const restored = readFiscalPreparation(JSON.stringify(p));
assert.deepEqual(restored, p);
assert.deepEqual(fiscalPreparationIssues(restored), []);
assert.equal(restored.values[second.code], '');
assert.equal(Object.values(restored.values).includes('0'), false);
}
});
test('foreign editions, unknown fields and malformed or oversized files cannot replace preparation', () => {
const p = newFiscalPreparation('iva');
for (const v of [{...p, sourceHash: 'different'}, {...p, values: {'999': '1'}}, {...p, values: []}, {...p, nuit: 123}, {...p, version: 'later'}]) assert.throws(() => readFiscalPreparation(JSON.stringify(v)));
assert.throws(() => readFiscalPreparation('{broken'));
assert.throws(() => readFiscalPreparation('x'.repeat(100001)));
assert.equal(p.kind, 'iva'); assert.deepEqual(p.values, {});
});
test('invalid format is identified without rounding or discarding an incomplete preparation', () => {
const p = newFiscalPreparation('irpc');
p.values['303'] = '1.234'; p.values['304'] = '25,00';
const restored = readFiscalPreparation(JSON.stringify(p));
assert.equal(restored.values['303'], '1.234');
assert.ok(fiscalPreparationIssues(restored).some(i => i.startsWith('Campo 303:')));
assert.equal(fiscalFormFields('irpc').find(f => f.code === '303').label, 'Dupla tributação económica');
assert.equal(fiscalFormFields('irpc').find(f => f.code === '304').label, 'Dupla tributação internacional');
});
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,28 @@
import {internationalCase} from './irpc-international-case.mjs';
import {prepareCreditCarry} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newCarryLot} from '../../../resources/js/lib/irpc-credit-carry.ts';
export function carryCase() {
const c = internationalCase();
c.b = prepareCreditCarry(c.b);
Object.assign(c.b.creditCarry, {
state: 'known', reference: 'SYNTHETIC QA complete prior balance inventory',
currentInternational: '8', currentPec: '200', assessmentKey: c.b.assessmentKey,
allocationReference: 'SYNTHETIC QA explicit allocation: current international8, prior international50, currentPEC200, priorPEC100',
lots: [
{...newCarryLot('international-2021'), kind: 'international', country: 'ZA', subjectNuit: c.b.subjectNuit,
year: '2021', ordinary: 'yes', originDocument: 'SYNTHETIC foreign-credit-assessment2021',
originReference: 'SYNTHETIC QA origin inclusion, eligible tax, national/CDT limits, insufficient collecta',
ruleReference: 'SYNTHETIC QA documented ordinary origin rule art65, no real foreign treaty claim',
eligible: '200', originDeducted: '100', insufficient: 'yes', usesState: 'known',
usesReference: 'SYNTHETIC QA all actual uses reconciled through current exercise',
uses: [{id: 'use-2023', year: '2023', amount: '30', document: 'SYNTHETIC use2023', reference: 'SYNTHETIC QA actual documented use, not simulated'}], selected: '50'},
{...newCarryLot('pec-2023'), kind: 'pec', subjectNuit: c.b.subjectNuit,
year: '2023', ordinary: 'yes', originDocument: 'SYNTHETIC PEC2023 assessment and receipts',
originReference: 'SYNTHETIC QA actual PEC paid, initial deduction and collecta insufficiency',
ruleReference: 'SYNTHETIC QA origin ordinary art66', eligible: '300', originDeducted: '150',
insufficient: 'yes', usesState: 'absent', usesReference: 'SYNTHETIC QA no actual subsequent use', selected: '100'},
],
});
return c;
}
@@ -0,0 +1,25 @@
import {internationalCase} from './irpc-international-case.mjs';
import {carryCase} from './irpc-carry-case.mjs';
import {prepareEconomicBook} from '../../../resources/js/lib/irpc-annual-settlement.ts';
import {newEconomicPosition} from '../../../resources/js/lib/irpc-economic-credit.ts';
export function economicCase(withCarry = false) {
const c = withCarry ? carryCase() : internationalCase();
c.b = prepareEconomicBook(c.b);
Object.assign(c.b.economicCredits, {state: 'known', reference: 'SYNTHETIC QA full ordinary economic-credit inventory', rows: [{
...newEconomicPosition('economic-1'), subjectNuit: c.b.subjectNuit, year: c.b.year, assessmentKey: c.b.assessmentKey,
kind: 'ordinary_profit', payerNuit: '111222333', recipientResident: 'yes', payerResident: 'yes', payerIrpc: 'yes', payerExempt: 'no',
article40: 'no', qualificationReference: 'SYNTHETIC QA entities seated/effectively managed in MZ; payer subject nonexempt IRPC',
article40Reference: 'SYNTHETIC QA explicit nonapplication of40(1), including2009 participation/period/recipient conditions',
distributionDocument: 'SYNTHETIC-DIVIDEND2026', distributionParcel: 'distribution-1', distributionDate: '2026-09-30',
income: '100', incomeIncluded: 'yes', incomeReference: 'SYNTHETIC QA100 gross of beneficiary withholding already included in current L6; no actual dividend assertion',
taxIssuer: 'SYNTHETIC domestic IRPC issuer', taxDocument: 'SYNTHETIC-SOURCE-IRPC2026', taxParcel: 'underlying-tax-1',
parcelReference: 'SYNTHETIC QA underlying domestic IRPC parcel, distinct from recipient withholding or foreign income tax',
proofAmount: '20', taxAmount: '20', attributionReference: 'SYNTHETIC QA documented IRPC20 corresponding to included profits100, not inferred by applying a rate to dividends',
previouslyAttributed: '0', priorAttributionReference: 'SYNTHETIC QA actual previous attribution to other profits known zero',
grossUpIncluded: '12', grossUpReference: 'SYNTHETIC QA53 nominal credit12 already included in reconciled current base4400; no base mutation',
nationalLimit: '32', nationalLimitReference: 'SYNTHETIC QA documented proportional current collecta ceiling32 after credit addition; not an automatic fraction derivation',
previousUse: {state: 'known', amount: '0', reference: 'SYNTHETIC QA actual prior economic-credit use known zero'},
}]});
return c;
}
@@ -0,0 +1,80 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
import * as flow from '../../resources/js/lib/opportunity-fill-flow.ts';
import { fiscalPreparationGuide } from '../../resources/js/lib/fiscal-preparation-guide.ts';
const require=createRequire(import.meta.url);
function load(path,mocks={},exportName='default',extra=''){
const source=fs.readFileSync(new URL(path,import.meta.url),'utf8');
const output=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
const module={exports:{}};new Function('require','module','exports',output+extra)(name=>mocks[name]??(name.startsWith('@/')?{default:()=>null}:require(name)),module,module.exports);return module.exports[exportName];
}
function stateHooks(){const memory=[];let cursor=0;return{hooks:{...React,useState(initial){const i=cursor++;if(!(i in memory))memory[i]=typeof initial==='function'?initial():initial;return[memory[i],next=>memory[i]=typeof next==='function'?next(memory[i]):next];},useRef:()=>({current:null}),useEffect:()=>{}},reset:()=>cursor=0};}
const flat=node=>!node||typeof node!=='object'?[]:[node,...React.Children.toArray(node.props?.children).flatMap(flat)];
test('free navigation keeps every field mounted and reports resource work in the current group',()=>{
const state=stateHooks();const Component=load('../../resources/js/components/opportunity-fill-flow.tsx',{'react':state.hooks,'@/lib/opportunity-fill-flow':flow});
const groups=flow.opportunityFillGroups(['official_title','locations','documents']);const saved={official_title:'Deliberate user title',locations:['saved-site']};
const opened=[];let tree;
const render=()=>{state.reset();tree=Component({groups,errors:{},renderField:field=>React.createElement('input',{name:field,value:JSON.stringify(saved[field]??''),readOnly:true}),onOpenResources:group=>opened.push(group)});};
const priorWindow=globalThis.window,priorFrame=globalThis.requestAnimationFrame;
globalThis.window={history:{state:{existing:'inertia-state'},replaceState(state,_title,url){assert.deepEqual(state,{existing:'inertia-state'});this.url=url;}}};globalThis.requestAnimationFrame=callback=>callback();
try{
render();assert.equal(flat(tree).filter(node=>node.type==='input').length,3);
flat(tree).find(node=>node.type==='a'&&node.props.href==='#fill-territory').props.onClick({preventDefault(){}});render();
const sections=flat(tree).filter(node=>node.type==='section');
assert.equal(sections.find(node=>node.props.id==='fill-territory').props.hidden,false);
assert.equal(sections.find(node=>node.props.id==='fill-idea').props.hidden,true);
assert.equal(flat(tree).filter(node=>node.type==='input').length,3);
flat(tree).find(node=>node.type==='button').props.onClick();assert.deepEqual(opened,['territory']);
assert.equal(saved.official_title,'Deliberate user title');assert.deepEqual(saved.locations,['saved-site']);
assert.equal(globalThis.window.history.url,'#fill-territory');
}finally{globalThis.window=priorWindow;globalThis.requestAnimationFrame=priorFrame;}
});
test('profile request renders readable labels without dumping every available document into the form',()=>{
const Picker=load('../../resources/js/components/profile-proof-picker.tsx');
const Page=load('../../resources/js/pages/profiles/request.tsx',{
'@/lib/operation-key':{createOperationKey:()=> 'synthetic-key'},
'@inertiajs/react':{Head:()=>null,Link:({href,children})=>React.createElement('a',{href},children),router:{}},
'@/components/profile-navigation':{default:()=>null},'@/lib/profile-json':{},
'@/pages/management/shared':{button:'button',control:'control'},
'@/components/opportunity-search-filters':{modalityLabels:{investment_project:'Projecto de investimento',land_rights:'Direitos fundiários'}},
'@/components/profile-proof-picker':{default:Picker},
});
const html=renderToStaticMarkup(React.createElement(Page,{requests:[],types:['investment_project','land_rights'],organizations:[],documents:Array.from({length:80},(_,i)=>({id:`doc-${i}`,file_name:`UNSELECTED-DOCUMENT-${i}.txt`}))}));
assert.match(html,/Em nome próprio/);assert.match(html,/Entidade pública/);assert.match(html,/Projecto de investimento/);assert.match(html,/Direitos fundiários/);
assert.doesNotMatch(html,/UNSELECTED-DOCUMENT/);assert.match(html,/Pesquisar nos meus ficheiros/);
const visible=html.replace(/<[^>]+>/g,'');assert.doesNotMatch(visible,/investment_project|land_rights|public_entity/);
});
test('proof selection is explicit and retained when the filename search changes',()=>{
const state=stateHooks();const Component=load('../../resources/js/components/profile-proof-picker.tsx',{'react':state.hooks});
const documents=[{id:'identity',file_name:'Documento próprio'},{id:'law',file_name:'Lei.pdf'}];const values=[];let tree;
const render=()=>{state.reset();tree=Component({documents,value:values,onChange:ids=>{values.splice(0,values.length,...ids);}});};
render();assert.equal(flat(tree).filter(node=>node.type==='input'&&node.props.type==='checkbox').length,0);
flat(tree).find(node=>node.type==='input').props.onChange({target:{value:'próprio'}});render();
flat(tree).find(node=>node.type==='input'&&node.props.type==='checkbox').props.onChange();render();assert.deepEqual(values,['identity']);
flat(tree).find(node=>node.type==='input'&&node.props.type==='search').props.onChange({target:{value:'Lei'}});render();
assert.deepEqual(values,['identity']);assert.equal(flat(tree).filter(node=>node.type==='input'&&node.props.type==='checkbox')[0].props.checked,false);
});
test('document entry leads to existing fillable preparation and keeps sources optional',()=>{
const context='10000000-0000-4000-8000-000000000001';
const inertia={Link:({href,children})=>React.createElement('a',{href},children),usePage:()=>({url:`/documentos?context=${context}`})};
const Hub=load('../../resources/js/components/journey-document-resources.tsx',{'@inertiajs/react':inertia,'@/lib/fiscal-preparation-guide':{fiscalPreparationGuide}},'JourneyDocumentResources');
const hub=renderToStaticMarkup(React.createElement(Hub,{}));
assert.match(hub,new RegExp(`/investimentos/${context}/contexto/editar#preparation-questions`));assert.match(hub,/href="\/terra-duat"/);
assert.match(hub,/Preparação digital e exemplar oficial/);assert.doesNotMatch(hub,/<details[^>]*\bopen\b/);
const Editor=load('../../resources/js/components/private-investment-preparation.tsx',{'@inertiajs/react':inertia,'@/pages/investment/shared':{card:'card',input:'input'}},'PreparationEditor');
const html=renderToStaticMarkup(React.createElement(Editor,{data:{questions:[{key:'investment_preparation',label:'Preparar pedido?',options:{yes:'Sim',no:'Não'},source:'SYNTHETIC QA'},{key:'declared_amount',label:'Valor do investimento',type:'number',source:'SYNTHETIC QA'}],requirements:[],enabled:true,mode:'authorization',missing_fields:['declared_amount']},fields:{investment_preparation:'yes'},changes:{},documents:[],links:{},onChange(){},onLink(){},disabled:false}));
assert.match(html,/<input/);assert.match(html,/Valor do investimento/);assert.match(html,/id="preparation-questions"/);
});
test('investment stages expose readable next actions while internal codes and sources remain consultable',()=>{
const useForm=data=>({data,errors:{},processing:false,setData(){},transform(){return this;},post(){}});
const Stage=load('../../resources/js/pages/investor-path/show.tsx',{'@inertiajs/react':{useForm,Link:({href,children})=>React.createElement('a',{href},children)},'@/lib/investor-path':{pathStates:{not_started:'Por iniciar'}}},'Stage','\nmodule.exports.Stage=Stage;');
const step={code:'S01',title:'Sistematizar a ideia',state:'not_started',detail:{scope:'promoter_preparation'},preparation_allowed:true,action_gaps:{},source_paragraph:22,applicability:'applicable'};
const html=renderToStaticMarkup(React.createElement(Stage,{step,path:{case:{id:'synthetic',version:1},next:{code:'S01'},canWrite:true,canReview:false,steps:[step],documents:[]}}));
assert.match(html,/<details[^>]*id="S01"[^>]*open/);assert.match(html,/<summary[^>]*>Sistematizar a ideia/);
assert.doesNotMatch(html,/<summary[^>]*>S01/);assert.match(html,/Fonte e referência desta etapa/);
});
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {carryCase} from './helpers/irpc-carry-case.mjs';
import {internationalCase} from './helpers/irpc-international-case.mjs';
import {newCarryUse, calculateCarryLot} from '../../resources/js/lib/irpc-credit-carry.ts';
import {calculateAnnual, prepareCreditCarry, recordAnnual, annualBook, annualCurrent, saveAnnualBook, annualHtml, annualReportRows} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
const number = v => v ? Number(v.numerator) / Number(v.denominator) : null;
const calc = c => calculateAnnual(c.d, c.b);
const lot = (c, i = 0) => c.b.creditCarry.lots[i];
const pending = c => {const m = calc(c); assert.equal(m.status, 'indeterminate', JSON.stringify(m.pending)); assert.equal(m.arithmeticBalance, null); assert.equal(m.internationalCredit.deducted, null); assert.equal(m.pecDeduction.deducted, null); return m;};
test('2021 international and2023 PEC remain eligible in2026; origin deductions/uses count once:1408-8-50-200-100-500=550', () => {
const m = calc(carryCase()); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 550);
assert.equal(number(m.creditCarry.lots[0].opening), 100); assert.equal(number(m.creditCarry.lots[0].used), 30);
assert.equal(number(m.creditCarry.lots[0].available), 70); assert.equal(number(m.creditCarry.lots[0].remaining), 20);
assert.equal(m.creditCarry.lots[0].lastYear, 2026); assert.equal(m.creditCarry.lots[1].lastYear, 2026);
assert.equal(number(m.creditCarry.lots[1].remaining), 50); assert.equal(m.creditCarry.carryCreated, false); assert.equal(m.creditCarry.officialBalancesConsumed, false);
});
test('five subsequent exercises differs from PEC three; expired source retained with zero selection', () => {
for (const [i, year] of [[0, '2020'], [1, '2022']]) {
const c = carryCase(); lot(c, i).year = year;
if (i === 0) lot(c).uses[0].year = '2023';
assert.match(pending(c).pending.join(' '), /Prazo ordinário terminado/);
lot(c, i).selected = '0'; const m = calc(c);
assert.deepEqual(m.pending, []); assert.equal(m.creditCarry.lots[i].expired, true);
assert.equal(number(m.creditCarry.lots[i].available), 0); assert.ok(number(m.creditCarry.lots[i].remaining) > 0);
}
});
test('future/current origin, nonordinary periods, currency and wrong subject do not create an eligible carry', () => {
for (const patch of [{year: '2026'}, {year: '2027'}, {year: ''}, {ordinary: ''}, {ordinary: 'no'}, {currency: 'USD'}, {subjectNuit: '999999999'}, {country: 'MZ'}, {country: 'ZZ'}, {kind: ''}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
const c = carryCase(); lot(c, 1).country = 'ZA'; pending(c);
});
test('origin eligibility, insufficient collecta and applicable rule require concrete evidence', () => {
for (const patch of [{originDocument: ''}, {originReference: ''}, {ruleReference: ''}, {insufficient: ''}, {insufficient: 'no'}, {eligible: ''}, {originDeducted: ''}, {originDeducted: '201'}, {selected: ''}, {selected: '70.01'}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
});
test('unknown uses are not zero; every actual use must fit its origin/window and documentary identity', () => {
for (const patch of [{usesState: ''}, {usesReference: ''}, {usesState: 'absent'}, {uses: []}, {uses: [{...newCarryUse('u'), year: '2021', amount: '1', document: 'D', reference: 'R'}]}]) {
const c = carryCase(); Object.assign(lot(c), patch); pending(c);
}
for (const patch of [{year: '2027'}, {amount: '101'}, {document: ''}, {reference: ''}, {amount: ''}]) {
const c = carryCase(); Object.assign(lot(c).uses[0], patch); pending(c);
}
const c = carryCase(); lot(c).uses.push({...lot(c).uses[0], id: 'copy', year: '2024', document: ' synthetic USE2023 '});
assert.match(pending(c).pending.join(' '), /repetido/);
});
test('actual current-year use is subtracted before the proposed new deduction', () => {
const c = carryCase(); lot(c).uses.push({id: 'current-actual', year: '2026', amount: '10', document: 'SYNTHETIC current actual use', reference: 'SYNTHETIC actual assessment, not this simulation'});
const m = calc(c); assert.equal(number(m.creditCarry.lots[0].available), 60); assert.equal(number(m.creditCarry.lots[0].remaining), 10); assert.equal(number(m.payable), 550);
});
test('original country/nature/year cannot be duplicated by changing document or id', () => {
const c = carryCase(); c.b.creditCarry.lots.push({...structuredClone(lot(c)), id: 'other', originDocument: 'OTHER', uses: [] , usesState: 'absent'});
assert.match(pending(c).pending.join(' '), /mesma natureza/);
});
test('cross-context duplicate origin blocks and external edits invalidate saved current result', () => {
const c = carryCase(); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b));
const b = annualBook(c.d); assert.equal(annualCurrent(c.d, b), true);
const s = JSON.parse(c.d.modelo_a_snapshot), other = structuredClone(c.b);
other.creditCarry.lots = [{...structuredClone(lot(c)), id: 'copied-origin', originDocument: 'OTHER', uses: [], usesState: 'absent'}];
s.irpcAnnual['opportunity:other'] = other; c.d.modelo_a_snapshot = JSON.stringify(s);
assert.equal(annualCurrent(c.d, b), false); assert.match(pending(c).pending.join(' '), /noutro mapa/);
});
test('explicit allocation can favour older balances without automatic reduction or FIFO', () => {
const c = carryCase(); Object.assign(c.b.creditCarry, {currentInternational: '0', currentPec: '100'});
const m = calc(c); assert.equal(number(m.payable), 658); assert.equal(number(m.internationalCredit.deducted), 0);
assert.equal(number(m.internationalCredit.notSelected), 8); assert.equal(m.internationalCredit.insufficientCollecta, null);
assert.equal(number(m.pecDeduction.deducted), 100); assert.equal(number(m.pecDeduction.remaining), 100);
});
test('current selection cannot exceed known availability or total collecta; planned choices are kept on failure', () => {
for (const patch of [{currentInternational: '9'}, {currentPec: '201'}, {currentInternational: ''}, {currentPec: ''}, {allocationReference: ''}, {assessmentKey: 'stale'}]) {
const c = carryCase(); Object.assign(c.b.creditCarry, patch); pending(c);
}
const c = carryCase(); lot(c).eligible = '5000'; lot(c).selected = '1400';
const before = structuredClone(c.b); assert.match(pending(c).pending.join(' '), /ultrapassam a colecta/); assert.deepEqual(c.b, before);
});
test('no credit or PEC reimbursement is generated by old balances; PPC refund stays separate', () => {
const c = carryCase(); Object.assign(c.b.creditCarry, {currentInternational: '8', currentPec: '0'}); lot(c).eligible = '2000'; lot(c).selected = '1300'; lot(c, 1).selected = '100';
const m = calc(c); assert.equal(number(m.recoverable), 500); assert.equal(number(m.pecDeduction.deducted), 0);
assert.equal(m.creditCarry.carryCreated, false); assert.equal(number(m.creditCarry.lots[0].remaining), 570);
});
test('exact foreign-credit fractions are preserved; decimal presentation is never fiscal rounding', () => {
const c = carryCase(); Object.assign(lot(c), {eligible: '2/3', originDeducted: '1/3', selected: '1/3', usesState: 'absent', uses: []});
Object.assign(c.b.creditCarry, {currentInternational: '1/3'});
const m = calc(c); assert.deepEqual(m.pending, []); assert.deepEqual(m.creditCarry.lots[0].available, {numerator: '1', denominator: '3'});
assert.deepEqual(m.payable, {numerator: '1822', denominator: '3'});
lot(c).selected = '1/0'; pending(c);
});
test('missing/absent/known-zero remain distinct; absence does not demand unused allocation fields', () => {
const c = internationalCase(), baseline = calc(c); c.b = prepareCreditCarry(c.b); pending(c);
c.b.creditCarry.state = 'absent'; c.b.creditCarry.reference = 'SYNTHETIC QA documented absence';
let m = calc(c); assert.equal(number(m.payable), number(baseline.payable)); assert.deepEqual(m.internationalCredit, baseline.internationalCredit);
c.b.creditCarry.lots.push({...carryCase().b.creditCarry.lots[0]}); pending(c);
const z = carryCase(); Object.assign(lot(z), {eligible: '0', originDeducted: '0', selected: '0', usesState: 'absent', uses: []});
m = calc(z); assert.deepEqual(m.pending, []); assert.equal(number(m.creditCarry.lots[0].available), 0);
});
test('optional preparation, recording, JSON recovery, HTML and dossier preserve accepted books and frozen history', () => {
const c = internationalCase(); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b, '2026-10-27T17:00:00+02:00'));
const old = annualBook(c.d), frozen = structuredClone(old.result), existing = JSON.parse(c.d.modelo_a_snapshot), plan = c.d.business_plan_snapshot;
const next = prepareCreditCarry(old); next.creditCarry = carryCase().b.creditCarry;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, next, '2026-10-28T12:00:00+02:00'));
const recovered = annualBook(JSON.parse(JSON.stringify(c.d))); assert.deepEqual(recovered.history, [frozen]); assert.equal(number(recovered.result.model.payable), 550);
assert.equal(annualCurrent(c.d, recovered), true); assert.equal(c.d.business_plan_snapshot, plan);
const after = JSON.parse(c.d.modelo_a_snapshot); delete after.irpcAnnual; delete existing.irpcAnnual; assert.deepEqual(after, existing);
assert.match(annualHtml(c.d), /Saldo anterior — Crédito internacional ZA — 2021/);
assert.match(annualHtml(c.d), /550.00/); assert.match(annualHtml(c.d), /2026/);
assert.match(JSON.stringify(createProjectDossierReport(c.d, {selectedSections: new Set(['finance'])})), /Afectação escolhida entre exercícios/);
recovered.creditCarry.lots[0].selected = '49'; c.d.modelo_a_snapshot = saveAnnualBook(c.d, recovered);
assert.equal(annualCurrent(c.d, recovered), false); assert.deepEqual(recovered.result.model, annualBook(c.d).result.model);
assert.throws(() => annualHtml(c.d), /fontes actuais/); assert.match(annualReportRows(c.d).flat().join(' '), /Histórico/);
});
test('malformed detail and duplicate internal ids cannot overwrite original snapshots', () => {
for (const mutate of [c => c.b.creditCarry.lots[0].uses = null, c => c.b.creditCarry.version = 2, c => c.b.creditCarry.lots[0].uses[0].amount = null, c => c.b.creditCarry.lots[1].id = c.b.creditCarry.lots[0].id]) {
const c = carryCase(), before = c.d.modelo_a_snapshot; mutate(c);
assert.throws(() => saveAnnualBook(c.d, c.b), /recuper|repetido/); assert.equal(c.d.modelo_a_snapshot, before);
}
});
test('standalone expired PEC keeps origin and is not silently converted to international five-year window', () => {
const c = carryCase(), r = {...lot(c, 1), year: '2022', selected: '0'};
const m = calculateCarryLot(r, c.b.subjectNuit, c.b.year); assert.equal(m.expired, true); assert.equal(m.lastYear, 2025); assert.equal(number(m.remaining), 150);
});
@@ -0,0 +1,141 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {economicCase} from './helpers/irpc-economic-case.mjs';
import {internationalCase} from './helpers/irpc-international-case.mjs';
import {calculateAnnual, prepareEconomicBook, annualBook, recordAnnual, saveAnnualBook, annualCurrent, annualHtml, annualReportRows} from '../../resources/js/lib/irpc-annual-settlement.ts';
import {createProjectDossierReport} from '../../resources/js/lib/project-dossier-report.ts';
import {irpcBook, recordIrpc, saveIrpcBook} from '../../resources/js/lib/irpc-withholdings.ts';
const number = v => v ? Number(v.numerator) / Number(v.denominator) : null;
const row = c => c.b.economicCredits.rows[0];
const foreign = c => c.b.internationalCredits.positions[0].payments[0];
const calc = c => calculateAnnual(c.d, c.b);
const pending = c => {const m = calc(c); assert.equal(m.status, 'indeterminate', JSON.stringify(m.pending)); assert.equal(m.arithmeticBalance, null); assert.equal(m.economicCredit.deducted, null); assert.equal(m.internationalCredit.deducted, null); assert.equal(m.pecDeduction.deducted, null); return m;};
test('economic60% of documented sourceIRPC20 yields12 before international8,PEC200 andPPC500:688', () => {
const m = calc(economicCase()); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.rows[0].nominal), 12);
assert.equal(number(m.economicCredit.deducted), 12); assert.equal(number(m.economicCredit.afterCredit), 1396);
assert.equal(number(m.internationalCredit.deducted), 8); assert.equal(number(m.internationalCredit.afterCredit), 1388); assert.equal(number(m.payable), 688);
assert.equal(m.economicCredit.carryCreated, false); assert.equal(m.economicCredit.officialBalancesConsumed, false); assert.equal(m.submitted, false);
});
test('documented proportional ceiling and prior actual use limit economic deduction,not a second tax rate on dividends', () => {
const c = economicCase(); row(c).nationalLimit = '5'; let m = calc(c); assert.equal(number(m.economicCredit.rows[0].nominal), 12); assert.equal(number(m.payable), 695);
row(c).previousUse.amount = '3'; m = calc(c); assert.equal(number(m.economicCredit.deducted), 2); assert.equal(number(m.payable), 698);
row(c).previousUse.amount = '6'; pending(c);
});
test('article40 exclusion, payer exemption/foreign residence and special distributions do not become international credit', () => {
for (const patch of [{article40: ''}, {article40: 'yes'}, {article40Reference: ''}, {payerResident: ''}, {payerResident: 'no'}, {recipientResident: 'no'}, {payerIrpc: 'no'}, {payerExempt: ''}, {payerExempt: 'yes'}, {kind: 'liquidation'}, {kind: 'association'}, {kind: ''}, {qualificationReference: ''}]) {
const c = economicCase(); Object.assign(row(c), patch); const m = pending(c); assert.equal(m.internationalCredit.positions.length, 1); assert.equal(number(m.internationalCredit.positions[0].eligible), 8);
if (patch.article40 === 'yes' || patch.kind === 'liquidation' || patch.kind === 'association') assert.equal(m.economicCredit.rows[0].status, 'outside_scope');
}
});
test('inclusion,credit gross-up and current assessment must be reconciled without silently changing L6', () => {
for (const patch of [{incomeIncluded: ''}, {incomeIncluded: 'no'}, {incomeReference: ''}, {assessmentKey: ''}, {assessmentKey: 'stale'}, {grossUpIncluded: ''}, {grossUpIncluded: '0'}, {grossUpIncluded: '11.99'}, {grossUpReference: ''}, {nationalLimit: ''}, {nationalLimit: '1409'}, {nationalLimitReference: ''}, {income: '0'}]) {
const c = economicCase(), before = c.d.modelo_a_snapshot; Object.assign(row(c), patch); pending(c); assert.equal(c.d.modelo_a_snapshot, before);
}
});
test('dividend/source tax identity,date,year,subject and actual allocated source amount require support', () => {
for (const patch of [{subjectNuit: '999999999'}, {payerNuit: ''}, {year: '2025'}, {distributionDate: '2026-02-30'}, {distributionDate: '2025-12-31'}, {distributionDocument: ''}, {distributionParcel: ''}, {taxIssuer: ''}, {taxDocument: ''}, {taxParcel: ''}, {parcelReference: ''}, {currency: 'USD'}, {proofAmount: ''}, {taxAmount: '21'}, {taxAmount: ''}, {attributionReference: ''}, {previouslyAttributed: ''}, {previouslyAttributed: '1'}, {priorAttributionReference: ''}]) {
const c = economicCase(); Object.assign(row(c), patch); pending(c);
}
});
test('same distributed profit parcel cannot be re-used by changing source-tax document,id or date', () => {
const c = economicCase(); c.b.economicCredits.rows.push({...structuredClone(row(c)), id: 'other', taxDocument: 'OTHER', distributionDate: '2026-10-01', distributionDocument: ' synthetic-dividend2026 ', distributionParcel: ' DISTRIBUTION-1 '});
assert.match(pending(c).pending.join(' '), /Mesma parcela de lucros/);
});
test('one source-tax parcel can support distinct documented distributions only within its actual available amount', () => {
const c = economicCase(), other = {...structuredClone(row(c)), id: 'second', distributionParcel: 'distribution-2'};
c.b.economicCredits.rows.push(other); assert.match(pending(c).pending.join(' '), /disponível/);
for (const r of c.b.economicCredits.rows) {r.taxAmount = '10'; r.grossUpIncluded = '6';}
let m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.deducted), 12);
row(c).previouslyAttributed = '1'; other.previouslyAttributed = '1'; pending(c);
row(c).taxAmount = '9'; other.taxAmount = '9'; row(c).grossUpIncluded = '5.4'; other.grossUpIncluded = '5.4'; m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.economicCredit.deducted), 10.8);
other.previouslyAttributed = '0'; assert.match(pending(c).pending.join(' '), /divergente/);
});
test('economic and international use of the same actual tax parcel is rejected even with changed receipt date', () => {
const c = economicCase(); Object.assign(foreign(c), {issuer: row(c).taxIssuer, document: row(c).taxDocument, parcel: ' UNDERLYING-TAX-1 ', parcelReference: 'SYNTHETIC same parcel', proofAmount: '20', date: '2026-10-01'});
assert.match(pending(c).pending.join(' '), /natureza|naturezas/);
});
test('an old proof with no parcel overlaps the whole document;new names require supported partition on both sides', () => {
const c = economicCase(); Object.assign(foreign(c), {issuer: row(c).taxIssuer, document: row(c).taxDocument, proofAmount: '20'}); pending(c);
foreign(c).parcel = 'foreign-tax-line'; pending(c); foreign(c).parcelReference = 'SYNTHETIC evidence of a distinct foreign-tax line in shared document';
const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 688);
});
test('economic source IRPC is not beneficiary withholding,PPC or PEC;distinct supported parcels may share a document', () => {
for (const kind of ['ppc', 'pec']) {
const c = economicCase(), proof = kind === 'ppc' ? c.b.ppc.rows[0] : c.b.pecPayments.rows[0];
Object.assign(row(c), {taxIssuer: proof.issuer, taxDocument: proof.document, proofAmount: proof.proofAmount}); pending(c);
Object.assign(proof, {parcel: 'own-' + kind, parcelReference: 'SYNTHETIC distinct payment parcel'}); assert.deepEqual(calc(c).pending, []);
proof.parcel = row(c).taxParcel; pending(c);
}
});
test('underlying domestic IRPC and beneficiary withholding remain separate even when supported by the same paper', () => {
const c = internationalCase('10', '8', '200', '500', '300'); c.b = prepareEconomicBook(c.b); c.b.economicCredits = economicCase().b.economicCredits;
const withholding = c.b.withholdings.rows[0], proof = calc(c).claims.find(x => x.kind === 'withholding');
Object.assign(row(c), {taxIssuer: proof.issuer, taxDocument: proof.document, proofAmount: '300'}); pending(c);
Object.assign(withholding, {parcel: 'beneficiary-withholding', parcelReference: 'SYNTHETIC separate recipient-tax parcel'});
assert.equal(number(calc(c).payable), 388);
const other = structuredClone(c.b), s = JSON.parse(c.d.modelo_a_snapshot);
other.economicCredits.rows = []; other.economicCredits.state = 'absent'; other.internationalCredits.positions = []; other.internationalCredits.state = 'absent';
other.ppc.rows = []; other.ppc.state = 'absent'; other.pecPayments.rows = []; other.pecPayments.state = 'absent';
other.withholdings.rows[0].parcel = 'relabelled-same-L5-allocation';
s.irpcAnnual = {'opportunity:other': other}; s.irpcWithholdings['opportunity:other'] = structuredClone(Object.values(s.irpcWithholdings)[0]); c.d.modelo_a_snapshot = JSON.stringify(s);
c.d.modelo_a_snapshot = saveIrpcBook(c.d, recordIrpc(c.d, irpcBook(c.d), '2026-10-28T14:00:00+02:00'));
assert.match(pending(c).pending.join(' '), /calculada e reconciliada emL5|afectação L5/);
});
test('documented economic inclusion is not rejected merely because fiscal losses reduce total taxable base below dividends', () => {
const c = economicCase(); row(c).income = '5000';
const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 688);
});
test('cross-context source capacity and distributed-income duplication cannot be evaded with new ids/documents', () => {
const c = economicCase(), other = structuredClone(c.b), s = JSON.parse(c.d.modelo_a_snapshot);
other.internationalCredits.positions = []; other.internationalCredits.state = 'absent'; other.ppc.rows = []; other.ppc.state = 'absent'; other.pecPayments.rows = []; other.pecPayments.state = 'absent';
other.economicCredits.rows[0].id = 'other-id'; other.economicCredits.rows[0].taxDocument = 'OTHER';
s.irpcAnnual = {'opportunity:other': other}; c.d.modelo_a_snapshot = JSON.stringify(s); assert.match(pending(c).pending.join(' '), /lucros económicos já/);
other.economicCredits.rows[0].distributionParcel = 'other-distribution'; other.economicCredits.rows[0].taxDocument = row(c).taxDocument; c.d.modelo_a_snapshot = JSON.stringify(s); pending(c);
other.economicCredits.rows[0].taxAmount = '10'; row(c).taxAmount = '10'; row(c).grossUpIncluded = '6'; c.d.modelo_a_snapshot = JSON.stringify(s);
assert.deepEqual(calc(c).pending, []);
});
test('economic and accepted carry increments compose:1408-12-8-50-200-100-500=538', () => {
const m = calc(economicCase(true)); assert.deepEqual(m.pending, []); assert.equal(number(m.payable), 538);
assert.equal(number(m.creditCarry.afterInternational), 1338); assert.equal(number(m.creditCarry.afterPec), 1038);
});
test('economic priority leaves prior explicit allocations intact when remaining collecta becomes insufficient', () => {
const c = economicCase(true); c.b.creditCarry.lots[0].eligible = '2000'; c.b.creditCarry.lots[0].selected = '1300'; c.b.creditCarry.currentPec = '0';
const before = structuredClone(c.b.creditCarry); assert.match(pending(c).pending.join(' '), /ultrapassam a colecta/); assert.deepEqual(c.b.creditCarry, before);
c.b.creditCarry.lots[0].selected = '1288'; const m = calc(c); assert.deepEqual(m.pending, []); assert.equal(number(m.recoverable), 500); assert.equal(m.economicCredit.carryCreated, false);
});
test('zero,absence and missing differ; earlier deliberate economic summary remains frozen and does not block detailed calculation', () => {
const c = economicCase(); c.b.internationalCredits.economic = {state: 'known', amount: '999', reference: 'SYNTHETIC previous deliberate summary'};
assert.equal(number(calc(c).payable), 688); assert.equal(c.b.internationalCredits.economic.amount, '999');
c.b.economicCredits.state = 'absent'; pending(c); c.b.economicCredits.rows = []; assert.equal(number(calc(c).payable), 700);
c.b.economicCredits.state = ''; pending(c);
const z = economicCase(); Object.assign(row(z), {taxAmount: '0', proofAmount: '0', grossUpIncluded: '0', income: '0', nationalLimit: '0'}); assert.equal(number(calc(z).payable), 700);
});
test('exact60% arithmetic and fractional quota never invent fiscal rounding', () => {
const c = economicCase(); Object.assign(row(c), {taxAmount: '0.01', proofAmount: '0.01', grossUpIncluded: '0.006'});
const m = calc(c); assert.deepEqual(m.economicCredit.deducted, {numerator: '3', denominator: '500'}); assert.deepEqual(m.payable, {numerator: '349997', denominator: '500'});
row(c).nationalLimit = '1/1000'; assert.deepEqual(calc(c).economicCredit.deducted, {numerator: '1', denominator: '1000'});
});
test('save/recover/history,HTML and dossier preserve current L6,original snapshots and accepted carry results', () => {
const c = economicCase(true), prior = structuredClone(c.b); delete prior.economicCredits;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, prior, '2026-10-28T12:00:00+02:00'));
const old = annualBook(c.d), frozen = structuredClone(old.result), base = JSON.parse(c.d.modelo_a_snapshot), plan = c.d.business_plan_snapshot;
const next = prepareEconomicBook(old); next.economicCredits = c.b.economicCredits;
c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, next, '2026-10-28T14:00:00+02:00'));
const back = annualBook(JSON.parse(JSON.stringify(c.d))); assert.equal(annualCurrent(c.d, back), true); assert.deepEqual(back.history, [frozen]); assert.equal(number(back.result.model.payable), 538);
const after = JSON.parse(c.d.modelo_a_snapshot); delete after.irpcAnnual; delete base.irpcAnnual; assert.deepEqual(after, base); assert.equal(c.d.business_plan_snapshot, plan);
assert.match(annualHtml(c.d), /Crédito económico — antes do internacional/); assert.match(annualHtml(c.d), /538.00/);
assert.match(JSON.stringify(createProjectDossierReport(c.d, {selectedSections: new Set(['finance'])})), /Crédito económico/);
back.economicCredits.rows[0].nationalLimit = '5'; c.d.modelo_a_snapshot = saveAnnualBook(c.d, back); assert.equal(annualCurrent(c.d, back), false); assert.deepEqual(back.result, annualBook(c.d).result); assert.throws(() => annualHtml(c.d), /fontes actuais/); assert.match(annualReportRows(c.d).flat().join(' '), /Histórico/);
});
test('malformed optional evidence and parcels are rejected without resetting snapshots', () => {
for (const mutate of [c => c.b.economicCredits.version = 2, c => row(c).previousUse = null, c => row(c).article40 = null, c => foreign(c).parcel = 1]) {
const c = economicCase(), before = c.d.modelo_a_snapshot; mutate(c); assert.throws(() => saveAnnualBook(c.d, c.b), /recuperável/); assert.equal(c.d.modelo_a_snapshot, before);
}
const c = internationalCase(); const once = prepareEconomicBook(c.b); assert.equal(prepareEconomicBook(once), once);
});
test('a partially identified document parcel remains recoverable and indeterminate rather than acquiring absent fields', () => {
const c = economicCase(); foreign(c).parcel = 'foreign-tax-line';
const model = pending(c); c.d.modelo_a_snapshot = saveAnnualBook(c.d, recordAnnual(c.d, c.b));
const back = annualBook(JSON.parse(JSON.stringify(c.d))); assert.deepEqual(calculateAnnual(c.d, back), back.result.model); assert.equal(back.result.model.status, model.status);
});
@@ -0,0 +1,54 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
import {portalNavigation,currentNavigationItem} from '../../resources/js/lib/portal-navigation.ts';
import {searchTerritoryHref} from '../../resources/js/lib/search-territory.ts';
// Shallow SSR of the actual navigation component. Inertia and visual primitives
// are replaced by semantic wrappers; this is not a browser/viewport proof.
const require=createRequire(import.meta.url);
const source=fs.readFileSync(new URL('../../resources/js/components/portal-sidebar-navigation.tsx',import.meta.url),'utf8');
const output=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
const primitive=(tag)=>({children,asChild,...props})=>asChild?React.cloneElement(children,{}):React.createElement(tag,props,children);
const module={exports:{}};
new Function('require','module','exports',output)((name)=>{
if(name==='@inertiajs/react')return {Link:({href,children,...props})=>React.createElement('a',{href,...props},children)};
if(name==='@/lib/portal-navigation')return {currentNavigationItem};
if(name==='@/lib/search-territory')return {searchTerritoryHref};
if(name==='lucide-react')return {LayoutGrid:()=>null};
if(name==='@/components/ui/sidebar')return {SidebarGroup:primitive('section'),SidebarGroupLabel:primitive('h2'),SidebarMenu:primitive('ul'),SidebarMenuButton:primitive('div'),SidebarMenuItem:primitive('li')};
return require(name);
},module,module.exports);
const Component=module.exports.PortalSidebarNavigation;
const flatten=(rows)=>rows.flatMap(r=>[...(r.href?[r.href]:[]),...flatten(r.children??[])]);
const render=(access,url='/')=>{const groups=portalNavigation(access);return {groups,html:renderToStaticMarkup(React.createElement(Component,{groups,url}))};};
void test('sidebar renders every nested authorised destination instead of a first-child shortcut',()=>{
const {groups,html}=render({authenticated:true,manager:true,businesses:true,education:true,ai:true,contentManagementHref:'/gestao-conteudos',contentManagementAccess:{opportunities:{index:'/management/opportunities',create:'/management/opportunities/create'}},scopedAdministration:[{label:'Referências económicas',href:'/management/economic-references/lot-01'}]});
const hrefs=[...html.matchAll(/<a\b[^>]*href="([^"]+)"/g)].map(m=>m[1].replaceAll('&amp;','&'));
assert.deepEqual([...hrefs].sort(),flatten(groups).sort());
assert.equal(hrefs[0],'/gestao-conteudos');
for(const href of ['/carteira','/zonas','/documentos','/legislacao','/management/opportunities','/management/economic-references/lot-01'])assert.ok(hrefs.includes(href),href);
assert.match(html,/Área de trabalho/);
});
void test('nested current destination is selected without changing its URL or replacing it with a group root',()=>{
const {html}=render({authenticated:true,manager:false},'/zonas?category=zee');
const current=[...html.matchAll(/<a\b([^>]*aria-current="page"[^>]*)>/g)];
assert.equal(current.length,1);
assert.match(current[0][1],/href="\/zonas"/);
});
void test('rendered visitor sidebar explains access without private operation links',()=>{
const {html}=render({authenticated:false,manager:false});
assert.match(html,/href="\/acesso-gestao"/);
assert.doesNotMatch(html,/href="\/management\//);
assert.doesNotMatch(html,/analysis=proactive/);
});
void test('sidebar carries the existing search territory when moving between catalogues',()=>{
const {html}=render({authenticated:false,manager:false},'/oportunidades?province_id=QA-province&district_id=QA-district');
assert.match(html,/href="\/carteira\?province_id=QA-province&amp;district_id=QA-district"/);
assert.match(html,/href="\/zonas\?province_id=QA-province&amp;district_id=QA-district"/);
assert.match(html,/href="\/acesso-gestao"/);
});
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {opportunityFillGroups,opportunityErrorGroup,opportunityMissingGroups} from '../../resources/js/lib/opportunity-fill-flow.ts';
import {territorialSearchParams} from '../../resources/js/lib/territorial-search-params.ts';
import {documentFacetLabel} from '../../resources/js/lib/document-facet-label.ts';
test('adaptive groups keep every applicable schema field once, including new specialized fields',()=>{
const keys=['official_title','locations','sector_id','documents','currency','real_estate','future_schema_field','currency'];
const groups=opportunityFillGroups(keys);
assert.deepEqual(groups.flatMap(group=>group.fields).sort(),[...new Set(keys)].sort());
assert.ok(groups.find(group=>group.id==='specific').fields.includes('future_schema_field'));
assert.deepEqual(opportunityFillGroups(['official_title']).map(group=>group.id),['idea']);
assert.deepEqual(opportunityFillGroups([]),[]);
});
test('saved pending fields and validation errors point to the correct existing group without inventing applicability',()=>{
const groups=opportunityFillGroups(['official_title','locations','total_investment']);
assert.equal(opportunityErrorGroup(groups,{'canonical.total_investment':'Valor em falta'}),'finance');
assert.equal(opportunityErrorGroup(groups,{'canonical.locations.0':'Local em falta'}),'territory');
assert.deepEqual(opportunityMissingGroups(groups,['locations.0','canonical.total_investment']).map(group=>group.id),['territory','finance']);
assert.equal(opportunityErrorGroup(groups,{reason:'Motivo em falta'}),undefined);
});
test('territorial search replaces old descendants while retaining all selected non-territorial filters',()=>{
const entries=[['province_id','old'],['district_id','old-child'],['locality_id','old-leaf'],['category','zee'],['q','Nacala'],['page','5']];
const scoped=territorialSearchParams(entries,[{id:'new',location_type:'province'}]);
assert.equal(scoped.get('province_id'),'new');assert.equal(scoped.has('district_id'),false);assert.equal(scoped.has('locality_id'),false);
assert.equal(scoped.get('category'),'zee');assert.equal(scoped.get('q'),'Nacala');assert.equal(scoped.has('page'),false);
const all=territorialSearchParams(entries,[]);assert.equal(all.has('province_id'),false);assert.equal(all.get('category'),'zee');
const unchanged=territorialSearchParams(entries);assert.equal(unchanged.get('district_id'),'old-child');
});
test('document facets have readable labels while original query identifiers remain unchanged',()=>{
const original=['agronegocio','education','media','pt','turismo'];
assert.deepEqual(original.map(documentFacetLabel),['Agronegócio','Formação e competências','Imagens e conteúdos de apoio','Português','Turismo']);
assert.deepEqual(original,['agronegocio','education','media','pt','turismo']);
assert.equal(documentFacetLabel('Tema definido pela Tempo'),'Tema definido pela Tempo');
});
+47 -2
View File
@@ -9,6 +9,7 @@ import {
legacyPortalNavigation,
currentNavigationGroup,
currentNavigationItem,
canShowLegacyManagement,
} from '../../resources/js/lib/portal-navigation.ts';
void test('public and authenticated navigation share groups without revealing management', () => {
@@ -20,7 +21,7 @@ void test('public and authenticated navigation share groups without revealing ma
assert.deepEqual(publicGroups.slice(0, 3), investor.slice(0, 3));
assert.deepEqual(
publicGroups.map((g) => g.id),
['discovery', 'realization', 'support', 'account'],
['discovery', 'realization', 'support', 'work', 'account'],
);
const hrefs = JSON.stringify(investor);
assert.equal(hrefs.includes('/management/'), false);
@@ -37,7 +38,7 @@ void test('management and optional modules follow permissions and feature flags'
education: true,
ai: true,
});
assert.ok(groups.some((group) => group.id === 'management'));
assert.ok(groups.some((group) => group.id === 'work'));
assert.equal(JSON.stringify(groups).includes('/investidor/negocios'), true);
assert.equal(JSON.stringify(groups).includes('/management/ai'), true);
assert.equal(
@@ -151,3 +152,47 @@ void test('catalogue detail and return preserve the search inside the local cata
'/zonas?https%3A%2F%2Foutside.invalid=',
);
});
const destinations=(items)=>items.flatMap(item=>[...(item.href?[item.href]:[]),...destinations(item.children??[])]);
void test('both menu consumers respect the existing scoped server decision rather than generic manager status',()=>{
assert.equal(canShowLegacyManagement({user:{id:1},canManagePortal:true,legacyManagementAccess:false}),false);
assert.equal(canShowLegacyManagement({user:{id:1},canManagePortal:true,legacyManagementAccess:true}),true);
assert.equal(canShowLegacyManagement({user:null,canManagePortal:true,legacyManagementAccess:true}),false);
assert.equal(canShowLegacyManagement({user:{id:1},canManagePortal:true}),true);
});
void test('work entry is discoverable without exposing private capabilities to an anonymous visitor',()=>{
const groups=portalNavigation({authenticated:false,manager:true,contentManagementHref:'/gestao-conteudos',contentManagementAccess:{opportunities:{index:'/management/opportunities',create:'/management/opportunities/create'}},scopedAdministration:[{label:'Private QA administration',href:'/management/secret'}]});
assert.deepEqual(destinations(groups.find(g=>g.id==='work').children),['/acesso-gestao']);
assert.equal(JSON.stringify(groups).includes('/management/'),false);
assert.equal(JSON.stringify(groups).includes('/gestao-conteudos'),false);
});
void test('work area exposes existing content capability even when the old dashboard flag has no menu object',()=>{
const groups=portalNavigation({authenticated:true,manager:true,opportunityManagement:null,contentManagementHref:'/gestao-conteudos',contentManagementAccess:{opportunities:{index:'/management/opportunities',create:'/management/opportunities/create'}}});
const work=groups.find(g=>g.id==='work');
assert.equal(work.label,'Área de trabalho');
assert.ok(work.children.some(i=>i.label==='Preparar análise e ideia'&&i.href==='/management/opportunities/create?analysis=proactive'));
assert.ok(work.children.some(i=>i.href==='/gestao-conteudos'));
assert.ok(work.children.some(i=>i.href==='/management/opportunities'));
});
void test('every previously authorised management/profile destination survives the regrouping exactly once',()=>{
const access={authenticated:true,manager:true,businesses:true,education:true,ai:true,contentManagementHref:'/gestao-conteudos',profileAccess:{contexts:[],mine:'/minhas-oportunidades',create:'/minhas-oportunidades/create',request:'/perfil/promotor',review:null,audit:'/perfis/auditoria',administration:'/perfis/gestao'},scopedAdministration:[{label:'Referências económicas',href:'/management/economic-references/lot-01'}]};
const old=destinations(legacyPortalNavigation(access).filter(g=>['management','profile-opportunities'].includes(g.id)));
const groups=portalNavigation(access);const after=destinations(groups);
for(const href of old)assert.equal(after.filter(x=>x===href).length,1,href);
assert.equal(after.length,new Set(after).size);
assert.ok(destinations(groups.find(g=>g.id==='work').children).includes('/management/economic-references/lot-01'));
assert.equal(after.filter(href=>href==='/management/profile-install').length,1,'profile installation already present in the old authorised sidebar must survive');
});
void test('ordinary authenticated account has an explanation entry and does not acquire creation or management links',()=>{
const groups=portalNavigation({authenticated:true,manager:false});
assert.deepEqual(destinations(groups.find(g=>g.id==='work').children),['/acesso-gestao']);
assert.equal(JSON.stringify(groups).includes('analysis=proactive'),false);
assert.equal(JSON.stringify(groups).includes('/management/'),false);
});
void test('direct analysis and ordinary creation preserve distinct selection state in the same work group',()=>{
const access={authenticated:true,manager:false,profileAccess:{contexts:[],mine:'/minhas-oportunidades',create:'/minhas-oportunidades/create',request:'/perfil/promotor',review:null,administration:null}};
const groups=portalNavigation(access);
assert.equal(currentNavigationGroup(groups,'/minhas-oportunidades/create?analysis=proactive'),'work');
assert.equal(currentNavigationItem(groups,'/minhas-oportunidades/create?analysis=proactive'),'prepare-analysis');
assert.equal(currentNavigationItem(groups,'/minhas-oportunidades/create'),'new-my-opportunity');
});
@@ -0,0 +1,56 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import ts from 'typescript';
// Exercise the real component's event/state contract; this is not browser visual QA.
const require=createRequire(import.meta.url);
const source=fs.readFileSync(new URL('../../resources/js/components/territory-search-select.tsx',import.meta.url),'utf8');
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX}}).outputText;
function harness(overrides={}){
const memory=[];let cursor=0;const chosen=[];
const hooks={...React,useState(initial){const i=cursor++;if(!(i in memory))memory[i]=initial;return[memory[i],value=>{memory[i]=typeof value==='function'?value(memory[i]):value;}];},useRef:()=>({current:null}),useEffect:()=>{}};
const module={exports:{}};
new Function('require','module','exports',compiled)(name=>name==='react'?hooks:require(name),module,module.exports);
const options=[{id:'province-a',name:'Nampula'},{id:'province-b',name:'Maputo Província'}];
const props={id:'territory',label:'Província',search:'',options,onSearch(query){props.search=query;},onChange(option){chosen.push(option);props.selected=option;},...overrides};
let tree;
const flat=node=>!node||typeof node!=='object'?[]:[node,...React.Children.toArray(node.props?.children).flatMap(flat)];
const render=()=>{cursor=0;tree=module.exports.default(props);return tree;};
const find=predicate=>flat(tree).find(predicate);
const input=()=>find(node=>node.type==='input');
const key=value=>input().props.onKeyDown({key:value,preventDefault(){}});
render();return{props,chosen,render,find,input,key,options};
}
test('one search input owns the dropdown; the separate select is absent',()=>{
const h=harness();assert.equal(h.find(node=>node.type==='select'),undefined);
assert.equal(h.input().props.role,'combobox');assert.equal(h.input().props['aria-expanded'],false);
h.input().props.onFocus();h.render();
assert.equal(h.input().props['aria-expanded'],true);
assert.ok(h.find(node=>node.props?.role==='listbox'));
h.find(node=>node.props?.role==='option'&&node.props.id==='territory-options-1').props.onClick();h.render();
assert.deepEqual(h.chosen,[h.options[1]]);assert.equal(h.input().props.value,'Maputo Província');
assert.equal(h.input().props['aria-expanded'],false);
});
test('typing and Escape preserve the existing selection until an option is explicitly chosen',()=>{
const selected={id:'saved',name:'Selecção guardada fora desta página'};const h=harness({selected});
h.input().props.onFocus();h.render();h.input().props.onChange({target:{value:'Map'}});h.render();
assert.equal(h.props.search,'Map');assert.deepEqual(h.chosen,[]);
h.key('Escape');h.render();assert.equal(h.input().props.value,selected.name);assert.deepEqual(h.chosen,[]);
});
test('arrow keys and Enter choose from the list; loading cannot commit an old result',()=>{
const h=harness();h.input().props.onFocus();h.render();h.key('ArrowDown');h.render();h.key('ArrowDown');h.render();
assert.equal(h.input().props['aria-activedescendant'],'territory-options-1');
h.key('Enter');h.render();assert.deepEqual(h.chosen,[h.options[1]]);
const busy=harness({loading:true});busy.input().props.onFocus();busy.render();busy.key('Enter');
assert.deepEqual(busy.chosen,[]);
});
test('clear is explicit; disabled dependent levels cannot expose the dropdown',()=>{
const h=harness({selected:{id:'saved',name:'Nampula'}});
h.find(node=>node.props?.['aria-label']==='Limpar Província').props.onClick();h.render();
assert.deepEqual(h.chosen,[undefined]);assert.equal(h.input().props.value,'');
const disabled=harness({disabled:true});assert.equal(disabled.input().props.disabled,true);
assert.equal(disabled.find(node=>node.props?.role==='listbox'),undefined);
});