merge: reconcile pending integration preserving local history and delivered features

This commit is contained in:
2026-11-22 08:35:36 +02:00
384 changed files with 49619 additions and 3495 deletions
@@ -0,0 +1,189 @@
<?php
namespace Tests\Feature;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\User;
use App\Services\ClusterCompetitiveness;
use App\Services\ContentManagement;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class ClusterEditorialWorkflowTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $author;
private User $reviewer;
private EconomicCluster $cluster;
private array $draft;
private int $version = 0;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
[$this->author, $this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email], 'portal.profile_access_enabled' => false,
'editorial_workflow.cluster_competitiveness' => true, 'editorial_workflow.independent_approval.kinds' => ['cluster_competitiveness']]);
$this->cluster = EconomicCluster::create(['code' => 'ED-QA-'.bin2hex(random_bytes(6)), 'name' => 'Cluster sintético QA', 'sector' => 'Energia', 'status' => 'planned']);
$this->draft = ['version' => 1, 'clusterId' => $this->cluster->id, 'sector' => 'Energia', 'region' => 'Local sintético', 'forces' => []];
foreach (ClusterCompetitiveness::FORCES as $force) {
$this->draft['forces'][$force] = ['pressure' => 'medium', 'evidence' => 'Exemplo sintético', 'source' => 'Fonte sintética QA p. 2', 'period' => '2026',
'rationale' => 'Hipótese sintética', 'limitations' => 'Não são dados reais', 'opportunity' => 'Ideia de demonstração'];
}
}
private function url(): string
{
return '/management/clusters/'.$this->cluster->id.'/competitiveness';
}
private function action(User $actor, string $action, array $extra = [], int $status = 200): array
{
$this->actingAsWithMfa($actor);
$response = $this->postJson($this->url().'/'.$action, ['expected_version' => $this->version, 'reason' => 'Decisão sintética fundamentada em QA', ...$extra])->assertStatus($status);
if ($status !== 200) {
return [];
}
$this->version++;
return $response->assertJsonPath('version', $this->version)->json();
}
private function approved(): array
{
$this->action($this->author, 'saved', ['draft' => $this->draft]);
$this->action($this->author, 'submitted');
$this->action($this->reviewer, 'review_started');
return $this->action($this->reviewer, 'approved');
}
public function test_separate_approval_publication_drafts_restore_archive_and_public_projection(): void
{
$dossier = InvestmentDossier::create(['cluster_id' => $this->cluster->id, 'title' => 'Dossier QA', 'source' => 'Fonte sintética', 'content' => ['sector' => 'Energia'],
'publication_status' => 'published', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Publicação sintética em QA', 'published_at' => now()]);
$approved = $this->approved();
$service = app(ClusterCompetitiveness::class);
$this->assertNull($service->publicData($this->cluster->id));
$this->assertSame('approved', $approved['workflow']['state']);
$this->action($this->reviewer, 'published');
$public = $service->publicData($this->cluster->id);
$this->assertSame($this->draft, $public['draft']);
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (Assert $p) => $p->where('competitiveness.draft.region', 'Local sintético')->missing('competitiveness.workflow')->missing('competitiveness.actor'));
$changed = [...$this->draft, 'region' => 'Edição privada deliberada'];
$draft = $this->action($this->author, 'saved', ['draft' => $changed]);
$this->assertNull($draft['workflow']['approval']);
$this->assertSame($public, $service->publicData($this->cluster->id));
$this->action($this->author, 'published', [], 409);
$this->action($this->author, 'restored', ['revision' => 1]);
$this->action($this->author, 'archived');
$this->assertSame($public, $service->publicData($this->cluster->id));
$this->getJson($this->url())->assertJsonPath('workflow.state', 'archived')->assertJsonPath('draft', $this->draft);
$this->action($this->reviewer, 'withdrawn');
$this->assertNull($service->publicData($this->cluster->id));
$this->assertSame($this->version, DB::table('audit_events')->where('source_system', 'cluster-competitiveness')->where('entity_id', $this->cluster->id)->count());
}
public function test_independence_contributors_return_reject_and_conflicts(): void
{
$this->action($this->author, 'saved', ['draft' => $this->draft]);
$this->action($this->author, 'submitted');
$this->action($this->reviewer, 'review_started');
$this->action($this->author, 'approved', [], 403);
$this->action($this->reviewer, 'returned');
$this->action($this->reviewer, 'saved', ['draft' => [...$this->draft, 'region' => 'Alteração do revisor']]);
$this->action($this->author, 'saved', ['draft' => $this->draft, 'expected_version' => 0], 409);
$this->action($this->author, 'submitted');
$this->action($this->reviewer, 'review_started');
$this->action($this->reviewer, 'approved', [], 403);
$this->action($this->reviewer, 'rejected');
$this->action($this->author, 'submitted', [], 409);
$this->action($this->author, 'restored', ['revision' => 1]);
$this->getJson($this->url())->assertJsonPath('workflow.state', 'draft')->assertJsonPath('workflow.approval', null);
}
public function test_changed_cluster_context_or_revoked_approval_requires_new_decision(): void
{
$this->approved();
$this->cluster->update(['sector' => 'Outro sector sintético']);
$this->getJson($this->url())->assertJsonPath('workflow.fresh', false);
$this->action($this->reviewer, 'published', [], 409);
$this->approved();
config(['portal.managers' => [$this->author->email]]);
$this->action($this->author, 'published', [], 403);
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($this->cluster->id));
}
public function test_legacy_publication_survives_activation_and_disabling_cannot_bypass_workflow(): void
{
config(['editorial_workflow.cluster_competitiveness' => false]);
$this->action($this->author, 'saved', ['draft' => $this->draft]);
$this->action($this->author, 'approved');
$service = app(ClusterCompetitiveness::class);
$public = $service->publicData($this->cluster->id);
config(['editorial_workflow.cluster_competitiveness' => true]);
$this->action($this->author, 'submitted', [], 409);
$this->action($this->author, 'saved', ['draft' => [...$this->draft, 'region' => 'Nova edição privada']]);
$this->assertSame($public, $service->publicData($this->cluster->id));
config(['editorial_workflow.cluster_competitiveness' => false]);
$this->action($this->author, 'approved', [], 503);
$this->action($this->author, 'saved', ['draft' => $this->draft], 503);
$this->assertSame($public, $service->publicData($this->cluster->id));
}
public function test_permissions_mfa_and_incomplete_evidence_do_not_write(): void
{
$this->getJson($this->url())->assertUnauthorized();
$this->actingAs(User::factory()->create());
$this->postJson($this->url().'/published', [])->assertForbidden();
$this->actingAsWithMfa($this->author);
session()->forget('portal.mfa_at');
$this->postJson($this->url().'/saved', ['expected_version' => 0, 'draft' => $this->draft])->assertForbidden();
$draft = $this->draft;
$draft['forces']['buyers']['source'] = '';
$this->action($this->author, 'saved', ['draft' => $draft]);
$this->action($this->author, 'submitted', [], 422);
$this->action($this->author, 'restored', ['revision' => 999], 404);
$this->getJson($this->url())->assertJsonPath('version', 1)->assertJsonCount(1, 'history');
}
public function test_existing_management_entry_and_cluster_list_show_editorial_state_without_new_grants(): void
{
$this->action($this->author, 'saved', ['draft' => $this->draft]);
$this->get('/gestao-conteudos')->assertOk()->assertInertia(fn (Assert $p) => $p->where('access.clusters.index', '/management/clusters'));
$this->get('/management/clusters?q='.$this->cluster->code)->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.data.0.editorial_state', 'draft')->where('records.data.0.status', 'planned'));
$other = User::factory()->create();
$this->assertArrayNotHasKey('clusters', app(ContentManagement::class)->access($other));
config(['editorial_workflow.cluster_competitiveness' => false]);
$this->assertArrayNotHasKey('clusters', app(ContentManagement::class)->access($this->author));
}
public function test_withdrawal_and_context_changes_do_not_cancel_or_trap_a_private_review(): void
{
$this->approved();
$this->action($this->reviewer, 'published');
$this->action($this->author, 'saved', ['draft' => [...$this->draft, 'region' => 'Revisão privada']]);
$this->action($this->author, 'submitted');
$this->action($this->reviewer, 'review_started');
$withdrawn = $this->action($this->reviewer, 'withdrawn');
$this->assertSame('in_review', $withdrawn['workflow']['state']);
$this->assertNull(app(ClusterCompetitiveness::class)->publicData($this->cluster->id));
$this->cluster->update(['name' => 'Contexto alterado durante revisão']);
$this->action($this->reviewer, 'approved', [], 409);
$returned = $this->action($this->reviewer, 'returned');
$this->assertSame('returned', $returned['workflow']['state']);
$this->assertSame('Revisão privada', $returned['draft']['region']);
}
}
@@ -0,0 +1,197 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\DemographicEvidence;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class DemographyEditorialWorkflowTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $editor;
private User $reviewer;
private string $batch;
private string $legacy;
private string $province;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
Storage::fake('local');
[$this->editor, $this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->editor->email, $this->reviewer->email], 'portal.profile_access_enabled' => false, 'demography.enabled' => true,
'editorial_workflow.enabled' => true, 'editorial_workflow.demography' => true, 'editorial_workflow.independent_approval.kinds' => ['demography']]);
$this->actingAsWithMfa($this->editor);
$this->actingAsWithMfa($this->reviewer);
$country = (string) Str::uuid();
$this->province = (string) Str::uuid();
foreach ([[$country, null, 'country'], [$this->province, $country, 'province']] as [$id, $parent, $type]) {
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC EDITORIAL '.$type, 'code' => $id, 'location_type' => $type,
'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id, 'data_classification' => 'public']);
}
$this->legacy = $this->batch('approved', '100.125');
$this->batch = $this->batch('imported', '110.250');
}
private function batch(string $status, string $value): string
{
$id = (string) Str::uuid();
$original = 'SYNTHETIC PREIMPORTED QA ONLY '.$id;
$preview = json_encode(['source' => 'SYNTHETIC QA ONLY', 'record_count' => 1]);
Storage::disk('local')->put('demography/'.$id.'/original.xlsx', $original);
Storage::disk('local')->put('demography/'.$id.'/preview.json', $preview);
$sha = hash('sha256', $original);
DB::table('demographic_imports')->insert(['id' => $id, 'sha256' => $sha, 'preview_sha256' => hash('sha256', $preview), 'file_name' => 'SYNTHETIC-EDITORIAL.xlsx',
'source' => 'SYNTHETIC QA ONLY', 'publication_version' => 'Exemplar sintético, não é fonte INE real', 'status' => $status, 'prepared_by' => $this->editor->id,
'report' => json_encode(['record_count' => 1, 'issue_counts' => ['unit_not_supplied' => 1], 'issues' => [], 'territories' => [], 'scan' => ['result' => 'clean', 'engine' => 'SYNTHETIC QA ONLY', 'sha256' => $sha]])]);
DB::table('demographic_observations')->insert(['import_id' => $id, 'geo_location_id' => $this->province, 'year' => 2026, 'indicator' => 'population', 'sex' => 'all', 'residence' => 'all', 'age_group' => 'all',
'unit' => 'pessoas', 'data_kind' => 'projected', 'original_value' => $value, 'numeric_value' => $value, 'sheet' => '2026', 'cell' => 'B4', 'validation_status' => 'warning']);
return $id;
}
private function draft(int $expected = 0, int $status = 201): ?\stdClass
{
$this->actingAsWithMfa($this->editor);
$this->postJson('/management/editorial/demography/'.$this->batch.'/drafts', ['expected_revision' => $expected])->assertStatus($status);
return app(PortalEditorialWorkflow::class)->latestDemography($this->batch);
}
private function action(\stdClass $edition, string $action, User $actor, int $status = 200): \stdClass
{
$this->actingAsWithMfa($actor);
$this->postJson('/management/editorial/demography/'.$this->batch.'/editions/'.$edition->id, ['version' => $edition->version, 'action' => $action,
'assigned_to' => $this->reviewer->id, 'reason' => 'Conferência sintética e publicação explícita em QA'])->assertStatus($status);
return DB::table('portal_editorial_editions')->where('id', $edition->id)->first();
}
private function approve(\stdClass $edition): \stdClass
{
$edition = $this->action($edition, 'submit', $this->editor);
$edition = $this->action($edition, 'start_review', $this->reviewer);
return $this->action($edition, 'approve', $this->reviewer);
}
public function test_approval_does_not_publish_new_series_and_legacy_values_are_preserved_through_publication_and_archive(): void
{
$legacy = DB::table('demographic_imports')->where('id', $this->legacy)->first();
$before = DB::table('demographic_observations')->whereIn('import_id', [$this->legacy, $this->batch])->orderBy('id')->get()->toJson();
$edition = $this->draft();
$this->draft(0, 409);
$edition = $this->approve($edition);
$service = app(DemographicEvidence::class);
$this->assertSame('no_data', $service->analyse([$this->province], 2026, 2026, 'general', $this->batch)['state']);
$this->assertSame('approved', $edition->state);
$this->assertSame('imported', DB::table('demographic_imports')->where('id', $this->batch)->value('status'));
$this->action($edition, 'publish', $this->reviewer);
$evidence = $service->analyse([$this->province], 2026, 2026, 'general', $this->batch);
$this->assertSame('available', $evidence['state']);
$this->assertSame('110.250', $evidence['territories'][0]['series'][0]['values'][0]['original_value']);
$this->assertSame(1, $evidence['territories'][0]['series'][0]['issue_counts']['unit_not_supplied']);
$this->assertEquals($legacy, DB::table('demographic_imports')->where('id', $this->legacy)->first());
$this->assertSame($before, DB::table('demographic_observations')->whereIn('import_id', [$this->legacy, $this->batch])->orderBy('id')->get()->toJson());
try {
(require database_path('migrations/2026_11_13_233000_extend_editorial_editions_to_demography.php'))->down();
$this->fail('Não eliminar histórico de publicação demográfica.');
} catch (\RuntimeException $exception) {
$this->assertStringContainsString('Preserve demographic', $exception->getMessage());
}
$published = app(PortalEditorialWorkflow::class)->latestDemography($this->batch);
$this->action($published, 'archive', $this->reviewer);
$this->assertSame('no_data', $service->analyse([$this->province], 2026, 2026, 'general', $this->batch)['state']);
$this->assertSame('approved', DB::table('demographic_imports')->where('id', $this->legacy)->value('status'));
$this->assertSame($before, DB::table('demographic_observations')->whereIn('import_id', [$this->legacy, $this->batch])->orderBy('id')->get()->toJson());
}
public function test_changed_observations_or_original_block_publication_and_cannot_be_blessed_by_a_new_draft(): void
{
$edition = $this->approve($this->draft());
DB::table('demographic_observations')->where('import_id', $this->batch)->update(['numeric_value' => '999.999']);
$this->action($edition, 'publish', $this->reviewer, 409);
$this->getJson('/management/editorial/demography/'.$this->batch)->assertJsonPath('edition.fresh', false);
$this->draft(1, 409);
DB::table('demographic_observations')->where('import_id', $this->batch)->update(['numeric_value' => '110.250']);
Storage::disk('local')->put('demography/'.$this->batch.'/original.xlsx', 'SYNTHETIC CHANGED ORIGINAL');
$this->action($edition, 'publish', $this->reviewer, 409);
$this->assertSame('imported', DB::table('demographic_imports')->where('id', $this->batch)->value('status'));
}
public function test_changed_territorial_context_requires_a_new_decision_without_overwriting_numbers(): void
{
$edition = $this->approve($this->draft());
DB::table('geo_locations')->where('id', $this->province)->update(['name' => 'SYNTHETIC REVISED TERRITORY']);
$this->action($edition, 'publish', $this->reviewer, 409);
$next = $this->draft(1);
$this->assertNull($next->approval);
$this->assertSame('110.250', DB::table('demographic_observations')->where('import_id', $this->batch)->value('numeric_value'));
$next = $this->approve($next);
$this->action($next, 'publish', $this->reviewer);
}
public function test_authority_mfa_independence_original_download_and_legacy_bypass_are_enforced(): void
{
$edition = $this->draft();
$this->postJson('/management/demography/'.$this->batch.'/transition', ['action' => 'approved', 'reason' => 'Tentativa por operação antiga'])->assertConflict();
$this->get('/management/editorial/demography/'.$this->batch.'/original')->assertOk()->assertDownload('SYNTHETIC-EDITORIAL.xlsx');
$edition = $this->action($edition, 'submit', $this->editor);
$edition = $this->action($edition, 'start_review', $this->reviewer);
$this->action($edition, 'approve', $this->editor, 403);
$this->actingAs(User::factory()->create())->getJson('/management/editorial/demography/'.$this->batch)->assertForbidden();
$this->getJson('/management/editorial/demography/'.$this->batch.'/original')->assertForbidden();
$this->actingAsWithMfa($this->reviewer);
session()->forget('portal.mfa_at');
$this->postJson('/management/editorial/demography/'.$this->batch.'/editions/'.$edition->id, ['version' => $edition->version, 'action' => 'approve', 'reason' => 'Tentativa sem MFA fresco'])->assertForbidden();
$edition = $this->action($edition, 'approve', $this->reviewer);
$publisher = User::factory()->create();
config(['portal.managers' => [$this->editor->email, $publisher->email]]);
$this->action($edition, 'publish', $publisher, 403);
config(['editorial_workflow.demography' => false]);
$this->actingAsWithMfa($this->editor)->postJson('/management/demography/'.$this->batch.'/transition', ['action' => 'approved', 'reason' => 'Tentativa após desactivação'])->assertStatus(503);
}
public function test_legacy_public_series_need_no_new_approval_and_notices_do_not_grant_access(): void
{
$this->actingAsWithMfa($this->editor);
$this->postJson('/management/editorial/demography/'.$this->legacy.'/drafts', ['expected_revision' => 0])->assertConflict();
$this->assertSame(0, DB::table('portal_editorial_editions')->where('demographic_import_id', $this->legacy)->count());
$edition = $this->action($this->draft(), 'submit', $this->editor);
$this->actingAsWithMfa($this->reviewer)->getJson('/management/editorial')->assertJsonPath('demographyPending', 1)->assertJsonPath('demographyUrl', '/management/demography')
->assertJsonPath('notices.0.href', '/management/editorial/demography/'.$this->batch.'?edition='.$edition->id);
config(['portal.managers' => [$this->editor->email]]);
$this->getJson('/management/editorial')->assertForbidden();
}
public function test_131400_observations_are_fingerprinted_and_published_with_bounded_php_memory(): void
{
DB::table('demographic_observations')->where('import_id', $this->batch)->delete();
DB::statement("INSERT INTO demographic_observations(import_id,geo_location_id,year,indicator,sex,residence,age_group,unit,data_kind,original_value,numeric_value,sheet,cell,validation_status) SELECT ?,?,2026,'population','all','all','SYNTHETIC-QA-'||i,'pessoas','projected','1','1','QA','B4','valid' FROM generate_series(1,131400) i", [$this->batch, $this->province]);
$report = json_decode(DB::table('demographic_imports')->where('id', $this->batch)->value('report'), true, 512, JSON_THROW_ON_ERROR);
$report['record_count'] = 131400;
$preview = json_encode(['source' => 'SYNTHETIC QA ONLY', 'record_count' => 131400], JSON_THROW_ON_ERROR);
Storage::disk('local')->put('demography/'.$this->batch.'/preview.json', $preview);
DB::table('demographic_imports')->where('id', $this->batch)->update(['report' => json_encode($report, JSON_THROW_ON_ERROR), 'preview_sha256' => hash('sha256', $preview)]);
$edition = $this->approve($this->draft());
$this->action($edition, 'publish', $this->reviewer);
$this->assertSame('approved', DB::table('demographic_imports')->where('id', $this->batch)->value('status'));
$this->assertSame(131400, DB::table('demographic_observations')->where('import_id', $this->batch)->count());
$this->assertLessThan(256 * 1024 * 1024, memory_get_peak_usage(true));
}
}
@@ -0,0 +1,35 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Vite;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class EditorialDashboardBuildTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
public function test_authenticated_full_html_opens_with_the_real_compiled_dashboard_entry(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$directory = getenv('EDITORIAL_QA_BUILD_DIRECTORY') ?: 'build';
$manifest = json_decode(file_get_contents(public_path($directory.'/manifest.json')), true, 512, JSON_THROW_ON_ERROR);
$key = 'resources/js/pages/management/editorial-workflow.tsx';
$this->assertArrayHasKey($key, $manifest, 'The authenticated dashboard must be a compiled page entry, not only a shared chunk.');
$this->app->make(Vite::class)->useBuildDirectory($directory)->useHotFile(storage_path('phpunit-no-vite-hot'));
config(['portal.qa_build_directory' => $directory, 'editorial_workflow.enabled' => true, 'portal.profile_access_enabled' => false]);
$actor = User::factory()->create();
config(['portal.managers' => [$actor->email]]);
$this->actingAsWithMfa($actor);
$nativeKey = 'resources/js/pages/dashboard.tsx';
$this->assertArrayHasKey($nativeKey, $manifest);
$this->get('/dashboard', ['Accept' => 'text/html'])->assertOk()->assertSee($manifest[$nativeKey]['file'], false);
foreach (['/management/editorial', '/management/editorial?kind=legislation'] as $url) {
$this->get($url, ['Accept' => 'text/html'])->assertOk()->assertSee('data-page=', false)->assertSee($manifest[$key]['file'], false);
}
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace Tests\Feature;
use App\Models\EconomicCluster;
use App\Models\User;
use App\Services\ClusterCompetitiveness;
use App\Services\ContentManagement;
use App\Services\PortalEditorialNativeNotices;
use App\Services\PortalEditorialWorkflow;
use App\Services\TerritorialRegistry;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class EditorialNativeNoticeTest extends TestCase
{
use AuthenticatesQaActors,DatabaseTransactions;
private User $author;
private User $reviewer;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
[$this->author,$this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email], 'portal.profile_access_enabled' => false, 'editorial_workflow.enabled' => true, 'editorial_workflow.cluster_competitiveness' => true, 'editorial_workflow.territorial_versions' => true, 'territorial.enabled' => true, 'territorial.editors' => [$this->author->email], 'territorial.reviewers' => [$this->reviewer->email], 'territorial.publishers' => [$this->reviewer->email]]);
$this->actingAsWithMfa($this->reviewer);
$this->actingAsWithMfa($this->author);
}
public function test_dashboard_navigation_uses_existing_scopes_and_does_not_expose_disabled_or_private_activities(): void
{
$service = app(ContentManagement::class);
$items = $service->dashboardNavigation($this->author, $service->access($this->author));
$this->assertSame(['label' => 'Visão geral', 'href' => '/dashboard'], $items[0]);
$this->assertNotContains('/management/clusters', array_column($items, 'href'));
$this->assertContains('/management/clusters', array_column($service->administrationNavigation($this->author, $service->access($this->author)), 'href'));
$this->assertContains('/dashboard#manifestacoes', array_column($items, 'href'));
$outsider = User::factory()->create();
$this->assertSame([], $service->dashboardNavigation($outsider, []));
$this->assertSame([], $service->dashboardNavigation(null, []));
config(['editorial_workflow.enabled' => false]);
$after = array_column($service->dashboardNavigation($this->author, $service->access($this->author)), 'href');
$this->assertContains('/dashboard', $after);
$this->assertNotContains('/management/editorial', $after);
}
public function test_cluster_events_use_the_common_inbox_and_recheck_current_scope_and_event_integrity(): void
{
$cluster = EconomicCluster::create(['code' => 'NOTICE-'.Str::random(12), 'name' => 'Synthetic notice cluster', 'sector' => 'Energy', 'status' => 'planned']);
$draft = ['version' => 1, 'clusterId' => $cluster->id, 'sector' => 'Energy', 'region' => 'Synthetic territory', 'forces' => []];
foreach (ClusterCompetitiveness::FORCES as $force) {
$draft['forces'][$force] = ['pressure' => 'medium', ...array_fill_keys(ClusterCompetitiveness::FIELDS, 'Synthetic evidence and limitations')];
}
$service = app(ClusterCompetitiveness::class);
$service->change($cluster, $this->author->id, 0, 'saved', ['draft' => $draft]);
$this->assertDatabaseMissing('portal_editorial_notifications', ['user_id' => $this->reviewer->id, 'action' => 'saved']);
$state = $service->change($cluster, $this->author->id, 1, 'submitted', ['reason' => 'Synthetic review requested']);
$notice = DB::table('portal_editorial_notifications')->where('user_id', $this->reviewer->id)->where('action', 'submitted')->first();
$this->assertNotNull($notice);
$this->assertTrue(app(PortalEditorialWorkflow::class)->visibleNotice($this->reviewer, $notice));
app(PortalEditorialNativeNotices::class)->emit($this->author, $notice->native_event_id, [$this->reviewer->id]);
$this->assertSame(1, DB::table('portal_editorial_notifications')->where('native_event_id', $notice->native_event_id)->where('user_id', $this->reviewer->id)->count());
$present = app(PortalEditorialNativeNotices::class)->present($notice);
$this->assertStringContainsString($cluster->id.'/edit?notice_version=2', $present['href']);
$this->assertSame('Competitividade — versão 2', $present['reference']);
$this->actingAsWithMfa($this->reviewer)->postJson('/management/editorial/notices/'.$notice->id.'/read')->assertOk();
config(['portal.managers' => [$this->author->email]]);
$this->assertFalse(app(PortalEditorialWorkflow::class)->visibleNotice($this->reviewer, $notice));
$this->postJson('/management/editorial/notices/'.$notice->id.'/read')->assertNotFound();
config(['portal.managers' => [$this->author->email, $this->reviewer->email]]);
DB::table('portal_editorial_notifications')->where('id', $notice->id)->update(['content_hash' => str_repeat('0', 64)]);
$tampered = DB::table('portal_editorial_notifications')->where('id', $notice->id)->first();
$this->assertFalse(app(PortalEditorialWorkflow::class)->visibleNotice($this->reviewer, $tampered));
}
public function test_territory_events_open_the_correct_record_without_publishing_or_granting_access(): void
{
$source = (string) Str::uuid();
DB::table('geo_sources')->insert(['id' => $source, 'name' => 'Synthetic source', 'reference' => 'Synthetic source reference', 'checksum' => str_repeat('f', 64), 'source_version' => 'qa', 'collected_at' => today(), 'editor_id' => $this->author->id]);
$registry = app(TerritorialRegistry::class);
$id = $registry->save($this->author, ['name' => 'Synthetic country', 'code' => 'NOTICE-'.Str::random(12), 'location_type' => 'country', 'source_id' => $source, 'valid_from' => '2020-01-01', 'reason' => 'Synthetic territorial preparation']);
$baseline = app(PortalEditorialNativeNotices::class)->pending($this->reviewer);
$registry->transitionEditorial($this->author, $id, ['action' => 'pending_review', 'version_no' => 1, 'reason' => 'Synthetic territorial review requested']);
$notice = DB::table('portal_editorial_notifications')->where('user_id', $this->reviewer->id)->where('action', 'pending_review')->first();
$this->assertNotNull($notice);
$this->assertTrue(app(PortalEditorialWorkflow::class)->visibleNotice($this->reviewer, $notice));
$this->assertStringContainsString('territory='.$id, app(PortalEditorialNativeNotices::class)->present($notice)['href']);
$this->actingAsWithMfa($this->reviewer)->get('/management/territorial/editorial?territory='.$id.'&notice_version=2')->assertOk();
$this->assertFalse($registry->published()->where('g.id', $id)->exists());
$registry->transitionEditorial($this->reviewer, $id, ['action' => 'in_review', 'version_no' => 2, 'reason' => 'Synthetic reviewer starts review']);
$this->assertSame($baseline['territories'], app(PortalEditorialNativeNotices::class)->pending($this->reviewer)['territories']);
$registry->transitionEditorial($this->reviewer, $id, ['action' => 'archived', 'version_no' => 3, 'reason' => 'Synthetic proposal archived']);
$this->assertSame($baseline['territories'] - 1, app(PortalEditorialNativeNotices::class)->pending($this->reviewer)['territories']);
$this->assertNotEmpty(app(PortalEditorialWorkflow::class)->notices($this->author));
}
public function test_email_designation_is_explicit_revocable_and_does_not_grant_content_management(): void
{
$outsider = User::factory()->create();
$workflow = app(PortalEditorialWorkflow::class);
$this->assertFalse($workflow->legalReviewer($outsider));
config(['editorial_workflow.legal_reviewer_emails' => [strtolower($outsider->email)]]);
$this->assertTrue($workflow->legalReviewer($outsider));
$this->assertFalse($outsider->can('manage-portal'));
$outsider->forceFill(['email_verified_at' => null])->save();
$this->assertFalse($workflow->legalReviewer($outsider));
config(['editorial_workflow.legal_reviewer_emails' => []]);
$this->assertFalse($workflow->legalReviewer($this->reviewer));
}
}
@@ -0,0 +1,207 @@
<?php
namespace Tests\Feature;
use App\Models\EconomicCluster;
use App\Models\Project;
use App\Models\User;
use App\Models\ValueChain;
use App\Models\ValueChainLink;
use App\Services\PortalEditorialSubjects;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class EditorialStructuralSubjectTest extends TestCase
{
use AuthenticatesQaActors,DatabaseTransactions;
private User $author;
private User $reviewer;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
[$this->author,$this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email], 'portal.profile_access_enabled' => false, 'editorial_workflow.enabled' => true, 'editorial_workflow.structural_subjects' => true]);
$this->actingAsWithMfa($this->author);
}
private function move(\stdClass $edition, string $action, ?User $actor = null): \stdClass
{
$actor ??= $action === 'submit' ? $this->author : $this->reviewer;
$this->actingAsWithMfa($actor);
return app(PortalEditorialWorkflow::class)->transition($actor, $edition->subject_key, $edition->id, ['action' => $action, 'version' => $edition->version, 'reason' => 'Synthetic subject review decision'], false, false, $edition->subject_kind);
}
private function approve(\stdClass $edition): \stdClass
{
foreach (['submit', 'start_review', 'approve'] as $action) {
$edition = $this->move($edition, $action);
}
return $edition;
}
public function test_a_structure_without_a_fiche_keeps_its_public_fields_until_explicit_publication(): void
{
$record = Project::create(['code' => 'SUB-'.Str::random(10), 'name' => 'Original public name', 'status' => 'active', 'data_classification' => 'public']);
$before = $record->fresh()->getAttributes();
$dossiersBefore = DB::table('investment_dossiers')->count();
$edition = app(PortalEditorialWorkflow::class)->saveSubject($this->author, 'projects', $record->id, 1, ['name' => 'Proposed private name', 'budget_amount' => '999999999999999999.99', 'budget_currency' => 'MZN']);
$this->assertEquals($before, $record->fresh()->getAttributes());
$this->assertSame(2, $edition->revision_no);
$edition = $this->approve($edition);
$this->assertEquals($before, $record->fresh()->getAttributes());
$edition = $this->move($edition, 'publish');
$this->assertSame('Proposed private name', $record->fresh()->name);
$this->assertSame('999999999999999999.99', $record->fresh()->getRawOriginal('budget_amount'));
$this->assertDatabaseCount('investment_dossiers', $dossiersBefore);
$this->assertSame('published', $edition->state);
}
public function test_relation_edits_do_not_invalidate_or_replace_the_current_public_association_before_publication(): void
{
$project = Project::create(['code' => 'REL-'.Str::random(10), 'name' => 'Synthetic project', 'status' => 'active']);
$cluster = EconomicCluster::create(['code' => 'REL-'.Str::random(10), 'name' => 'Synthetic cluster', 'sector' => 'Energy', 'status' => 'active']);
$id = (string) Str::uuid();
DB::table('cluster_projects')->insert(['id' => $id, 'cluster_id' => $cluster->id, 'project_id' => $project->id, 'role' => 'anchor', 'association_type' => 'potential', 'source_reference' => 'Synthetic identified source', 'evidence_reference' => 'Synthetic page 2', 'valid_from' => '2020-01-01', 'validation_status' => 'validated', 'editor_id' => $this->author->id, 'validator_id' => $this->reviewer->id, 'version_no' => 1, 'data_classification' => 'public']);
$before = DB::table('cluster_projects')->find($id);
$edition = app(PortalEditorialWorkflow::class)->saveSubject($this->author, 'cluster-project', $id, 1, ['role' => 'supporting']);
$edition = $this->move($edition, 'submit');
$edition = $this->move($edition, 'start_review');
try {
$this->move($edition, 'approve', $this->author);
$this->fail('Contributor approval must be rejected');
} catch (HttpException $e) {
$this->assertSame(403, $e->getStatusCode());
}
$edition = $this->move($edition, 'approve');
$this->assertEquals($before, DB::table('cluster_projects')->find($id));
$this->move($edition, 'publish');
$this->assertSame('supporting', DB::table('cluster_projects')->find($id)->role);
$this->assertSame('validated', DB::table('cluster_projects')->find($id)->validation_status);
}
public function test_new_value_chain_is_private_until_published_and_archiving_keeps_its_history(): void
{
$cluster = EconomicCluster::create(['code' => 'CHAIN-'.Str::random(10), 'name' => 'Synthetic cluster', 'sector' => 'Energy', 'status' => 'active']);
$chain = ValueChain::create(['cluster_id' => $cluster->id, 'code' => 'QA-'.Str::random(8), 'name' => 'Private new chain', 'stage' => 'production', 'deleted_at' => now()]);
$edition = app(PortalEditorialWorkflow::class)->saveSubject($this->author, 'value-chains', $chain->id, 0, [], true);
$this->assertNull(ValueChain::find($chain->id));
$edition = $this->approve($edition);
$this->assertNull(ValueChain::find($chain->id));
$edition = $this->move($edition, 'publish');
$this->assertNotNull(ValueChain::find($chain->id));
$edition = $this->move($edition, 'archive');
$this->assertNull(ValueChain::find($chain->id));
$this->assertNotNull(app(PortalEditorialWorkflow::class)->latestSubject('value-chains', $chain->id));
}
public function test_existing_editor_routes_and_private_subject_endpoints_preserve_context_and_permissions(): void
{
$record = Project::create(['code' => 'HTTP-'.Str::random(10), 'name' => 'Original HTTP name', 'status' => 'active']);
$this->put('/management/projects/'.$record->id, ['editorial_version' => 1, 'code' => $record->code, 'name' => 'Private HTTP name', 'status' => 'active'])->assertRedirect()->assertSessionHasNoErrors();
$this->assertSame('Original HTTP name', $record->fresh()->name);
$base = '/management/editorial/subjects/projects/'.$record->id;
$this->getJson($base)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('edition.payload.resource._subject.fields.name', 'Private HTTP name');
$this->getJson('/management/editorial/subjects')->assertOk();
$this->getJson($base.'/choices?field=primary_territory_id')->assertOk();
$this->getJson($base.'/choices?field=password')->assertNotFound();
$this->postJson($base.'/drafts', ['expected_revision' => 2, 'fields' => ['data_classification' => 'public']])->assertUnprocessable();
$this->postJson($base.'/drafts', ['expected_revision' => 2, 'fields' => ['name' => 'Deliberate revised name']])->assertCreated();
$this->getJson($base)->assertJsonPath('edition.payload.resource._subject.fields.name', 'Deliberate revised name');
$outsider = User::factory()->create();
$this->actingAsWithMfa($outsider)->getJson($base)->assertForbidden();
$this->postJson($base.'/drafts', ['expected_revision' => 3, 'fields' => ['name' => 'Forbidden']])->assertForbidden();
$this->assertSame('Original HTTP name', $record->fresh()->name);
}
public function test_withdrawal_of_an_existing_chain_link_is_a_separate_reviewed_publication(): void
{
$cluster = EconomicCluster::create(['code' => 'WITHDRAW-'.Str::random(10), 'name' => 'Synthetic cluster', 'sector' => 'Energy', 'status' => 'active']);
$a = ValueChain::create(['cluster_id' => $cluster->id, 'code' => 'A-'.Str::random(5), 'name' => 'Origin', 'stage' => 'production', 'data_classification' => 'public']);
$b = ValueChain::create(['cluster_id' => $cluster->id, 'code' => 'B-'.Str::random(5), 'name' => 'Destination', 'stage' => 'processing', 'data_classification' => 'public']);
$link = ValueChainLink::create(['from_value_chain_id' => $a->id, 'to_value_chain_id' => $b->id, 'link_type' => 'supplies', 'data_classification' => 'public']);
$this->delete('/management/clusters/'.$cluster->id.'/chain-links/'.$link->id)->assertRedirect('/management/editorial/subjects/value-chain-links/'.$link->id);
$this->assertNotNull(ValueChainLink::find($link->id));
$edition = app(PortalEditorialWorkflow::class)->latestSubject('value-chain-links', $link->id);
$this->assertTrue(app(PortalEditorialWorkflow::class)->payload($edition)['resource']['_subject']['withdraw']);
$edition = $this->approve($edition);
$this->assertNotNull(ValueChainLink::find($link->id));
$this->move($edition, 'publish');
$this->assertNull(ValueChainLink::find($link->id));
$this->getJson('/management/editorial/subjects/value-chain-links/'.$link->id)->assertOk();
}
public function test_new_chain_form_creates_a_private_proposal_in_the_existing_model(): void
{
$cluster = EconomicCluster::create(['code' => 'FORM-'.Str::random(10), 'name' => 'Synthetic cluster', 'sector' => 'Energy', 'status' => 'active']);
$code = 'NEW-'.Str::random(10);
$this->post('/management/clusters/'.$cluster->id.'/chains', ['code' => $code, 'name' => 'Private new stage', 'stage' => 'production'])->assertRedirect()->assertSessionHasNoErrors();
$chain = ValueChain::withTrashed()->where('code', $code)->firstOrFail();
$this->assertNull(ValueChain::find($chain->id));
$edition = app(PortalEditorialWorkflow::class)->latestSubject('value-chains', $chain->id);
$this->assertSame('draft', $edition->state);
$this->getJson('/management/editorial/subjects/value-chains/'.$chain->id)->assertOk()->assertJsonPath('edition.payload.resource._subject.new_record', true);
}
public function test_duplicate_relation_publication_is_refused_and_keeps_both_original_links(): void
{
$cluster = EconomicCluster::create(['code' => 'DUP-'.Str::random(10), 'name' => 'Synthetic cluster', 'sector' => 'Energy', 'status' => 'active']);
$chains = collect(['A', 'B', 'C'])->map(fn ($code) => ValueChain::create(['cluster_id' => $cluster->id, 'code' => $code, 'name' => $code, 'stage' => 'production']));
$existing = ValueChainLink::create(['from_value_chain_id' => $chains[0]->id, 'to_value_chain_id' => $chains[1]->id, 'link_type' => 'supplies']);
$edited = ValueChainLink::create(['from_value_chain_id' => $chains[0]->id, 'to_value_chain_id' => $chains[2]->id, 'link_type' => 'supplies']);
$edition = app(PortalEditorialWorkflow::class)->saveSubject($this->author, 'value-chain-links', $edited->id, 1, ['to_value_chain_id' => $chains[1]->id]);
$edition = $this->approve($edition);
try {
$this->move($edition, 'publish');
$this->fail('Duplicate must be refused before writing');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertSame($chains[2]->id, $edited->fresh()->to_value_chain_id);
$this->assertNotNull($existing->fresh());
}
public function test_partial_edits_validate_against_the_preserved_dates_and_currency(): void
{
$record = Project::create(['code' => 'DATES-'.Str::random(10), 'name' => 'Original', 'status' => 'active', 'start_date' => '2026-05-01']);
$base = '/management/editorial/subjects/projects/'.$record->id.'/drafts';
$this->postJson($base, ['expected_revision' => 1, 'fields' => ['end_date' => '2026-04-01']])->assertUnprocessable();
$this->postJson($base, ['expected_revision' => 1, 'fields' => ['budget_amount' => '2000.25']])->assertUnprocessable();
$this->assertSame(0, DB::table('portal_editorial_editions')->where('subject_key', $record->id)->count());
$this->assertSame('Original', $record->fresh()->name);
}
public function test_context_changes_and_disabled_workflow_do_not_allow_legacy_bypass(): void
{
$record = Project::create(['code' => 'STALE-'.Str::random(10), 'name' => 'Original', 'status' => 'active']);
$edition = app(PortalEditorialWorkflow::class)->saveSubject($this->author, 'projects', $record->id, 1, ['name' => 'Private']);
$edition = $this->approve($edition);
$record->forceFill(['description' => 'Changed contextual evidence'])->save();
try {
$this->move($edition, 'publish');
$this->fail('Context changed');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertSame('Original', $record->fresh()->name);
config(['editorial_workflow.structural_subjects' => false]);
try {
app(PortalEditorialSubjects::class)->writes('projects', $record->id);
$this->fail('Legacy bypass');
} catch (HttpException $e) {
$this->assertSame(503, $e->getStatusCode());
}
}
}
@@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\FundingProgrammes;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
final class FundingCriteriaCoherenceTest extends TestCase
{
use DatabaseTransactions;
private User $editor;
private array $geo = [];
private int $sector;
protected function setUp(): void
{
parent::setUp(); $this->withoutVite();
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
$this->assertSame('investor_intent_20261115_test', $db->name); $this->assertSame(55441, (int) $db->port);
$this->editor = User::factory()->create(); config(['portal.managers' => [$this->editor->email]]);
$parent = null;
foreach (['country', 'province', 'district'] as $type) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
$this->geo[$type] = $id; $parent = $id;
}
$this->sector = Sector::create(['slug' => 'synthetic-funding-qa', 'name' => 'SYNTHETIC sector', 'is_active' => true, 'published_at' => now()])->id;
}
private function publish(string $code, string $kind = 'institution', array $overrides = []): string
{
$source = ['source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'SYNTHETIC QA ONLY', 'checked_on' => today()->toDateString()];
$draft = ['title' => 'SYNTHETIC '.$code, 'kind' => $kind, 'manager_name' => 'SYNTHETIC manager', 'summary' => 'Synthetic isolated record, not real content.', 'source_url' => $source['source_url'], 'source_reference' => $source['source_reference'], 'source_checked_on' => $source['checked_on'], 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'all', 'funding_needs' => ['investment'], 'windows' => []];
if ($kind === 'institution') $draft += ['institution_key' => $code, 'institution_nature' => 'bank', 'institution_categories' => ['banking'], 'institution_types' => ['commercial_bank'], 'institution_status' => 'reported',
'locations' => [['role' => 'headquarters', 'label' => 'Synthetic headquarters', 'territory_id' => $this->geo['district'], 'evidence_status' => 'reported', ...$source]],
'products' => [['code' => 'investment', 'title' => 'Synthetic investment product', 'needs' => ['investment'], 'coverage' => 'national', 'availability' => 'documented', ...$source]]];
$service = app(FundingProgrammes::class);
$id = $service->save($this->editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Synthetic QA fixture', 'draft' => array_replace($draft, $overrides)]);
$plan = $service->preview($this->editor, $id);
$service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'confirm' => true, 'reason' => 'Synthetic QA only, rolled back']);
return $id;
}
public function test_bank_filters_apply_to_the_shared_query_and_never_return_brokers_or_microinsurers(): void
{
$bank = $this->publish('qa-bank');
$this->publish('qa-broker', overrides: ['institution_categories' => ['intermediation'], 'institution_types' => ['broker']]);
$this->publish('qa-microinsurance', overrides: ['institution_categories' => ['insurance'], 'institution_types' => ['microinsurer']]);
$fund = $this->publish('qa-fund', 'fund');
$service = app(FundingProgrammes::class);
$filters = ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'institution', 'certainty' => 'documented', 'location_mode' => 'physical', 'territory' => $this->geo['district'], 'sector' => $this->sector, 'need' => 'investment'];
$this->assertSame([$bank], $service->catalogueQuery($filters)->pluck('p.id')->all());
$this->assertSame([$fund], $service->catalogueQuery(['kind' => 'fund'])->pluck('p.id')->all());
$this->assertSame(0, $service->catalogueQuery(['q' => 'no-such-record'])->count());
$this->assertSame(0, $service->catalogueQuery(['category' => 'banking', 'institution_type' => 'investment_bank'])->count(), 'A valid combination without records is an empty result, not an invalid combination.');
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $bank)->where('territorySelection.0.id', $this->geo['province'])->where('territorySelection.1.id', $this->geo['district']));
$returnFilters = [...$filters, 'q' => 'qa', 'state' => 'closed', 'kind' => 'institution', 'include_historical' => '0', 'province_id' => $this->geo['province'], 'district_id' => $this->geo['district'], 'page' => '2'];
$this->get('/fundos/'.$bank.'?'.http_build_query($returnFilters))->assertOk()->assertInertia(function ($page) use ($returnFilters) {
foreach ($returnFilters as $key => $value) $page->where('selection.'.$key, (string) $value);
});
$this->getJson('/api/v1/investment/territory-options?type=district')->assertOk()->assertJsonCount(0, 'data');
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
}
public function test_physical_search_defaults_to_documented_presence_but_preserves_explicit_unknown_choice(): void
{
$local = $this->publish('qa-local');
$this->publish('qa-unlocated', overrides: ['locations' => []]);
$filters = ['q' => 'SYNTHETIC qa-', 'location_mode' => 'physical', 'territory' => $this->geo['province']];
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'documented')->has('items.data', 1)->where('items.data.0.id', $local));
$this->get('/fundos?'.http_build_query([...$filters, 'certainty' => 'include_unknown']))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'include_unknown')->has('items.data', 2));
}
public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void
{
foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) {
try { app(FundingProgrammes::class)->catalogueQuery($filters)->count(); $this->fail('Contradictory criteria must not silently broaden a query.'); }
catch (ValidationException $error) { $this->assertNotEmpty($error->errors()); }
$this->getJson('/fundos?'.http_build_query($filters))->assertUnprocessable();
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page->has('criteriaErrors')->has('items.data', 0));
}
}
public function test_unknown_scope_is_not_a_documented_match_and_physical_presence_does_not_prove_coverage(): void
{
$this->publish('qa-unknown', overrides: ['sectors_scope' => 'unknown', 'products' => []]);
$service = app(FundingProgrammes::class);
$this->assertSame(0, $service->catalogueQuery(['need' => 'investment', 'certainty' => 'documented'])->count());
$this->assertSame(0, $service->catalogueQuery(['sector' => $this->sector, 'certainty' => 'documented'])->count());
$this->assertSame(1, $service->catalogueQuery(['territory' => $this->geo['district'], 'location_mode' => 'physical', 'certainty' => 'documented'])->count());
$this->assertSame(0, $service->catalogueQuery(['territory' => $this->geo['district'], 'location_mode' => 'coverage', 'certainty' => 'documented'])->count());
$this->assertSame(1, $service->catalogueQuery(['need' => 'investment', 'certainty' => 'include_unknown'])->count());
$this->assertSame(0, $service->catalogueQuery(['state' => 'closed'])->count(), 'An institution without a window is not a closed funding window.');
}
public function test_window_state_and_scope_are_matched_on_the_same_window_without_inventing_a_local_window(): void
{
$source = ['source_url' => 'https://example.invalid/synthetic-qa', 'source_reference' => 'Synthetic window', 'checked_on' => today()->toDateString()];
$id = $this->publish('qa-closed-window', overrides: ['windows' => [['code' => 'closed', 'title' => 'Synthetic closed window', 'mode' => 'closed', 'coverage' => 'unknown', ...$source]]]);
$service = app(FundingProgrammes::class);
$criteria = ['territory' => $this->geo['district'], 'certainty' => 'documented', 'state' => 'closed', 'location_mode' => 'coverage'];
$this->assertSame(0, $service->catalogueQuery($criteria)->count());
$this->assertSame([$id], $service->catalogueQuery([...$criteria, 'certainty' => 'include_unknown'])->pluck('p.id')->all());
$this->assertSame([$id], $service->catalogueQuery([...$criteria, 'location_mode' => 'physical'])->pluck('p.id')->all());
$this->assertSame(0, $service->catalogueQuery([...$criteria, 'state' => 'open'])->count());
}
}
@@ -0,0 +1,202 @@
<?php
namespace Tests\Feature;
use App\Http\Requests\StoreSimulationFormDraftRequest;
use App\Models\InvestmentZone;
use App\Models\Sector;
use App\Models\User;
use App\Services\InvestorContext;
use App\Services\ProactiveSupply;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class InvestorIntentContinuityTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
$this->assertSame('investor_intent_20261115_test', $db->name);
$this->assertSame(55441, (int) $db->port);
$this->withoutVite();
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
}
public function test_internal_business_observations_remain_closed_to_an_ordinary_investor(): void
{
$this->expectException(HttpException::class);
app(ProactiveSupply::class)->authorize(User::factory()->create());
}
public function test_demography_source_recovers_its_hierarchy_without_replacing_a_saved_location(): void
{
$owner = User::factory()->create();
$parent = null;
$ids = [];
foreach (['country', 'province', 'district'] as $type) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type,
'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
$ids[$type] = $id;
$parent = $id;
}
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => 'SYNTHETIC demography source', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$url = '/investimentos/'.$id.'/contexto/editar?'.http_build_query(['source' => 'territory:'.$ids['district']]);
$this->get($url)->assertOk()->assertInertia(fn ($page) => $page->where('entryTerritory.id', $ids['district'])->where('territorySelection.0.id', $ids['province'])->where('territorySelection.1.id', $ids['district']));
$version = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json('case.version');
$body = ['version' => $version, 'selection' => ['territory' => 'territory:'.$ids['province']], 'opportunity_choices' => [], 'declarations' => []];
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
$this->get($url)->assertOk()->assertInertia(fn ($page) => $page->where('initial.context.selection.territory.id', $ids['province'])->where('territorySelection.0.id', $ids['province'])->has('territorySelection', 1));
$this->actingAs(User::factory()->create())->get($url)->assertForbidden();
}
public function test_an_own_idea_preserves_sector_locality_and_budget_interval_without_any_advert_or_corridor(): void
{
$owner = User::factory()->create();
$parent = null;
$path = [];
foreach (['country' => 'QA Mozambique', 'province' => 'Maputo Provincia', 'district' => 'Boane', 'admin_post' => 'Matola Rio', 'locality' => 'Matola Rio-Sede'] as $type => $name) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$name, 'code' => $id, 'location_type' => $type,
'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
$path[$type.'_id'] = $id;
$parent = $id;
}
$reviewer = User::factory()->create();
$zone = InvestmentZone::query()->create(['id' => (string) Str::uuid(), 'code' => 'SINT-QA-'.Str::random(8), 'name' => 'SYNTHETIC documented site',
'category' => 'industrial_park', 'physical_category' => 'industrial_park', 'primary_territory_id' => $parent, 'publication_status' => 'published', 'validation_status' => 'validated',
'editor_id' => $owner->id, 'reviewer_id' => $reviewer->id, 'published_at' => now(), 'source_evidence' => [['source_type' => 'promoter', 'url' => 'https://example.invalid/synthetic-qa', 'supports' => 'Synthetic QA only, no operational or legal assertion.']]]);
$zones = $this->actingAs($owner)->getJson('/investimentos/opcoes-corredor?include_corridors=0&territory='.$parent);
$this->assertSame(200, $zones->status(), $zones->getContent());
$zones->assertJsonPath('parks.0.id', $zone->id)->assertJsonCount(1, 'parks');
$this->getJson('/investimentos/opcoes-corredor?include_corridors=0')->assertOk()->assertJsonPath('parks', []);
config(['investor-path.aggregate_supply_qa_enabled' => true]);
$source = hash('sha256', 'Synthetic private aggregate source');
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'PRIVATE-SOURCE-NOT-FOR-OUTPUT.xlsx', 'period' => '2020', 'limitations' => 'Synthetic only', 'receipt' => '{}', 'imported_at' => now()]);
$base = ['source_hash' => $source, 'sheet' => 'PRIVATE-SHEET', 'entity_key' => hash('sha256', 'entity-a'), 'name' => 'PRIVATE-COMPANY-NAME', 'province' => 'Synthetic', 'district' => 'Synthetic', 'cae' => '01110', 'activity' => 'PRIVATE-CONTACT-+258000000000', 'sector' => 'PRIVATE-RAW-SECTOR', 'source_date' => '2020', 'fingerprint' => hash('sha256', 'fingerprint'), 'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $path['district_id'], 'territory_resolution' => 'exact_normalized_province_district'];
foreach ([1 => [], 2 => ['duplicate_of' => hash('sha256', 'row-1')], 3 => ['identity_conflict' => true, 'entity_key' => hash('sha256', 'uncertain')], 4 => ['entity_key' => hash('sha256', 'unclassified'), 'cae' => 'PRIVATE-UNCLASSIFIED-TEXT']] as $number => $changes) {
DB::table('proactive_supply_observations')->insert([...$base, 'id' => hash('sha256', 'row-'.$number), 'row_number' => $number, ...$changes]);
}
foreach (['Agronegocio' => 'agro-qa', 'Criar Hotel' => 'hotel-qa'] as $title => $slug) {
$sector = Sector::create(['name' => 'SYNTHETIC '.$slug, 'slug' => $slug, 'is_active' => true]);
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$entry = [...array_diff_key($path, ['country_id' => true]), 'sector_id' => (string) $sector->id, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000'];
$this->get('/investimentos/iniciar?'.http_build_query($entry))->assertOk()->assertInertia(fn ($page) => $page->where('entryQuery.investment_budget_max', '5000000')->where('entryQuery.locality_id', $parent));
$this->get('/investimentos/'.$id.'/contexto/editar?'.http_build_query($entry))->assertOk()->assertInertia(fn ($page) => $page->where('entryTerritory.id', $parent)->where('entryIdea.sector_id', (string) $sector->id));
$body = ['version' => $view['case']['version'], 'selection' => ['sector' => 'sector:'.$sector->id, 'territory' => 'territory:'.$parent],
'opportunity_choices' => [], 'declarations' => ['project_title' => $title, 'products_services' => 'SYNTHETIC explicit activity '.$slug, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
$saved = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.locality_id', $parent)
->assertJsonPath('prefill.simulator.investment_budget_min', '1000000')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000')
->assertJsonPath('prefill.simulator.project_title', $title)->json();
$this->assertSame('SYNTHETIC explicit activity '.$slug, $saved['prefill']['simulator']['products_services']);
$this->assertEmpty($saved['context']['opportunity_choices'] ?? []);
$this->assertEmpty($saved['context']['selection']['opportunity'] ?? null);
$this->assertEmpty($saved['prefill']['simulator']['total_investment'] ?? null);
$command = ['version' => $saved['case']['version'], 'operation_key' => (string) Str::uuid()];
$url = '/investimentos/'.$id.'/contexto/oferta-agregada';
$aggregate = $this->postJson($url, $command)->assertOk()->assertJsonPath('analysis.entities', 2)->assertJsonPath('analysis.repeated', 1)->assertJsonPath('analysis.uncertain', 1)
->assertJsonPath('analysis.broader_context', true)->assertJsonPath('analysis.scope.id', $path['district_id']);
$this->assertStringNotContainsString('PRIVATE-', $aggregate->getContent());
$this->assertStringNotContainsString($source, $aggregate->getContent());
$this->postJson($url, $command)->assertOk()->assertJsonPath('replayed', true);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'supply_aggregates')->assertJsonPath('supply_aggregates.0.entities', 2);
config(['investor-path.aggregate_supply_qa_enabled' => false]);
$this->postJson($url, $command)->assertNotFound();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates', [])->assertJsonPath('supply_aggregate_enabled', false);
config(['investor-path.aggregate_supply_qa_enabled' => true]);
$this->actingAs(User::factory()->create())->postJson($url, $command)->assertForbidden();
$this->actingAs($owner);
// UI keeps display labels in selection_labels, outside canonical fields.
$economic = array_filter($saved['prefill']['simulator'], fn ($key) => ! str_ends_with($key, '_label') && $key !== 'email', ARRAY_FILTER_USE_KEY);
$economic['purpose'] = 'own_investment';
// Explicit synthetic scenario; the budget interval remains separate.
$economic['total_investment'] = '2000000';
$economic['secured_amount'] = '1000000';
$economic['annual_revenue'] = '300000';
$economic['planning_loan'] = 'no';
$economic['planning_assumptions_snapshot'] = json_encode(['version' => 1, 'data' => ['model' => 'other', 'capacity' => '100', 'price' => '250', 'occupancy' => '', 'frequency' => '12', 'source' => 'Synthetic explicit assumptions', 'costs' => []]], JSON_THROW_ON_ERROR);
$economic['financial_tools_snapshot'] = json_encode(['version' => 1, 'data' => ['budgetPeriod' => 'Mensal',
'loan' => ['principal' => '', 'rate' => '', 'months' => '', 'rateType' => 'nominal', 'periodMonths' => '1', 'gracePeriods' => '', 'upfrontFee' => '', 'recurringFee' => ''],
'breakEven' => ['fixed' => '100000', 'price' => '5000', 'variable' => '2000'], 'funding' => ['total' => '2000000', 'secured' => '1000000'],
'incomes' => [['label' => 'Synthetic declared revenue', 'amount' => '300000']], 'expenses' => [['label' => 'Synthetic declared costs', 'amount' => '200000']]]], JSON_THROW_ON_ERROR);
$allowed = explode(',', substr((new StoreSimulationFormDraftRequest)->rules()['economic_snapshot'][1], 6));
$this->assertSame([], array_values(array_diff(array_keys($economic), $allowed)));
$simulation = $this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$draft = $this->getJson('/api/v1/simulation-drafts/'.$simulation)->assertOk()->assertJsonPath('data.economic_snapshot.investment_budget_min', '1000000')->assertJsonPath('data.economic_snapshot.investment_budget_max', '5000000')->assertJsonPath('data.economic_snapshot.financial_tools_snapshot', $economic['financial_tools_snapshot'])->json('data');
$dossier = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$return = ['version' => $dossier['case']['version'], 'draft_id' => $simulation, 'draft_version' => $draft['version_no'], 'context_revision' => $dossier['investment_context']['revision'], 'context_reviewed' => true];
$result = $this->postJson('/investimentos/'.$id.'/resultados', $return)->assertOk()->assertJsonPath('result.financial_snapshot', $economic['financial_tools_snapshot'])->assertJsonPath('result.preparation_snapshot.planning_loan', 'no')->assertJsonPath('result.preparation_snapshot.annual_revenue', '300000')->assertJsonPath('result.preparation_snapshot.planning_assumptions_snapshot', $economic['planning_assumptions_snapshot'])->json('result.id');
$this->postJson('/investimentos/'.$id.'/resultados', $return)->assertOk()->assertJsonPath('result.id', $result);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'results')->assertJsonPath('results.0.id', $result)->assertJsonPath('results.0.currency', 'MZN');
$this->actingAs(User::factory()->create())->getJson('/api/v1/simulation-drafts/'.$simulation)->assertNotFound();
$this->actingAs($owner);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_budget_max', '5000000');
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$id.'/contexto')->assertForbidden();
}
}
public function test_an_incomplete_currency_can_be_recovered_privately_but_cannot_be_confirmed(): void
{
$this->actingAs(User::factory()->create());
$id = $this->postJson('/investimentos', ['title' => 'Synthetic draft', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$body = ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['currency' => 'MZ']];
$this->postJson('/investimentos/'.$id.'/contexto/rascunho', [...$body, 'draft_sequence' => 1])->assertOk();
$this->assertSame('MZ', app(InvestorContext::class)->draft(auth()->user(), $id)['declarations']['currency']);
$this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertUnprocessable()->assertJsonValidationErrors('declarations.currency');
$body['declarations'] = ['currency' => 'MZN', 'investment_budget_min' => '5000000', 'investment_budget_max' => '1000000'];
$this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertUnprocessable()->assertJsonValidationErrors('declarations.investment_budget_max');
}
public function test_district_demography_is_never_presented_as_locality_population(): void
{
$owner = User::factory()->create();
$parent = null;
$district = null;
foreach (['country', 'province', 'district', 'admin_post', 'locality'] as $type) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => 'SYNTHETIC '.$type, 'code' => $id, 'location_type' => $type, 'data_classification' => 'public',
'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
if ($type === 'district') {
$district = $id;
}
$parent = $id;
}
$batch = (string) Str::uuid();
DB::table('demographic_imports')->insert(['id' => $batch, 'sha256' => hash('sha256', $batch), 'file_name' => 'SYNTHETIC.xlsx', 'source' => 'Synthetic only', 'publication_version' => 'QA/1', 'status' => 'approved', 'report' => '{}', 'preview_sha256' => str_repeat('0', 64), 'prepared_by' => $owner->id, 'created_at' => now(), 'updated_at' => now()]);
DB::table('demographic_observations')->insert(['import_id' => $batch, 'geo_location_id' => $district, 'year' => 2026, 'indicator' => 'population', 'sex' => 'all', 'residence' => 'all', 'age_group' => 'all', 'unit' => 'pessoas', 'data_kind' => 'projected', 'original_value' => '12345', 'numeric_value' => '12345', 'sheet' => '2026', 'cell' => 'B4', 'validation_status' => 'valid']);
$url = '/api/v1/investment/demography?'.http_build_query(['territories' => [$parent], 'start_year' => 2026, 'investment_context' => 1]);
$this->getJson($url)->assertOk()->assertJsonPath('broader_context', true)->assertJsonPath('requested_territory.id', $parent)
->assertJsonPath('territories.0.id', $district)->assertJsonPath('territories.0.level', 'district')->assertJsonPath('territories.0.series.0.values.0.original_value', '12345');
DB::table('geo_locations')->where('id', $parent)->update(['data_classification' => 'internal']);
$this->getJson($url)->assertOk()->assertJsonPath('requested_territory', null)->assertJsonPath('territories', []);
}
public function test_guided_unknown_answers_and_their_labels_save_and_recover_in_the_existing_simulator_contract(): void
{
$this->actingAs(User::factory()->create());
$economic = ['purpose' => 'simulate_only', 'journey_type' => 'investor'];
$economic['preparation_step'] = 'operating';
$economic['fiscal_tools_selection'] = ['tax:sales', 'iva:acquisitions'];
$economic['initial_budget_snapshot'] = json_encode(['version' => 1, 'rows' => [['label' => 'Synthetic equipment', 'amount' => '1000000']]], JSON_THROW_ON_ERROR);
$economic['planning_assumptions_snapshot'] = json_encode(['version' => 1, 'data' => ['model' => 'hotel', 'capacity' => '10', 'price' => '5000', 'occupancy' => '50', 'frequency' => '300', 'source' => 'Synthetic only', 'costs' => []]], JSON_THROW_ON_ERROR);
foreach (['customer_validation_status', 'location_assessment_status', 'cost_estimate_status', 'receivables_timing_status', 'funding_status'] as $field) {
$economic[$field] = 'unknown';
$economic['selection_labels'][$field] = 'Ainda não sei';
}
$id = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->assertJsonPath('data.economic_snapshot.selection_labels.funding_status', 'Ainda não sei')->assertJsonPath('data.economic_snapshot.preparation_step', 'operating')->assertJsonPath('data.economic_snapshot.planning_assumptions_snapshot', $economic['planning_assumptions_snapshot'])->assertJsonPath('data.economic_snapshot.fiscal_tools_selection', $economic['fiscal_tools_selection'])->assertJsonPath('data.economic_snapshot.initial_budget_snapshot', $economic['initial_budget_snapshot']);
$economic['selection_labels']['unsupported_field'] = 'Unsupported';
$this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot.selection_labels.unsupported_field');
}
}
@@ -0,0 +1,117 @@
<?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 InvestorPromoterContinuityTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$db = DB::selectOne('select current_database() as name, inet_server_port() as port');
$this->assertSame('investor_intent_20261115_test', $db->name);
$this->assertSame(55441, (int) $db->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
}
private function dossier(User $owner, string $title): string
{
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => $title, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$view = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$body = ['version' => $view['case']['version'], 'selection' => [], 'declarations' => ['products_services' => 'SYNTHETIC activity '.$title, 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
return $id;
}
public function test_existing_company_is_reused_without_changing_ownership_or_repeating_the_comparison(): void
{
$owner = User::factory()->create();
$this->actingAs($owner);
$company = $this->postJson('/api/v1/investment/companies', ['version' => 0, 'operation_key' => (string) Str::uuid(), 'payload' => ['name' => 'SYNTHETIC Hotel Company', 'incorporation_country_code' => 'MZ', 'registration' => 'SYNTHETIC-QA-REG', 'role' => 'SYNTHETIC representative', 'legal_form' => 'quotas']])->assertSuccessful()->json('id');
$id = $this->dossier($owner, 'Criar Hotel');
$options = $this->getJson('/investimentos/'.$id.'/contexto/entidade')->assertOk()->assertJsonPath('companies.0.id', $company)->json();
$memberships = DB::table('memberships')->count();
$command = ['version' => $options['version'], 'operation_key' => (string) Str::uuid(), 'kind' => 'company', 'id' => $company, 'source_version' => 1];
$url = '/investimentos/'.$id.'/contexto/entidade';
$this->postJson($url, $command)->assertOk()->assertJsonPath('continue', '/investimentos/'.$id);
$this->postJson($url, $command)->assertOk()->assertJsonPath('replayed', true);
$case = DB::table('desk_cases')->where('id', $id)->first();
$this->assertSame($owner->id, (int) $case->user_id);
$this->assertNull($case->organization_id);
$this->assertSame($company, $case->company_id);
$this->assertSame($memberships, DB::table('memberships')->count());
$this->assertSame(1, DB::table('investment_company_declarations')->where('user_id', $owner->id)->count());
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.legal_name', 'SYNTHETIC Hotel Company')->assertJsonPath('prefill.simulator.legal_form', 'quotas')->assertJsonPath('prefill.simulator.entity_stage', 'existing')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000');
$preparation = $this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.proposed_name', 'SYNTHETIC Hotel Company')->assertJsonPath('facts.form', 'quotas')->json();
$facts = $preparation['facts'];
$facts['notes'] = 'SYNTHETIC deliberate note';
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $preparation['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertOk();
$recovered = $this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.notes', 'SYNTHETIC deliberate note')->json();
$facts['form'] = 'anonymous';
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $recovered['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertUnprocessable();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('tools.simulator', '/simulador-fiscal?context='.$id);
$this->actingAs(User::factory()->create())->postJson($url, $command)->assertForbidden();
$otherCase = $this->dossier(auth()->user(), 'Another private idea');
$v = $this->getJson('/investimentos/'.$otherCase.'/contexto/entidade')->assertOk()->assertJsonCount(0, 'companies')->json('version');
$this->postJson('/investimentos/'.$otherCase.'/contexto/entidade', [...$command, 'version' => $v, 'operation_key' => (string) Str::uuid()])->assertNotFound();
}
public function test_optional_comparison_can_continue_into_the_same_unconstituted_entity_and_recover_without_creating_a_company(): void
{
$owner = User::factory()->create();
foreach (['Criar Hotel', 'Agronegocio QA'] as $title) {
$id = $this->dossier($owner, $title);
$comparison = $this->getJson('/investimentos/'.$id.'/forma-juridica')->assertOk()->json();
$answers = $comparison['answers'];
$answers['preferred'] = 'quotas';
$body = ['version' => $comparison['case']['version'], 'operation_key' => (string) Str::uuid(), 'answers' => $answers, 'continue_preparation' => true];
$this->postJson('/investimentos/'.$id.'/forma-juridica', $body)->assertOk();
$this->postJson('/investimentos/'.$id.'/forma-juridica', $body)->assertOk()->assertJsonPath('replayed', true);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.entity_stage', 'being_formed');
$preparation = $this->getJson('/investimentos/'.$id.'/preparar-empresa?form=quotas')->assertOk()->assertJsonPath('facts.form', 'quotas')->assertJsonPath('facts.activities', 'SYNTHETIC activity '.$title)->json();
$facts = $preparation['facts'];
$facts['proposed_name'] = 'SYNTHETIC new company '.$title;
$this->postJson('/investimentos/'.$id.'/preparar-empresa', ['version' => $preparation['case']['version'], 'operation_key' => (string) Str::uuid(), 'facts' => $facts])->assertOk();
$this->getJson('/investimentos/'.$id.'/preparar-empresa?form=anonymous')->assertOk()->assertJsonPath('facts.form', 'quotas')->assertJsonPath('proposedForm', 'anonymous');
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('investment_context.promoter_entity.kind', 'being_formed');
$this->assertSame(0, DB::table('investment_company_declarations')->where('user_id', $owner->id)->count());
$this->assertNull(DB::table('desk_cases')->where('id', $id)->value('company_id'));
$version = $this->getJson('/investimentos/'.$id.'/contexto/entidade')->json('version');
$this->postJson('/investimentos/'.$id.'/contexto/entidade', ['version' => $version, 'operation_key' => (string) Str::uuid(), 'kind' => 'undetermined'])->assertOk();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('investment_context.promoter_entity.kind', 'undetermined')->assertJsonPath('tools.simulator', '/simulador-fiscal?context='.$id);
$this->getJson('/investimentos/'.$id.'/preparar-empresa')->assertOk()->assertJsonPath('facts.proposed_name', $facts['proposed_name']);
}
}
public function test_an_authorised_organization_snapshot_does_not_transfer_the_case_or_grant_master_write_access(): void
{
$owner = User::factory()->create();
$org = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $org, 'name' => 'SYNTHETIC represented organization', 'source_system' => 'unit-qa', 'organization_type' => 'private']);
DB::table('memberships')->insert(['user_id' => $owner->id, 'organization_id' => $org, 'role' => 'viewer']);
$id = $this->dossier($owner, 'Hotel with existing organization');
$url = '/investimentos/'.$id.'/contexto/entidade';
$options = $this->getJson($url)->assertOk()->assertJsonPath('organizations.0.id', $org)->json();
$command = ['kind' => 'organization', 'id' => $org, 'version' => $options['version'], 'operation_key' => (string) Str::uuid(), 'source_version' => 99];
$this->postJson($url, $command)->assertConflict();
$command['source_version'] = 1;
$this->postJson($url, $command)->assertOk();
$case = DB::table('desk_cases')->where('id', $id)->first();
$this->assertNull($case->organization_id); $this->assertNull($case->company_id); $this->assertSame($owner->id, (int) $case->user_id);
$this->assertSame('viewer', DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $org)->value('role'));
config(['portal.organization_country_enabled' => true]);
$this->putJson('/api/v1/investment/organizations/'.$org.'/country', ['version' => 1, 'country' => 'MZ', 'source_reference' => 'Synthetic QA'])->assertForbidden();
DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $org)->update(['deleted_at' => now()]);
$current = $this->getJson($url)->assertOk()->assertJsonCount(0, 'organizations')->assertJsonPath('selected.snapshot.name', 'SYNTHETIC represented organization')->json();
$this->postJson($url, [...$command, 'version' => $current['version'], 'operation_key' => (string) Str::uuid()])->assertForbidden();
}
}
@@ -0,0 +1,175 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\InvestorContext;
use App\Services\OfferPublicCatalogue;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAdministration;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Tests\TestCase;
/** Synthetic acceptance regression for the existing investment-context boundary. */
final class OfferInvestmentAcceptanceAuditTest extends TestCase
{
use RefreshDatabase;
private function prepare(array $location = []): array
{
$this->withoutVite();
config(['portal.profile_access_enabled' => true]);
$owner = User::factory()->create();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $owner->id, 'role' => 'promoter', 'organization_id' => null,
'opportunity_types' => ['business_sale'], 'source' => 'synthetic-acceptance-audit',
]);
$payload = ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'business_sale',
'title' => 'Synthetic acquisition acceptance', 'description' => 'Existing company description to reuse once in investment preparation.',
'private_offer' => ['price_mode' => 'amount', 'amount' => '120000.00', 'currency' => 'MZN',
'business' => ['revenue' => '60000.00', 'cash_flow' => '20000.00', 'currency' => 'MZN']],
'reason' => 'Synthetic final acceptance integration audit only.', ...$location];
$record = $this->actingAs($owner)->postJson('/minhas-oportunidades/ofertas/rascunhos', $payload)->assertCreated()->json('record');
return [$owner, $record, $payload];
}
public function test_saved_offer_reuses_its_description_in_the_existing_investment_context(): void
{
[$owner, $record, $payload] = $this->prepare();
$reference = app(InvestorContext::class)->reference('opportunity:'.$record['id']);
$this->assertSame('private', $reference['visibility']);
$this->assertSame($payload['title'], $reference['fields']['project_title']);
$this->assertSame($payload['description'], $reference['fields']['project_summary'] ?? null,
'Write once/read always: the existing description must not disappear at the investment-context boundary.');
$this->assertSame('/minhas-oportunidades/ofertas/'.$record['id'], $reference['href']);
$this->assertArrayNotHasKey('private_offer', $reference);
$this->assertArrayNotHasKey('revenue', $reference['fields']);
$this->assertArrayNotHasKey('currency', $reference['fields']);
}
public function test_native_context_options_do_not_disclose_another_owners_private_offer(): void
{
[$owner, $record, $payload] = $this->prepare();
$this->getJson('/minhas-oportunidades/ofertas/'.$record['id'])->assertOk()
->assertJsonPath('record.values.private_offer.business.revenue', '60000.00')
->assertJsonPath('record.values.private_offer.business.cash_flow', '20000.00');
$this->assertFalse(Opportunity::published()->whereKey($record['id'])->exists());
$this->actingAs(User::factory()->create());
$this->assertNotContains('opportunity:'.$record['id'], array_column(app(InvestorContext::class)->options(), 'key'));
$this->getJson('/minhas-oportunidades/ofertas/'.$record['id'])->assertForbidden();
}
public function test_private_description_is_not_truncated_and_does_not_replace_an_existing_summary(): void
{
[$owner, $record, $payload] = $this->prepare();
$description = str_repeat('Synthetic complete description. ', 400);
$this->postJson('/minhas-oportunidades/ofertas/'.$record['id'].'/guardar', [
'etag' => $record['etag'], 'description' => $description, 'reason' => $payload['reason'],
])->assertOk();
$this->assertSame(trim($description), app(InvestorContext::class)->reference('opportunity:'.$record['id'])['fields']['project_summary']);
DB::table('opportunities')->where('id', $record['id'])->update(['summary' => 'Deliberate existing summary']);
$this->assertSame('Deliberate existing summary', app(InvestorContext::class)->reference('opportunity:'.$record['id'])['fields']['project_summary']);
$this->assertSame(trim($description), Opportunity::findOrFail($record['id'])->description);
}
public function test_approved_offer_continues_in_same_dossier_location_analysis_saved_result_and_report_input(): void
{
Mail::fake();
config(['editorial_workflow.enabled' => true, 'investor-path.enabled' => true, 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
$country = (string) Str::uuid();
$province = (string) Str::uuid();
foreach ([[$country, 'country', null], [$province, 'province', $country]] as [$id, $type, $parent]) {
DB::table('geo_locations')->insert(['id' => $id, 'code' => 'SYNTHETIC-'.$id, 'name' => 'Synthetic '.$type,
'location_type' => $type, 'parent_id' => $parent, 'data_classification' => 'public',
// Same isolated reference contract as OpportunitySearchFixture; never an operational import.
'source_system' => 'cartografia-workbook',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id]);
}
[$owner, $record, $payload] = $this->prepare(['province_id' => $province]);
$contact = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'Synthetic private contact', 'source_system' => 'portal-user-contact', 'external_id' => 'user:'.$owner->id]);
$url = '/minhas-oportunidades/ofertas/'.$record['id'];
$this->postJson($url.'/guardar', ['etag' => $record['etag'], 'private_offer' => [...$payload['private_offer'], 'contact_id' => $contact], 'reason' => $payload['reason']])->assertOk();
$this->postJson($url.'/submeter', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($record['id'])), 'confirm' => true])->assertOk()->assertJsonPath('record.state', 'submitted');
$reviewer = User::factory()->withTwoFactor()->create();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $reviewer->id, 'role' => 'validator', 'responsibilities' => ['validation_coordinator'],
'opportunity_types' => ['business_sale'], 'source' => 'synthetic-acceptance-audit',
]);
$this->actingAs($reviewer)->withSession(['portal.mfa_actor' => $reviewer->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $reviewer->fresh()->portal_access_revision]);
foreach (['start_review', 'approve'] as $action) {
$this->postJson($url.'/revisao', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($record['id'])),
'action' => $action, 'reason' => 'Synthetic independent review for investment continuity.'])->assertOk();
}
$offer = Opportunity::findOrFail($record['id']);
$public = ['title' => 'Synthetic public acquisition', 'summary' => 'Approved synthetic public summary only.', 'category' => 'business_sale',
'province_id' => $province, 'district_id' => null, 'price_mode' => 'negotiable', 'amount' => null, 'currency' => null];
$hash = OfferPublicCatalogue::projectionHash($public);
$context = $offer->workflow_context;
$context['offer_publication'] = ['contract' => OfferPublicCatalogue::CONTRACT, 'qa_fixture' => true, 'revision' => 1, 'payload' => $public,
'approval' => ['state' => 'approved', 'hash' => $hash, 'actor_id' => $reviewer->id, 'at' => now()->subMinutes(2)->toIso8601String()],
'publication' => ['state' => 'published', 'hash' => $hash, 'actor_id' => User::factory()->create()->id, 'at' => now()->subMinute()->toIso8601String()]];
$offer->forceFill(['workflow_context' => $context])->save();
$this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 0);
$this->app->instance(OfferPublicCatalogue::class, new OfferPublicCatalogue(true));
$response = $this->getJson('/api/v1/offers/'.$offer->id)->assertOk()->assertJsonPath('data.summary', $public['summary']);
$this->assertStringNotContainsString($payload['description'], $response->getContent());
$this->assertStringNotContainsString('60000.00', $response->getContent());
$this->assertNull($offer->fresh()->published_at);
$this->actingAs($owner);
$case = $this->postJson('/investimentos', ['title' => $payload['title'], 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$view = $this->getJson('/investimentos/'.$case.'/contexto')->assertOk()->json();
$body = ['version' => $view['case']['version'], 'selection' => ['opportunity' => 'opportunity:'.$offer->id], 'declarations' => ['currency' => 'MZN']];
$plan = $this->postJson('/investimentos/'.$case.'/contexto/previa', $body)->assertOk()->json();
$this->assertSame($payload['description'], $plan['fields']['project_summary']);
$this->postJson('/investimentos/'.$case.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
$view = $this->getJson('/investimentos/'.$case.'/contexto')->assertOk()->json();
$prefill = $view['prefill']['simulator'];
$this->assertSame($province, $prefill['province_id']);
$this->assertSame($payload['description'], $prefill['project_summary']);
$this->assertStringNotContainsString('60000.00', json_encode($view, JSON_THROW_ON_ERROR));
$financial = ['version' => 1, 'data' => ['budgetPeriod' => 'Mensal',
'loan' => ['principal' => '100000', 'rate' => '0', 'months' => '24', 'rateType' => 'nominal', 'periodMonths' => '1', 'gracePeriods' => '0', 'upfrontFee' => '0', 'recurringFee' => '0'],
'breakEven' => ['fixed' => '3000', 'price' => '100', 'variable' => '50'], 'funding' => ['total' => '100000', 'secured' => '30000'],
'incomes' => [['label' => 'Synthetic scenario revenue', 'amount' => '10000']],
'expenses' => [['label' => 'Declared rent at synthetic province', 'amount' => '2000'], ['label' => 'Declared transport at synthetic province', 'amount' => '1000']]]];
$draft = $this->postJson('/api/v1/simulation-drafts', ['context' => $case, 'personal_snapshot' => [],
'economic_snapshot' => [...array_intersect_key($prefill, array_flip(['purpose', 'journey_type', 'project_title', 'project_summary', 'currency', 'province_id', 'context_applicability_snapshot'])),
'financial_tools_snapshot' => json_encode($financial, JSON_THROW_ON_ERROR)]],
['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$saved = $this->getJson('/api/v1/simulation-drafts/'.$draft.'?context='.$case)->assertOk()->json('data.economic_snapshot');
$this->assertSame($payload['description'], $saved['project_summary']);
$path = $this->getJson('/investimentos/'.$case)->assertOk()->json();
$this->postJson('/investimentos/'.$case.'/resultados', ['version' => $path['case']['version'], 'draft_id' => $draft, 'draft_version' => 1,
'context_revision' => $path['investment_context']['revision'], 'context_reviewed' => true])->assertOk();
auth()->logout();
$this->actingAs(User::findOrFail($owner->id));
$path = $this->getJson('/investimentos/'.$case)->assertOk()->json();
$this->assertSame($draft, $path['results'][0]['draft_id']);
$this->assertSame($payload['description'], $path['investment_context']['fields']['project_summary']);
$this->assertSame(1, Opportunity::count());
$this->assertSame(1, DB::table('desk_cases')->count());
$this->assertStringNotContainsString('60000.00', json_encode($path, JSON_THROW_ON_ERROR));
$output = base_path('outputs/offers-investment-continuity-20261114');
if (! is_dir($output)) {
mkdir($output, 0777, true);
}
file_put_contents($output.'/integrated-report-input.json', json_encode(['path' => $path, 'saved' => $saved], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
$body = ['version' => $path['case']['version'], 'selection' => ['opportunity' => 'opportunity:'.$offer->id],
'declarations' => ['project_summary' => 'Deliberate investment-specific summary']];
$plan = $this->postJson('/investimentos/'.$case.'/contexto/previa', $body)->assertOk()->json();
$this->assertSame('Deliberate investment-specific summary', $plan['fields']['project_summary']);
$this->postJson('/investimentos/'.$case.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
$view = $this->getJson('/investimentos/'.$case.'/contexto')->assertOk()->json();
$this->postJson('/investimentos/'.$case.'/contexto/previa', ['version' => $view['case']['version'],
'selection' => ['opportunity' => 'opportunity:'.$offer->id]])->assertOk()->assertJsonPath('fields.project_summary', 'Deliberate investment-specific summary');
$this->assertSame($payload['description'], $offer->fresh()->description);
$this->actingAs(User::factory()->create())->getJson('/investimentos/'.$case)->assertForbidden();
$this->getJson('/api/v1/simulation-drafts/'.$draft.'?context='.$case)->assertNotFound();
}
}
+228
View File
@@ -0,0 +1,228 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\InvestmentCatalogue;
use App\Services\OfferPublicCatalogue;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Vite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\Support\OpportunitySearchFixture;
use Tests\TestCase;
final class OfferPublicCatalogueTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
}
private function fixture(array $payload = [], array $changes = []): Opportunity
{
$payload = array_replace(['title' => 'Synthetic public offer', 'summary' => 'Approved public summary.',
'category' => 'business_sale', 'province_id' => null, 'district_id' => null,
'price_mode' => 'amount', 'amount' => '12345.67', 'currency' => 'MZN'], $payload);
$hash = OfferPublicCatalogue::projectionHash($payload);
$publication = array_replace_recursive(['contract' => OfferPublicCatalogue::CONTRACT, 'qa_fixture' => true,
'revision' => 1, 'payload' => $payload,
'approval' => ['state' => 'approved', 'hash' => $hash, 'actor_id' => 1, 'at' => now()->subDays(2)->toIso8601String()],
'publication' => ['state' => 'published', 'hash' => $hash, 'actor_id' => 2, 'at' => now()->subDay()->toIso8601String()]], $changes);
$record = Opportunity::create(['title' => 'PRIVATE_CANARY', 'slug' => 'qa-'.Str::uuid(), 'reference' => 'QA-'.Str::uuid(),
'description' => 'PRIVATE_CANARY financial details', 'status' => 'draft']);
$record->forceFill(['management_draft' => json_encode(['contact' => 'PRIVATE_CANARY', 'coordinates' => [33.123456, -18.654321]]),
'workflow_context' => ['private_offer_preparation' => ['version' => 2, 'working_state' => 'draft'], 'offer_publication' => $publication]])->save();
return $record;
}
private function enableSyntheticConsumer(): void
{
$this->app->instance(OfferPublicCatalogue::class, new OfferPublicCatalogue(true));
}
public function test_effective_publication_remains_closed_even_with_a_stored_projection(): void
{
$offer = $this->fixture();
$this->getJson('/api/v1/offers?qa_fixture=true')->assertOk()->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers/'.$offer->id)->assertNotFound();
$this->get('/ofertas/'.$offer->id)->assertNotFound();
$this->assertStringNotContainsString('Synthetic public offer', $this->get('/api/v1/offers/export')->assertOk()->streamedContent());
$this->enableSyntheticConsumer();
$this->app['env'] = 'production';
try {
$this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers/'.$offer->id)->assertNotFound();
} finally {
$this->app['env'] = 'testing';
}
}
public function test_pages_api_csv_and_map_only_use_the_explicit_public_projection(): void
{
$this->enableSyntheticConsumer();
$offer = $this->fixture();
$response = $this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 1)
->assertJsonPath('results.data.0.title', 'Synthetic public offer');
$this->assertStringNotContainsString('PRIVATE_CANARY', $response->getContent());
$this->get('/ofertas')->assertOk()->assertInertia(fn (Assert $page) => $page->component('offers/catalogue')->has('results.data', 1));
$this->get('/ofertas/'.$offer->id)->assertOk()->assertInertia(fn (Assert $page) => $page->component('offers/public-detail')->where('offer.title', 'Synthetic public offer'));
$detail = $this->getJson('/api/v1/offers/'.$offer->id)->assertOk();
$this->assertSame(['id', 'title', 'summary', 'category', 'location', 'price', 'status', 'published_at', 'revision', 'url'], array_keys($detail->json('data')));
$csv = $this->get('/api/v1/offers/export')->assertOk()->streamedContent();
$this->assertStringContainsString('Synthetic public offer', $csv);
$this->assertStringNotContainsString('PRIVATE_CANARY', $csv);
$this->getJson('/api/v1/offers/map')->assertOk()->assertJsonPath('features', [])->assertJsonPath('exact_locations_disclosed', false);
$this->getJson('/api/v1/opportunities/'.$offer->slug)->assertNotFound();
$this->assertSame('draft', $offer->fresh()->status);
$this->assertNull($offer->fresh()->published_at);
}
public function test_invalid_unapproved_unpublished_or_sensitive_snapshots_are_not_readable(): void
{
$this->enableSyntheticConsumer();
foreach ([['approval' => ['state' => 'rejected']], ['publication' => ['state' => 'draft']],
['publication' => ['actor_id' => 1]], ['publication' => ['at' => now()->addDay()->toIso8601String()]],
['approval' => ['hash' => str_repeat('0', 64)]], ['payload' => ['contact' => 'PRIVATE_CANARY']],
['contract' => 'unknown'], ['qa_fixture' => false]] as $invalid) {
$offer = $this->fixture([], $invalid);
$this->getJson('/api/v1/offers/'.$offer->id)->assertNotFound();
}
$this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 0);
}
public function test_pending_private_edits_do_not_replace_the_previously_approved_projection(): void
{
$this->enableSyntheticConsumer();
$offer = $this->fixture();
$before = $this->getJson('/api/v1/offers/'.$offer->id)->assertOk()->json('data');
$context = $offer->workflow_context;
$context['private_offer_preparation']['working_state'] = 'rejected';
$context['draft'] = ['title' => 'PRIVATE_CANARY revision', 'amount' => '999999.99'];
$offer->forceFill(['title' => 'PRIVATE_CANARY edited', 'workflow_context' => $context])->save();
$this->assertSame($before, $this->getJson('/api/v1/offers/'.$offer->id)->assertOk()->json('data'));
$this->getJson('/api/v1/offers?q=PRIVATE_CANARY')->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers?q=Synthetic')->assertJsonPath('results.total', 1);
$offer->delete();
$this->getJson('/api/v1/offers/'.$offer->id)->assertNotFound();
}
public function test_prices_are_exact_and_currencies_are_never_converted(): void
{
$this->enableSyntheticConsumer();
$first = $this->fixture(['amount' => '9999999999999999.01', 'currency' => 'USD']);
$second = $this->fixture(['amount' => '9999999999999999.02', 'currency' => 'USD']);
$this->fixture(['amount' => '9999999999999999.02', 'currency' => 'MZN']);
$this->fixture(['price_mode' => 'negotiable', 'amount' => null, 'currency' => null]);
$this->getJson('/api/v1/offers?currency=USD&min_amount=9999999999999999.02')->assertOk()->assertJsonPath('results.total', 1)->assertJsonPath('results.data.0.id', $second->id);
$this->getJson('/api/v1/offers?currency=USD&sort=amount_asc')->assertOk()->assertJsonPath('results.data.0.id', $first->id);
$this->getJson('/api/v1/offers?price_mode=negotiable')->assertOk()->assertJsonPath('results.total', 1);
foreach (['min_amount=1', 'currency=EUR', 'sort=amount_asc', 'currency=MZN&min_amount=2&max_amount=1', 'price_mode=negotiable&currency=USD'] as $query) {
$this->getJson('/api/v1/offers?'.$query)->assertUnprocessable();
}
}
public function test_csv_formula_text_is_escaped_and_http_has_no_publication_operation(): void
{
$this->enableSyntheticConsumer();
$offer = $this->fixture(['title' => '=SYNTHETIC()']);
$csv = $this->get('/api/v1/offers/export')->assertOk()->streamedContent();
$this->assertStringContainsString("'=SYNTHETIC()", $csv);
$this->postJson('/api/v1/offers/'.$offer->id)->assertMethodNotAllowed();
$this->postJson('/api/v1/offers/'.$offer->id.'/publish')->assertNotFound();
$this->assertSame('draft', $offer->fresh()->status);
}
public function test_location_category_and_pagination_use_only_the_published_snapshot(): void
{
$this->enableSyntheticConsumer();
$country = $this->territory('country');
$province = $this->territory('province', $country);
$district = $this->territory('district', $province);
$other = $this->territory('province', $country);
$boundary = (string) Str::uuid();
DB::insert("INSERT INTO geo_geometries(id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,'polygon',ST_GeomFromText('POLYGON((32 -20,33 -20,33 -19,32 -19,32 -20))',4326),?::jsonb,'public')",
[$boundary, $district, json_encode(['purpose' => 'administrative_boundary', 'authority' => 'Synthetic QA'])]);
DB::insert("INSERT INTO geo_geometries(id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,'point',ST_GeomFromText('POINT(33.123456 -18.654321)',4326),?::jsonb,'confidential')",
[(string) Str::uuid(), $district, json_encode(['purpose' => 'investment_site', 'contact' => 'PRIVATE_CANARY'])]);
$offer = $this->fixture(['province_id' => $province, 'district_id' => $district]);
$offer->forceFill(['primary_territory_id' => $other])->save();
$this->fixture(['title' => 'Another offer', 'province_id' => $province]);
$this->getJson('/api/v1/offers?category=business_sale&province_id='.$province.'&district_id='.$district)
->assertOk()->assertJsonPath('results.total', 1)->assertJsonPath('results.data.0.id', $offer->id);
$this->getJson('/api/v1/offers?province_id='.$other)->assertOk()->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers?province_id='.$other.'&district_id='.$district)->assertUnprocessable();
$this->getJson('/api/v1/offers?district_id='.$district)->assertUnprocessable();
$this->getJson('/api/v1/offers?category=invalid')->assertUnprocessable();
$this->getJson('/api/v1/offers?per_page=1&page=1&sort=title&private_flag=secret')->assertOk()
->assertJsonPath('results.total', 2)->assertJsonPath('results.data.0.title', 'Another offer');
$next = $this->getJson('/api/v1/offers?per_page=1&page=1')->json('results.next_page_url');
$this->assertStringNotContainsString('private_flag', $next);
$this->getJson('/api/v1/offers?per_page=1&page=2&sort=title')->assertOk()->assertJsonPath('results.data.0.id', $offer->id);
$map = $this->getJson('/api/v1/offers/map?province_id='.$province)->assertOk()->assertJsonPath('features', [])->assertJsonPath('exact_locations_disclosed', false);
$this->assertContains($boundary, array_column($map->json('areas'), 'id'));
$this->assertStringNotContainsString('33.123456', $map->getContent());
$this->assertStringNotContainsString('PRIVATE_CANARY', $map->getContent());
DB::table('geo_locations')->where('id', $province)->update(['data_classification' => 'internal']);
$this->getJson('/api/v1/offers/'.$offer->id)->assertNotFound();
$this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 0);
}
private function territory(string $type, ?string $parent = null): string
{
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Synthetic '.$type, 'location_type' => $type,
'parent_id' => $parent, 'source_system' => 'cartografia-workbook',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id, 'data_classification' => 'public']);
return $id;
}
public function test_public_html_resolves_the_real_compiled_pages_without_private_fields(): void
{
$this->enableSyntheticConsumer();
$offer = $this->fixture();
$directory = getenv('EDITORIAL_QA_BUILD_DIRECTORY') ?: 'build';
$manifest = json_decode(file_get_contents(public_path($directory.'/manifest.json')), true, 512, JSON_THROW_ON_ERROR);
$this->app->instance(Vite::class, (new Vite)->useBuildDirectory($directory)->useHotFile(storage_path('phpunit-offers-no-hot')));
foreach (['offers/catalogue' => '/ofertas', 'offers/public-detail' => '/ofertas/'.$offer->id] as $page => $url) {
$key = 'resources/js/pages/'.$page.'.tsx';
$this->assertArrayHasKey($key, $manifest);
$this->get($url, ['Accept' => 'text/html'])->assertOk()->assertSee($manifest[$key]['file'], false)->assertDontSee('PRIVATE_CANARY');
}
}
public function test_existing_catalogue_keeps_its_own_currency_and_price_validation_contract(): void
{
$filters = app(InvestmentCatalogue::class)->filters(Request::create('/oportunidades', 'GET', ['currency' => 'EUR', 'min_amount' => '10', 'max_amount' => '20']));
$this->assertSame('EUR', $filters['currency']);
$this->assertSame('10', $filters['min_amount']);
$this->getJson('/api/v1/offers?currency=EUR&min_amount=10')->assertUnprocessable();
}
public function test_native_combined_filters_and_export_with_self_contained_synthetic_references(): void
{
$province = $this->territory('province', $this->territory('country'));
DB::table('geo_locations')->where('id', $province)->update(['name' => 'Inhambane']);
Sector::create(['slug' => 'turismo', 'name' => 'Synthetic QA tourism', 'is_active' => true]);
$fixture = OpportunitySearchFixture::create();
$this->getJson('/api/v1/investment/search?max_amount=500000')->assertUnprocessable()->assertJsonValidationErrors('currency');
$filters = ['q' => $fixture['query'], 'sector' => 'turismo', 'province_id' => $province,
'category' => 'investment_project', 'preparation' => 'historical:2', 'max_amount' => '500000', 'currency' => 'USD', 'park_id' => $fixture['zone']->id];
$query = http_build_query($filters);
$this->getJson('/api/v1/investment/search?'.$query)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $fixture['associated']->id);
$this->getJson('/api/v1/investment/search?'.http_build_query([...$filters, 'max_amount' => '1']))->assertOk()->assertJsonPath('total', 0);
$this->get('/oportunidades?'.$query)->assertOk()->assertInertia(fn (Assert $page) => $page->component('investment/catalogue')->where('results.total', 1));
$csv = $this->get('/api/v1/investment/export?'.$query)->assertOk()->streamedContent();
$this->assertStringContainsString($fixture['associated']->title, $csv);
$this->assertStringNotContainsString($fixture['private']->title, $csv);
$this->assertStringNotContainsString($fixture['nearby']->title, $csv);
}
}
@@ -160,6 +160,82 @@ class OpportunityCanonicalWorkflowTest extends TestCase
$this->assertNotNull($response['materiality']);
}
public function test_phase_one_requires_a_new_legal_decision_for_each_content_and_attachment_version(): void
{
config(['editorial_workflow.enabled' => true]);
$this->withoutVite();
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
$this->action($promoter, $id, 'submit');
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
}
$this->action($validator, $id, 'approve');
$signed = Opportunity::findOrFail($id)->workflow_context['reviews']['registry_urban_review'];
$this->action($promoter, $id, 'request_revision');
$payload['official_title'] .= ' — edição privada da Fase 1';
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
$this->action($promoter, $id, 'submit');
$context = Opportunity::findOrFail($id)->workflow_context;
$this->assertContains('registry_urban_review', $context['materiality']['reopened']);
$this->assertArrayNotHasKey('registry_urban_review', $context['reviews']);
$this->assertSame($signed['hash'], $context['decision_history'][0]['reviews']['registry_urban_review']['hash']);
$this->action($validator, $id, 'approve', [], 422);
$this->action($validator, $id, 'review_gate', ['gate' => 'registry_urban_review', 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
$this->action($validator, $id, 'approve');
$this->action($publisher, $id, 'assign_publication', ['assignee_user_id' => $publisher->id]);
$file = DB::table('opportunity_documents')->where('id', $document)->value('document_id');
DB::table('documents')->where('id', $file)->increment('version_no');
$this->action($publisher, $id, 'publish', [], 409);
}
public function test_phase_one_activation_preserves_an_approved_legacy_submission_without_rewriting_its_hash(): void
{
config(['editorial_workflow.enabled' => false]);
$this->withoutVite();
[$id, $promoter, $validator, $publisher, , $document] = $this->fixture();
$this->action($promoter, $id, 'submit');
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
}
$this->action($validator, $id, 'approve');
$approved = Opportunity::findOrFail($id)->workflow_context['approval']['hash'];
config(['editorial_workflow.enabled' => true]);
$this->action($publisher, $id, 'assign_publication', ['assignee_user_id' => $publisher->id]);
$this->action($publisher, $id, 'publish');
$record = Opportunity::findOrFail($id);
$this->assertSame('published', $record->status);
$this->assertSame($approved, $record->workflow_context['approval']['hash']);
$this->assertArrayNotHasKey('editorial_version_binding', $record->workflow_context);
}
public function test_phase_one_opportunity_notices_follow_current_access_and_do_not_grant_resource_access(): void
{
config(['editorial_workflow.enabled' => true]);
$this->withoutVite();
[$id, $promoter, $validator] = $this->fixture();
$this->action($promoter, $id, 'submit');
$this->action($validator, $id, 'start_review');
$notice = DB::table('portal_editorial_notifications')->where('user_id', $promoter->id)->where('opportunity_id', $id)->first();
$this->assertNotNull($notice);
$this->assertNotNull($notice->opportunity_version);
$data = $this->loginFixture($promoter)->getJson('/management/editorial')->assertOk()->assertJsonPath('resourceAccess', false)->assertJsonPath('items.total', 0)->json();
$this->assertNotEmpty($data['notices']);
$this->assertSame('/minhas-oportunidades/'.$id, $data['notices'][0]['href']);
$this->postJson('/management/editorial/notices/'.$notice->id.'/read')->assertOk();
$this->assertNotNull(DB::table('portal_editorial_notifications')->where('id', $notice->id)->value('read_at'));
$administrator = User::factory()->create();
config(['portal.managers' => [$administrator->email]]);
DB::table('portal_editorial_notifications')->insert(['user_id' => $administrator->id, 'edition_id' => null, 'opportunity_id' => $id,
'opportunity_version' => $notice->opportunity_version, 'action' => 'start_review', 'created_at' => now()]);
$this->loginFixture($administrator)->getJson('/management/editorial')->assertOk()->assertJsonPath('resourceAccess', true)->assertJsonPath('notices', [])->assertJsonPath('opportunityPending', 0);
$adminNotice = DB::table('portal_editorial_notifications')->where('user_id', $administrator->id)->value('id');
$this->postJson('/management/editorial/notices/'.$adminNotice.'/read')->assertNotFound();
$this->loginFixture($promoter);
DB::table('portal_role_assignments')->where('user_id', $promoter->id)->update(['revoked_at' => now()]);
$this->getJson('/management/editorial')->assertForbidden();
$this->postJson('/management/editorial/notices/'.$notice->id.'/read')->assertNotFound();
}
public function test_geometry_order_is_material_and_object_key_order_is_not(): void
{
$materiality = app(OpportunityReviewMateriality::class);
@@ -0,0 +1,304 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class PortalEditorialWorkflowTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $author;
private User $reviewer;
private User $legal;
private User $publisher;
private int $resource;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
if (! Schema::hasTable('portal_editorial_editions')) {
(require database_path('migrations/2026_11_13_220000_create_portal_editorial_editions.php'))->up();
}
$this->assertTrue(Schema::hasColumns('portal_editorial_editions', ['payload', 'content_hash', 'state', 'version', 'approval', 'legal_validation']));
if (! Schema::hasColumn('portal_editorial_notifications', 'opportunity_id')) {
(require database_path('migrations/2026_11_13_223000_extend_editorial_notifications_to_opportunities.php'))->up();
}
config(['editorial_workflow.enabled' => true, 'editorial_workflow.independent_approval.kinds' => ['article', 'legislation', 'document']]);
$this->withoutVite();
Storage::fake('local');
[$this->author, $this->reviewer, $this->legal, $this->publisher] = User::factory()->count(4)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email, $this->legal->email, $this->publisher->email], 'editorial_workflow.legal_reviewers' => [$this->legal->id]]);
$document = $this->document('Conteúdo público original.');
$this->resource = DB::table('portal_resources')->insertGetId(['document_id' => $document, 'title' => 'Artigo sintético QA', 'category' => 'guide', 'topic' => 'qa', 'document_type' => 'guide',
'published' => true, 'approved_by' => $this->reviewer->id, 'created_by' => $this->author->id, 'source_reference' => 'Fonte sintética de teste isolado', 'source_url' => 'https://example.invalid/source',
'source_confirmation' => 'identified', 'rights_status' => 'authorized', 'independent_review' => true, 'metadata_version' => 1,
'editorial_content' => json_encode(['body' => 'Conteúdo público original.', 'image_mode' => 'none', 'preserve_original_html' => false]), 'created_at' => now(), 'updated_at' => now()]);
}
private function document(string $body): string
{
$id = (string) Str::uuid();
$bytes = json_encode(['format' => 'investmoz-legacy-article-v1', 'content_html' => '<p>'.$body.'</p>']);
$hash = hash('sha256', $bytes);
Storage::disk('local')->put('qa/'.$id.'.json', $bytes);
DB::table('documents')->insert(['id' => $id, 'file_name' => 'synthetic.json', 'media_type' => 'application/json', 'storage_key' => 'qa/'.$id.'.json',
'sha256' => $hash, 'malware_scanned_sha256' => $hash, 'malware_scan_status' => 'clean', 'rights_status' => 'authorized', 'status' => 'active', 'data_classification' => 'public', 'source_system' => 'portal-services', 'uploaded_by' => $this->author->id]);
return $id;
}
private function save(array $fields = []): \stdClass
{
$this->actingAsWithMfa($this->author);
$resource = DB::table('portal_resources')->where('id', $this->resource)->first();
return app(PortalEditorialWorkflow::class)->save($this->author, $this->resource, (int) app(PortalEditorialWorkflow::class)->workingResource($resource)->metadata_version, $fields);
}
private function action(User $actor, \stdClass $edition, string $action, int $status = 200, array $extra = [])
{
$this->actingAsWithMfa($actor);
$response = $this->postJson('/management/editorial/resources/'.$this->resource.'/editions/'.$edition->id, ['version' => $edition->version, 'action' => $action, 'reason' => 'Decisão sintética fundamentada QA', ...$extra])->assertStatus($status);
return $status === 200 ? DB::table('portal_editorial_editions')->where('id', $edition->id)->first() : $response;
}
public function test_editing_and_private_preview_preserve_the_public_article_and_its_original_version(): void
{
$before = DB::table('portal_resources')->where('id', $this->resource)->first();
$this->actingAsWithMfa($this->author)->put('/management/portal-services/resources/'.$this->resource.'/article', ['metadata_version' => 1, 'body' => 'Nova edição privada.', 'image_mode' => 'none'])->assertRedirect();
$r = DB::table('portal_resources')->where('id', $this->resource)->first();
$this->assertEquals($before, $r, 'The complete public resource must remain unchanged while a private edition is saved.');
$this->assertTrue((bool) $r->published);
$this->assertSame(1, (int) $r->metadata_version, 'A private edit must not change even the public metadata version.');
$this->assertSame('Conteúdo público original.', json_decode($r->editorial_content, true)['body']);
$this->assertSame(2, DB::table('portal_editorial_editions')->where('resource_id', $this->resource)->count());
$this->get('/management/editorial/resources/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('current', true)->where('canApprove', false)->where('resource.public_edition_no', 1));
$this->get('/management/portal-services/resources/'.$this->resource.'/article/preview')->assertOk()->assertInertia(fn (Assert $p) => $p->where('article.body', 'Nova edição privada.'));
$this->get('/artigos/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('article.body', 'Conteúdo público original.'));
$this->put('/management/portal-services/resources/'.$this->resource.'/article', ['metadata_version' => 1, 'body' => 'Resposta atrasada.', 'image_mode' => 'none'])->assertConflict();
$this->assertSame(2, DB::table('portal_editorial_editions')->where('resource_id', $this->resource)->count());
$e = app(PortalEditorialWorkflow::class)->latest($this->resource);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'approve');
$this->get('/artigos/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('article.body', 'Conteúdo público original.'));
$this->action($this->publisher, $e, 'publish');
$this->get('/artigos/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('article.body', 'Nova edição privada.'));
}
public function test_legal_approval_and_publication_are_separate_version_bound_operations(): void
{
$e = $this->save(['title' => 'Legislação revista QA', 'legislation' => true, 'document_type' => 'legislation', 'source_confirmation' => 'official_confirmed']);
$e = $this->action($this->author, $e, 'submit', extra: ['assigned_to' => $this->reviewer->id]);
$e = $this->action($this->reviewer, $e, 'start_review');
$this->action($this->author, $e, 'approve', 403);
$this->action($this->reviewer, $e, 'approve', 422);
$this->action($this->reviewer, $e, 'legal_validate', 403);
$e = $this->action($this->legal, $e, 'legal_validate');
$e = $this->action($this->reviewer, $e, 'approve');
$this->assertSame('Artigo sintético QA', DB::table('portal_resources')->where('id', $this->resource)->value('title'));
$this->assertSame('approved', $e->state);
$approved = $e;
$e = $this->action($this->publisher, $e, 'publish');
$this->assertSame('published', $e->state);
$this->assertSame('Legislação revista QA', DB::table('portal_resources')->where('id', $this->resource)->value('title'));
$this->action($this->publisher, $approved, 'publish', 409);
$draft = $this->save(['title' => 'Alteração posterior privada']);
$this->assertNull($draft->approval);
$this->assertNull($draft->legal_validation);
$this->assertSame('Legislação revista QA', DB::table('portal_resources')->where('id', $this->resource)->value('title'));
$this->actingAsWithMfa($this->author)->getJson('/management/editorial/resources/'.$this->resource)->assertOk()->assertJsonPath('edition.id', $draft->id)->assertJsonPath('resource.published', true);
$this->assertGreaterThan(0, DB::table('portal_editorial_notifications')->where('user_id', $this->author->id)->count());
$this->assertGreaterThan(0, DB::table('audit_events')->where('action', 'editorial_publish')->count());
$this->getJson('/management/editorial/resources/'.$this->resource.'?edition='.$approved->id)->assertOk()->assertJsonPath('current', false)->assertJsonPath('edition.payload.resource.title', 'Legislação revista QA');
}
public function test_replacing_an_attachment_invalidates_approval_and_private_file_routes_are_scoped(): void
{
$doc = $this->document('Anexo novo, apenas na edição privada.');
$e = $this->save(['document_id' => $doc]);
$url = '/management/editorial/resources/'.$this->resource.'/editions/'.$e->id.'/files/'.$doc;
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'no-store, private');
$outsider = User::factory()->create();
$this->actingAsWithMfa($outsider)->getJson($url)->assertForbidden();
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'approve');
DB::table('documents')->where('id', $doc)->increment('version_no');
$this->action($this->publisher, $e, 'publish', 409);
$this->actingAsWithMfa($this->author)->getJson($url)->assertConflict();
$this->assertNotSame($doc, DB::table('portal_resources')->where('id', $this->resource)->value('document_id'));
}
public function test_returns_rejection_archive_permissions_and_legacy_publication_cannot_bypass_review(): void
{
$e = $this->save(['title' => 'Edição para devolver']);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'return');
$this->assertSame('returned', $e->state);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'reject');
$e = $this->action($this->author, $e, 'archive');
$this->assertTrue((bool) DB::table('portal_resources')->where('id', $this->resource)->value('published'));
$this->actingAsWithMfa($this->publisher)->post('/management/portal-services/resources/'.$this->resource, ['published' => true])->assertConflict();
$this->actingAs(User::factory()->create())->getJson('/management/editorial')->assertForbidden();
$this->actingAs($this->author)->withSession(['portal.mfa_at' => 0])->postJson('/management/editorial/resources/'.$this->resource.'/editions/'.$e->id, ['action' => 'submit', 'version' => $e->version, 'reason' => 'MFA expirado'])->assertForbidden();
}
public function test_document_metadata_replacement_remains_private_and_is_recovered_with_its_original_file(): void
{
$doc = $this->document('Documento de substituição privado.');
DB::table('documents')->where('id', $doc)->update(['data_classification' => 'internal']);
$fields = ['document_id' => $doc, 'title' => 'Documento revisto QA', 'description' => 'Descrição privada', 'category' => 'guide', 'topic' => 'qa',
'document_type' => 'guide', 'language' => 'pt', 'territorial_scope' => 'national', 'source_confirmation' => 'identified', 'legal_status' => 'not_applicable',
'rights_status' => 'authorized', 'independent_review' => true, 'source_reference' => 'Ensaio sintético de referência documental', 'source_url' => 'https://example.invalid/document',
'legislation' => false, 'essential' => false, 'data_classification' => 'public', 'metadata_version' => 1, 'issuer' => 'Emissor sintético QA'];
$before = DB::table('portal_resources')->where('id', $this->resource)->first();
$this->actingAsWithMfa($this->author)->put('/management/portal-services/resources/'.$this->resource, $fields)->assertSessionHasNoErrors()->assertRedirect();
$this->assertSame($before->document_id, DB::table('portal_resources')->where('id', $this->resource)->value('document_id'));
$this->assertSame('internal', DB::table('documents')->where('id', $doc)->value('data_classification'));
$this->getJson('/management/editorial/resources/'.$this->resource)->assertOk()->assertJsonPath('edition.payload.resource.title', $fields['title'])->assertJsonPath('edition.payload.resource.document_id', $doc);
$this->get('/documentos/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('resource.title', $before->title));
$e = app(PortalEditorialWorkflow::class)->latest($this->resource);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'approve');
$e = $this->action($this->publisher, $e, 'publish');
$this->assertSame('public', DB::table('documents')->where('id', $doc)->value('data_classification'));
$this->assertSame($doc, DB::table('portal_resources')->where('id', $this->resource)->value('document_id'));
$this->assertSame('Emissor sintético QA', DB::table('documents')->where('id', $doc)->value('issuer'));
}
public function test_notice_receipt_never_grants_access_and_revocation_blocks_publication(): void
{
$e = $this->save();
$e = $this->action($this->author, $e, 'submit', extra: ['assigned_to' => $this->reviewer->id]);
$this->actingAsWithMfa($this->reviewer)->getJson('/management/editorial')->assertOk()->assertJsonPath('items.data.0.edition_id', $e->id);
$this->getJson('/management/editorial?state=submitted&kind=article')->assertOk()->assertJsonPath('items.data.0.edition_id', $e->id);
$this->getJson('/management/editorial?state=approved')->assertOk()->assertJsonPath('items.total', 0);
$notice = DB::table('portal_editorial_notifications')->where('user_id', $this->reviewer->id)->value('id');
$this->postJson('/management/editorial/notices/'.$notice.'/read')->assertOk();
$this->assertNotNull(DB::table('portal_editorial_notifications')->where('id', $notice)->value('read_at'));
$this->actingAsWithMfa($this->author)->postJson('/management/editorial/notices/'.$notice.'/read')->assertNotFound();
$outsider = User::factory()->create();
DB::table('portal_editorial_notifications')->insert(['edition_id' => $e->id, 'user_id' => $outsider->id, 'action' => 'submit', 'created_at' => now()]);
$this->actingAsWithMfa($outsider)->getJson('/management/editorial')->assertForbidden();
$this->getJson('/management/editorial/resources/'.$this->resource)->assertForbidden();
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'approve');
config(['portal.managers' => [$this->author->email, $this->publisher->email, $this->legal->email]]);
$this->action($this->publisher, $e, 'publish', 403);
$this->assertSame('Artigo sintético QA', DB::table('portal_resources')->where('id', $this->resource)->value('title'));
}
public function test_all_contributors_are_excluded_from_independent_approval_and_modified_bytes_block_review(): void
{
$this->save(['description' => 'Contributo deliberado da autora.']);
$this->actingAsWithMfa($this->reviewer);
$e = app(PortalEditorialWorkflow::class)->save($this->reviewer, $this->resource, 2, ['title' => 'Edição colaborativa']);
$e = $this->action($this->reviewer, $e, 'submit');
$e = $this->action($this->legal, $e, 'start_review');
$this->action($this->author, $e, 'approve', 403);
$this->action($this->reviewer, $e, 'approve', 403);
$e = $this->action($this->legal, $e, 'approve');
$this->assertSame('approved', $e->state);
$doc = $this->document('Anexo íntegro inicial.');
$e = $this->save(['document_id' => $doc]);
$key = DB::table('documents')->where('id', $doc)->value('storage_key');
Storage::disk('local')->put($key, 'Alteração dos bytes sem actualizar os metadados.');
$this->action($this->author, $e, 'submit', 404);
$this->getJson('/management/editorial/resources/'.$this->resource)->assertOk()->assertJsonPath('edition.fresh', false);
$this->get('/artigos/'.$this->resource)->assertOk()->assertInertia(fn (Assert $p) => $p->where('article.body', 'Conteúdo público original.'));
}
public function test_new_document_is_prepared_privately_without_disclosure_or_direct_publication(): void
{
$doc = $this->document('Documento novo não publicado.');
DB::table('documents')->where('id', $doc)->update(['data_classification' => 'internal']);
$marker = 'SYNTHEDITORIAL'.Str::random(10);
$this->actingAsWithMfa($this->author)->post('/management/portal-services/resources', ['document_id' => $doc, 'title' => $marker, 'category' => 'guide', 'topic' => 'qa',
'document_type' => 'guide', 'language' => 'pt', 'territorial_scope' => 'national', 'source_confirmation' => 'identified', 'legal_status' => 'not_applicable', 'rights_status' => 'authorized',
'independent_review' => true, 'source_reference' => 'Fonte sintética QA, sem divulgação', 'source_url' => 'https://example.invalid/source', 'legislation' => false, 'essential' => false, 'data_classification' => 'public'])->assertSessionHasNoErrors()->assertRedirect();
$id = DB::table('portal_resources')->where('title', $marker)->value('id');
$this->assertNotNull($id);
$this->assertSame('draft', app(PortalEditorialWorkflow::class)->latest($id)->state);
$this->assertFalse((bool) DB::table('portal_resources')->where('id', $id)->value('published'));
$this->assertSame('internal', DB::table('documents')->where('id', $doc)->value('data_classification'));
$this->get('/documentos/'.$id.'/download')->assertNotFound();
$this->get('/pesquisa?q='.$marker)->assertOk()->assertInertia(fn (Assert $p) => $p->where('results.total', 0));
$this->resource = (int) $id;
$e = app(PortalEditorialWorkflow::class)->latest($this->resource);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->reviewer, $e, 'start_review');
$e = $this->action($this->reviewer, $e, 'approve');
$this->get('/documentos/'.$id.'/download')->assertNotFound();
$this->action($this->publisher, $e, 'publish');
$this->get('/documentos/'.$id.'/download')->assertOk();
}
public function test_migration_refuses_an_operational_target_and_destructive_rollback_with_history(): void
{
$this->save();
$migration = require database_path('migrations/2026_11_13_220000_create_portal_editorial_editions.php');
try {
$migration->down();
$this->fail('Existing editions must not be removed by rollback.');
} catch (\RuntimeException $exception) {
$this->assertStringContainsString('Preserve editions', $exception->getMessage());
}
config(['database.connections.pgsql.port' => 5432]);
try {
$migration->up();
$this->fail('Operational-target schema change must be refused.');
} catch (\RuntimeException $exception) {
$this->assertStringContainsString('only in isolated QA', $exception->getMessage());
} finally {
config(['database.connections.pgsql.port' => 55441]);
}
$this->assertSame(2, DB::table('portal_editorial_editions')->where('resource_id', $this->resource)->count());
$this->assertTrue((bool) DB::table('portal_resources')->where('id', $this->resource)->value('published'));
}
public function test_missing_editorial_schema_blocks_writes_without_blocking_the_existing_dashboard(): void
{
(require database_path('migrations/2026_11_13_220000_create_portal_editorial_editions.php'))->down();
$before = DB::table('portal_resources')->where('id', $this->resource)->first();
$this->actingAsWithMfa($this->author)->get('/dashboard')->assertOk();
$this->putJson('/management/portal-services/resources/'.$this->resource.'/article', ['metadata_version' => 1, 'body' => 'Não aplicar sem estrutura.', 'image_mode' => 'none'])->assertStatus(503);
$this->postJson('/management/portal-services/resources/'.$this->resource, ['published' => true])->assertStatus(503);
$this->assertEquals($before, DB::table('portal_resources')->where('id', $this->resource)->first());
}
public function test_review_independence_fact_is_not_a_policy_and_cannot_be_claimed_by_the_author(): void
{
config(['editorial_workflow.independent_approval.kinds' => [], 'editorial_workflow.independent_approval.resources' => []]);
$e = $this->save(['independent_review' => true]);
$this->assertFalse(app(PortalEditorialWorkflow::class)->requiresIndependent($e));
$this->assertFalse(app(PortalEditorialWorkflow::class)->payload($e)['resource']['independent_review']);
$e = $this->action($this->author, $e, 'submit');
$e = $this->action($this->author, $e, 'start_review');
$e = $this->action($this->author, $e, 'approve');
$this->action($this->author, $e, 'publish');
$this->assertFalse((bool) DB::table('portal_resources')->where('id', $this->resource)->value('independent_review'));
}
}
+45
View File
@@ -225,6 +225,51 @@ class PortalServicesTest extends TestCase
$this->assertDatabaseCount('portal_resource_links', 20);
}
public function test_public_document_lists_paginate_five_results_and_preserve_filters(): void
{
Storage::fake('local');
$this->withoutMiddleware(\Illuminate\Routing\Middleware\ThrottleRequests::class);
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAs($manager);
for ($number = 1; $number <= 12; $number++) {
$filename = sprintf('pagination-%02d.txt', $number);
$this->post('/management/portal-services/upload', [
'file' => UploadedFile::fake()->createWithContent($filename, 'pagination fixture '.$number),
])->assertRedirect()->assertSessionHasNoErrors();
$document = DB::table('documents')->where('file_name', $filename)->firstOrFail();
$id = $this->registerDocumentResource($document->id, sprintf('Pagination QA %02d', $number), [
'legislation' => true,
]);
if ($number <= 11) {
// The transaction-wrapped test does not run the after-commit scan job.
DB::table('documents')->where('id', $document->id)->update([
'status' => 'active', 'data_classification' => 'public',
'malware_scan_status' => 'clean', 'malware_scanned_sha256' => $document->sha256,
]);
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertSessionHasNoErrors();
}
}
auth()->logout();
foreach (['documentos', 'legislacao'] as $path) {
foreach ([1 => [5, 1, 5], 2 => [5, 6, 10], 3 => [1, 11, 11]] as $number => [$count, $from, $to]) {
$this->get('/'.$path.'?topic=Investimento&page='.$number)->assertOk()->assertInertia(fn (Assert $page) => $page
->has('resources.data', $count)->where('resources.total', 11)
->where('resources.current_page', $number)->where('resources.last_page', 3)
->where('resources.from', $from)->where('resources.to', $to)
->where('resources.data.0.title', sprintf('Pagination QA %02d', $from))
->where('resources.prev_page_url', fn ($url) => $number === 1 ? $url === null : str_contains($url, 'topic=Investimento') && str_contains($url, 'page='.($number - 1)))
->where('resources.next_page_url', fn ($url) => $number === 3 ? $url === null : str_contains($url, 'topic=Investimento') && str_contains($url, 'page='.($number + 1))));
}
$this->get('/'.$path.'?q=Pagination%20QA%2001')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('resources.data', 1)->where('resources.total', 1)->where('resources.data.0.title', 'Pagination QA 01'));
$this->get('/'.$path.'?q=nao-existe')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('resources.data', 0)->where('resources.total', 0));
}
}
public function test_legislation_with_an_identified_source_can_be_published_for_consultation_without_claiming_confirmation(): void
{
Storage::fake('local');
@@ -0,0 +1,183 @@
<?php
namespace Tests\Feature;
use App\Models\DevelopmentCorridor;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\Project;
use App\Models\User;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class PortfolioEditorialWorkflowTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $author;
private User $reviewer;
private InvestmentDossier $dossier;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
if (! Schema::hasColumn('portal_editorial_editions', 'dossier_id')) {
(require database_path('migrations/2026_11_13_230000_extend_editorial_editions_to_portfolio.php'))->up();
}
$this->withoutVite();
[$this->author, $this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email], 'portal.profile_access_enabled' => false,
'editorial_workflow.enabled' => true, 'editorial_workflow.portfolio' => true]);
$this->makeDossier('project');
}
private function makeDossier(string $kind): void
{
$model = match ($kind) {
'project' => Project::class, 'cluster' => EconomicCluster::class, 'corridor' => DevelopmentCorridor::class,
};
$entity = $model::create(['code' => 'ED-QA-'.bin2hex(random_bytes(6)), 'name' => 'Contexto sintético', 'status' => 'active', ...($kind === 'cluster' ? ['sector' => 'Energia'] : [])]);
$this->dossier = InvestmentDossier::create([$kind.'_id' => $entity->id, 'title' => 'Ficha pública sintética '.$kind, 'source' => 'Fonte sintética QA', 'content' => ['description' => 'Texto público original'],
'version_no' => 1, 'publication_status' => 'published', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Publicação sintética aceite em QA', 'published_at' => now()]);
}
private function edit(string $text = 'Alteração privada deliberada', int $status = 302, ?int $expected = null): ?\stdClass
{
$this->actingAsWithMfa($this->author);
$record = app(PortalEditorialWorkflow::class)->workingPortfolio($this->dossier->fresh());
$this->put('/management/portfolio/'.$record->id, ['version_no' => $expected ?? $record->version_no, 'title' => 'Novo título privado', 'source' => 'Fonte sintética revista', 'content' => ['description' => $text]])->assertStatus($status);
return app(PortalEditorialWorkflow::class)->latestPortfolio($record->id);
}
private function action(User $actor, \stdClass $edition, string $action, int $status = 200, array $extra = []): ?\stdClass
{
$this->actingAsWithMfa($actor);
$this->postJson('/management/editorial/portfolio/'.$this->dossier->id.'/editions/'.$edition->id,
['version' => $edition->version, 'action' => $action, 'reason' => 'Decisão fundamentada de demonstração em QA', ...$extra])->assertStatus($status);
return DB::table('portal_editorial_editions')->where('id', $edition->id)->first();
}
private function approve(\stdClass $edition): \stdClass
{
$edition = $this->action($this->author, $edition, 'submit', 200, ['assigned_to' => $this->reviewer->id]);
$edition = $this->action($this->reviewer, $edition, 'start_review');
return $this->action($this->reviewer, $edition, 'approve');
}
public function test_public_project_cluster_and_corridor_fiches_survive_private_edit_review_and_approval(): void
{
foreach (['project', 'cluster', 'corridor'] as $kind) {
if ($kind !== 'project') {
$this->makeDossier($kind);
}
$before = $this->dossier->fresh()->getAttributes();
$edition = $this->edit();
$this->assertSame($before, $this->dossier->fresh()->getAttributes());
$this->get('/carteira/'.$this->dossier->id)->assertOk()->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Texto público original'));
$this->get('/management/portfolio/'.$this->dossier->id)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Alteração privada deliberada')->where('editorialEnabled', true));
$this->edit('Edição obsoleta', 409, 1);
$edition = $this->approve($edition);
$this->assertSame($before, $this->dossier->fresh()->getAttributes());
$this->action($this->author, $edition, 'publish', 403);
$this->action($this->reviewer, $edition, 'publish');
$this->get('/carteira/'.$this->dossier->id)->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Alteração privada deliberada'));
$this->assertSame($this->dossier->id, $this->dossier->fresh()->id);
$this->assertSame($this->reviewer->id, $this->dossier->fresh()->reviewer_id);
if ($kind === 'corridor') {
$published = app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id);
$this->action($this->reviewer, $published, 'archive');
$this->get('/carteira/'.$this->dossier->id)->assertNotFound();
}
}
}
public function test_changed_context_and_edits_reset_decisions_and_old_publication_remains(): void
{
$edition = $this->approve($this->edit());
Project::whereKey($this->dossier->project_id)->update(['name' => 'Contexto revisto']);
$this->getJson('/management/editorial/portfolio/'.$this->dossier->id)->assertJsonPath('edition.fresh', false);
$this->action($this->reviewer, $edition, 'publish', 409);
$new = $this->edit('Nova edição após alteração do contexto');
$this->assertNull($new->approval);
$this->assertNull($new->legal_validation);
$this->action($this->reviewer, $edition, 'publish', 409);
$this->get('/carteira/'.$this->dossier->id)->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Texto público original'));
$this->getJson('/management/editorial/portfolio/'.$this->dossier->id.'?edition='.$edition->id)->assertJsonPath('current', false)->assertJsonPath('edition.id', $edition->id);
}
public function test_permissions_api_notice_scope_and_legacy_bypass_fail_closed(): void
{
$edition = $this->edit();
$this->post('/management/portfolio/'.$this->dossier->id.'/publish', ['version_no' => 1, 'approval_evidence' => 'Tentativa legada sintética'])->assertConflict();
$edition = $this->action($this->author, $edition, 'submit', 200, ['assigned_to' => $this->reviewer->id]);
$this->actingAsWithMfa($this->reviewer);
$this->getJson('/management/editorial')->assertOk()->assertJsonPath('portfolioUrl', '/management/portfolio')->assertJsonPath('portfolioPending', 1)
->assertJsonPath('notices.0.href', '/management/editorial/portfolio/'.$this->dossier->id.'?edition='.$edition->id);
$this->get('/gestao-conteudos')->assertInertia(fn (Assert $p) => $p->where('access.portfolio.index', '/management/portfolio'));
$other = User::factory()->create();
$this->actingAs($other)->getJson('/management/editorial/portfolio/'.$this->dossier->id)->assertForbidden();
$this->action($other, $edition, 'start_review', 403);
$this->actingAsWithMfa($this->reviewer);
session()->forget('portal.mfa_at');
$this->postJson('/management/editorial/portfolio/'.$this->dossier->id.'/editions/'.$edition->id, ['version' => $edition->version, 'action' => 'start_review', 'reason' => 'Motivo sintético QA'])->assertForbidden();
config(['editorial_workflow.portfolio' => false]);
$this->actingAsWithMfa($this->author);
$this->put('/management/portfolio/'.$this->dossier->id, ['version_no' => 1, 'title' => 'Não escrever', 'source' => 'Fonte QA', 'content' => ['description' => 'Não escrever']])->assertStatus(503);
$this->get('/carteira/'.$this->dossier->id)->assertOk();
$this->actingAsWithMfa($this->reviewer);
$this->getJson('/management/editorial')->assertJsonCount(0, 'notices');
}
public function test_revoked_reviewer_and_foreign_edition_cannot_publish_and_private_archive_preserves_public(): void
{
$firstId = $this->dossier->id;
$edition = $this->approve($this->edit());
$this->makeDossier('cluster');
$this->action($this->reviewer, $edition, 'publish', 404);
$this->getJson('/management/editorial/portfolio/'.$this->dossier->id.'?edition='.$edition->id)->assertNotFound();
$this->dossier = InvestmentDossier::findOrFail($firstId);
config(['portal.managers' => [$this->author->email]]);
// The author cannot publish, and a different authorised publisher must recheck the old reviewer.
$publisher = User::factory()->create();
config(['portal.managers' => [$this->author->email, $publisher->email]]);
$this->action($publisher, $edition, 'publish', 403);
$this->action($this->author, $edition, 'archive');
$this->get('/carteira/'.$this->dossier->id)->assertOk();
$this->assertSame('Texto público original', $this->dossier->fresh()->content['description']);
}
public function test_every_private_contributor_is_excluded_and_portfolio_history_cannot_be_removed(): void
{
$this->edit();
$this->actingAsWithMfa($this->reviewer);
$this->put('/management/portfolio/'.$this->dossier->id, ['version_no' => 2, 'title' => 'Colaboração privada', 'source' => 'Fonte sintética', 'content' => ['description' => 'Revisão deliberada pelo colaborador']])->assertRedirect();
$edition = app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id);
$edition = $this->action($this->author, $edition, 'submit');
$edition = $this->action($this->reviewer, $edition, 'start_review');
$this->action($this->reviewer, $edition, 'approve', 403);
$this->action($this->author, $edition, 'approve', 403);
Project::whereKey($this->dossier->project_id)->update(['name' => 'Contexto alterado; é necessária correcção']);
$this->action($this->reviewer, $edition, 'return');
$this->get('/management/portfolio/'.$this->dossier->id)->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Revisão deliberada pelo colaborador'));
try {
(require database_path('migrations/2026_11_13_230000_extend_editorial_editions_to_portfolio.php'))->down();
$this->fail('Histórico não vazio não pode ser eliminado.');
} catch (\RuntimeException $exception) {
$this->assertStringContainsString('Preserve portfolio', $exception->getMessage());
}
$this->assertTrue(Schema::hasColumn('portal_editorial_editions', 'dossier_id'));
$this->assertSame(3, DB::table('portal_editorial_editions')->where('dossier_id', $this->dossier->id)->count());
}
}
@@ -0,0 +1,213 @@
<?php
namespace Tests\Feature;
use App\Models\DevelopmentCorridor;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\Project;
use App\Models\User;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class PortfolioStructureEditorialTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $editor;
private User $reviewer;
private Model $entity;
private InvestmentDossier $dossier;
private string $kind;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
[$this->editor, $this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->editor->email, $this->reviewer->email], 'portal.profile_access_enabled' => false,
'editorial_workflow.enabled' => true, 'editorial_workflow.portfolio' => true]);
$this->fixture('projects');
}
private function fixture(string $kind): void
{
$this->kind = $kind;
$class = ['projects' => Project::class, 'clusters' => EconomicCluster::class, 'corridors' => DevelopmentCorridor::class][$kind];
$this->entity = $class::create(['code' => 'STRUCT-QA-'.bin2hex(random_bytes(5)), 'name' => 'Designação pública original', 'status' => 'active',
...($kind === 'clusters' ? ['sector' => 'Energia'] : ['description' => 'Descrição original']),
...($kind === 'projects' ? ['budget_amount' => '1500.25', 'budget_currency' => 'MZN'] : [])]);
$foreign = ['projects' => 'project_id', 'clusters' => 'cluster_id', 'corridors' => 'corridor_id'][$kind];
$this->dossier = InvestmentDossier::create([$foreign => $this->entity->getKey(), 'title' => 'Ficha sintética de dados-base', 'source' => 'Fonte sintética QA', 'content' => ['description' => 'Conteúdo público original'],
'version_no' => 1, 'publication_status' => 'published', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Publicação sintética de demonstração', 'published_at' => now()]);
}
private function fields(int $expected = 1): array
{
return ['editorial_version' => $expected, 'code' => $this->entity->getAttribute('code'), 'name' => 'Nova designação privada', 'status' => 'active',
...($this->kind === 'clusters' ? ['sector' => 'Indústria'] : ['description' => 'Descrição privada revista']),
...($this->kind === 'projects' ? ['budget_amount' => '999999999999999999.99', 'budget_currency' => 'USD'] : [])];
}
private function save(int $expected = 1): \stdClass
{
$this->actingAsWithMfa($this->editor);
$this->put('/management/'.$this->kind.'/'.$this->entity->getKey(), $this->fields($expected))->assertRedirect()->assertSessionHasNoErrors();
return app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id);
}
private function action(\stdClass $edition, string $action, int $status = 200): \stdClass
{
$actor = $action === 'submit' ? $this->editor : $this->reviewer;
$this->actingAsWithMfa($actor);
$this->postJson('/management/editorial/portfolio/'.$this->dossier->id.'/editions/'.$edition->id, ['version' => $edition->version, 'action' => $action, 'reason' => 'Decisão fundamentada de dados-base em QA'])->assertStatus($status);
return DB::table('portal_editorial_editions')->where('id', $edition->id)->first();
}
private function approve(\stdClass $edition): \stdClass
{
foreach (['submit', 'start_review', 'approve'] as $action) {
$edition = $this->action($edition, $action);
}
return $edition;
}
public function test_project_cluster_and_corridor_base_data_and_fiche_are_published_atomically_without_precision_loss(): void
{
foreach (['projects', 'clusters', 'corridors'] as $kind) {
if ($kind !== 'projects') {
$this->fixture($kind);
}
$before = $this->entity->fresh()->getAttributes();
$this->actingAsWithMfa($this->editor)->put('/management/portfolio/'.$this->dossier->id, ['version_no' => 1, 'title' => 'Título privado deliberado', 'source' => 'Fonte QA', 'content' => ['description' => 'Texto deliberado em paralelo']])->assertRedirect();
$edition = $this->save(2);
$this->assertSame($before, $this->entity->fresh()->getAttributes());
$this->get('/management/'.$kind.'/'.$this->entity->getKey().'/edit')->assertInertia(fn (Assert $p) => $p->where('record.name', 'Nova designação privada')->where('record.editorial_version', 3)->where('editorialDossier', $this->dossier->id));
$edition = $this->approve($edition);
$this->assertSame($before, $this->entity->fresh()->getAttributes());
$this->get('/carteira/'.$this->dossier->id)->assertInertia(fn (Assert $p) => $p->where('record.content.description', 'Conteúdo público original'));
$this->action($edition, 'publish');
$this->assertSame('Nova designação privada', $this->entity->fresh()->getAttribute('name'));
$this->assertSame('Texto deliberado em paralelo', $this->dossier->fresh()->content['description']);
if ($kind === 'projects') {
$this->assertSame('999999999999999999.99', $this->entity->fresh()->getAttribute('budget_amount'));
$this->get('/carteira/'.$this->dossier->id)->assertInertia(fn (Assert $p) => $p->where('anchorProject.name', 'Nova designação privada')->where('anchorProject.budget_currency', 'USD'));
}
$this->assertGreaterThan(0, DB::table('audit_events')->where('source_system', 'portal-management')->where('entity_id', $this->entity->getKey())->count());
if ($kind === 'corridors') {
$this->action(app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id), 'archive');
$this->entity->update(['name' => 'Actualização de contexto após arquivo']);
$this->get('/management/corridors/'.$this->entity->getKey().'/edit')->assertInertia(fn (Assert $p) => $p->where('record.name', 'Actualização de contexto após arquivo'));
}
$this->actingAsWithMfa($this->editor)->put('/management/portfolio/'.$this->dossier->id, ['version_no' => $this->dossier->fresh()->version_no, 'title' => 'Outra edição', 'source' => 'Fonte QA', 'content' => ['description' => 'Outra alteração narrativa']])->assertRedirect();
$next = app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id);
$this->assertArrayNotHasKey('_structure', app(PortalEditorialWorkflow::class)->payload($next)['resource']);
}
}
public function test_territory_is_staged_recovered_and_versioned_without_changing_the_public_location(): void
{
[$province, $district] = $this->locations();
$url = '/management/territories/projects/'.$this->entity->getKey();
$this->actingAsWithMfa($this->editor);
$this->postJson($url, ['version' => 0, 'path' => [$province, $district]])->assertOk()->assertJsonPath('version', 1)->assertJsonPath('pending_publication', true);
$this->assertNull($this->entity->fresh()->getAttribute('primary_territory_id'));
$this->getJson($url)->assertOk()->assertJsonPath('version', 1)->assertJsonPath('path.0.id', $district);
$this->postJson($url, ['version' => 0, 'path' => [$province]])->assertConflict();
$this->put('/management/projects/'.$this->entity->getKey(), $this->fields(1))->assertConflict();
$edition = $this->approve(app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id));
$this->assertNull($this->entity->fresh()->getAttribute('primary_territory_id'));
$this->action($edition, 'publish');
$this->assertSame($district, $this->entity->fresh()->getAttribute('primary_territory_id'));
$this->assertSame(1, (int) $this->entity->fresh()->getAttribute('territory_version'));
$this->assertSame(1, DB::table('audit_events')->where('source_system', 'investment-territory')->where('after_data->record_id', $this->entity->getKey())->count());
$this->actingAsWithMfa($this->editor)->postJson($url, ['version' => 1, 'path' => []])->assertOk()->assertJsonPath('pending_publication', true);
$this->assertSame($district, $this->entity->fresh()->getAttribute('primary_territory_id'));
$edition = $this->approve(app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id));
$this->action($edition, 'publish');
$this->assertNull($this->entity->fresh()->getAttribute('primary_territory_id'));
}
public function test_conflicting_code_after_approval_rolls_back_base_data_and_fiche_together(): void
{
$data = $this->fields();
$data['code'] = 'CONFLICT-QA-'.bin2hex(random_bytes(4));
$this->actingAsWithMfa($this->editor)->put('/management/projects/'.$this->entity->getKey(), $data)->assertRedirect();
$edition = $this->approve(app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id));
Project::create(['code' => $data['code'], 'name' => 'Outro registo sintético', 'status' => 'planned']);
$before = $this->entity->fresh()->getAttributes();
$fiche = $this->dossier->fresh()->getAttributes();
$this->action($edition, 'publish', 409);
$this->assertSame($before, $this->entity->fresh()->getAttributes());
$this->assertSame($fiche, $this->dossier->fresh()->getAttributes());
$this->assertSame('approved', app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id)->state);
}
public function test_changed_territory_evidence_requires_a_new_approval_and_cross_context_intents_are_rejected(): void
{
[$province, $district] = $this->locations();
$this->actingAsWithMfa($this->editor)->postJson('/management/territories/projects/'.$this->entity->getKey(), ['version' => 0, 'path' => [$province, $district]])->assertOk();
$edition = $this->approve(app(PortalEditorialWorkflow::class)->latestPortfolio($this->dossier->id));
DB::table('geo_locations')->where('id', $district)->update(['name' => 'Localização revista']);
$this->action($edition, 'publish', 409);
$other = Project::create(['code' => 'OTHER-QA-'.bin2hex(random_bytes(4)), 'name' => 'Outro contexto', 'status' => 'planned']);
$this->actingAsWithMfa($this->editor);
try {
app(PortalEditorialWorkflow::class)->saveStructure($this->editor, $other, $this->dossier, 2, ['name' => 'Não aplicar']);
$this->fail('Uma alteração não pode migrar para outro contexto.');
} catch (HttpException $exception) {
$this->assertSame(422, $exception->getStatusCode());
}
$this->assertNull($this->entity->fresh()->getAttribute('primary_territory_id'));
}
public function test_missing_mfa_and_disabling_cannot_bypass_private_structure_editions(): void
{
$this->actingAsWithMfa($this->editor);
session()->forget('portal.mfa_at');
$this->put('/management/projects/'.$this->entity->getKey(), $this->fields())->assertForbidden();
$this->save();
config(['editorial_workflow.portfolio' => false]);
$this->put('/management/projects/'.$this->entity->getKey(), $this->fields(2))->assertStatus(503);
$this->postJson('/management/territories/projects/'.$this->entity->getKey(), ['version' => 0, 'path' => []])->assertStatus(503);
$this->assertSame('Designação pública original', $this->entity->fresh()->getAttribute('name'));
}
public function test_archived_fiche_cannot_be_used_to_bypass_base_data_review(): void
{
$this->save();
$this->dossier->delete();
$this->put('/management/projects/'.$this->entity->getKey(), $this->fields(2))->assertConflict();
$this->assertSame('Designação pública original', $this->entity->fresh()->getAttribute('name'));
}
private function locations(): array
{
$parent = null;
$ids = [];
foreach (['country', 'province', 'district'] as $type) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Local sintético '.$type, 'location_type' => $type, 'parent_id' => $parent, 'data_classification' => 'public']);
$parent = $id;
$ids[$type] = $id;
}
return [$ids['province'], $ids['district']];
}
}
@@ -0,0 +1,358 @@
<?php
namespace Tests\Feature;
use App\Jobs\ScanDocumentForMalware;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\InvestorContext;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAdministration;
use App\Services\PrivateOfferConfidentiality;
use App\Services\PrivateOfferPreparation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Vite;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Testing\TestResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\CleanScannerFixture;
use Tests\TestCase;
final class PrivateOfferConfidentialityTest extends TestCase
{
use RefreshDatabase;
private const BASE = '/minhas-oportunidades/ofertas';
private const REASON = 'Operação exclusivamente sintética na base QA isolada.';
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
Storage::fake('local');
Queue::fake();
Mail::fake();
config(['portal.profile_access_enabled' => true, 'editorial_workflow.enabled' => true, 'private_offers.nda' => null]);
}
private function actor(?string $role = null, string $category = 'business_sale'): User
{
$actor = User::factory()->create(['two_factor_secret' => Crypt::encryptString('SYNTHETIC-QA'), 'two_factor_confirmed_at' => now()]);
if ($role) {
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $actor->id, 'role' => $role, 'organization_id' => null, 'responsibilities' => [], 'opportunity_types' => [$category], 'source' => 'synthetic-test-fixture']);
}
return $actor;
}
private function login(User $actor): static
{
$actor = $actor->fresh();
return $this->actingAs($actor)->withSession(['login.id' => null, 'portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $actor->fresh()->portal_access_revision]);
}
private function draft(User $owner, string $category = 'business_sale', array $details = []): Opportunity
{
$contact = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'PRIVATE-CONTACT-CANARY', 'source_system' => 'portal-user-contact', 'external_id' => 'user:'.$owner->id]);
$result = $this->login($owner)->postJson(self::BASE.'/rascunhos', ['creation_key' => (string) Str::uuid(), 'title' => 'Synthetic QA private offer',
'description' => 'PRIVATE-DESCRIPTION-CANARY', 'opportunity_category' => $category,
'private_offer' => ['price_mode' => 'amount', 'amount' => '100.01', 'currency' => 'MZN', 'contact_id' => $contact, ...$details], 'reason' => self::REASON])->assertCreated();
return Opportunity::findOrFail($result->json('record.id'));
}
private function etag(Opportunity $record): string
{
return app(OpportunityManagement::class)->etag($record->fresh());
}
private function approve(User $owner, Opportunity $record): void
{
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/submeter', ['etag' => $this->etag($record), 'confirm' => true])->assertOk();
$reviewer = $this->actor('validator', $record->opportunity_category);
foreach (['start_review', 'approve'] as $action) {
$this->login($reviewer)->postJson(self::BASE.'/'.$record->id.'/revisao', ['etag' => $this->etag($record), 'action' => $action, 'reason' => self::REASON])->assertOk();
}
}
private function nda(): array
{
// Deliberately non-legal bytes, never registered as an operational NDA.
$bytes = "%PDF-1.7\nSYNTHETIC QA - NOT A LEGAL AGREEMENT\n%%EOF";
$id = (string) Str::uuid();
$sha = hash('sha256', $bytes);
Storage::disk('local')->put('qa-nda/'.$id, Crypt::encryptString($bytes));
DB::table('documents')->insert(['id' => $id, 'file_name' => 'synthetic-qa.pdf', 'media_type' => 'application/pdf', 'storage_key' => 'qa-nda/'.$id,
'storage_encryption' => 'laravel', 'sha256' => $sha, 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => $sha,
'malware_engine' => 'QA-Test-Double', 'version_no' => 1, 'data_classification' => 'restricted']);
config(['private_offers.nda' => ['document_id' => $id, 'version' => 1, 'sha256' => $sha, 'approval_reference' => 'SYNTHETIC-QA-NOT-LEGAL']]);
return app(PrivateOfferConfidentiality::class)->nda();
}
private function command(Opportunity $offer, array $nda, string $action, array $extra = []): array
{
return ['action' => $action, 'version_hash' => $offer->fresh()->workflow_context['approval']['hash'], 'nda_sha256' => $nda['sha256'],
'nda_fingerprint' => $nda['fingerprint'], 'confirm' => true, 'reason' => self::REASON, ...$extra];
}
public function test_confirmed_specific_fields_save_recover_and_bind_the_editorial_version(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner, details: ['business' => ['revenue' => '10000000000000.01', 'cash_flow' => '-123.45', 'currency' => 'USD', 'reason' => 'PRIVATE-FINANCIAL-CANARY']]);
$this->login($owner)->getJson(self::BASE.'/'.$record->id)->assertOk()->assertJsonPath('record.values.private_offer.business.cash_flow', '-123.45');
$this->approve($owner, $record);
$this->assertSame('private-offer-editorial-v3', $record->fresh()->workflow_context['submission']['contract_version']);
$this->assertSame('-123.45', $record->fresh()->workflow_context['submission']['payload']['private_offer']['business']['cash_flow']);
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/guardar', ['etag' => $this->etag($record), 'private_offer' => ['business' => ['reason' => 'Changed']], 'reason' => self::REASON])->assertForbidden();
}
public function test_property_fields_are_optional_and_categories_and_unknown_fields_are_enforced(): void
{
$owner = $this->actor('promoter', 'real_estate');
$record = $this->draft($owner, 'real_estate', ['property' => ['transaction_type' => 'lease', 'property_type' => 'house', 'built_area' => '120.50', 'area_unit' => 'sqm', 'bedrooms' => 3, 'bathrooms' => 2, 'amenities' => ['Água', 'Acesso']]]);
$this->login($owner)->getJson(self::BASE.'/'.$record->id)->assertOk()->assertJsonPath('record.values.private_offer.property.bedrooms', 3);
foreach ([['business' => ['revenue' => '5', 'currency' => 'USD']], ['property' => ['title_certified' => true]], ['property' => ['property_type' => 'invented']]] as $invalid) {
$this->postJson(self::BASE.'/'.$record->id.'/guardar', ['etag' => $this->etag($record), 'private_offer' => $invalid, 'reason' => self::REASON])->assertUnprocessable();
}
$this->assertSame(3, app(OpportunityManagement::class)->values($record->fresh())['private_offer']['property']['bedrooms']);
}
public function test_six_photos_limit_includes_restoration_and_alternate_routes_and_cleans_failed_uploads(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$ids = [];
for ($index = 0; $index < 6; $index++) {
$response = $this->upload($owner, $record, 'images', $this->png('qa-'.$index.'.png', 400 + $index, 400));
$ids[] = $response->assertCreated()->json('id');
}
$this->upload($owner, $record, 'images', $this->png('seventh.png', 420, 420))->assertUnprocessable();
$this->assertDatabaseCount('opportunity_images', 6);
$this->assertCount(6, Storage::disk('local')->allFiles('opportunity-resources'));
$life = ['etag' => $this->etag($record), 'version' => 1, 'confirm' => true, 'action' => 'delete', 'reason' => self::REASON];
$this->postJson(self::BASE.'/'.$record->id.'/recursos/images/'.$ids[0], $life)->assertOk();
$this->upload($owner, $record, 'images', $this->png('new.png', 430, 430))->assertCreated();
$restore = [...$life, 'etag' => $this->etag($record), 'version' => 2, 'action' => 'restore'];
$this->postJson(self::BASE.'/'.$record->id.'/recursos/images/'.$ids[0], $restore)->assertUnprocessable();
// The accepted F1 guard closes the native promoter route for private offers.
$this->postJson('/minhas-oportunidades/'.$record->id.'/resources/images/'.$ids[0].'/lifecycle', $restore)->assertForbidden();
$this->assertSame(6, DB::table('opportunity_images')->whereNull('deleted_at')->count());
}
private function upload(User $owner, Opportunity $record, string $kind, UploadedFile $file, array $override = []): TestResponse
{
$payload = $kind === 'images' ? ['visibility' => 'internal', 'caption' => 'Synthetic QA', 'digitally_edited' => false] : ['visibility' => 'internal', 'classification' => 'restricted', 'category' => 'real_estate_proof'];
return $this->login($owner)->post(self::BASE.'/'.$record->id.'/recursos/'.$kind, ['etag' => $this->etag($record), 'creation_key' => (string) Str::uuid(), 'reason' => self::REASON,
'payload' => json_encode([...$payload, ...$override]), 'file' => $file], ['Accept' => 'application/json']);
}
/** Valid synthetic PNG bytes, independent of the optional GD extension. */
private function png(string $name, int $width, int $height): UploadedFile
{
$chunk = static fn (string $type, string $bytes): string => pack('N', strlen($bytes)).$type.$bytes.pack('N', crc32($type.$bytes));
$pixels = gzcompress(str_repeat("\0".str_repeat("\0", $width * 3), $height));
if ($pixels === false) {
throw new \RuntimeException('Synthetic PNG compression failed.');
}
return UploadedFile::fake()->createWithContent($name, "\x89PNG\r\n\x1a\n".$chunk('IHDR', pack('NNCCCCC', $width, $height, 8, 2, 0, 0, 0)).$chunk('IDAT', $pixels).$chunk('IEND', ''));
}
public function test_upload_validation_and_quarantine_do_not_grant_publication_or_read_access(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->upload($owner, $record, 'images', UploadedFile::fake()->createWithContent('fake.jpg', '<?php echo 1;'))->assertUnprocessable();
$this->upload($owner, $record, 'images', $this->png('small.png', 20, 20))->assertUnprocessable();
$this->upload($owner, $record, 'images', $this->png('edited.png', 400, 400), ['digitally_edited' => true])->assertUnprocessable();
$this->upload($owner, $record, 'images', $this->png('public.png', 400, 400), ['visibility' => 'public'])->assertUnprocessable();
$id = $this->upload($owner, $record, 'images', $this->png('good.png', 400, 400))->assertCreated()->json('id');
$this->getJson(self::BASE.'/'.$record->id.'/recursos/images/'.$id)->assertNotFound();
$this->postJson(self::BASE.'/'.$record->id.'/submeter', ['etag' => $this->etag($record), 'confirm' => true])->assertUnprocessable();
$this->assertSame('draft', $record->fresh()->status);
}
public function test_proof_bytes_are_encrypted_and_only_a_scoped_internal_validator_can_read_them(): void
{
$owner = $this->actor('promoter', 'real_estate');
$record = $this->draft($owner, 'real_estate');
$bytes = "%PDF-1.7\nSYNTHETIC QA PROPERTY PROOF - NOT A TITLE\n%%EOF";
$resourceId = $this->upload($owner, $record, 'documents', UploadedFile::fake()->createWithContent('qa.pdf', $bytes))->assertCreated()->json('id');
$link = DB::table('opportunity_documents')->where('id', $resourceId)->first();
$doc = DB::table('documents')->where('id', $link->document_id)->first();
$this->assertNotSame($bytes, Storage::disk('local')->get($doc->storage_key));
(new ScanDocumentForMalware($doc->id))->handle(new CleanScannerFixture);
$url = self::BASE.'/'.$record->id.'/recursos/documents/'.$resourceId;
$this->login($owner)->get($url)->assertForbidden();
$this->get('/minhas-oportunidades/'.$record->id.'/resources/documents/'.$resourceId.'/download')->assertForbidden();
$reviewer = $this->actor('validator', 'real_estate');
$this->login($reviewer)->get($url)->assertOk()->assertContent($bytes)->assertHeader('Cache-Control', 'no-store, private');
$this->login($this->actor('validator', 'business_sale'))->get($url)->assertForbidden();
$this->login($this->actor('auditor', 'real_estate'))->get($url)->assertForbidden();
$this->login($reviewer)->withSession(['portal.mfa_at' => time() - 1000])->get($url)->assertForbidden();
$this->assertGreaterThan(0, DB::table('audit_events')->where('action', 'offer_proof_access_authorized')->count());
$this->assertGreaterThan(0, DB::table('audit_events')->where('action', 'offer_proof_access_denied')->count());
}
public function test_nda_absence_keeps_access_closed_and_acceptance_alone_never_grants_access(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$interested = $this->actor();
$this->login($interested)->getJson(self::BASE.'/'.$record->id.'/confidencialidade')->assertOk()->assertJsonPath('nda_pending', true)->assertJsonPath('requests', []);
$this->getJson(self::BASE.'/'.$record->id.'/confidencial')->assertForbidden();
$this->get(self::BASE.'/'.$record->id.'/nda')->assertConflict();
$this->postJson(self::BASE.'/'.$record->id.'/confidencialidade', $this->command($record, ['sha256' => str_repeat('0', 64), 'fingerprint' => str_repeat('0', 64)], 'accept'))->assertConflict();
$nda = $this->nda();
$command = $this->command($record, $nda, 'accept');
unset($command['reason']); // Accepting an identified NDA does not require invented justification.
$this->postJson(self::BASE.'/'.$record->id.'/confidencialidade', $command)->assertOk();
$this->getJson(self::BASE.'/'.$record->id.'/confidencial')->assertForbidden();
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/confidencialidade', $this->command($record, $nda, 'authorize', ['interested_user_id' => $interested->id, 'acceptance_id' => (string) Str::uuid()]))->assertConflict();
}
public function test_both_conditions_exact_versions_revocation_and_audit_are_required_on_every_read(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner, details: ['business' => ['revenue' => '789.01', 'currency' => 'MZN', 'reason' => 'PRIVATE-FINANCIAL-CANARY']]);
$this->approve($owner, $record);
$nda = $this->nda();
$interested = $this->actor();
$url = self::BASE.'/'.$record->id;
$this->login($interested)->postJson($url.'/confidencialidade', $this->command($record, $nda, 'accept'))->assertOk();
$accept = $this->getJson($url.'/confidencialidade')->json('acceptance');
$grant = $this->command($record, $nda, 'authorize', ['interested_user_id' => $interested->id, 'acceptance_id' => $accept['id']]);
$this->login($this->actor('validator'))->postJson($url.'/confidencialidade', $grant)->assertForbidden();
$this->login($owner)->postJson($url.'/confidencialidade', $grant)->assertOk();
$data = $this->login($interested)->getJson($url.'/confidencial')->assertOk()->assertJsonPath('business.revenue', '789.01')->getContent();
$this->assertStringNotContainsString('PRIVATE-CONTACT-CANARY', $data);
$this->assertStringNotContainsString('PRIVATE-DESCRIPTION-CANARY', $data);
// NDA permission is a bounded read, not permission to copy the private
// Opportunity into another investment context or its downstream reports.
try {
app(InvestorContext::class)->reference('opportunity:'.$record->id);
$this->fail('An NDA grant must not grant private investment-context access.');
} catch (HttpException $error) {
$this->assertSame(404, $error->getStatusCode());
}
$this->login($this->actor())->getJson($url.'/confidencial')->assertForbidden();
$this->login($owner)->postJson($url.'/confidencialidade', $this->command($record, $nda, 'revoke', ['interested_user_id' => $interested->id]))->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertForbidden();
$this->assertSame(1, DB::table('audit_events')->where('action', 'offer_confidential_access')->count());
$this->assertSame(1, DB::table('audit_events')->where('action', 'offer_confidentiality_revoke')->count());
$this->assertNull($record->fresh()->published_at);
}
public function test_nda_version_changes_withdrawal_session_revocation_and_private_revision_close_access(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner, details: ['business' => ['revenue' => '900.00', 'currency' => 'USD', 'reason' => 'PRIVATE-VERSION-CANARY']]);
$this->approve($owner, $record);
$nda = $this->nda();
$interested = $this->actor();
$url = self::BASE.'/'.$record->id;
$authorize = function (array $currentNda) use ($owner, $record, $interested, $url) {
$this->login($interested)->postJson($url.'/confidencialidade', $this->command($record, $currentNda, 'accept'))->assertOk();
$acceptance = $this->getJson($url.'/confidencialidade')->json('acceptance');
$this->login($owner)->postJson($url.'/confidencialidade', $this->command($record, $currentNda, 'authorize', ['interested_user_id' => $interested->id, 'acceptance_id' => $acceptance['id']]))->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertOk();
};
$authorize($nda);
// Identical document bytes in another approved version do not reuse the acceptance.
DB::table('documents')->where('id', $nda['document_id'])->update(['version_no' => 2]);
config(['private_offers.nda.version' => 2]);
$this->getJson($url.'/confidencial')->assertForbidden();
$this->postJson($url.'/confidencialidade', $this->command($record, $nda, 'accept'))->assertConflict();
$nda = app(PrivateOfferConfidentiality::class)->nda();
$authorize($nda);
$this->postJson($url.'/confidencialidade', $this->command($record, $nda, 'withdraw'))->assertOk();
$this->getJson($url.'/confidencial')->assertForbidden();
$authorize($nda);
DB::table('users')->where('id', $interested->id)->increment('portal_access_revision');
$this->login($interested->fresh())->getJson($url.'/confidencial')->assertForbidden();
$authorize($nda);
$withdraw = $this->command($record, $nda, 'withdraw');
$this->login($owner)->postJson($url.'/revisao', ['etag' => $this->etag($record), 'action' => 'request_revision', 'reason' => self::REASON])->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertConflict();
$this->getJson($url.'/confidencialidade')->assertOk()->assertJsonPath('can_accept', false)->assertJsonPath('etag', null);
$this->postJson($url.'/confidencialidade', $withdraw)->assertOk();
$this->getJson('/api/v1/offers')->assertOk()->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers/'.$record->id)->assertNotFound();
$this->assertStringNotContainsString('PRIVATE-VERSION-CANARY', $this->get('/api/v1/offers/export')->assertOk()->streamedContent());
$this->getJson('/api/v1/offers/map')->assertOk()->assertJsonPath('features', []);
$this->assertSame(2, DB::table('audit_events')->where('action', 'offer_confidentiality_withdraw')->count());
}
public function test_nda_integrity_and_authority_loss_are_rechecked_without_exposing_the_company(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$interested = $this->actor();
$nda = $this->nda();
$url = self::BASE.'/'.$record->id;
$this->login($interested)->get($url.'/nda')->assertOk()->assertSee('SYNTHETIC QA - NOT A LEGAL AGREEMENT');
$this->postJson($url.'/confidencialidade', $this->command($record, $nda, 'accept'))->assertOk();
$accept = $this->getJson($url.'/confidencialidade')->json('acceptance');
$this->login($owner)->postJson($url.'/confidencialidade', $this->command($record, $nda, 'authorize', ['interested_user_id' => $interested->id, 'acceptance_id' => $accept['id']]))->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertOk();
DB::table('portal_role_assignments')->where('user_id', $owner->id)->where('role', 'promoter')->update(['revoked_at' => now()]);
$this->getJson($url.'/confidencial')->assertForbidden();
// Restore this synthetic fixture only, to isolate the byte-integrity check below.
DB::table('portal_role_assignments')->where('user_id', $owner->id)->where('role', 'promoter')->update(['revoked_at' => null]);
$doc = DB::table('documents')->where('id', $nda['document_id'])->first();
Storage::disk('local')->put($doc->storage_key, Crypt::encryptString('TAMPERED SYNTHETIC BYTES'));
$this->getJson($url.'/confidencial')->assertForbidden();
$this->getJson($url.'/confidencialidade')->assertOk()->assertJsonPath('nda_pending', true);
$this->assertNull($record->fresh()->published_at);
}
public function test_compiled_confidential_page_has_no_company_data_before_both_conditions(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner, details: ['business' => ['reason' => 'PRIVATE-HTML-CANARY']]);
$this->approve($owner, $record);
$directory = getenv('EDITORIAL_QA_BUILD_DIRECTORY') ?: 'build';
$manifest = json_decode(file_get_contents(public_path($directory.'/manifest.json')), true, 512, JSON_THROW_ON_ERROR);
$this->app->instance(Vite::class, (new Vite)->useBuildDirectory($directory)->useHotFile(storage_path('phpunit-offers-no-hot')));
$entry = 'resources/js/pages/offers/confidentiality.tsx';
$this->assertArrayHasKey($entry, $manifest);
$this->login($this->actor())->get(self::BASE.'/'.$record->id.'/confidencialidade', ['Accept' => 'text/html'])->assertOk()
->assertHeader('Cache-Control', 'no-store, private')->assertSee($manifest[$entry]['file'], false)->assertDontSee('PRIVATE-HTML-CANARY')->assertDontSee('PRIVATE-CONTACT-CANARY');
}
public function test_photo_metadata_and_original_are_bound_to_the_editorial_fingerprint(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$resourceId = $this->upload($owner, $record, 'images', $this->png('metadata.png', 400, 400))->assertCreated()->json('id');
$resource = DB::table('opportunity_images')->where('id', $resourceId)->first();
(new ScanDocumentForMalware($resource->document_id))->handle(new CleanScannerFixture);
$before = app(PrivateOfferPreparation::class)->snapshot($record->fresh());
$this->postJson(self::BASE.'/'.$record->id.'/recursos/images/'.$resourceId.'/guardar', ['etag' => $this->etag($record), 'version' => 1,
'payload' => ['visibility' => 'internal', 'caption' => 'Changed synthetic caption', 'digitally_edited' => true, 'edit_description' => 'Synthetic QA declared edit'], 'reason' => self::REASON])->assertOk();
$after = app(PrivateOfferPreparation::class)->snapshot($record->fresh());
$this->assertNotSame($before['hash'], $after['hash']);
$this->assertSame(1, $before['resources']['images'][$resourceId]['version']);
$this->assertSame(2, $after['resources']['images'][$resourceId]['version']);
$this->assertSame($resource->document_id, $after['resources']['images'][$resourceId]['document_id']);
$this->assertTrue($after['resources']['images'][$resourceId]['payload']['digitally_edited']);
$this->approve($owner, $record);
DB::table('documents')->where('id', $resource->document_id)->update(['status' => 'quarantined', 'malware_scan_status' => 'pending']);
$this->login($owner)->getJson(self::BASE.'/'.$record->id)->assertOk()->assertJsonPath('record.approvalFresh', false);
$this->postJson(self::BASE.'/'.$record->id.'/revisao', ['etag' => $this->etag($record), 'action' => 'request_revision', 'reason' => self::REASON])->assertOk()->assertJsonPath('record.state', 'needs_information')->assertJsonPath('record.canEdit', true);
}
}
+356
View File
@@ -0,0 +1,356 @@
<?php
namespace Tests\Feature;
use App\Jobs\NotifyPrivateOfferDecision;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityManagement;
use App\Services\OpportunityProfileWorkflow;
use App\Services\PortalEditorialWorkflow;
use App\Services\PortalProfileAdministration;
use App\Services\PrivateOfferPreparation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class PrivateOfferEditorialTest extends TestCase
{
use RefreshDatabase;
private const BASE = '/minhas-oportunidades/ofertas';
private const REASON = 'Decisão fundamentada exclusivamente com dados sintéticos QA.';
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
Mail::fake();
config(['portal.profile_access_enabled' => true, 'editorial_workflow.enabled' => true]);
}
private function actor(string $role, array $responsibilities = [], array $types = ['business_sale']): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC-QA'), 'two_factor_confirmed_at' => now()])->save();
$this->grant($user, $role, $responsibilities, $types);
return $user;
}
private function grant(User $user, string $role, array $responsibilities = [], array $types = ['business_sale']): void
{
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $user->id, 'role' => $role, 'organization_id' => null, 'responsibilities' => $responsibilities,
'opportunity_types' => $types, 'source' => 'synthetic-test-fixture',
]);
}
private function login(User $actor): static
{
return $this->actingAs($actor)->withSession(['login.id' => null, 'portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $actor->fresh()->portal_access_revision]);
}
private function draft(User $owner): array
{
$contact = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'Contacto sintético QA', 'email' => 'synthetic-'.Str::uuid().'@example.test',
'source_system' => 'portal-user-contact', 'external_id' => 'user:'.$owner->id]);
return $this->login($owner)->postJson(self::BASE.'/rascunhos', ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'business_sale',
'title' => 'Negócio sintético privado', 'description' => 'Oferta sintética para testar o circuito editorial privado.',
'private_offer' => ['contact_id' => $contact, 'price_mode' => 'amount', 'amount' => '12345.67', 'currency' => 'MZN'], 'reason' => self::REASON])->assertCreated()->json('record');
}
private function submit(User $actor, int $id): array
{
return $this->login($actor)->postJson(self::BASE.'/'.$id.'/submeter', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'confirm' => true])->assertOk()->json('record');
}
private function action(User $actor, int $id, string $action, array $extra = [], int $status = 200): array
{
return $this->login($actor)->postJson(self::BASE.'/'.$id.'/revisao', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)),
'action' => $action, 'reason' => self::REASON, ...$extra])->assertStatus($status)->json('record') ?? [];
}
public function test_submitted_offer_enters_existing_dashboard_and_private_approval_has_exact_snapshot_and_audit(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator', ['validation_coordinator']);
$draft = $this->draft($owner);
$submitted = $this->submit($owner, $draft['id']);
$this->assertSame('submitted', $submitted['state']);
$record = Opportunity::findOrFail($draft['id']);
$hash = $record->workflow_context['submission']['hash'];
$this->assertSame(1, DB::table('tasks')->where('source_system', 'opportunity-workflow')->count());
$this->assertSame(1, app(PortalEditorialWorkflow::class)->opportunityPending($reviewer));
$this->login($reviewer)->getJson('/management/editorial')->assertOk()->assertJsonPath('offersUrl', self::BASE)->assertJsonPath('opportunityPending', 1);
$this->get(self::BASE.'?state=submitted')->assertInertia(fn (Assert $page) => $page->has('records.data', 1)->where('records.data.0.id', $record->id));
$review = $this->action($reviewer, $record->id, 'start_review');
$this->assertSame('in_review', $review['state']);
$approved = $this->action($reviewer, $record->id, 'approve');
$this->assertSame('approved', $approved['state']);
$this->assertSame($hash, $approved['approval']['hash']);
$this->assertTrue($approved['approvalFresh']);
$this->assertFalse($approved['canEdit']);
$this->assertDatabaseHas('opportunities', ['id' => $record->id, 'status' => 'draft', 'published_at' => null]);
$this->assertDatabaseCount('portal_editorial_editions', 0);
$this->assertSame(0, DB::table('tasks')->where('task_type', 'opportunity_publication')->count());
$audit = DB::table('audit_events')->where('action', 'workflow_approve')->first();
$data = json_decode($audit->after_data, true, 512, JSON_THROW_ON_ERROR);
$this->assertSame($hash, $data['decision']['hash']);
$this->assertSame($hash, json_decode(Crypt::decryptString($data['snapshot']), true)['hash']);
$this->assertSame(0, Opportunity::published()->count());
}
public function test_rejection_revision_correction_resubmission_preserve_identity_decisions_and_versions(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$firstHash = Opportunity::findOrFail($id)->workflow_context['submission']['hash'];
$this->action($reviewer, $id, 'start_review');
$rejected = $this->action($reviewer, $id, 'reject');
$this->assertSame('rejected', $rejected['state']);
$this->login($owner)->postJson(self::BASE.'/'.$id.'/guardar', ['etag' => $rejected['etag'], 'title' => 'Contorno', 'reason' => self::REASON])->assertForbidden();
$revision = $this->action($owner, $id, 'request_revision');
$this->assertTrue($revision['canEdit']);
$saved = $this->login($owner)->postJson(self::BASE.'/'.$id.'/guardar', ['etag' => $revision['etag'], 'title' => 'Oferta sintética corrigida',
'private_offer' => ['price_mode' => 'negotiable', 'amount' => null, 'currency' => null, 'contact_id' => $revision['values']['private_offer']['contact_id']], 'reason' => self::REASON])->assertOk()->json('record');
$this->getJson(self::BASE.'/'.$id)->assertJsonPath('record.values.title', 'Oferta sintética corrigida');
$resubmitted = $this->submit($owner, $id);
$this->assertSame(2, Opportunity::findOrFail($id)->workflow_context['review_cycle']);
$resubmission = Opportunity::findOrFail($id)->workflow_context;
$this->assertSame($resubmission['submission']['record_version'], $resubmission['last_decision']['submitted_revision']);
$this->assertNotSame($firstHash, Opportunity::findOrFail($id)->workflow_context['submission']['hash']);
$tasks = DB::table('tasks')->where('source_system', 'opportunity-workflow')->count();
$notices = DB::table('portal_editorial_notifications')->count();
$this->login($owner)->postJson(self::BASE.'/'.$id.'/submeter', ['etag' => $resubmitted['etag'], 'confirm' => true])->assertOk();
$this->assertSame($tasks, DB::table('tasks')->where('source_system', 'opportunity-workflow')->count());
$this->assertSame($notices, DB::table('portal_editorial_notifications')->count());
$this->action($reviewer, $id, 'start_review');
$approved = $this->action($reviewer, $id, 'approve');
$this->assertSame(2, count($approved['submittedVersions']));
$this->assertSame(self::REASON, $approved['submittedVersions'][0]['rejection']['reason']);
$this->assertSame('Negócio sintético privado', $approved['submittedVersions'][0]['submission']['payload']['title']);
$this->assertSame('Oferta sintética corrigida', $approved['submittedVersions'][1]['submission']['payload']['title']);
$new = $this->action($owner, $id, 'request_revision');
$this->assertNull($new['approval']);
$this->assertNotNull($new['submittedVersions'][1]['approval']);
$this->assertSame(1, Opportunity::count());
}
public function test_return_requires_reason_and_common_field_and_preserves_fields_on_conflict(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
DB::table('opportunities')->where('id', $id)->increment('management_version');
$this->action($reviewer, $id, 'approve', ['etag' => $etag], 409);
$this->action($reviewer, $id, 'reject', ['reason' => ''], 422);
$this->action($reviewer, $id, 'request_correction', ['correction_items' => ['not_a_common_field']], 422);
$returned = $this->action($reviewer, $id, 'request_correction', ['correction_items' => ['title']]);
$this->assertSame('needs_information', $returned['state']);
$this->assertTrue($this->login($owner)->getJson(self::BASE.'/'.$id)->json('record.canEdit'));
$this->action($reviewer, $id, 'approve', ['etag' => $etag], 403);
$this->assertSame('Negócio sintético privado', Opportunity::findOrFail($id)->title);
}
public function test_author_contributor_wrong_scope_auditor_and_unassigned_reviewer_cannot_approve(): void
{
$owner = $this->actor('promoter');
$this->grant($owner, 'validator');
$reviewer = $this->actor('validator');
$other = $this->actor('validator');
$wrongScope = $this->actor('validator', [], ['real_estate']);
$auditor = $this->actor('auditor');
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$this->action($owner, $id, 'start_review', [], 403);
$this->action($wrongScope, $id, 'start_review', [], 403);
$this->action($reviewer, $id, 'start_review');
$this->action($owner, $id, 'approve', [], 403);
$this->action($other, $id, 'approve', [], 403);
$this->action($auditor, $id, 'approve', [], 403);
$context = Opportunity::findOrFail($id)->workflow_context;
DB::table('opportunities')->where('id', $id)->update(['workflow_context' => json_encode([...$context, 'contributors' => [...$context['contributors'], $reviewer->id]])]);
$this->action($reviewer, $id, 'approve', [], 403);
DB::table('opportunities')->where('id', $id)->update(['workflow_context' => json_encode($context)]);
$this->login($reviewer)->withSession(['portal.mfa_at' => time() - 1000])->postJson(self::BASE.'/'.$id.'/revisao', [
'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'action' => 'approve', 'reason' => self::REASON])->assertForbidden()->assertHeader('X-Portal-Reauthentication', 'required');
DB::table('portal_role_assignments')->where('user_id', $reviewer->id)->update(['revoked_at' => now()]);
$this->action($reviewer, $id, 'approve', [], 403);
$this->assertNull(Opportunity::findOrFail($id)->workflow_context['approval'] ?? null);
}
public function test_reference_changes_block_approval_and_signal_reconfirmation_without_overwriting_decision(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$draft = $this->draft($owner);
$id = $draft['id'];
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
DB::table('contacts')->where('id', $draft['values']['private_offer']['contact_id'])->update(['full_name' => 'Alteração sintética na fonte']);
$this->action($reviewer, $id, 'approve', [], 409);
$this->action($reviewer, $id, 'request_correction', ['correction_items' => ['contact']]);
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
$approved = $this->action($reviewer, $id, 'approve');
DB::table('contacts')->where('id', $draft['values']['private_offer']['contact_id'])->update(['full_name' => 'Segunda alteração sintética']);
$this->login($owner)->getJson(self::BASE.'/'.$id)->assertJsonPath('record.approvalFresh', false)->assertJsonPath('record.approval.hash', $approved['approval']['hash']);
$this->assertTrue($this->action($owner, $id, 'request_revision')['canEdit']);
}
public function test_phase_one_submission_is_bound_only_on_explicit_first_review(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
config(['editorial_workflow.enabled' => false]);
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$phase1 = Opportunity::findOrFail($id)->workflow_context['private_offer_preparation'];
config(['editorial_workflow.enabled' => true]);
$this->login($reviewer)->getJson(self::BASE.'/'.$id)->assertOk();
$this->assertNull(Opportunity::findOrFail($id)->workflow_context['submission'] ?? null);
$this->action($reviewer, $id, 'start_review');
$context = Opportunity::findOrFail($id)->workflow_context;
$this->assertSame($phase1, $context['phase1_submission']);
$this->assertSame($phase1['submitted_at'], $context['submission']['at']);
$this->assertSame($phase1['submitted_by'], $context['submission']['actor_id']);
$this->assertSame($phase1['submitted_revision'], $context['submission']['record_version']);
$this->assertSame('not_recorded', $context['phase1_binding']['original_reference_fingerprint']);
$this->action($reviewer, $id, 'approve');
}
public function test_notices_are_scoped_deduplicated_and_use_private_destination_email_rechecks_permission(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator', ['validation_coordinator']);
$foreign = $this->actor('validator', ['validation_coordinator'], ['real_estate']);
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$workflow = app(PortalEditorialWorkflow::class);
$notice = DB::table('portal_editorial_notifications')->where('user_id', $reviewer->id)->first();
$this->assertNotNull($notice);
$this->assertSame(0, DB::table('portal_editorial_notifications')->where('user_id', $foreign->id)->count());
$workflow->notifyOpportunity($owner, Opportunity::findOrFail($id), 'submit');
$this->assertSame(1, DB::table('portal_editorial_notifications')->where('user_id', $reviewer->id)->count());
$this->assertSame(self::BASE.'/'.$id, $workflow->notices($reviewer)[0]['href']);
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => [$reviewer->email]]);
Mail::swap(new MailManager($this->app));
$transport = Mail::mailer('array')->getSymfonyTransport();
(new NotifyPrivateOfferDecision($notice->id))->handle();
$this->assertCount(1, $transport->messages());
DB::table('portal_role_assignments')->where('user_id', $reviewer->id)->update(['revoked_at' => now()]);
$this->assertFalse($workflow->visibleNotice($reviewer, $notice));
(new NotifyPrivateOfferDecision($notice->id))->handle();
$this->assertCount(1, $transport->messages());
$this->login($reviewer)->getJson(self::BASE.'/'.$id)->assertForbidden();
}
public function test_publication_and_alternative_routes_remain_blocked_after_private_approval(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$publisher = $this->actor('publisher');
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
$this->action($reviewer, $id, 'approve');
$this->action($publisher, $id, 'publish', [], 422);
$this->login($publisher)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['action' => 'publish'])->assertForbidden();
$this->postJson('/minhas-oportunidades/'.$id.'/divulgacao/confirmar')->assertForbidden();
$record = Opportunity::findOrFail($id);
try {
app(OpportunityProfileWorkflow::class)->transition($publisher, $id, ['etag' => app(OpportunityManagement::class)->etag($record), 'action' => 'publish', 'reason' => self::REASON]);
$this->fail('Private approval was published.');
} catch (HttpException $exception) {
$this->assertSame(403, $exception->getStatusCode());
}
$this->assertSame(0, Opportunity::published()->count());
$this->getJson('/api/v1/opportunities/'.$record->slug)->assertNotFound();
$this->get('/oportunidades/'.$record->slug)->assertNotFound();
$this->assertDatabaseHas('opportunities', ['id' => $id, 'status' => 'draft', 'published_at' => null]);
}
public function test_rollback_preserves_draft_and_does_not_leave_tasks_notices_audit_or_send_mail(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator', ['validation_coordinator']);
$draft = $this->draft($owner);
$auditCount = DB::table('audit_events')->count();
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => [$reviewer->email]]);
Mail::swap(new MailManager($this->app));
$transport = Mail::mailer('array')->getSymfonyTransport();
try {
DB::transaction(function () use ($owner, $draft, $transport) {
app(PrivateOfferPreparation::class)->submit($owner, $draft['id'], ['etag' => $draft['etag'], 'confirm' => true]);
$this->assertCount(0, $transport->messages());
throw new \RuntimeException('synthetic QA rollback');
});
$this->fail('The synthetic transaction did not roll back.');
} catch (\RuntimeException $error) {
$this->assertSame('synthetic QA rollback', $error->getMessage());
}
$record = Opportunity::findOrFail($draft['id']);
$this->assertSame('draft', $record->workflow_context['private_offer_preparation']['state']);
$this->assertNull($record->first_submitted_at);
$this->assertDatabaseCount('tasks', 0);
$this->assertDatabaseCount('portal_editorial_notifications', 0);
$this->assertSame($auditCount, DB::table('audit_events')->count());
$this->assertCount(0, $transport->messages());
}
public function test_disabling_editorial_does_not_downgrade_a_phase_two_submission_to_phase_one(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
$this->action($reviewer, $id, 'request_correction', ['correction_items' => ['title']]);
$record = Opportunity::findOrFail($id);
$before = $record->getRawOriginal();
config(['editorial_workflow.enabled' => false]);
$this->login($owner)->postJson(self::BASE.'/'.$id.'/submeter', ['etag' => app(OpportunityManagement::class)->etag($record), 'confirm' => true])->assertStatus(503);
$this->assertSame($before, $record->fresh()->getRawOriginal());
$this->getJson(self::BASE.'/'.$id)->assertOk()->assertJsonPath('record.state', 'needs_information');
}
public function test_existing_coordinator_can_reassign_only_to_a_scoped_independent_validator(): void
{
$owner = $this->actor('promoter');
$reviewer = $this->actor('validator');
$replacement = $this->actor('validator');
$coordinator = $this->actor('validator', ['validation_coordinator']);
$wrong = $this->actor('validator', [], ['real_estate']);
$id = $this->draft($owner)['id'];
$this->submit($owner, $id);
$this->action($reviewer, $id, 'start_review');
$this->action($owner, $id, 'assign_review', ['assignee_user_id' => $replacement->id], 403);
$this->action($coordinator, $id, 'assign_review', ['assignee_user_id' => $wrong->id], 403);
$assigned = $this->action($coordinator, $id, 'assign_review', ['assignee_user_id' => $replacement->id]);
$this->assertSame('in_review', $assigned['state']);
$this->assertSame($replacement->id, Opportunity::findOrFail($id)->workflow_context['assignment']['assignee_user_id']);
$assignmentHistory = Opportunity::findOrFail($id)->workflow_context['assignment_history'];
$this->assertCount(2, $assignmentHistory);
$this->assertSame($reviewer->id, $assignmentHistory[1]['previous_assignee_user_id']);
$this->assertSame($replacement->id, $assignmentHistory[1]['assignee_user_id']);
$this->action($reviewer, $id, 'approve', [], 403);
$this->assertSame('approved', $this->action($replacement, $id, 'approve')['state']);
$this->assertDatabaseCount('opportunities', 1);
$this->assertSame(1, DB::table('tasks')->where('source_system', 'opportunity-workflow')->count());
}
}
@@ -0,0 +1,351 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OfferAvailability;
use App\Services\OfferPublicCatalogue;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAdministration;
use App\Services\PrivateOfferConfidentiality;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Vite;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Testing\TestResponse;
use Tests\TestCase;
final class PrivateOfferOperationsTest extends TestCase
{
use RefreshDatabase;
private const BASE = '/minhas-oportunidades/ofertas';
private const REASON = 'Fundamento exclusivamente sintético para ensaio QA isolado.';
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
Queue::fake();
Mail::fake();
Storage::fake('local');
config(['portal.profile_access_enabled' => true, 'editorial_workflow.enabled' => true, 'private_offers.validity_days' => null, 'private_offers.validity_policy_reference' => null]);
}
private function actor(?string $role = null, string $category = 'business_sale'): User
{
$actor = User::factory()->create(['two_factor_secret' => Crypt::encryptString('SYNTHETIC QA'), 'two_factor_confirmed_at' => now()]);
if ($role) {
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $actor->id,
'role' => $role, 'organization_id' => null, 'responsibilities' => [], 'opportunity_types' => [$category], 'source' => 'synthetic-test-fixture']);
}
return $actor;
}
private function login(User $actor): static
{
$actor = $actor->fresh();
return $this->actingAs($actor)->withSession(['login.id' => null, 'portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $actor->portal_access_revision]);
}
private function draft(User $owner): Opportunity
{
$contact = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'PRIVATE CONTACT CANARY', 'source_system' => 'portal-user-contact', 'external_id' => 'user:'.$owner->id]);
$id = $this->login($owner)->postJson(self::BASE.'/rascunhos', ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'business_sale', 'title' => 'PRIVATE TITLE CANARY',
'description' => 'PRIVATE DESCRIPTION CANARY', 'private_offer' => ['contact_id' => $contact, 'price_mode' => 'amount', 'amount' => '1200.01', 'currency' => 'MZN'], 'reason' => self::REASON])->assertCreated()->json('record.id');
return Opportunity::findOrFail($id);
}
private function etag(Opportunity $record): string
{
return app(OpportunityManagement::class)->etag($record->fresh());
}
private function approve(User $owner, Opportunity $record): void
{
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/submeter', ['etag' => $this->etag($record), 'confirm' => true])->assertOk();
$reviewer = $this->actor('validator');
foreach (['start_review', 'approve'] as $action) {
$this->login($reviewer)->postJson(self::BASE.'/'.$record->id.'/revisao', ['etag' => $this->etag($record), 'action' => $action, 'reason' => self::REASON])->assertOk();
}
}
private function publication(Opportunity $record, ?string $at = null): void
{
$record = $record->fresh();
$context = $record->workflow_context;
$payload = ['title' => 'Synthetic public summary', 'summary' => 'Safe synthetic summary.', 'category' => 'business_sale', 'province_id' => null, 'district_id' => null,
'price_mode' => 'amount', 'amount' => '1200.01', 'currency' => 'MZN'];
$hash = OfferPublicCatalogue::projectionHash($payload);
$context['offer_publication'] = ['contract' => OfferPublicCatalogue::CONTRACT, 'qa_fixture' => true, 'revision' => 1, 'payload' => $payload,
'approval' => ['state' => 'approved', 'hash' => $hash, 'actor_id' => 1, 'at' => now()->subYears(2)->toIso8601String()],
'publication' => ['state' => 'published', 'hash' => $hash, 'actor_id' => 2, 'at' => $at ?? now()->subHour()->toIso8601String()],
'offer_cycle' => $context['offer_operation']['cycle'] ?? 0, 'editorial_hash' => $context['approval']['hash'] ?? 'synthetic-legacy'];
$record->workflow_context = $context;
$record->save();
$this->app->instance(OfferPublicCatalogue::class, new OfferPublicCatalogue(true));
}
private function owner(User $actor, Opportunity $record, string $action, ?string $etag = null): TestResponse
{
return $this->login($actor)->postJson(self::BASE.'/'.$record->id.'/operacoes', ['action' => $action, 'etag' => $etag ?? $this->etag($record), 'confirm' => true]);
}
public function test_withdrawal_is_immediate_with_a_stale_form_and_excludes_every_public_consumer(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->publication($record);
$this->getJson('/api/v1/offers')->assertJsonPath('results.total', 1)->assertHeader('Cache-Control', 'no-store, private');
$this->owner($owner, $record, 'withdraw', str_repeat('0', 64))->assertOk()->assertJsonPath('availability.state', 'withdrawn');
$this->getJson('/api/v1/offers')->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers/'.$record->id)->assertNotFound();
$this->get('/ofertas/'.$record->id)->assertNotFound();
$this->getJson('/api/v1/offers/map')->assertJsonPath('matched_count', 0)->assertJsonPath('features', []);
$this->assertStringNotContainsString('Synthetic public summary', $this->get('/api/v1/offers/export')->streamedContent());
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->assertSame(1, DB::table('audit_events')->where('action', 'offer_withdrawn')->count());
$this->assertNotNull($record->fresh()->workflow_context['offer_publication']);
$this->assertNull($record->fresh()->published_at);
}
public function test_reactivation_requires_a_new_exact_validation_and_does_not_resurrect_old_publication(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$this->publication($record);
$old = $record->fresh()->workflow_context['approval']['hash'];
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->owner($owner, $record, 'reactivate')->assertConflict();
$this->owner($owner, $record, 'request_reactivation')->assertOk()->assertJsonPath('availability.state', 'revalidation');
$this->owner($owner, $record, 'reactivate')->assertConflict();
$this->approve($owner, $record);
$fresh = $record->fresh();
$this->assertNotSame($old, $fresh->workflow_context['approval']['hash']);
$this->assertSame(1, $fresh->workflow_context['submission']['payload']['operational_cycle']);
$this->owner($owner, $record, 'reactivate')->assertOk()->assertJsonPath('availability.state', 'available');
$this->getJson('/api/v1/offers/'.$record->id)->assertNotFound();
$this->publication($record);
$this->getJson('/api/v1/offers/'.$record->id)->assertOk()->assertJsonPath('data.title', 'Synthetic public summary');
$this->assertSame('draft', $record->fresh()->status);
$this->assertNull($record->fresh()->published_at);
}
public function test_withdrawal_during_review_can_be_reopened_by_the_owner_without_erasing_history(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/submeter', ['etag' => $this->etag($record), 'confirm' => true])->assertOk();
$submission = $record->fresh()->workflow_context['submission'];
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->owner($owner, $record, 'request_reactivation')->assertOk();
$history = $record->fresh()->workflow_context['decision_history'];
$this->assertSame($submission['hash'], end($history)['submission']['hash']);
$this->login($owner)->getJson(self::BASE.'/'.$record->id)->assertOk()->assertJsonPath('record.canEdit', true);
}
public function test_expiry_is_immediate_at_the_boundary_frozen_and_independent_of_nda_and_scheduler(): void
{
config(['private_offers.validity_days' => 7, 'private_offers.validity_policy_reference' => 'SYNTHETIC QA POLICY NOT A FINAL DEADLINE']);
$this->travelTo(now()->startOfSecond());
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$start = now()->toIso8601String();
$this->publication($record, $start);
$this->getJson('/api/v1/offers/'.$record->id)->assertOk()->assertJsonPath('data.expires_at', app(OfferAvailability::class)->record($record->fresh())['expires_at']);
config(['private_offers.validity_days' => 365, 'private_offers.nda' => null]);
$this->travel(7)->days();
$view = app(OfferAvailability::class)->record($record->fresh());
$this->assertSame('expired', $view['state']);
$this->getJson('/api/v1/offers?currency=MZN&min_amount=1')->assertOk()->assertJsonPath('results.total', 0);
$this->getJson('/api/v1/offers/'.$record->id)->assertNotFound();
$before = $record->fresh()->management_version;
$this->artisan('investmoz:offers-expire')->assertSuccessful();
$this->assertSame($before, $record->fresh()->management_version);
$this->artisan('investmoz:offers-expire', ['--confirm' => true])->assertSuccessful();
$this->artisan('investmoz:offers-expire', ['--confirm' => true])->assertSuccessful();
$this->assertSame(1, DB::table('audit_events')->where('action', 'offer_expired')->count());
$this->owner($owner, $record, 'reactivate')->assertConflict();
$this->travelBack();
}
public function test_no_deadline_is_invented_when_the_policy_is_pending(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$this->publication($record, now()->subYear()->toIso8601String());
$this->assertSame(['state' => 'available', 'expires_at' => null, 'policy_pending' => true], app(OfferAvailability::class)->record($record->fresh()));
$this->assertFalse(config('private_offers.expiry_scheduler_enabled'));
$this->assertNull(config('private_offers.validity_days'));
}
public function test_strangers_reviewers_wrong_scopes_and_auditors_cannot_withdraw_or_reactivate(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
foreach ([$this->actor(), $this->actor('promoter'), $this->actor('validator'), $this->actor('auditor')] as $other) {
$this->owner($other, $record, 'withdraw')->assertForbidden();
}
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->owner($owner, $record, 'request_reactivation', str_repeat('0', 64))->assertConflict();
$this->assertSame('withdrawn', app(OfferAvailability::class)->record($record->fresh())['state']);
}
public function test_reports_are_private_idempotent_and_treated_in_the_existing_dashboard_and_tasks(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->publication($record);
$reporter = $this->actor();
$key = (string) Str::uuid();
$input = ['client_key' => $key, 'reason' => 'PRIVATE REPORT CANARY with concrete synthetic facts.', 'confirm' => true];
$url = self::BASE.'/'.$record->id;
$this->login($reporter)->postJson($url.'/denuncias', $input)->assertCreated();
$this->postJson($url.'/denuncias', $input)->assertCreated()->assertJsonPath('replayed', true);
$this->postJson($url.'/denuncias', [...$input, 'reason' => self::REASON])->assertConflict();
$this->assertSame(1, DB::table('tasks')->where('task_type', 'offer_report_'.$key)->count());
$this->assertStringNotContainsString('PRIVATE REPORT CANARY', json_encode($record->fresh()->workflow_context));
$reviewer = $this->actor('validator');
$this->login($reviewer)->getJson('/management/editorial')->assertOk()->assertJsonPath('offerOperationsUrl', '/minhas-oportunidades/ofertas?operational=1');
$this->get(self::BASE.'?operational=1&pending_reports=1')->assertOk();
$this->getJson($url.'/operacoes')->assertOk()->assertJsonPath('reports.0.reason', $input['reason']);
$this->getJson($url.'/operacoes')->assertJsonPath('reports.0.source_snapshot.title', 'Synthetic public summary');
$handle = ['etag' => $this->etag($record), 'version' => 1, 'action' => 'start_review', 'reason' => self::REASON, 'confirm' => true];
$this->login($owner)->postJson($url.'/denuncias/'.$key, $handle)->assertForbidden();
$this->login($reviewer)->postJson($url.'/denuncias/'.$key, $handle)->assertOk();
$this->postJson($url.'/denuncias/'.$key, [...$handle, 'action' => 'resolve_withdrawal'])->assertConflict();
$this->postJson($url.'/denuncias/'.$key, [...$handle, 'etag' => $this->etag($record), 'version' => 2, 'action' => 'resolve_withdrawal'])->assertOk()->assertJsonPath('availability.state', 'withdrawn');
$this->assertSame('done', DB::table('tasks')->where('task_type', 'offer_report_'.$key)->value('status'));
$this->login($owner)->getJson($url.'/operacoes')->assertOk()->assertJsonPath('reports', []);
$this->getJson('/api/v1/offers/'.$record->id)->assertNotFound();
$this->login($reporter)->postJson($url.'/denuncias', $input)->assertCreated()->assertJsonPath('replayed', true);
}
public function test_drafts_cannot_be_reported_by_unrelated_users_and_report_read_requires_current_scope_and_mfa(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$other = $this->actor();
$this->login($other)->postJson(self::BASE.'/'.$record->id.'/denuncias', ['client_key' => (string) Str::uuid(), 'reason' => self::REASON, 'confirm' => true])->assertNotFound();
$this->getJson(self::BASE.'/'.$record->id.'/operacoes')->assertForbidden();
$this->login($this->actor('validator', 'real_estate'))->get(self::BASE.'?operational=1')->assertOk();
$this->getJson(self::BASE.'/'.$record->id.'/operacoes')->assertForbidden();
$this->login($this->actor('validator'))->withSession(['portal.mfa_at' => time() - 1000])->get(self::BASE.'?operational=1')->assertForbidden();
$this->login($this->actor('auditor'))->get(self::BASE.'?operational=1')->assertForbidden();
}
public function test_highlights_are_versioned_administrative_only_and_cannot_set_commercial_flags(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$publisher = $this->actor('publisher');
$url = self::BASE.'/'.$record->id;
$plan = ['etag' => $this->etag($record), 'version' => 0, 'label' => 'Synthetic plan', 'status' => 'draft', 'note' => self::REASON, 'confirm' => true, 'is_featured' => true, 'payment_enabled' => true];
$this->login($owner)->postJson($url.'/destaque-administrativo', $plan)->assertForbidden();
$this->login($this->actor('validator'))->postJson($url.'/destaque-administrativo', $plan)->assertForbidden();
$this->login($publisher)->postJson($url.'/destaque-administrativo', $plan)->assertOk()->assertJsonPath('commercial_activation', false);
$this->postJson($url.'/destaque-administrativo', $plan)->assertConflict();
$this->postJson($url.'/destaque-administrativo', [...$plan, 'etag' => $this->etag($record), 'version' => 1, 'status' => 'active'])->assertUnprocessable();
$this->postJson($url.'/destaque-administrativo', [...$plan, 'etag' => $this->etag($record), 'version' => 1, 'status' => 'archived'])->assertOk()->assertJsonPath('highlight.version', 2);
$this->assertFalse($record->fresh()->is_featured);
$this->assertNull($record->fresh()->published_at);
$this->login($owner)->getJson($url.'/operacoes')->assertJsonPath('highlight', null);
}
public function test_a_withdrawn_first_draft_still_requires_its_first_editorial_validation(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->owner($owner, $record, 'request_reactivation')->assertOk()->assertJsonPath('availability.state', 'revalidation');
$this->owner($owner, $record, 'reactivate')->assertConflict();
$this->approve($owner, $record);
$this->owner($owner, $record, 'reactivate')->assertOk();
$this->assertSame('draft', $record->fresh()->status);
}
public function test_withdrawal_and_revalidation_do_not_restore_previous_nda_grants(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$bytes = "%PDF-1.7\nSYNTHETIC QA NOT A LEGAL NDA\n%%EOF";
$docId = (string) Str::uuid();
$sha = hash('sha256', $bytes);
Storage::disk('local')->put('qa-nda/'.$docId, Crypt::encryptString($bytes));
DB::table('documents')->insert(['id' => $docId, 'file_name' => 'qa-only.pdf', 'media_type' => 'application/pdf', 'storage_key' => 'qa-nda/'.$docId, 'storage_encryption' => 'laravel',
'sha256' => $sha, 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => $sha, 'malware_engine' => 'QA-Test-Double', 'version_no' => 1, 'data_classification' => 'restricted']);
config(['private_offers.nda' => ['document_id' => $docId, 'version' => 1, 'sha256' => $sha, 'approval_reference' => 'SYNTHETIC QA NOT LEGAL APPROVAL']]);
$nda = app(PrivateOfferConfidentiality::class)->nda();
$interested = $this->actor();
$url = self::BASE.'/'.$record->id;
$input = ['action' => 'accept', 'confirm' => true, 'version_hash' => $record->fresh()->workflow_context['approval']['hash'], 'nda_sha256' => $sha, 'nda_fingerprint' => $nda['fingerprint']];
$this->login($interested)->postJson($url.'/confidencialidade', $input)->assertOk();
$acceptance = $this->getJson($url.'/confidencialidade')->json('acceptance');
$this->login($owner)->postJson($url.'/confidencialidade', [...$input, 'action' => 'authorize', 'interested_user_id' => $interested->id, 'acceptance_id' => $acceptance['id'], 'reason' => self::REASON])->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertOk();
$this->owner($owner, $record, 'withdraw')->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertConflict();
$this->owner($owner, $record, 'request_reactivation')->assertOk();
$this->approve($owner, $record);
$this->owner($owner, $record, 'reactivate')->assertOk();
$this->login($interested)->getJson($url.'/confidencial')->assertForbidden();
$this->assertSame($acceptance['id'], $record->fresh()->workflow_context['offer_confidentiality']['acceptances'][(string) $interested->id]['id']);
}
public function test_operational_and_report_screens_use_real_compiled_entries_and_private_cache_headers(): void
{
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$directory = getenv('EDITORIAL_QA_BUILD_DIRECTORY') ?: 'build';
$manifest = json_decode(file_get_contents(public_path($directory.'/manifest.json')), true, 512, JSON_THROW_ON_ERROR);
$this->app->instance(Vite::class, (new Vite)->useBuildDirectory($directory)->useHotFile(storage_path('phpunit-offers-no-hot')));
foreach (['offers/preparation' => self::BASE.'/'.$record->id, 'offers/report' => self::BASE.'/'.$record->id.'/denunciar'] as $page => $url) {
$key = 'resources/js/pages/'.$page.'.tsx';
$this->assertArrayHasKey($key, $manifest);
$response = $this->login($owner)->get($url, ['Accept' => 'text/html'])->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertSee($manifest[$key]['file'], false);
if ($page === 'offers/report') {
$response->assertDontSee('PRIVATE CONTACT CANARY')->assertDontSee('PRIVATE DESCRIPTION CANARY');
}
}
$reviewer = $this->actor('validator');
foreach (['offers/preparation-index' => self::BASE.'?operational=1', 'management/editorial-workflow' => '/management/editorial'] as $page => $url) {
$key = 'resources/js/pages/'.$page.'.tsx';
$this->assertArrayHasKey($key, $manifest);
$this->login($reviewer)->get($url, ['Accept' => 'text/html'])->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertSee($manifest[$key]['file'], false);
}
}
public function test_an_edited_private_approval_does_not_extend_the_existing_public_deadline(): void
{
config(['private_offers.validity_days' => 7, 'private_offers.validity_policy_reference' => 'SYNTHETIC QA FIRST']);
$owner = $this->actor('promoter');
$record = $this->draft($owner);
$this->approve($owner, $record);
$this->publication($record);
$deadline = app(OfferAvailability::class)->record($record->fresh())['expires_at'];
$this->login($owner)->postJson(self::BASE.'/'.$record->id.'/revisao', ['action' => 'request_revision', 'etag' => $this->etag($record), 'reason' => self::REASON])->assertOk();
$this->postJson(self::BASE.'/'.$record->id.'/guardar', ['title' => 'Changed private title', 'etag' => $this->etag($record), 'reason' => self::REASON])->assertOk();
config(['private_offers.validity_days' => 30, 'private_offers.validity_policy_reference' => 'SYNTHETIC QA SECOND']);
$this->approve($owner, $record);
$this->assertSame($deadline, app(OfferAvailability::class)->record($record->fresh())['expires_at']);
$context = $record->fresh()->workflow_context;
unset($context['offer_publication']['editorial_hash']);
$record->forceFill(['workflow_context' => $context])->save();
$this->assertSame($deadline, app(OfferAvailability::class)->record($record->fresh())['expires_at']);
$this->getJson('/api/v1/offers/'.$record->id)->assertOk()->assertJsonPath('data.title', 'Synthetic public summary');
}
}
@@ -0,0 +1,282 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityProfileWorkflow;
use App\Services\OpportunityPromotion;
use App\Services\PortalProfileAdministration;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Vite;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class PrivateOfferPreparationTest extends TestCase
{
use RefreshDatabase;
private const BASE = '/minhas-oportunidades/ofertas';
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
config(['portal.profile_access_enabled' => true]);
}
private function promoter(string $category = 'business_sale', ?string $organization = null): User
{
$user = User::factory()->create();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $user->id, 'role' => 'promoter', 'organization_id' => $organization,
'opportunity_types' => [$category], 'source' => 'synthetic-test-fixture',
]);
return $user;
}
private function payload(): array
{
return ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'business_sale',
'title' => 'Empresa sintética QA', 'description' => 'Descrição sintética privada para preparação de uma oferta.',
'private_offer' => ['price_mode' => 'amount', 'amount' => '123456.78', 'currency' => 'MZN', 'contact_id' => null],
'reason' => 'Preparação sintética da oferta na base isolada QA.'];
}
private function contact(User $owner): string
{
$id = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $id, 'full_name' => 'Contacto sintético QA', 'email' => 'offer-'.Str::uuid().'@example.test',
'phone' => '+258840000000', 'source_system' => 'portal-user-contact', 'external_id' => 'user:'.$owner->id]);
return $id;
}
public function test_private_creation_recovery_edit_conflict_and_idempotency_use_one_opportunity(): void
{
$actor = $this->promoter();
$payload = $this->payload();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $payload)->assertCreated()->json('record');
$this->postJson(self::BASE.'/rascunhos', $payload)->assertCreated()->assertJsonPath('record.id', $saved['id']);
$this->assertSame(1, Opportunity::count());
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'owner_user_id' => $actor->id, 'status' => 'draft', 'published_at' => null, 'estimated_investment_amount' => null]);
$this->getJson(self::BASE.'/'.$saved['id'])->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('record.values.private_offer.amount', '123456.78');
$this->get(self::BASE.'/'.$saved['id'])->assertInertia(fn (Assert $page) => $page->component('offers/preparation')->where('record.canEdit', true));
$updated = $this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'title' => 'Título revisto QA',
'private_offer' => ['price_mode' => 'negotiable', 'amount' => null, 'currency' => null], 'reason' => $payload['reason']])->assertOk()->json('record');
$this->assertSame($saved['id'], $updated['id']);
$this->getJson(self::BASE.'/'.$saved['id'])->assertJsonPath('record.values.title', 'Título revisto QA')->assertJsonPath('record.values.private_offer.price_mode', 'negotiable');
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'title' => 'Edição concorrente', 'reason' => $payload['reason']])->assertConflict();
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'title' => 'Título revisto QA']);
}
public function test_incomplete_draft_is_saved_but_submission_requires_common_fields_and_authorized_contact(): void
{
$actor = $this->promoter();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', ['creation_key' => (string) Str::uuid(),
'opportunity_category' => 'business_sale', 'private_offer' => ['price_mode' => null], 'reason' => $this->payload()['reason']])->assertCreated()->json('record');
$this->postJson(self::BASE.'/'.$saved['id'].'/submeter', ['etag' => $saved['etag'], 'confirm' => true])->assertUnprocessable()->assertJsonValidationErrors(['title', 'description', 'private_offer.contact_id']);
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'status' => 'draft', 'published_at' => null]);
}
public function test_submit_is_private_exact_version_confirmed_and_recoverable_without_editorial_actions(): void
{
$actor = $this->promoter();
$payload = $this->payload();
$payload['private_offer']['contact_id'] = $this->contact($actor);
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $payload)->assertCreated()->json('record');
$url = self::BASE.'/'.$saved['id'].'/submeter';
$this->postJson($url, ['etag' => $saved['etag'], 'confirm' => false])->assertUnprocessable();
$this->postJson($url, ['etag' => str_repeat('0', 64), 'confirm' => true])->assertConflict();
$submitted = $this->postJson($url, ['etag' => $saved['etag'], 'confirm' => true])->assertOk()->assertJsonPath('record.state', 'submitted')->assertJsonPath('record.canEdit', false)->json('record');
$this->postJson($url, ['etag' => $submitted['etag'], 'confirm' => true])->assertOk();
$this->getJson(self::BASE.'/'.$saved['id'])->assertOk()->assertJsonPath('record.state', 'submitted');
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $submitted['etag'], 'reason' => $payload['reason']])->assertForbidden();
$record = Opportunity::findOrFail($saved['id']);
$this->assertSame([], app(OpportunityProfileWorkflow::class)->actions($actor, $record));
$this->assertFalse(app(OpportunityPromotion::class)->allowed($actor, $record));
$this->assertNull($record->published_at);
$this->assertSame('draft', $record->status);
$this->assertSame(1, DB::table('audit_events')->where('action', 'private_offer_submitted')->count());
$this->assertDatabaseCount('portal_editorial_editions', 0);
$this->assertDatabaseCount('portal_editorial_notifications', 0);
}
public function test_other_accounts_ungranted_unverified_and_revoked_actors_cannot_operate(): void
{
$this->get(self::BASE.'/criar')->assertRedirect('/login');
$ungranted = User::factory()->create();
$this->actingAs($ungranted)->postJson(self::BASE.'/rascunhos', $this->payload())->assertForbidden();
$this->actingAs(User::factory()->unverified()->create())->get(self::BASE.'/criar')->assertRedirect('/email/verify');
$actor = $this->promoter();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $this->payload())->assertCreated()->json('record');
$other = $this->promoter();
$this->actingAs($other)->getJson(self::BASE.'/'.$saved['id'])->assertForbidden();
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag']])->assertForbidden();
$this->postJson(self::BASE.'/'.$saved['id'].'/submeter', ['etag' => $saved['etag'], 'confirm' => true])->assertForbidden();
$this->get(self::BASE)->assertInertia(fn (Assert $page) => $page->has('records.data', 0));
DB::table('portal_role_assignments')->where('user_id', $actor->id)->update(['starts_at' => now()->subHour(), 'expires_at' => now()->subMinute()]);
$this->actingAs($actor)->getJson(self::BASE.'/'.$saved['id'])->assertForbidden();
}
public function test_contact_scope_and_malicious_fields_roll_back_without_parallel_records(): void
{
$actor = $this->promoter();
$payload = $this->payload();
$payload['private_offer']['contact_id'] = $this->contact($this->promoter());
$this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $payload)->assertUnprocessable()->assertJsonValidationErrors('private_offer.contact_id');
$this->assertDatabaseCount('opportunities', 0);
$payload = $this->payload();
foreach (['status' => 'published', 'owner_user_id' => $actor->id, 'workflow_context' => ['publication' => ['visibility' => 'public']]] as $key => $value) {
$this->postJson(self::BASE.'/rascunhos', [...$payload, $key => $value])->assertUnprocessable();
}
$this->postJson(self::BASE.'/rascunhos', [...$payload, 'opportunity_category' => 'real_estate'])->assertForbidden();
$this->assertDatabaseCount('opportunities', 0);
}
public function test_price_contract_rejects_conversion_modes_precision_and_negotiable_amount(): void
{
$actor = $this->promoter();
foreach ([['price_mode' => 'amount', 'amount' => '10.123', 'currency' => 'MZN'], ['price_mode' => 'amount', 'amount' => '100', 'currency' => 'EUR'],
['price_mode' => 'negotiable', 'amount' => '100', 'currency' => 'USD'], ['price_mode' => 'amount', 'amount' => '-1', 'currency' => 'USD'], ['price_mode' => 'amount', 'amount' => 100.01, 'currency' => 'USD']] as $price) {
$this->actingAs($actor)->postJson(self::BASE.'/rascunhos', [...$this->payload(), 'private_offer' => $price])->assertUnprocessable();
}
$this->assertDatabaseCount('opportunities', 0);
}
public function test_no_public_exposure_and_native_routes_cannot_edit_or_publish_offer(): void
{
$actor = $this->promoter();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $this->payload())->assertCreated()->json('record');
$id = $saved['id'];
$this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $saved['etag'], 'title' => 'Contorno', 'reason' => $this->payload()['reason']])->assertForbidden();
foreach (['submit', 'approve', 'publish'] as $action) {
$this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $saved['etag'], 'action' => $action, 'reason' => $this->payload()['reason']])->assertForbidden();
}
$this->postJson('/minhas-oportunidades/'.$id.'/divulgacao/confirmar', [])->assertForbidden();
$this->get('/minhas-oportunidades/'.$id.'/edit')->assertRedirect(self::BASE.'/'.$id);
$record = Opportunity::findOrFail($id);
$this->assertFalse(app(OpportunityPromotion::class)->allowed($actor, $record));
$this->actingAs(User::factory()->create())->getJson('/api/v1/opportunities/'.$record->slug)->assertNotFound();
$this->get('/oportunidades/'.$record->slug)->assertNotFound();
$this->getJson('/api/v1/opportunities/search?q=Empresa')->assertOk()->assertJsonPath('total', 0);
// Defence in depth: even inconsistent data from an external writer is excluded.
DB::table('opportunities')->where('id', $id)->update(['status' => 'published', 'published_at' => now()->subMinute(),
'workflow_context' => json_encode([...$record->workflow_context, 'publication' => ['visibility' => 'public']])]);
$this->assertSame(0, Opportunity::published()->count());
$this->getJson('/api/v1/opportunities/'.$record->slug)->assertNotFound();
}
public function test_existing_opportunity_cannot_be_converted_through_offer_adapter(): void
{
$actor = $this->promoter();
$native = $this->actingAs($actor)->postJson('/minhas-oportunidades/drafts', $this->payload())->assertCreated()->json();
$this->getJson(self::BASE.'/'.$native['id'])->assertNotFound();
$this->postJson(self::BASE.'/'.$native['id'].'/guardar', ['etag' => $native['etag']])->assertNotFound();
$this->assertFalse(Opportunity::findOrFail($native['id'])->isPrivateOfferPreparation());
$publisher = User::factory()->create();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $publisher->id, 'role' => 'publisher', 'organization_id' => null,
'opportunity_types' => ['business_sale'], 'source' => 'synthetic-test-fixture',
]);
$this->assertTrue(app(OpportunityPromotion::class)->allowed($publisher, Opportunity::findOrFail($native['id'])));
$this->assertSame(1, Opportunity::count());
}
public function test_existing_contacts_registration_still_requires_fresh_mfa_and_submission_rechecks_contact(): void
{
$actor = $this->promoter();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $this->payload())->assertCreated()->json('record');
$data = ['etag' => $saved['etag'], 'full_name' => 'Contacto de teste QA', 'email' => 'private-offer@example.test', 'phone' => '+258840000001'];
$url = '/minhas-oportunidades/'.$saved['id'].'/contacts';
$this->postJson($url, $data)->assertForbidden();
$actor->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC-QA'), 'two_factor_confirmed_at' => now()])->save();
$this->withSession(['portal.mfa_actor' => $actor->id, 'portal.mfa_at' => time()]);
$contact = $this->postJson($url, $data)->assertOk()->json('contact');
$this->postJson($url, $data)->assertOk()->assertJsonPath('contact.id', $contact['id']);
$payload = $this->payload();
$payload['private_offer']['contact_id'] = $contact['id'];
$saved = $this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'private_offer' => $payload['private_offer'], 'reason' => $payload['reason']])->assertOk()->json('record');
DB::table('contacts')->where('id', $contact['id'])->update(['deleted_at' => now()]);
$this->postJson(self::BASE.'/'.$saved['id'].'/submeter', ['etag' => $saved['etag'], 'confirm' => true])->assertUnprocessable()->assertJsonValidationErrors('private_offer.contact_id');
$this->assertSame('draft', Opportunity::findOrFail($saved['id'])->workflow_context['private_offer_preparation']['state']);
}
public function test_model_cannot_publish_or_remove_private_phase_marker(): void
{
$actor = $this->promoter();
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $this->payload())->assertCreated()->json('record');
foreach ([['status' => 'published', 'published_at' => now()], ['workflow_context' => []]] as $change) {
try {
Opportunity::findOrFail($saved['id'])->forceFill($change)->save();
$this->fail('A preparação privada foi exposta ou convertida.');
} catch (HttpException $exception) {
$this->assertSame(403, $exception->getStatusCode());
}
}
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'status' => 'draft', 'published_at' => null]);
}
public function test_location_uses_existing_hierarchy_and_invalid_selection_never_saves(): void
{
$actor = $this->promoter();
$ids = [];
foreach (['country', 'province', 'district'] as $index => $type) {
$ids[$index] = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $ids[$index], 'code' => $ids[$index], 'name' => 'QA '.$type,
'location_type' => $type, 'parent_id' => $index ? $ids[$index - 1] : null, 'data_classification' => 'internal']);
}
$payload = [...$this->payload(), 'province_id' => $ids[1], 'district_id' => $ids[2]];
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $payload)->assertCreated()->json('record');
$this->getJson(self::BASE.'/'.$saved['id'])->assertOk()->assertJsonPath('record.territory.0.id', $ids[1])->assertJsonPath('record.territory.1.id', $ids[2]);
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'province_id' => $ids[2], 'district_id' => $ids[1], 'reason' => $payload['reason']])->assertUnprocessable();
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'primary_territory_id' => $ids[2]]);
}
public function test_full_html_uses_real_compiled_private_page_entries(): void
{
$actor = $this->promoter();
$directory = getenv('EDITORIAL_QA_BUILD_DIRECTORY') ?: 'build';
$manifest = json_decode(file_get_contents(public_path($directory.'/manifest.json')), true, 512, JSON_THROW_ON_ERROR);
$this->app->instance(Vite::class, (new Vite)->useBuildDirectory($directory)->useHotFile(storage_path('phpunit-offers-no-hot')));
$this->actingAs($actor);
foreach (['offers/preparation-index' => self::BASE, 'offers/preparation' => self::BASE.'/criar'] as $page => $url) {
$key = 'resources/js/pages/'.$page.'.tsx';
$this->assertArrayHasKey($key, $manifest);
$this->get($url, ['Accept' => 'text/html'])->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertSee($manifest[$key]['file'], false);
}
}
public function test_organization_representation_is_rechecked_and_other_organizations_are_not_assignable(): void
{
$organization = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $organization, 'name' => 'Organização sintética QA', 'organization_type' => 'private']);
$actor = $this->promoter('business_sale', $organization);
$membership = (string) Str::uuid();
DB::table('memberships')->insert(['id' => $membership, 'user_id' => $actor->id, 'organization_id' => $organization, 'role' => 'officer']);
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', [...$this->payload(), 'organization_id' => $organization])->assertCreated()->json('record');
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'organization_id' => null, 'reason' => $this->payload()['reason']])->assertForbidden();
DB::table('memberships')->where('id', $membership)->update(['deleted_at' => now()]);
$this->getJson(self::BASE.'/'.$saved['id'])->assertForbidden();
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'reason' => $this->payload()['reason']])->assertForbidden();
$this->assertDatabaseHas('opportunities', ['id' => $saved['id'], 'organization_id' => $organization]);
}
public function test_incomplete_price_is_preserved_but_cannot_be_submitted_and_invalid_structures_return_validation_errors(): void
{
$actor = $this->promoter();
$payload = $this->payload();
$payload['private_offer'] = ['price_mode' => 'amount', 'amount' => null, 'currency' => null, 'contact_id' => $this->contact($actor)];
$saved = $this->actingAs($actor)->postJson(self::BASE.'/rascunhos', $payload)->assertCreated()->json('record');
$this->getJson(self::BASE.'/'.$saved['id'])->assertJsonPath('record.values.private_offer.price_mode', 'amount');
$this->postJson(self::BASE.'/'.$saved['id'].'/submeter', ['etag' => $saved['etag'], 'confirm' => true])->assertUnprocessable()->assertJsonValidationErrors(['private_offer.amount', 'private_offer.currency']);
$this->postJson(self::BASE.'/rascunhos', [...$this->payload(), 'private_offer' => 'invalid'])->assertUnprocessable();
$this->postJson(self::BASE.'/'.$saved['id'].'/guardar', ['etag' => $saved['etag'], 'opportunity_category' => null, 'reason' => $payload['reason']])->assertUnprocessable();
$this->assertSame(1, Opportunity::count());
}
}
@@ -0,0 +1,297 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\ProactiveSupply;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class ProtectedSupplyAggregateTest extends TestCase
{
use DatabaseTransactions;
private User $owner;
private array $geo = [];
private array $sectors = [];
private array $activities = [];
private int $observationSequence = 0;
private string $sourceHash;
protected function setUp(): void
{
parent::setUp();
$db = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('sector_context_20261115_test', $db->name);
$this->assertSame(55441, (int) $db->port);
$this->withoutVite();
config(['portal.profile_access_enabled' => true, 'investor-path.enabled' => true, 'investor-path.protected_supply_enabled' => true, 'investor-path.aggregate_supply_qa_enabled' => false]);
$this->owner = User::factory()->create();
foreach (['country' => [null, 'country'], 'province' => ['country', 'province'], 'other_province' => ['country', 'province'], 'small' => ['province', 'district'], 'large' => ['province', 'district'], 'post' => ['large', 'admin_post'], 'locality_a' => ['post', 'locality'], 'locality_b' => ['post', 'locality']] as $key => [$parent, $type]) {
$id = (string) Str::uuid();
$this->geo[$key] = $id;
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent ? $this->geo[$parent] : null, 'name' => 'SYNTHETIC '.$key, 'code' => $id,
'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
}
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'published']);
foreach (['agro' => ['A', '01'], 'hotel' => ['I', '55'], 'infrastructure' => ['F', '41'], 'mining' => ['B', '07'], 'energy' => ['D', '35']] as $key => [$section, $division]) {
$sector = Sector::create(['name' => 'SYNTHETIC '.$key, 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors[$key] = $sector->id;
$parent = null;
foreach ([$section, $division, $division.'110'] as $index => $code) {
$id = (string) Str::uuid();
DB::table('economic_activities')->insert(['id' => $id, 'parent_id' => $parent, 'sector_id' => $index === 0 ? $sector->id : null,
'catalog_version_id' => $catalog, 'code' => $code, 'label_pt_mz' => 'SYNTHETIC public '.$key.' '.$code,
'status' => 'published', 'valid_from' => '2020-01-01']);
$parent = $id;
}
$this->activities[$key] = $parent;
}
$source = hash('sha256', Str::uuid());
$this->sourceHash = $source;
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'PRIVATE-ORIGINAL.xlsx', 'period' => '2020', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'a022ed9848b41ba342b4209414c2bbf2ebd0a7a3', 'access' => 'internal', 'synthetic' => true], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
foreach (['01', '55', '41', '07', '35'] as $division) {
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-'.$i, $this->geo[$i < 3 ? 'locality_a' : 'locality_b']);
}
for ($i = 0; $i < 4; $i++) {
$this->observation($source, $division, 'small-'.$i, $this->geo['small']);
}
for ($i = 0; $i < 5; $i++) {
$this->observation($source, $division, 'other-'.$i, $this->geo['other_province']);
}
for ($i = 0; $i < 6; $i++) {
$this->observation($source, $division, 'large-0', $this->geo['locality_a']);
}
}
}
private function observation(string $source, string $division, string $entity, string $territory): string
{
$id = hash('sha256', Str::uuid());
DB::table('proactive_supply_observations')->insert(['id' => $id, 'source_hash' => $source, 'sheet' => 'PRIVATE-SHEET', 'row_number' => ++$this->observationSequence,
'entity_key' => hash('sha256', $division.$entity), 'name' => 'PRIVATE-COMPANY-'.$entity, 'province' => 'PRIVATE', 'district' => 'PRIVATE',
'cae' => $division.'110', 'activity' => 'PRIVATE-CONTACT +258000000000', 'sector' => 'PRIVATE-RAW-SECTOR', 'source_date' => '2020', 'fingerprint' => $id,
'duplicate_of' => null, 'identity_conflict' => false, 'territory_id' => $territory, 'territory_resolution' => 'SYNTHETIC']);
return $id;
}
private function dossier(string $sector = 'agro', string $territory = 'locality_a'): string
{
$id = $this->actingAs($this->owner)->postJson('/investimentos', ['title' => 'SYNTHETIC deliberate '.$sector, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$v = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json('case.version');
$body = ['version' => $v, 'selection' => ['sector' => 'sector:'.$this->sectors[$sector], 'territory' => 'territory:'.$this->geo[$territory]],
'opportunity_choices' => [], 'declarations' => ['project_title' => 'SYNTHETIC deliberate '.$sector, 'products_services' => 'SYNTHETIC deliberate activity', 'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$hash = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json('preview_hash');
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $hash, 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
return $id;
}
private function aggregateSnapshot(string $id, array $extra = []): array
{
$version = $this->getJson('/investimentos/'.$id)->assertOk()->json('case.version');
return $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), ...$extra])->assertOk()->json('analysis');
}
public function test_five_sector_dossiers_save_recover_and_filter_only_protected_statistics(): void
{
$assignments = DB::table('portal_role_assignments')->count();
foreach (array_keys($this->sectors) as $sector) {
$id = $this->dossier($sector);
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities[$sector]]);
$this->assertSame(1, $a['privacy_version']);
$this->assertNull($a['entities']);
$this->assertNull($a['repeated']);
$this->assertNull($a['uncertain']);
$this->assertCount(1, $a['groups']);
$this->assertSame('5–9', $a['groups'][0]['entities_band']);
$this->assertSame('10–14', $a['groups'][0]['observations_band']);
$this->assertNull($a['groups'][0]['total']);
$this->assertSame($this->geo['large'], $a['groups'][0]['scope']['id']);
$this->assertTrue($a['broader_context']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertSame($this->activities[$sector], $a['filters']['activity_id']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
$v = $this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'supply_aggregates')->assertJsonPath('supply_aggregates.0.privacy_version', 1)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v - 1, 'operation_key' => $a['operation_key'], 'activity_id' => $this->activities[$sector]])->assertOk()->assertJsonPath('replayed', true);
$this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->assertJsonPath('prefill.simulator.investment_budget_min', '1000000')->assertJsonPath('prefill.simulator.investment_budget_max', '5000000')->assertJsonPath('prefill.simulator.project_title', 'SYNTHETIC deliberate '.$sector);
}
$this->assertSame($assignments, DB::table('portal_role_assignments')->count());
}
public function test_small_cells_and_differencing_do_not_reveal_exact_counts(): void
{
$id = $this->dossier();
$service = app(ProactiveSupply::class);
$fields = ['sector_id' => $this->sectors['agro']];
$before = DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope");
$local = $service->protectedAggregate($this->owner, $id, $this->geo['locality_a'], $fields);
$otherLocal = $service->protectedAggregate($this->owner, $id, $this->geo['locality_b'], $fields);
$district = $service->protectedAggregate($this->owner, $id, $this->geo['large'], $fields);
$province = $service->protectedAggregate($this->owner, $id, $this->geo['province'], $fields);
$small = $service->protectedAggregate($this->owner, $id, $this->geo['small'], $fields);
$this->assertSame($local['groups'], $otherLocal['groups']);
$this->assertSame($local['groups'], $district['groups']);
$this->assertSame($district['groups'], $province['groups']);
$this->assertSame([], $small['groups']);
$this->assertNull($province['entities']);
$this->assertNull($district['groups'][0]['total']);
$this->assertSame((array) $before, (array) DB::selectOne("select NULLIF(current_setting('app.actor_user_id',true),'') as actor,NULLIF(current_setting('app.proactive_supply_read',true),'') as scope"));
}
public function test_owner_isolation_no_raw_access_unknown_filter_rejection_and_disabled_guard(): void
{
$id = $this->dossier();
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$body = ['version' => $version, 'operation_key' => (string) Str::uuid()];
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'territory_id' => $this->geo['other_province']])->assertUnprocessable();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', [...$body, 'activity_id' => $this->activities['hotel']])->assertUnprocessable();
$this->getJson('/minhas-oportunidades/oferta-interna')->assertForbidden();
try {
app(ProactiveSupply::class)->authorize($this->owner);
$this->fail('Aggregate capability must not grant internal source access.');
} catch (HttpException $error) {
$this->assertSame(403, $error->getStatusCode());
}
$this->actingAs(User::factory()->create())->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertForbidden();
$this->getJson('/investimentos/'.$id)->assertForbidden();
$this->actingAs($this->owner);
$a = $this->aggregateSnapshot($id);
config(['investor-path.protected_supply_enabled' => false]);
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', $body)->assertNotFound();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates', [])->assertJsonPath('supply_aggregate_enabled', false);
config(['investor-path.protected_supply_enabled' => true]);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('supply_aggregates.0.operation_key', $a['operation_key']);
}
public function test_no_raw_export_no_guest_access_and_no_legacy_exact_history_disclosure(): void
{
$id = $this->dossier();
$a = $this->aggregateSnapshot($id, ['activity_id' => $this->activities['agro']]);
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => $a['operation_key'], 'activity_id' => null])->assertConflict();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid(), 'export' => 'csv'])->assertUnprocessable();
$this->getJson('/investimentos/'.$id.'/contexto/oferta-agregada?export=csv')->assertStatus(405);
$row = [...$a, 'PRIVATE-RAW' => 'PRIVATE-COMPANY', 'entities' => 1];
$row['groups'][0]['total'] = 1;
$row['groups'][0]['PRIVATE-CONTACT'] = 'PRIVATE-CONTACT';
$safe = app(ProactiveSupply::class)->protectedHistory([[...$a, 'privacy_version' => 0], $row]);
$this->assertCount(1, $safe);
$this->assertNull($safe[0]['entities']);
$this->assertNull($safe[0]['groups'][0]['total']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($safe, JSON_THROW_ON_ERROR));
$row['groups'][0]['entities_band'] = '1–1';
$this->assertSame([], app(ProactiveSupply::class)->protectedHistory([$row])[0]['groups']);
$this->app['auth']->forgetGuards();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $version, 'operation_key' => (string) Str::uuid()])->assertUnauthorized();
}
public function test_unpublished_classification_is_not_presented_as_an_empty_business_result(): void
{
$sector = Sector::create(['name' => 'SYNTHETIC without public CAE', 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors['without_cae'] = $sector->id;
$catalog = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $catalog, 'catalog_code' => 'qa-'.Str::random(16), 'version_no' => 1, 'source_system' => 'SYNTHETIC', 'source_version' => 'SYNTHETIC', 'source_reference' => 'SYNTHETIC', 'status' => 'draft']);
DB::table('economic_activities')->insert(['id' => (string) Str::uuid(), 'sector_id' => $sector->id, 'catalog_version_id' => $catalog, 'code' => '01', 'label_pt_mz' => 'SYNTHETIC unpublished division', 'status' => 'draft', 'valid_from' => '2020-01-01']);
$id = $this->dossier('without_cae', 'locality_a');
$before = $this->actingAs($this->owner)->getJson('/investimentos/'.$id)->assertOk()->json();
$response = $this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $before['case']['version'], 'operation_key' => (string) Str::uuid(), 'activity_id' => null])->assertUnprocessable();
$this->assertStringContainsString('não significa ausência de empresas', $response->json('message'));
$after = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->assertSame($before['case']['version'], $after['case']['version']);
$this->assertSame([], $after['supply_aggregates']);
$this->assertContains('ebau:979', array_column($after['supply_activity_options'], 'id'));
}
public function test_accepted_source_classification_works_by_code_or_exact_label_without_public_numeric_catalogue(): void
{
$sector = Sector::create(['name' => 'SYNTHETIC general tourism', 'slug' => 'qa-'.Str::lower(Str::random(16)), 'is_active' => true]);
$this->sectors['source_only'] = $sector->id;
$id = $this->dossier('source_only');
DB::table('proactive_supply_observations')->where('source_hash', $this->sourceHash)->where('cae', '55110')->update(['cae' => '55111', 'activity' => 'HOTÉIS COM RESTAURANTE']);
$coded = $this->aggregateSnapshot($id, ['classification_key' => 'ebau:979']);
$this->assertSame('55', $coded['groups'][0]['code']);
$this->assertSame('5–9', $coded['groups'][0]['entities_band']);
$this->assertSame('ebau:979', $coded['filters']['classification_key']);
$this->assertSame($sector->id, $coded['filters']['sector_id']);
DB::table('proactive_supply_observations')->where('source_hash', $this->sourceHash)->where('cae', '55111')->update(['cae' => '']);
$labelled = $this->aggregateSnapshot($id, ['classification_key' => 'ebau:979']);
$this->assertSame($coded['groups'], $labelled['groups']);
for ($i = 0; $i < 6; $i++) {
$row = $this->observation($this->sourceHash, '56', 'restaurant-'.$i, $this->geo['large']);
DB::table('proactive_supply_observations')->where('id', $row)->update(['cae' => '', 'activity' => 'RESTAURANTES (INCLUI ACTIVIDADES DE RESTAURAÇÃO EM MEIOS MÓVEIS)']);
}
$restaurant = $this->aggregateSnapshot($id, ['classification_key' => 'ebau:345']);
$this->assertSame('56', $restaurant['groups'][0]['code']);
$this->assertSame('5–9', $restaurant['groups'][0]['entities_band']);
$after = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->assertCount(3, $after['supply_aggregates']);
$this->assertSame('ebau:345', $after['supply_aggregates'][2]['filters']['classification_key']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($after['supply_aggregates'], JSON_THROW_ON_ERROR));
$this->assertSame('1000000', $after['investment_context']['fields']['investment_budget_min']);
}
public function test_conflicting_and_unidentified_source_classifications_are_not_invented_matches(): void
{
$id = $this->dossier('hotel');
DB::table('proactive_supply_observations')->where('source_hash', $this->sourceHash)->where('cae', '55110')->update(['cae' => '01', 'activity' => 'HOTÉIS COM RESTAURANTE']);
$a = $this->aggregateSnapshot($id, ['classification_key' => 'ebau:979']);
$this->assertSame([], $a['groups']);
$v = $this->getJson('/investimentos/'.$id)->json('case.version');
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v, 'operation_key' => (string) Str::uuid(), 'classification_key' => 'ebau:99999999'])->assertUnprocessable();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v, 'operation_key' => (string) Str::uuid(), 'classification_key' => 'ebau:979', 'activity_id' => $this->activities['hotel']])->assertUnprocessable();
$this->actingAs(User::factory()->create())->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $v, 'operation_key' => (string) Str::uuid(), 'classification_key' => 'ebau:979'])->assertForbidden();
}
public function test_previously_accepted_tourism_scope_is_accommodation_without_inventing_a_specific_subtype(): void
{
$source = 'f02e086ed4973ef17234aa6cc54b98fbb7a6952ffb16ec4dc4f7d0c72af6400c';
$this->assertFalse(DB::table('proactive_supply_sources')->where('sha256', $source)->exists(), 'Only isolated synthetic source allowed');
DB::table('proactive_supply_sources')->insert(['sha256' => $source, 'name' => 'SYNTHETIC accepted tourism contract', 'period' => '2024', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'a022ed9848b41ba342b4209414c2bbf2ebd0a7a3', 'access' => 'internal', 'synthetic' => true], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
for ($i = 0; $i < 6; $i++) {
$row = $this->observation($source, '55', 'tourism-broad-'.$i, $this->geo['large']);
DB::table('proactive_supply_observations')->where('id', $row)->update(['cae' => '', 'activity' => 'Alojamento (âmbito do exemplar; categoria por conferir)']);
}
$id = $this->dossier('hotel');
$a = $this->aggregateSnapshot($id, ['classification_key' => 'ebau:158']);
$this->assertSame('ALOJAMENTO', $a['groups'][0]['label']);
$this->assertSame('5–9', $a['groups'][0]['entities_band']);
$this->assertStringNotContainsString('HOTÉIS COM RESTAURANTE', $a['groups'][0]['label']);
}
public function test_unresolved_observation_keys_conflicts_duplicates_and_unknown_import_contracts_do_not_form_a_publishable_cohort(): void
{
$unknown = hash('sha256', Str::uuid());
DB::table('proactive_supply_sources')->insert(['sha256' => $unknown, 'name' => 'PRIVATE-FUTURE-SOURCE', 'period' => '2025', 'limitations' => 'SYNTHETIC', 'receipt' => json_encode(['candidate' => 'UNKNOWN', 'access' => 'internal'], JSON_THROW_ON_ERROR), 'imported_at' => now()]);
for ($i = 0; $i < 6; $i++) {
$id = $this->observation($this->sourceHash, '01', 'unresolved-'.$i, $this->geo['small']);
$unresolved = hash('sha256', 'unresolved:'.$this->sourceHash.'|PRIVATE-SHEET|'.$this->observationSequence);
DB::table('proactive_supply_observations')->where('id', $id)->update(['entity_key' => $unresolved]);
$conflict = $this->observation($this->sourceHash, '01', 'conflict-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $conflict)->update(['identity_conflict' => true]);
$duplicate = $this->observation($this->sourceHash, '01', 'duplicate-'.$i, $this->geo['small']);
DB::table('proactive_supply_observations')->where('id', $duplicate)->update(['duplicate_of' => $id]);
$this->observation($unknown, '01', 'unknown-'.$i, $this->geo['small']);
}
$id = $this->dossier('agro', 'small');
$a = $this->aggregateSnapshot($id);
$this->assertSame([], $a['groups']);
$this->assertNull($a['entities']);
$this->assertSame('2020', $a['source_summary']['period']);
$this->assertStringNotContainsString('PRIVATE-', json_encode($a, JSON_THROW_ON_ERROR));
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\LegacyContent;
use App\Services\SectorContentAnalysis;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\TestCase;
final class SectorContentAnalysisTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('sector_context_20261115_test', $identity->name);
$this->assertSame(55441, (int) $identity->port);
$this->withoutVite();
Storage::fake('local');
config(['portal.legacy_content_qa_enabled' => true, 'investor-path.enabled' => true]);
}
private function source(string $sector, int $legacy = 999999): array
{
$s = Sector::firstOrCreate(['slug' => $sector], ['name' => 'SYNTHETIC '.$sector, 'is_active' => true]);
$slug = match ($sector) {
'energia-especifica' => 'energia', default => $sector
};
$external = 'post-'.$legacy.'-synthetic-sector-'.Str::random(10);
$url = 'https://example.invalid/'.$slug;
config(['legacy_content.articles.'.$slug => ['external_id' => $external, 'source_url' => $url,
'group' => $sector === 'mineracao' || $sector === 'energia-especifica' ? 'energia-mineracao' : $sector,
'sector_slug' => $sector, 'publishable' => true]]);
$id = (string) Str::uuid();
$quote = 'SYNTHETIC: hotelaria, turismo cultural, conservacao; produção agrícola, processamento, logística, água, saneamento, construção, geração e distribuição de electricidade. Não representa uma oferta aberta.';
$bytes = json_encode(['format' => 'investmoz-legacy-article-v1', 'source_url' => $url,
'content_html' => '<h2>Contexto sintetico</h2><p>'.$quote.'</p>',
'title' => 'SYNTHETIC context', 'author' => 'SYNTHETIC', 'legacy_id' => $legacy,
'legacy_category' => 'SYNTHETIC', 'published_at' => '2026-01-01', 'modified_at' => '2026-01-02'], JSON_THROW_ON_ERROR);
Storage::disk('local')->put('synthetic/'.$id, $bytes);
DB::table('documents')->insert(['id' => $id, 'source_system' => 'synthetic-test', 'external_id' => $external,
'file_name' => 'synthetic.json', 'media_type' => 'application/json', 'storage_key' => 'synthetic/'.$id,
'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes),
'malware_scan_status' => 'clean', 'size_bytes' => strlen($bytes), 'status' => 'active',
'rights_status' => 'authorized', 'data_classification' => 'public']);
$resource = DB::table('portal_resources')->insertGetId(['document_id' => $id, 'title' => 'SYNTHETIC context',
'category' => 'education', 'topic' => $sector, 'published' => true, 'rights_status' => 'authorized',
'source_url' => $url, 'source_reference' => 'SYNTHETIC', 'metadata_version' => 1]);
return [app(LegacyContent::class)->article($slug, false), $resource, $slug];
}
public function test_five_sectors_save_the_exact_passage_in_the_same_dossier_without_an_advert_and_isolate_accounts(): void
{
$owner = User::factory()->create();
$stranger = User::factory()->create();
$country = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $country, 'name' => 'SYNTHETIC country', 'code' => $country,
'location_type' => 'country', 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$country]);
$territory = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $territory, 'parent_id' => $country, 'name' => 'SYNTHETIC outside zones', 'code' => $territory,
'location_type' => 'province', 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$territory]);
config(['investor-path.aggregate_supply_qa_enabled' => true]);
foreach (['turismo', 'agronegocio', 'infraestruturas', 'mineracao', 'energia-especifica'] as $sector) {
[$article, $resource, $slug] = $this->source($sector);
$idea = $article['sector_analysis']['ideas'][0];
$input = ['evidence' => $idea['evidence']['key'], 'source_sha256' => $article['sha256'], 'source_version' => $article['version'], 'idea' => $idea['title']];
$this->actingAs($owner)->get('/investimentos/a-partir-de/'.$slug.'?'.http_build_query($input))->assertOk();
$before = DB::table('opportunities')->count();
$id = $this->postJson('/investimentos', ['title' => 'SYNTHETIC '.$sector, 'client_key' => (string) Str::uuid(),
'reuse_consent' => true, 'content_resource_id' => $resource, ...$input])->assertCreated()->json('id');
$view = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->assertSame($id, $view['case']['id']);
$this->assertSame($idea['evidence']['quote'], $view['content_sources'][0]['analyses'][0]['quote']);
$this->assertSame($article['sha256'], $view['content_sources'][0]['analyses'][0]['source_sha256']);
$this->assertFalse($view['content_sources'][0]['analyses'][0]['open_participation']);
$this->assertSame($before, DB::table('opportunities')->count());
$context = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$body = ['version' => $context['case']['version'], 'selection' => ['sector' => 'sector:'.$article['sector']['id'], 'territory' => 'territory:'.$territory],
'opportunity_choices' => [], 'declarations' => ['project_title' => 'SYNTHETIC '.$sector, 'products_services' => $idea['title'],
'currency' => 'MZN', 'investment_budget_min' => '1000000', 'investment_budget_max' => '5000000']];
$plan = $this->postJson('/investimentos/'.$id.'/contexto/previa', $body)->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/contexto/confirmar', [...$body, 'preview_hash' => $plan['preview_hash'], 'operation_key' => (string) Str::uuid(), 'confirm' => true])->assertOk();
$context = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/contexto/oferta-agregada', ['version' => $context['case']['version'], 'operation_key' => (string) Str::uuid()])->assertOk()->assertJsonPath('analysis.coverage_unknown', true);
$context = $this->getJson('/investimentos/'.$id.'/contexto')->assertOk()->json();
$economic = array_filter($context['prefill']['simulator'], fn ($k) => ! str_ends_with($k, '_label') && $k !== 'email', ARRAY_FILTER_USE_KEY);
$economic = [...$economic, 'purpose' => 'own_investment', 'total_investment' => '2000000', 'secured_amount' => '1000000', 'annual_revenue' => '300000', 'planning_loan' => 'no'];
$economic['financial_tools_snapshot'] = json_encode(['version' => 1, 'data' => ['budgetPeriod' => 'Mensal',
'loan' => ['principal' => '', 'rate' => '', 'months' => '', 'rateType' => 'nominal', 'periodMonths' => '1', 'gracePeriods' => '', 'upfrontFee' => '', 'recurringFee' => ''],
'breakEven' => ['fixed' => '100000', 'price' => '5000', 'variable' => '2000'], 'funding' => ['total' => '2000000', 'secured' => '1000000'],
'incomes' => [['label' => 'SYNTHETIC revenue', 'amount' => '300000']], 'expenses' => [['label' => 'SYNTHETIC costs', 'amount' => '200000']]]], JSON_THROW_ON_ERROR);
$draft = $this->postJson('/api/v1/simulation-drafts', ['context' => $id, 'personal_snapshot' => [], 'economic_snapshot' => $economic], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data');
$view = $this->getJson('/investimentos/'.$id)->assertOk()->json();
$this->postJson('/investimentos/'.$id.'/resultados', ['version' => $view['case']['version'], 'draft_id' => $draft['id'], 'draft_version' => $draft['version_no'], 'context_revision' => $view['investment_context']['revision'], 'context_reviewed' => true])->assertOk();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'results')->assertJsonPath('results.0.preparation_snapshot.annual_revenue', '300000')
->assertJsonPath('content_sources.0.analyses.0.quote', $idea['evidence']['quote']);
$this->actingAs($stranger)->getJson('/investimentos/'.$id)->assertForbidden();
$this->actingAs($owner);
}
}
public function test_all_eleven_regions_keep_provincial_scope_and_never_assign_districts(): void
{
foreach (SectorContentAnalysis::REGIONS as $legacy => $name) {
[$a] = $this->source('turismo', $legacy);
$analysis = $a['sector_analysis'];
$this->assertSame($name, $analysis['region']);
$this->assertSame('province', $analysis['ideas'][0]['location_precision']);
$this->assertArrayNotHasKey('district_id', $analysis['ideas'][0]);
}
}
public function test_district_consultation_reuses_only_the_matching_provincial_reading(): void
{
[$article] = $this->source('turismo', 172237);
$country = (string) Str::uuid();
$province = (string) Str::uuid();
$district = (string) Str::uuid();
foreach ([[$country, null, 'SYNTHETIC country', 'country'], [$province, $country, 'Maputo Província', 'province'], [$district, $province, 'SYNTHETIC district', 'district']] as [$id, $parent, $name, $type]) {
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => $name, 'code' => $id,
'location_type' => $type, 'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
}
$readings = app(SectorContentAnalysis::class)->forTerritories([$district]);
$this->assertCount(1, $readings);
$this->assertSame($article['href'], $readings[0]['href']);
$this->assertSame('Maputo Província', $readings[0]['analysis']['region']);
$this->assertSame('province', $readings[0]['analysis']['ideas'][0]['location_precision']);
$this->assertSame([], app(SectorContentAnalysis::class)->forTerritories([(string) Str::uuid()]));
}
public function test_changed_source_or_fabricated_passage_cannot_be_attached(): void
{
[$a, $resource] = $this->source('turismo');
$owner = User::factory()->create();
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => 'SYNTHETIC guard', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$idea = $a['sector_analysis']['ideas'][0];
$input = ['version' => $version, 'resource_id' => $resource, 'evidence' => $idea['evidence']['key'], 'idea' => $idea['title'], 'source_version' => $a['version'], 'source_sha256' => str_repeat('0', 64)];
$this->postJson('/investimentos/'.$id.'/conteudos', $input)->assertConflict();
$this->postJson('/investimentos/'.$id.'/conteudos', [...$input, 'source_sha256' => $a['sha256'], 'idea' => 'Fabricated availability'])->assertUnprocessable();
$this->assertSame([], $this->getJson('/investimentos/'.$id)->json('content_sources'));
}
public function test_saved_passage_survives_editorial_changes_and_withdrawal_with_a_review_notice(): void
{
[$a, $resource] = $this->source('turismo');
$owner = User::factory()->create();
$idea = $a['sector_analysis']['ideas'][0];
$id = $this->actingAs($owner)->postJson('/investimentos', ['title' => 'SYNTHETIC deliberate title', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true,
'content_resource_id' => $resource, 'evidence' => $idea['evidence']['key'], 'idea' => $idea['title'], 'source_sha256' => $a['sha256'], 'source_version' => $a['version']])->assertCreated()->json('id');
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('content_sources.0.analysis_review_required', false);
$selection = app(SectorContentAnalysis::class)->selection($a, ['evidence' => $idea['evidence']['key'], 'idea' => $idea['title'], 'source_sha256' => $a['sha256'], 'source_version' => $a['version']]);
$this->assertStringNotContainsString('project_title=', app(SectorContentAnalysis::class)->continuation($id, $selection));
$version = $this->getJson('/investimentos/'.$id)->json('case.version');
$this->postJson('/investimentos/'.$id.'/conteudos', ['version' => $version, 'resource_id' => $resource,
'evidence' => $idea['evidence']['key'], 'idea' => $idea['title'], 'source_sha256' => $a['sha256'], 'source_version' => $a['version']])->assertOk();
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonCount(1, 'content_sources.0.analyses')->assertJsonPath('case.title', 'SYNTHETIC deliberate title');
DB::table('portal_resources')->where('id', $resource)->update(['metadata_version' => 2, 'editorial_content' => json_encode(['body' => 'SYNTHETIC amended source; the saved conclusion must not change.'], JSON_THROW_ON_ERROR)]);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('case.title', 'SYNTHETIC deliberate title')
->assertJsonPath('content_sources.0.analysis_review_required', true)->assertJsonPath('content_sources.0.analyses.0.quote', $idea['evidence']['quote']);
DB::table('portal_resources')->where('id', $resource)->update(['published' => false]);
$this->getJson('/investimentos/'.$id)->assertOk()->assertJsonPath('content_sources.0.analysis_review_required', true)
->assertJsonPath('content_sources.0.analyses.0.source_version', 1)->assertJsonPath('content_sources.0.analyses.0.quote', $idea['evidence']['quote']);
}
}
@@ -0,0 +1,141 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\TerritorialRegistry;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class TerritorialEditorialWorkflowTest extends TestCase
{
use AuthenticatesQaActors, DatabaseTransactions;
private User $editor;
private User $reviewer;
private User $publisher;
private string $id;
private array $fields;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
[$this->editor,$this->reviewer,$this->publisher] = User::factory()->count(3)->create()->all();
config(['territorial.enabled' => true, 'editorial_workflow.territorial_versions' => true, 'portal.profile_access_enabled' => false,
'portal.managers' => [$this->editor->email, $this->reviewer->email, $this->publisher->email],
'territorial.editors' => [$this->editor->email], 'territorial.reviewers' => [$this->reviewer->email], 'territorial.publishers' => [$this->publisher->email]]);
$this->actingAsWithMfa($this->reviewer);
$this->actingAsWithMfa($this->publisher);
$this->actingAsWithMfa($this->editor);
$source = (string) Str::uuid();
$this->id = (string) Str::uuid();
$code = 'QA-'.Str::random(12);
DB::table('geo_sources')->insert(['id' => $source, 'name' => 'Synthetic source', 'reference' => 'Synthetic QA only', 'checksum' => str_repeat('c', 64), 'source_version' => 'qa', 'collected_at' => today(), 'status' => 'approved', 'responsible_entity' => 'Synthetic entity', 'license' => 'Synthetic licence', 'editor_id' => $this->editor->id, 'reviewer_id' => $this->reviewer->id]);
DB::table('geo_locations')->insert(['id' => $this->id, 'name' => 'Public original', 'code' => $code, 'location_type' => 'country', 'data_classification' => 'public', 'version_no' => 1]);
DB::table('geo_territory_profiles')->insert(['geo_location_id' => $this->id, 'source_id' => $source, 'valid_from' => '2020-01-01', 'status' => 'published', 'editor_id' => $this->editor->id, 'reviewer_id' => $this->reviewer->id, 'publisher_id' => $this->publisher->id]);
$this->fields = ['name' => 'Private proposal', 'code' => $code, 'location_type' => 'country', 'parent_id' => null, 'source_id' => $source, 'valid_from' => '2020-01-01', 'valid_to' => null, 'version_no' => 1, 'reason' => 'Synthetic editorial proposal'];
}
private function save(int $version = 1): void
{
$this->actingAsWithMfa($this->editor)->patchJson('/api/v1/geo/territories/'.$this->id, [...$this->fields, 'version_no' => $version], ['Idempotency-Key' => (string) Str::uuid()])->assertOk()->assertJsonPath('version_no', $version + 1);
}
private function action(string $action, int $version, int $status = 200): void
{
$actor = match ($action) {
'pending_review' => $this->editor,'in_review','approved','rejected' => $this->reviewer,default => $this->publisher
};
$this->actingAsWithMfa($actor)->postJson('/api/v1/geo/territories/'.$this->id.'/transitions', ['action' => $action, 'version_no' => $version, 'reason' => 'Synthetic reason for '.$action], ['Idempotency-Key' => (string) Str::uuid()])->assertStatus($status);
}
public function test_publication_is_preserved_through_exact_private_review_until_explicit_publication(): void
{
$before = DB::table('geo_locations')->find($this->id);
$profile = DB::table('geo_territory_profiles')->where('geo_location_id', $this->id)->first();
$this->save();
$this->getJson('/api/v1/geo/drafts?limit=100')->assertOk();
$this->assertSame('Private proposal', app(TerritorialRegistry::class)->working($this->id)['location']['name']);
$this->getJson('/api/v1/geo/drafts/'.$this->id)->assertOk()->assertHeader('Cache-Control', 'no-store, private')
->assertJsonPath('working.location.name', 'Private proposal')->assertJsonPath('public.location.name', 'Public original')->assertJsonCount(2, 'history');
$this->withoutVite();
$this->get('/management/territorial/editorial')->assertOk();
foreach (['pending_review' => 2, 'in_review' => 3, 'approved' => 4] as $action => $version) {
$this->action($action, $version);
}
$this->assertEquals($before, DB::table('geo_locations')->find($this->id));
$this->assertEquals($profile, DB::table('geo_territory_profiles')->where('geo_location_id', $this->id)->first());
$this->assertTrue(app(TerritorialRegistry::class)->published()->where('g.id', $this->id)->exists());
$this->action('published', 5);
$this->assertSame('Private proposal', DB::table('geo_locations')->find($this->id)->name);
$this->assertSame('published', DB::table('geo_territory_profiles')->where('geo_location_id', $this->id)->value('status'));
$this->assertDatabaseHas('geo_territory_revisions', ['geo_location_id' => $this->id, 'version_no' => 6]);
$this->save(6);
$this->action('archived', 7);
$this->assertTrue(app(TerritorialRegistry::class)->published()->where('g.id', $this->id)->exists());
}
public function test_changed_evidence_and_concurrent_edits_cannot_reuse_approval(): void
{
$this->save();
$this->action('pending_review', 2);
$this->action('in_review', 3);
$this->action('approved', 4);
DB::table('geo_sources')->where('id', $this->fields['source_id'])->update(['reference' => 'Changed synthetic source']);
$this->action('published', 5, 409);
$this->assertSame('Public original', DB::table('geo_locations')->find($this->id)->name);
$this->action('rejected', 5, 409);
$this->save(5);
$this->action('published', 6, 409);
config(['editorial_workflow.territorial_versions' => false]);
$this->actingAsWithMfa($this->editor)->patchJson('/api/v1/geo/territories/'.$this->id, [...$this->fields, 'version_no' => 6], ['Idempotency-Key' => (string) Str::uuid()])->assertStatus(503);
}
public function test_explicit_withdrawal_preserves_the_pending_private_review(): void
{
$this->save();
$this->action('pending_review', 2);
$this->action('in_review', 3);
$this->action('approved', 4);
$this->action('withdrawn', 5);
$state = app(TerritorialRegistry::class)->working($this->id);
$this->assertSame('approved', $state['profile']['status']);
$this->assertTrue($state['fresh']);
$this->assertFalse(app(TerritorialRegistry::class)->published()->where('g.id', $this->id)->exists());
$this->action('published', 6);
$this->assertTrue(app(TerritorialRegistry::class)->published()->where('g.id', $this->id)->exists());
}
public function test_replays_recheck_fresh_mfa_and_revoked_reviewer_blocks_publication(): void
{
$key = ['Idempotency-Key' => (string) Str::uuid()];
$this->actingAsWithMfa($this->editor)->patchJson('/api/v1/geo/territories/'.$this->id, $this->fields, $key)->assertOk();
$this->withSession(['portal.mfa_at' => time() - 1000])->patchJson('/api/v1/geo/territories/'.$this->id, $this->fields, $key)->assertForbidden();
$this->action('pending_review', 2);
$this->action('in_review', 3);
$this->action('approved', 4);
config(['territorial.reviewers' => []]);
$this->action('published', 5, 409);
$this->assertSame('Public original', DB::table('geo_locations')->find($this->id)->name);
}
public function test_private_previews_and_review_cannot_be_obtained_by_unassigned_accounts_or_contributors(): void
{
$this->save();
config(['territorial.reviewers' => [$this->reviewer->email, $this->editor->email]]);
$this->action('pending_review', 2);
$this->actingAsWithMfa($this->editor)->postJson('/api/v1/geo/territories/'.$this->id.'/transitions', ['action' => 'in_review', 'version_no' => 3, 'reason' => 'Synthetic independent decision'], ['Idempotency-Key' => (string) Str::uuid()])->assertForbidden();
$outsider = User::factory()->create();
$this->actingAsWithMfa($outsider)->getJson('/api/v1/geo/drafts/'.$this->id)->assertForbidden();
$this->actingAsWithMfa($this->editor)->getJson('/api/v1/geo/territories/country/'.$this->id)->assertOk()->assertJsonPath('territory.name', 'Public original');
}
}
@@ -0,0 +1,163 @@
<?php
namespace Tests\Feature;
use App\Models\InvestmentZone;
use App\Models\User;
use App\Services\InvestmentMapIndicators;
use App\Services\InvestmentZoneOperationalDetails;
use App\Services\InvestmentZoneOperationalProfile;
use App\Services\InvestmentZones;
use App\Services\PortalEditorialNativeNotices;
use App\Services\PortalEditorialWorkflow;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class ZoneStatisticsEditorialTest extends TestCase
{
use AuthenticatesQaActors,DatabaseTransactions;
private User $author;
private User $reviewer;
private InvestmentZone $zone;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->assertTrue(Schema::hasColumn('investment_zones', 'editorial_draft'));
$this->assertTrue(Schema::hasColumn('investment_zones', 'operational_details'));
$this->withoutVite();
[$this->author,$this->reviewer] = User::factory()->count(2)->create()->all();
config(['portal.managers' => [$this->author->email, $this->reviewer->email], 'portal.profile_access_enabled' => false, 'editorial_workflow.enabled' => true, 'editorial_workflow.zone_review' => true]);
$this->actingAsWithMfa($this->reviewer);
$this->actingAsWithMfa($this->author);
$country = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $country, 'code' => 'ZONE-'.Str::random(12), 'name' => 'Synthetic reviewed country', 'location_type' => 'country', 'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$country]);
$province = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $province, 'parent_id' => $country, 'code' => 'ZONE-'.Str::random(12), 'name' => 'Synthetic reviewed province', 'location_type' => 'province', 'data_classification' => 'public', 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$province]);
// Previously published synthetic baseline; this is not an approval of a real source.
$this->zone = InvestmentZone::create(['code' => 'ZONE-'.Str::random(10), 'name' => 'Original public zone', 'description' => 'Synthetic informational description', 'category' => 'industrial_park', 'physical_category' => 'industrial_park', 'legal_regime' => 'pending', 'primary_territory_id' => $province, 'territory_version' => 1, 'version_no' => 1, 'publication_status' => 'published', 'validation_status' => 'validated', 'editor_id' => $this->author->id, 'reviewer_id' => $this->author->id, 'published_at' => now(),
'source_evidence' => [['title' => 'Synthetic institutional report', 'url' => 'https://example.test/institutional', 'source_type' => 'institutional', 'supports' => 'Synthetic evidence of the identity and location only']]]);
}
private function profile(): InvestmentZoneOperationalProfile
{
return app(InvestmentZoneOperationalProfile::class);
}
private function prepare(): void
{
$this->actingAsWithMfa($this->author);
$fields = ['version_no' => $this->profile()->workingVersion($this->zone->fresh()), 'name' => 'Private revised zone', 'operational_details' => ['schema_version' => 1, 'integral' => ['schema_version' => 1, 'observations' => [['id' => (string) Str::uuid(), 'label' => 'Synthetic investment observation', 'knowledge' => 'documented', 'disclosure' => true, 'source_reference' => 'Synthetic report page 2', 'source_date' => '2026-01-15', 'scope' => 'This synthetic zone only', 'indicator' => 'investment', 'measure_kind' => 'observed', 'value' => '9007199254740.25', 'unit' => 'MZN', 'period_start' => '2025-01-01', 'period_end' => '2025-12-31', 'population' => 'Declared establishments', 'methodology' => 'Synthetic documentary record']]]]];
app(InvestmentZones::class)->save($this->zone->id, $fields, $this->author->id);
}
private function decision(string $action, ?User $actor = null): array
{
$actor ??= $action === 'submit' ? $this->author : $this->reviewer;
$this->actingAsWithMfa($actor);
return $this->profile()->review($this->zone->id, $actor, $this->profile()->workingVersion($this->zone->fresh()), $action, 'Synthetic review decision with source');
}
private function approve(): void
{
foreach (['submit', 'start_review', 'approve'] as $action) {
$this->decision($action);
}
}
public function test_indicator_preparation_and_approval_preserve_the_public_projection_until_explicit_publication(): void
{
$before = Arr::except($this->zone->fresh()->getAttributes(), ['editorial_draft']);
$this->prepare();
$this->assertSame($before, Arr::except($this->zone->fresh()->getAttributes(), ['editorial_draft']));
$this->assertSame([], app(InvestmentZoneOperationalDetails::class)->publicData($this->zone->fresh()));
$this->approve();
$this->assertSame($before, Arr::except($this->zone->fresh()->getAttributes(), ['editorial_draft']));
$this->actingAsWithMfa($this->reviewer);
$saved = app(InvestmentZones::class)->publish($this->zone->id, $this->profile()->workingVersion($this->zone->fresh()), $this->reviewer->id);
$this->assertSame('Private revised zone', $saved->name);
$rows = app(InvestmentMapIndicators::class)->forZones(collect([$saved]))['records'];
$this->assertCount(1, $rows);
$this->assertSame('9007199254740.25', $rows[0]['value']);
$this->assertSame('observed', $rows[0]['measure_kind']);
$this->assertSame('This synthetic zone only', $rows[0]['scope']);
$this->assertSame('Synthetic report page 2', $rows[0]['source_reference']);
$this->assertNull($this->profile()->draft($saved));
$this->assertNotEmpty(app(PortalEditorialWorkflow::class)->notices($this->author));
}
public function test_editing_after_approval_requires_a_new_decision_and_direct_publish_cannot_bypass_it(): void
{
$this->prepare();
$this->approve();
$this->actingAsWithMfa($this->author);
app(InvestmentZones::class)->save($this->zone->id, ['version_no' => $this->profile()->workingVersion($this->zone->fresh()), 'description' => 'Deliberate later change'], $this->author->id);
$this->assertSame('draft', $this->profile()->management($this->zone->fresh())['editorial_workflow']['state']);
try {
app(InvestmentZones::class)->publish($this->zone->id, $this->profile()->workingVersion($this->zone->fresh()), $this->author->id);
$this->fail('Approval must be renewed');
} catch (HttpException $e) {
$this->assertSame(409, $e->getStatusCode());
}
$this->assertSame('Original public zone', $this->zone->fresh()->name);
}
public function test_public_suspension_preserves_the_private_review_and_approved_exact_content(): void
{
$this->prepare();
$this->approve();
$this->actingAsWithMfa($this->reviewer);
$saved = app(InvestmentZones::class)->suspend($this->zone->id, $this->profile()->workingVersion($this->zone->fresh()), $this->reviewer->id);
$working = $this->profile()->management($saved);
$this->assertSame('approved', $working['editorial_workflow']['state']);
$this->assertTrue($working['editorial_workflow']['fresh']);
$this->assertSame('suspended', $saved->publication_status);
app(InvestmentZones::class)->publish($saved->id, $working['version_no'], $this->reviewer->id);
$this->assertSame('Private revised zone', $saved->fresh()->name);
}
public function test_history_recovers_the_exact_private_observation_without_overwriting_current_content(): void
{
$this->prepare();
$version = $this->profile()->workingVersion($this->zone->fresh());
$url = '/api/v2/investment/admin/zones/'.$this->zone->id.'/revisions/'.$version;
$before = $this->zone->fresh()->getAttributes();
$this->getJson($url)->assertOk()->assertJsonPath('fields.name', 'Private revised zone')->assertJsonPath('observations.0.value', '9007199254740.25')->assertJsonMissingPath('fields.editorial_draft')->assertJsonMissingPath('private_ciphertext');
$this->assertSame($before, $this->zone->fresh()->getAttributes());
$this->getJson(str_replace($this->zone->id, (string) Str::uuid(), $url))->assertNotFound();
$this->actingAsWithMfa(User::factory()->create())->getJson($url)->assertForbidden();
}
public function test_http_decisions_require_scope_fresh_mfa_and_preserve_source_and_history(): void
{
$this->prepare();
$version = $this->profile()->workingVersion($this->zone->fresh());
$url = '/api/v2/investment/admin/zones/'.$this->zone->id.'/editorial/submit';
$this->withSession(['portal.mfa_at' => time() - 1000])->postJson($url, ['version_no' => $version, 'reason' => 'Synthetic decision reason'])->assertForbidden();
$this->actingAsWithMfa($this->author)->postJson($url, ['version_no' => $version, 'reason' => 'Synthetic decision reason'])->assertOk()->assertJsonPath('editorial_workflow.state', 'submitted');
$this->assertGreaterThan(1, app(PortalEditorialNativeNotices::class)->pending($this->reviewer)['zones'] + 1);
$outsider = User::factory()->create();
$this->actingAsWithMfa($outsider)->postJson($url, ['version_no' => $version, 'reason' => 'Synthetic decision reason'])->assertForbidden();
config(['editorial_workflow.zone_review' => false]);
$this->actingAsWithMfa($this->author);
try {
app(InvestmentZones::class)->save($this->zone->id, ['version_no' => $version, 'name' => 'Forbidden legacy overwrite'], $this->author->id);
$this->fail('Disabling must preserve workflow');
} catch (HttpException $e) {
$this->assertSame(503, $e->getStatusCode());
}
$this->assertSame('Original public zone', $this->zone->fresh()->name);
}
}
+707
View File
@@ -0,0 +1,707 @@
{
"provenance": "Texto colado(5).txt fornecido pela Tempo, conferido na página pública em 2026-11-15; Manica.xlsx, folha 2026, B/E/H54 e B/E/H56:72. Valores de apresentação, não reimportação.",
"values": [
{
"year": 2026,
"indicator": "population",
"age_group": "all",
"residence": "all",
"value": "248518.44160696748",
"original_value": "248518.44160696748",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B54",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "all",
"residence": "urban",
"value": "86749.367563197302",
"original_value": "86749.367563197302",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E54",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "all",
"residence": "rural",
"value": "161769.0740437702",
"original_value": "161769.0740437702",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H54",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "0-4",
"residence": "all",
"value": "44289.138086159306",
"original_value": "44289.138086159306",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B56",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "0-4",
"residence": "urban",
"value": "14514.88099755138",
"original_value": "14514.88099755138",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E56",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "0-4",
"residence": "rural",
"value": "29774.257088607934",
"original_value": "29774.257088607934",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H56",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "5-9",
"residence": "all",
"value": "35827.776591901806",
"original_value": "35827.776591901806",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B57",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "5-9",
"residence": "urban",
"value": "11793.491606737534",
"original_value": "11793.491606737534",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E57",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "5-9",
"residence": "rural",
"value": "24034.284985164271",
"original_value": "24034.284985164271",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H57",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "10-14",
"residence": "all",
"value": "33152.970732328176",
"original_value": "33152.970732328176",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B58",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "10-14",
"residence": "urban",
"value": "10676.607713136782",
"original_value": "10676.607713136782",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E58",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "10-14",
"residence": "rural",
"value": "22476.363019191398",
"original_value": "22476.363019191398",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H58",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "15-19",
"residence": "all",
"value": "29611.438388752566",
"original_value": "29611.438388752566",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B59",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "15-19",
"residence": "urban",
"value": "10262.814463997336",
"original_value": "10262.814463997336",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E59",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "15-19",
"residence": "rural",
"value": "19348.623924755229",
"original_value": "19348.623924755229",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H59",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "20-24",
"residence": "all",
"value": "24355.209722981959",
"original_value": "24355.209722981959",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B60",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "20-24",
"residence": "urban",
"value": "9042.4481146842572",
"original_value": "9042.4481146842572",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E60",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "20-24",
"residence": "rural",
"value": "15312.761608297704",
"original_value": "15312.761608297704",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H60",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "25-29",
"residence": "all",
"value": "19575.376496383324",
"original_value": "19575.376496383324",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B61",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "25-29",
"residence": "urban",
"value": "7599.5545011499053",
"original_value": "7599.5545011499053",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E61",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "25-29",
"residence": "rural",
"value": "11975.82199523342",
"original_value": "11975.82199523342",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H61",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "30-34",
"residence": "all",
"value": "14806.636171744825",
"original_value": "14806.636171744825",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B62",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "30-34",
"residence": "urban",
"value": "6262.1273781029959",
"original_value": "6262.1273781029959",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E62",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "30-34",
"residence": "rural",
"value": "8544.5087936418295",
"original_value": "8544.5087936418295",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H62",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "35-39",
"residence": "all",
"value": "11161.453343365156",
"original_value": "11161.453343365156",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B63",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "35-39",
"residence": "urban",
"value": "4625.8522262806891",
"original_value": "4625.8522262806891",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E63",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "35-39",
"residence": "rural",
"value": "6535.6011170844686",
"original_value": "6535.6011170844686",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H63",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "40-44",
"residence": "all",
"value": "8538.8490092624561",
"original_value": "8538.8490092624561",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B64",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "40-44",
"residence": "urban",
"value": "3443.8323932108847",
"original_value": "3443.8323932108847",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E64",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "40-44",
"residence": "rural",
"value": "5095.0166160515719",
"original_value": "5095.0166160515719",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H64",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "45-49",
"residence": "all",
"value": "7101.0415927196163",
"original_value": "7101.0415927196163",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B65",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "45-49",
"residence": "urban",
"value": "2463.4886973717157",
"original_value": "2463.4886973717157",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E65",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "45-49",
"residence": "rural",
"value": "4637.5528953479006",
"original_value": "4637.5528953479006",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H65",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "50-54",
"residence": "all",
"value": "5226.3070949472531",
"original_value": "5226.3070949472531",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B66",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "50-54",
"residence": "urban",
"value": "1679.6467072735772",
"original_value": "1679.6467072735772",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E66",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "50-54",
"residence": "rural",
"value": "3546.6603876736754",
"original_value": "3546.6603876736754",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H66",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "55-59",
"residence": "all",
"value": "3998.2566339012192",
"original_value": "3998.2566339012192",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B67",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "55-59",
"residence": "urban",
"value": "1240.8880754969321",
"original_value": "1240.8880754969321",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E67",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "55-59",
"residence": "rural",
"value": "2757.3685584042869",
"original_value": "2757.3685584042869",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H67",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "60-64",
"residence": "all",
"value": "3135.4929526634714",
"original_value": "3135.4929526634714",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B68",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "60-64",
"residence": "urban",
"value": "1009.9040617408737",
"original_value": "1009.9040617408737",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E68",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "60-64",
"residence": "rural",
"value": "2125.5888909225978",
"original_value": "2125.5888909225978",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H68",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "65-69",
"residence": "all",
"value": "2537.0624121248256",
"original_value": "2537.0624121248256",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B69",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "65-69",
"residence": "urban",
"value": "753.99704079870799",
"original_value": "753.99704079870799",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E69",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "65-69",
"residence": "rural",
"value": "1783.0653713261181",
"original_value": "1783.0653713261181",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H69",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "70-74",
"residence": "all",
"value": "2016.6006284927157",
"original_value": "2016.6006284927157",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B70",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "70-74",
"residence": "urban",
"value": "576.8557228333616",
"original_value": "576.8557228333616",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E70",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "70-74",
"residence": "rural",
"value": "1439.7449056593541",
"original_value": "1439.7449056593541",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H70",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "75-79",
"residence": "all",
"value": "1320.7863269208433",
"original_value": "1320.7863269208433",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B71",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "75-79",
"residence": "urban",
"value": "331.39109408599069",
"original_value": "331.39109408599069",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E71",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "75-79",
"residence": "rural",
"value": "989.39523283485266",
"original_value": "989.39523283485266",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H71",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "80+",
"residence": "all",
"value": "1864.0454223179609",
"original_value": "1864.0454223179609",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "B72",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "80+",
"residence": "urban",
"value": "471.58676874437788",
"original_value": "471.58676874437788",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "E72",
"validation_status": "warning"
},
{
"year": 2026,
"indicator": "population",
"age_group": "80+",
"residence": "rural",
"value": "1392.458653573583",
"original_value": "1392.458653573583",
"unit": "pessoas",
"data_kind": "projected",
"sheet": "2026",
"cell": "H72",
"validation_status": "warning"
}
]
}
+21 -2
View File
@@ -9,6 +9,7 @@ use App\Models\User;
use App\Services\InvestmentGeography;
use App\Services\OpportunityMaturity;
use App\Support\IsolatedQaDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class OpportunitySearchFixture
@@ -20,9 +21,27 @@ final class OpportunitySearchFixture
}
$province = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->where('name', 'Inhambane')->first();
if (! $province) {
throw new \LogicException('QA requires the existing public Inhambane reference');
// Tests must not depend on an operational import. These placeholders exist
// only in the already isolated test database and caller's rollback transaction.
if (DB::transactionLevel() < 1) {
throw new \LogicException('Synthetic references require test rollback');
}
$country = (string) Str::uuid();
$id = (string) Str::uuid();
foreach ([[$country, 'country', null, 'Synthetic QA country'], [$id, 'province', $country, 'Inhambane']] as [$key, $type, $parent, $name]) {
DB::table('geo_locations')->insert(['id' => $key, 'code' => 'SYNTHETIC-QA-'.$key, 'name' => $name,
'location_type' => $type, 'parent_id' => $parent, 'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$key]);
}
$province = app(InvestmentGeography::class)->publicReferences()->where('id', $id)->first();
}
$sector = Sector::where('slug', 'turismo')->first();
if (! $sector) {
if (DB::transactionLevel() < 1) {
throw new \LogicException('Synthetic sector requires test rollback');
}
$sector = Sector::create(['slug' => 'turismo', 'name' => 'Synthetic QA tourism', 'is_active' => true]);
}
$sector = Sector::where('slug', 'turismo')->firstOrFail();
$editor = User::factory()->create();
$reviewer = User::factory()->create();
$zone = InvestmentZone::query()->create(['id' => (string) Str::uuid(), 'code' => 'SINT-QA-'.Str::random(8),
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Tests\Unit;
use App\Services\OpportunityReviewMateriality;
use PHPUnit\Framework\TestCase;
final class EditorialLegalVersionTest extends TestCase
{
public function test_legal_decisions_cannot_be_carried_to_a_different_content_version_in_phase_one(): void
{
$service = new OpportunityReviewMateriality;
$before = ['hash' => str_repeat('a', 64), 'payload' => [], 'resources' => []];
$after = [...$before, 'hash' => str_repeat('b', 64)];
$review = ['decision' => 'approved', 'hash' => $before['hash'], 'scope_rule' => OpportunityReviewMateriality::VERSION];
$review['scope_hash'] = $service->hash($before, 'land_legal_review', $review);
$this->assertSame(['land_legal_review'], $service->reconcile($before, $after, ['land_legal_review' => $review], ['land_legal_review'])['retained']);
$strict = $service->reconcile($before, $after, ['land_legal_review' => $review], ['land_legal_review'], exactLegalVersion: true);
$this->assertSame([], $strict['reviews']);
$this->assertSame(['land_legal_review'], $strict['reopened']);
$this->assertFalse($service->matches($after, 'land_legal_review', [...$review, 'accepted_submission_hash' => $after['hash']], true));
$this->assertTrue($service->matches($before, 'land_legal_review', $review, true));
$this->assertSame($before['hash'], $review['hash']);
}
}
+21
View File
@@ -3,6 +3,7 @@
namespace Tests\Unit;
use App\Services\FederatedSearch;
use App\Services\SearchTerms;
use PHPUnit\Framework\TestCase;
final class FederatedSearchTest extends TestCase
@@ -44,4 +45,24 @@ final class FederatedSearchTest extends TestCase
$result = (new FederatedSearch)->page($factories, 1, 5, fn ($item) => $item['score']);
$this->assertSame(['Sectores', 'Informação'], array_column($result['data'], 'title'));
}
public function test_direct_matches_precede_associations_across_sources_and_pages(): void
{
$search = new SearchTerms;
$term = 'corredor da beira';
$tokens = $search->tokens($term);
$sources = [
'Oportunidades' => fn () => ['count' => 2, 'fetch' => fn ($offset, $limit) => array_slice([
['title' => 'Açúcar no Corredor da Beira'], ['title' => 'Produção de açúcar'],
], $offset, $limit)],
'Carteira' => fn () => ['count' => 1, 'fetch' => fn ($offset, $limit) => array_slice([
['title' => 'Corredor da Beira'],
], $offset, $limit)],
];
$score = fn ($item) => $search->score($item['title'], $term, $tokens);
$service = new FederatedSearch;
$this->assertSame(['Corredor da Beira', 'Açúcar no Corredor da Beira'], array_column($service->page($sources, 1, 2, $score)['data'], 'title'));
$this->assertSame(['Produção de açúcar'], array_column($service->page($sources, 2, 2, $score)['data'], 'title'));
}
}
+83
View File
@@ -0,0 +1,83 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
catalogueDetailHref,
catalogueReturnHref,
catalogueQuery,
} from '../../resources/js/lib/catalogue-context.ts';
test('return preserves deliberate destination edits, including cleared ancestors, without stale descendants', () => {
const detail = catalogueDetailHref(
'/carteira/a',
'q=energia&province_id=p&district_id=d&page=4',
);
assert.equal(
catalogueReturnHref('/carteira?q=turismo&province_id=', detail),
'/carteira?q=turismo&province_id=&page=4',
);
assert.equal(
catalogueReturnHref('/carteira?province_id=other', detail),
'/carteira?province_id=other&q=energia&page=4',
);
});
test('different catalogue families share geography but not text, kind, price, page or private context', () => {
const detail =
'/carteira/a?catalogue_query=' +
encodeURIComponent(
'q=airport&kind=project&page=4&province_id=p&context=private&min_amount=200',
);
assert.equal(
catalogueReturnHref('/zonas?category=zee', detail),
'/zonas?category=zee&province_id=p',
);
assert.equal(catalogueReturnHref('/documentos', detail), '/documentos');
});
test('resource-specific return queries do not inherit from other tabs or mutable storage', () => {
const a = catalogueDetailHref(
'/oportunidades/a',
'q=rice&facets[]=2&facets[]=3&currency=MZN',
);
const b = catalogueDetailHref('/oportunidades/b', 'q=gas&currency=USD');
const back = catalogueReturnHref('/oportunidades', a);
assert.deepEqual(
new URL(back, 'https://portal.invalid').searchParams.getAll('facets[]'),
['2', '3'],
);
assert.match(back, /q=rice/);
assert.match(catalogueReturnHref('/oportunidades', b), /q=gas/);
assert.equal(
catalogueReturnHref('/oportunidades', '/oportunidades/c'),
'/oportunidades',
);
});
test('detail URL preserves existing parameters and fragment; unsafe and recursive filters are not carried', () => {
const href = catalogueDetailHref(
'/oportunidades/a?from_dossier=origin#details',
'q=rice&context=other&catalogue_query=recursive&password=secret&kind=cluster',
);
const url = new URL(href, 'https://portal.invalid');
assert.equal(url.searchParams.get('from_dossier'), 'origin');
assert.equal(url.hash, '#details');
assert.equal(url.searchParams.get('catalogue_query'), 'q=rice');
assert.equal(
catalogueDetailHref('https://outside.test/a', 'q=rice'),
'https://outside.test/a',
);
});
test('only positive finite page numbers survive; repeated scalar criteria have one deliberate value', () => {
assert.equal(
catalogueQuery(
'/carteira',
'q=old&q=new&page=-1&per_page=Infinity',
).toString(),
'q=new',
);
assert.equal(
catalogueReturnHref(
'/carteira',
'/carteira/a?catalogue_query=' +
encodeURIComponent('https://outside.test'),
),
'/carteira',
);
});
+112
View File
@@ -0,0 +1,112 @@
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';
const require = createRequire(import.meta.url);
function load(path, dependencies = {}) {
const source = fs.readFileSync(new URL(path, import.meta.url), 'utf8');
const code = 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', code)(
(name) => dependencies[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/cluster-competitiveness.ts');
const Page = load('../../resources/js/pages/structures/competitiveness.tsx', {
'@/lib/cluster-competitiveness': lib,
'@/lib/portal-api': {
portalRequest() {
throw new Error('SSR must not send requests');
},
PortalApiError: Error,
},
'../management/shared': { button: '', control: '' },
'@/lib/editorial-states': {
states: {
draft: 'Rascunho',
approved: 'Aprovado',
published: 'Publicado',
},
},
}).default;
const draft = lib.newCompetitivenessDraft('qa-cluster', 'Energia');
draft.region = 'Local sintético';
for (const force of lib.forces) {
draft.forces[force] = {
pressure: 'medium',
evidence: 'Dado sintético',
source: 'Fonte QA',
period: '2026',
rationale: 'Hipótese',
limitations: 'Exemplo',
opportunity: 'Ideia',
};
}
const initial = {
version: 4,
draft,
approved: { draft, version: 4, at: '2026-11-13' },
published: null,
editorial_enabled: true,
history: [],
workflow: {
state: 'approved',
edition: 1,
hash: 'a'.repeat(64),
fresh: true,
contributors: [1],
independent_required: true,
},
};
const render = (state = initial, viewerId = 2) =>
renderToStaticMarkup(
React.createElement(Page, {
clusterId: 'qa-cluster',
sector: 'Energia',
initial: state,
viewerId,
}),
);
test('approved cluster edition requires explicit publication and retains a prior public version', () => {
const html = render();
assert.match(html, /Publicar edição aprovada/);
assert.doesNotMatch(html, /Aprovar torna a versão guardada/);
assert.match(html, /Sem análise aprovada para consulta pública/);
const later = render({
...initial,
published: { draft, version: 2, at: '2026-11-13' },
workflow: { ...initial.workflow, state: 'draft' },
});
assert.match(later, /Consulta pública: versão 2/);
assert.doesNotMatch(later, /Publicar edição aprovada/);
assert.match(later, /Submeter para revisão/);
});
test('changed context disables publication and a disabled workflow remains read only', () => {
const stale = render({
...initial,
workflow: { ...initial.workflow, fresh: false },
});
assert.match(stale, /O contexto do cluster mudou/);
assert.match(
stale,
/<button[^>]*disabled=""[^>]*>Publicar edição aprovada<\/button>/,
);
const disabled = render({ ...initial, editorial_enabled: false });
assert.match(disabled, /<fieldset disabled=""/);
assert.match(disabled, /temporariamente só para consulta/);
});
@@ -26,6 +26,23 @@ function load(file, mocks = {}) {
return module.exports;
}
const lib = load('../../resources/js/lib/company-preparation.ts');
test('historical delivery wording is presented professionally without changing the stored notice or legal limits', () => {
const legal =
' Esta ficha prepara dados para revisão; não é uma minuta contratual, assinatura, registo ou licença.';
const stored =
'Os sete exemplares referidos no complemento ainda não foram fornecidos.' +
legal;
assert.equal(
lib.companyPreparationNotice(stored),
'Os modelos contratuais não estão disponíveis nesta preparação.' +
legal,
);
assert.match(stored, /sete exemplares/);
assert.equal(
lib.companyPreparationNotice('Outro aviso específico.'),
'Outro aviso específico.',
);
});
const party = {
id: 'SYNTHETIC-party',
name: '<SYNTHETIC>',
@@ -148,6 +165,7 @@ function harness() {
router: { visit: (...args) => visits.push(args) },
},
'./shared': { Frame: 'main', card: '', input: '', button: '' },
'@/components/currency-select': { default: () => null },
'@/lib/company-preparation': lib,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
@@ -0,0 +1,19 @@
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';
const require=createRequire(import.meta.url),module={exports:{}};
const code=ts.transpileModule(fs.readFileSync(new URL('../../resources/js/pages/dashboard.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText;
new Function('require','module','exports',code)(name=>name==='@inertiajs/react'?{Head:()=>null,Link:({children,href,...props})=>React.createElement('a',{href,...props},children)}:name==='react/jsx-runtime'?require(name):name==='@/routes'?{dashboard:()=>'/dashboard'}:{default:()=>null},module,module.exports);
test('each manager dashboard menu anchor resolves to a real section',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{summary:{requestsByStatus:{},publishedOpportunities:0,draftOpportunities:0,activeSectors:0,recentRequests:[]},workQueue:null}));
for(const id of ['meu-trabalho','manifestacoes','indicadores-oportunidades','pedidos-recentes','accoes-rapidas'])assert.match(html,new RegExp('id="'+id+'"'));
assert.match(html,/Painel do portal/);
});
test('investor section remains distinct from administrative summary',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{summary:null,investorPath:{contexts:[],current:null}}));
assert.match(html,/id="meus-investimentos"/);assert.doesNotMatch(html,/id="manifestacoes"/);
});
+235
View File
@@ -0,0 +1,235 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
import pathModule from 'node:path';
const require = createRequire(import.meta.url);
function load(path, overrides = {}) {
const source = fs.readFileSync(
new URL('../../resources/js/' + path, import.meta.url),
'utf8',
);
const module = { exports: {} };
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(n) => {
if (n in overrides) return overrides[n];
const relative = n.startsWith('@/') ? n.slice(2) : n.startsWith('.') ? pathModule.posix.join(pathModule.posix.dirname(path), n) : null;
if (relative) {
for (const candidate of [relative, relative + '.tsx', relative + '.ts']) {
if (fs.existsSync(new URL('../../resources/js/' + candidate, import.meta.url))) return load(candidate, overrides);
}
}
return require(n);
},
module,
module.exports,
);
return module.exports;
}
const helpers = load('lib/demographic-reading.ts');
const Summary = load('components/demographic-reading-summary.tsx', {
'@/lib/demographic-reading': helpers,
}).default;
const Details = load('components/evidence-details.tsx').default;
const Component = load('components/demographic-evidence.tsx', {
'./demographic-reading-summary': { default: Summary },
'./evidence-details': { default: Details },
}).default;
const row = (age, value, residence = 'all', year = 2026, extra = {}) => ({
year,
indicator: 'population',
age_group: age,
residence,
value,
original_value: value,
unit: 'pessoas',
data_kind: 'projected',
sheet: String(year),
cell: `${age}-${residence}`,
validation_status: 'valid',
...extra,
});
const series = (values) => ({
import_id: 'source-one',
source: 'INE',
version: 'SYNTHETIC test edition',
sha256: 'a'.repeat(64),
file_name: 'source.xlsx',
missing_years: [],
issue_counts: {},
values,
});
const ages = [
'15-19',
'20-24',
'25-29',
'30-34',
'35-39',
'40-44',
'45-49',
'50-54',
'55-59',
'60-64',
];
const base = () =>
series([
row('all', '1000.1234567890123'),
row('all', '400', 'urban'),
row('all', '600.1234567890123', 'rural'),
row('0-4', '100'),
row('5-9', '100'),
row('10-14', '100'),
...ages.map((a) => row(a, '50')),
]);
const evidence = (s) => ({
state: 'available',
start_year: 2026,
end_year: 2026,
sector: 'general',
limitations: ['Population is not demand.'],
comparisons: [],
differences: [],
territories: [
{
id: 'district-one',
name: 'Báruè',
level: 'district',
factors_to_assess: [],
series: s,
},
],
});
test('summarises compatible age/residence groups without changing original decimals', () => {
const s = base(),
before = JSON.stringify(s),
r = helpers.demographicReading(s, 2026, 2026);
assert.equal(r.last.under15, 300);
assert.equal(r.last.age15to64, 500);
assert.ok(Math.abs(r.last.ruralShare - 60.00493766) < 0.00001);
assert.equal(JSON.stringify(s), before);
assert.equal(r.growth, null);
});
test('missing age bands remain unknown; zeros are preserved', () => {
const s = base();
s.values = s.values.filter((r) => r.age_group !== '5-9');
assert.equal(helpers.demographicReading(s, 2026, 2026).last.under15, null);
const r = helpers.demographicReading(
series([
row('all', '0'),
row('all', '0', 'urban'),
row('all', '0', 'rural'),
]),
2026,
2026,
);
assert.equal(r.last.total, 0);
assert.equal(r.last.ruralShare, null);
});
test('duplicate dimensions and incompatible kinds cannot supply invented shares', () => {
const s = base();
s.values.push(row('0-4', '200'));
s.values.find((r) => r.residence === 'rural').data_kind = 'observed';
const r = helpers.demographicReading(s, 2026, 2026).last;
assert.equal(r.under15, null);
assert.equal(r.rural, null);
assert.equal(r.ruralShare, null);
});
test('inconsistent residence components do not produce percentages', () => {
const s = series([
row('all', '100'),
row('all', '80', 'urban'),
row('all', '80', 'rural'),
]);
const r = helpers.demographicReading(s, 2026, 2026).last;
assert.equal(r.urban, 80);
assert.equal(r.urbanShare, null);
assert.equal(r.ruralShare, null);
});
test('growth uses explicit comparable endpoints and does not fill missing intermediate years', () => {
const s = series([
row('all', '100', 'all', 2026),
row('all', '120', 'all', 2028),
]);
const r = helpers.demographicReading(s, 2026, 2028);
assert.equal(r.growth, 20);
assert.equal(r.years[1].total, null);
assert.equal(helpers.demographicReading(s, 2026, 2030).growth, null);
s.values[1].data_kind = 'observed';
assert.equal(helpers.demographicReading(s, 2026, 2028).growth, null);
});
test('technical source and full decimals remain available in closed details after a readable summary', () => {
const html = renderToStaticMarkup(
React.createElement(Component, { evidence: evidence([base()]) }),
);
assert.ok(
html.indexOf('Retrato da população') <
html.indexOf('Valores originais por ano'),
);
assert.match(html, /1000.1234567890123/);
assert.match(html, /Valores por dimensão, fonte e advertências/);
assert.doesNotMatch(html, /<details[^>]*\bopen\b/);
assert.match(html, /um único ano/);
assert.match(html, /capacidade instalada/);
assert.match(html, /qualificações/);
});
test('multiple editions receive separate summaries rather than a summed population', () => {
const a = series([row('all', '100')]),
b = { ...series([row('all', '900')]), import_id: 'source-two' };
const html = renderToStaticMarkup(
React.createElement(Component, { evidence: evidence([a, b]) }),
);
assert.equal((html.match(/Retrato da população/g) || []).length, 2);
assert.match(html, />100<\/dd>/);
assert.match(html, />900<\/dd>/);
});
test('demographic page offers territory-only preparation independent of old commercial filters', () => {
const Page = load('pages/investment/demography.tsx', {
'@inertiajs/react': { router: {} },
'@/components/demographic-evidence': { default: Component },
'./shared': {
Frame: ({ children }) =>
React.createElement('main', null, children),
button: '',
},
}).default;
const html = renderToStaticMarkup(
React.createElement(Page, {
evidence: evidence([base()]),
filters: { territories: ['district-one'], sector: 'general' },
territories: [],
sectors: { general: 'Contexto geral' },
}),
);
assert.match(html, /source=territory%3Adistrict-one/);
assert.doesNotMatch(html, /compra de propriedade|sector=turismo|modality=/);
assert.match(html, /Não é necessário haver uma oportunidade publicada/);
});
test('Barue 2026 provided evidence produces the readable proportions without changing originals', () => {
const fixture = JSON.parse(
fs.readFileSync(
new URL('../Fixtures/demography/barue-2026.json', import.meta.url),
'utf8',
),
);
const s = series(fixture.values),
before = JSON.stringify(s);
const r = helpers.demographicReading(s, 2026, 2026).last;
assert.equal(Math.round(r.total), 248518);
assert.equal(Number(r.ruralShare.toFixed(1)), 65.1);
assert.equal(Number(r.under15Share.toFixed(1)), 45.6);
assert.equal(Number(r.age15to64Share.toFixed(1)), 51.3);
assert.equal(JSON.stringify(s), before);
});
@@ -0,0 +1,95 @@
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';
const require = createRequire(import.meta.url);
const source = fs.readFileSync(
new URL(
'../../resources/js/pages/management/demography.tsx',
import.meta.url,
),
'utf8',
);
const code = 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', code)(
(name) => {
if (name === '@inertiajs/react')
return {
Link: ({ href, children }) =>
React.createElement('a', { href }, children),
router: {},
useForm: () => ({ processing: false }),
};
if (name === './shared')
return {
Management: ({ children }) =>
React.createElement('main', null, children),
button: '',
control: '',
};
return require(name);
},
module,
module.exports,
);
const Page = module.exports.default;
const preview = {
id: 'qa-batch',
file_name: 'synthetic.xlsx',
sha256: 'a'.repeat(64),
publication_version: 'Edição não indicada',
status: 'imported',
report: { record_count: 10, issue_counts: {}, issues: [] },
matches: [],
territory_options: [],
events: [],
};
const render = (changes = {}) =>
renderToStaticMarkup(
React.createElement(Page, {
batches: [],
preview,
editorialEnabled: true,
editorialRevision: 0,
...changes,
}),
);
test('new imported batches enter review without a combined approval and publication button', () => {
const html = render();
assert.match(html, /Preparar revisão para publicação/);
assert.doesNotMatch(html, /Aprovar utilização em QA/);
assert.match(
html,
/aprovação e a publicação dos novos lotes são operações distintas/,
);
});
test('legacy public batches remain accepted and published new batches only offer their history', () => {
const legacy = render({ preview: { ...preview, status: 'approved' } });
assert.match(legacy, /preservado sem nova aprovação/);
assert.doesNotMatch(legacy, /Preparar revisão para publicação/);
const published = render({
preview: { ...preview, status: 'approved' },
editorialRevision: 1,
});
assert.match(
published,
/href="\/management\/editorial\/demography\/qa-batch"/,
);
assert.doesNotMatch(
published,
/Preparar nova edição de revisão|Desactivar série/,
);
});
@@ -0,0 +1,133 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const Empty = () => null;
function render(section, filters = {}) {
const source = fs.readFileSync(
new URL(
'../../resources/js/pages/portal/services.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
const props = { auth: { user: null } };
const mocks = {
'lucide-react': {
ChevronDown: Empty,
Search: Empty,
SlidersHorizontal: Empty,
},
'@inertiajs/react': {
Head: Empty,
Link: 'a',
usePage: () => ({ props, url: '/documentos' }),
useForm: (data) => ({ data, setData() {}, get() {} }),
},
'@/lib/document-facet-label': { documentFacetLabel: (value) => value },
'@/lib/portal-presentation': { PORTAL_MORE_LINK: '' },
'../../../css/investment-catalogue.css': {},
};
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (mocks[name]) return mocks[name];
if (name.startsWith('@/'))
return new Proxy(
{ __esModule: true, default: Empty },
{ get: (target, key) => target[key] ?? Empty },
);
return require(name);
},
module,
module.exports,
);
return renderToStaticMarkup(
createElement(module.exports.default, {
section,
filters,
topics: ['Fiscalidade'],
categories: ['Legislação'],
documentTypes: ['guide'],
activities: ['CAE exemplo'],
stages: ['Etapa exemplo'],
modules: ['simulator'],
issuers: ['Instituição exemplo'],
languages: ['Português'],
legalStatuses: ['amended'],
territories: [{ id: 'territory', name: 'Cabo Delgado' }],
resources: {
data: [],
total: 0,
prev_page_url: null,
next_page_url: null,
},
}),
);
}
test('biblioteca e legislação mantêm todos os critérios e opções visíveis no painel aberto', () => {
for (const section of ['documents', 'legislation']) {
const html = render(section);
for (const label of [
'Pesquisar',
'Tema',
'Fiscalidade',
'Categoria',
'Legislação',
'Tipo documental',
'Guia',
'Actividade ou CAE',
'CAE exemplo',
'Etapa do projecto',
'Etapa exemplo',
'Módulo',
'Simulador fiscal',
'Entidade emitente',
'Instituição exemplo',
'Idioma',
'Português',
'Situação jurídica indicada',
'Alterada; consulte alterações posteriores',
'Confirmação da fonte',
'Fonte oficial confirmada',
'Âmbito territorial',
'Cabo Delgado',
'Limpar filtros',
])
assert.ok(html.includes(label), `${section}: ${label}`);
assert.match(html, /aria-expanded="true"/);
}
});
test('critérios seleccionados continuam acessíveis quando já não constam das opções', () => {
const html = render('documents', {
topic: 'Tema antigo',
activity: ['CAE antigo'],
stage: ['Etapa antiga'],
module: ['outro'],
territory_id: 'old-territory',
});
for (const value of [
'Tema antigo',
'CAE antigo',
'Etapa antiga',
'Documentos de apoio',
'old-territory',
'Localização seleccionada indisponível',
])
assert.ok(html.includes(value), value);
});
@@ -0,0 +1,55 @@
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';
const require = createRequire(import.meta.url);
let states = [], formData;
const mockReact = { ...React, useState: initial => [states.length ? states.shift() : initial, () => {}], useEffect() {} };
function load(file, appended = '') {
const code = ts.transpileModule(fs.readFileSync(new URL('../../resources/js/pages/' + file, import.meta.url), 'utf8') + appended, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX } }).outputText;
const module = { exports: {} };
new Function('require', 'module', 'exports', code)(name => {
if (name === 'react') return mockReact;
if (name === 'react/jsx-runtime') return require(name);
if (name === '@inertiajs/react') return { useForm: data => { formData = data; return {data, errors: {}, processing: false, setData() {}, post() {}}; } };
if (name === './shared') return { Field: ({label, children}) => React.createElement('label', null, label, children), button: '', control: '', input: '', card: '' };
return {};
}, module, module.exports);
return module.exports;
}
const { ZoneReview, ZoneHistory } = load('investment/zone.tsx', '\nexport { ZoneReview, ZoneHistory };');
const SubjectForm = load('management/editorial-subject-form.tsx').default;
const zone = { id: 'synthetic-zone', version_no: 8, editorial_workflow: { state: 'in_review', content_version: 3, fresh: true, can_approve: true } };
const renderReview = (patch = {}, dirty = false) => { states = ['Documentary review reason']; return renderToStaticMarkup(React.createElement(ZoneReview, {zone: {...zone, editorial_workflow: {...zone.editorial_workflow, ...patch}}, busy: false, dirty, action() {}})); };
test('zone review separates approval from publication and hides unauthorised approval', () => {
const html = renderReview();
assert.match(html, /Aprovar esta edição/);
assert.doesNotMatch(html, />Publicar/);
assert.doesNotMatch(renderReview({can_approve: false}), /Aprovar esta edição/);
});
test('changed sources and unsaved edits disable decisions without hiding the history', () => {
for (const html of [renderReview({fresh: false}), renderReview({}, true)]) assert.match(html, /disabled=""[^>]*>Aprovar esta edição/);
assert.match(renderReview({fresh: false}), /fonte ou anexos mudaram/);
});
test('history displays exact observation and source without applying it', () => {
states = [{version_no: 4, fields: {name: 'Historical zone', description: 'Preserved description'}, observations: [{label: 'Investment', value: '9007199254740.25', unit: 'MZN', scope: 'Synthetic zone', source_reference: 'Report page 2'}]}, '', false];
const html = renderToStaticMarkup(React.createElement(ZoneHistory, {id: 'synthetic-zone', revisions: [{version_no: 4, action: 'profile_prepared', created_at: '2026-11-14'}]}));
assert.match(html, /9007199254740.25/);
assert.match(html, /Report page 2/);
assert.match(html, /preserva a versão actual/);
assert.doesNotMatch(html, /Restaurar|Publicar/);
});
test('structural form preserves revision and selected values and opens progressively', () => {
const props = {base: '/management/editorial/subjects/projects/synthetic', revision: 7, fields: [{name: 'name', label: 'Designação', type: 'text', options: []}], initial: {name: 'Deliberate edit'}};
states = [false];
assert.doesNotMatch(renderToStaticMarkup(React.createElement(SubjectForm, props)), /textarea/);
states = [true];
const html = renderToStaticMarkup(React.createElement(SubjectForm, props));
assert.equal(formData.expected_revision, 7);
assert.equal(formData.fields.name, 'Deliberate edit');
assert.match(html, /Deliberate edit/);
assert.match(html, /publicação expressa da decisão/);
});
@@ -0,0 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
test('compiled dashboard remains a resolvable page entry for authenticated full HTML', () => {
const manifestPath=process.env.EDITORIAL_BUILD_MANIFEST || fileURLToPath(new URL('../../public/build/manifest.json',import.meta.url));
const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));
const key='resources/js/pages/management/editorial-workflow.tsx';
assert.ok(manifest[key], 'Dashboard page entry missing; a shared chunk cannot satisfy the server-rendered Vite directive');
assert.equal(manifest[key].isDynamicEntry || manifest[key].isEntry, true);
assert.ok(fs.existsSync(path.join(path.dirname(manifestPath),manifest[key].file)));
});
@@ -0,0 +1,23 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {createRequire} from 'node:module';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import ts from 'typescript';
const require=createRequire(import.meta.url), module={exports:{}};
const code=ts.transpileModule(fs.readFileSync(new URL('../../resources/js/pages/management/editorial-workflow.tsx',import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText;
new Function('require','module','exports',code)(name=>name==='@/lib/editorial-states'?{states:{}}:name==='@inertiajs/react'?{Link:({href,children,...props})=>React.createElement('a',{href,...props},children),router:{}}:name==='./shared'?{Management:({title,children})=>React.createElement('main',null,React.createElement('h1',null,title),children),Field:({label,children})=>React.createElement('label',null,label,children),button:'',control:''}:require(name),module,module.exports);
const base={items:{data:[],current_page:1,last_page:1},notices:[],resourceAccess:true,opportunitiesUrl:'/opportunities-qa',opportunityPending:2,clustersUrl:'/clusters-qa',nativePending:{clusters:3,territories:0,zones:0},subjectsUrl:'/subjects-qa',territorialUrl:'/territories-qa',demographyUrl:'/demography-qa'};
test('dashboard groups authorised activities once with contextual counts and an empty notification state',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,base));
for(const title of ['Conteúdos e oportunidades','Investimentos e competitividade','Território e dados'])assert.match(html,new RegExp(title));
assert.equal((html.match(/href="\/opportunities-qa"/g)??[]).length,1);
assert.match(html,/2 pendentes/);assert.match(html,/3 pendentes/);
assert.match(html,/Não há notificações neste âmbito/);
assert.match(html,/md:grid-cols-2 xl:grid-cols-3/);
});
test('restricted dashboard omits unavailable groups, private content controls and counters',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{items:base.items,notices:[],resourceAccess:false,opportunitiesUrl:null,opportunityPending:0}));
assert.doesNotMatch(html,/Fila de conteúdos|kind=legislation|Biblioteca e editores|Investimentos e competitividade|Território e dados/);
});
+272
View File
@@ -0,0 +1,272 @@
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';
const require = createRequire(import.meta.url);
const source = fs.readFileSync(
new URL(
'../../resources/js/pages/management/editorial-edition.tsx',
import.meta.url,
),
'utf8',
);
const code = 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', code)(
(name) => {
if (name === './editorial-subject-form') return { default: () => null };
if (name === '../portfolio/shared')
return { labels: { description: 'Visão e proposta de valor' } };
if (name === '@inertiajs/react')
return {
Link: ({ href, children, ...rest }) =>
React.createElement('a', { href, ...rest }, children),
useForm: (data) => ({
data,
errors: {},
processing: false,
setData() {},
transform() {},
post() {},
}),
};
if (name === './shared')
return {
Management: ({ children }) =>
React.createElement('main', null, children),
Field: ({ label, children }) =>
React.createElement('label', null, label, children),
control: '',
button: '',
};
if (name === '@/lib/editorial-states')
return {
states: {
draft: 'Rascunho',
approved: 'Aprovado',
in_review: 'Em revisão',
},
};
return require(name);
},
module,
module.exports,
);
const Page = module.exports.default;
const props = {
resource: {
id: 91,
title: 'Artigo QA',
published: true,
public_edition_no: 1,
},
manager: true,
legalReviewer: true,
current: true,
canApprove: true,
independentRequired: true,
history: [],
editions: [{ id: 'qa-edition', revision_no: 2, state: 'draft' }],
reviewers: [{ id: 5, name: 'Equipa de revisão' }],
edition: {
id: 'qa-edition',
revision_no: 2,
version: 1,
state: 'draft',
content_hash: 'a'.repeat(64),
fresh: true,
legal_required: false,
approval: null,
legal_validation: null,
payload: {
resource: {
title: 'Novo título',
editorial_content: JSON.stringify({
body: '<script>não executar</script>',
}),
},
files: [
{
id: 'qa-file',
file_name: 'anexo.pdf',
version_no: 2,
sha256: 'b'.repeat(64),
},
],
},
},
};
const render = (changes = {}) =>
renderToStaticMarkup(React.createElement(Page, { ...props, ...changes }));
test('draft preserves public version and offers submission without approval or publication', () => {
const html = render();
assert.match(html, /Versão pública: edição 1/);
assert.match(html, /value="submit"/);
assert.doesNotMatch(html, /value="(?:approve|publish)"/);
assert.match(
html,
/href="\/management\/editorial\/resources\/91\/editions\/qa-edition\/files\/qa-file" target="_blank" rel="noopener noreferrer"/,
);
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>/);
});
test('approved edition offers explicit publication; stale files and historical versions cannot be published', () => {
assert.match(
render({
edition: { ...props.edition, state: 'approved', approval: '{}' },
}),
/value="publish"/,
);
const stale = render({
edition: { ...props.edition, state: 'approved', fresh: false },
});
assert.match(stale, /O conteúdo, contexto ou anexos mudaram/);
assert.doesNotMatch(stale, /value="publish"/);
const staleReview = render({
edition: { ...props.edition, state: 'in_review', fresh: false },
});
assert.match(staleReview, /value="return"/);
assert.doesNotMatch(staleReview, /value="approve"/);
const historical = render({ current: false });
assert.match(historical, /Versão histórica para consulta/);
assert.doesNotMatch(historical, /<form/);
assert.match(historical, /edition=qa-edition/);
});
test('contributor does not see independent approval or legal-validation actions', () => {
const html = render({
canApprove: false,
edition: { ...props.edition, state: 'in_review' },
});
assert.doesNotMatch(html, /value="(?:approve|legal_validate)"/);
assert.match(html, /responsável independente/);
});
test('portfolio edition reuses review screen with its own context, history and edit routes', () => {
const html = render({
subject: 'portfolio',
resource: { ...props.resource, id: 'qa-dossier' },
edition: {
...props.edition,
payload: {
...props.edition.payload,
resource: {
title: 'Ficha privada',
source: 'Fonte QA',
content: { description: '<script>não executar</script>' },
},
files: [],
links: [
{
target_type: 'projects',
target_key: 'qa-project',
context: { name: 'Projecto QA', code: 'QA-1' },
},
],
},
},
});
assert.match(html, /href="\/management\/portfolio\/qa-dossier"/);
assert.match(
html,
/\/management\/editorial\/portfolio\/qa-dossier\?edition=qa-edition/,
);
assert.match(html, /Visão e proposta de valor/);
assert.match(html, /Contexto: Projecto QA/);
assert.doesNotMatch(html, /Alterar artigo|Alterar metadados\/documento/);
assert.match(html, /&lt;script&gt;/);
});
test('portfolio contributor cannot select publication of an approved edition', () => {
assert.doesNotMatch(
render({
subject: 'portfolio',
canApprove: false,
edition: { ...props.edition, state: 'approved' },
}),
/value="publish"/,
);
assert.match(
render({
subject: 'portfolio',
canApprove: true,
edition: { ...props.edition, state: 'approved' },
}),
/value="publish"/,
);
});
test('portfolio review presents proposed base data and territory without applying them', () => {
const html = render({
subject: 'portfolio',
edition: {
...props.edition,
payload: {
...props.edition.payload,
resource: {
title: 'Ficha existente',
_structure: {
fields: {
name: 'Nome proposto',
budget_amount: '999999999999999999.99',
primary_territory_id: 'qa-district',
territory_version: 1,
},
territory_context: [
{ id: 'qa-district', name: 'Distrito sintético' },
],
},
},
files: [],
},
},
});
assert.match(html, /Alterações propostas nos dados-base/);
assert.match(html, /Nome proposto/);
assert.match(html, /999999999999999999.99/);
assert.match(html, /Localização proposta: Distrito sintético/);
assert.doesNotMatch(html, /qa-district|territory_version/);
});
test('demographic edition presents provenance, warnings and protected original with a separate publication step', () => {
const html = render({
subject: 'demography',
resource: { ...props.resource, id: 'qa-batch', published: false },
edition: {
...props.edition,
state: 'approved',
payload: {
...props.edition.payload,
resource: {
title: 'Exemplar sintético',
source: 'Fonte QA',
publication_version: 'Edição não indicada no original',
observations: 10,
sha256: 'a'.repeat(64),
dataset_hash: 'b'.repeat(64),
report: { issue_counts: { unit_not_supplied: 2 } },
},
files: [],
},
},
});
assert.match(html, /10 observações conferidas/);
assert.match(html, /Edição não indicada no original/);
assert.match(html, /unit_not_supplied: 2 advertências conservadas/);
assert.match(
html,
/href="\/management\/editorial\/demography\/qa-batch\/original"/,
);
assert.match(html, /value="publish"/);
assert.doesNotMatch(html, /Alterar artigo|Alterar ficha da carteira/);
});
@@ -325,7 +325,8 @@ void test('financial tools CSV records reproducible assumptions, periods, formul
});
assert.match(csv, /^\uFEFF/);
assert.match(csv, /financial-tools-v1/);
assert.match(csv, /valores iniciais sao exemplos demonstrativos/);
assert.match(csv, /Pressupostos editáveis introduzidos ou recuperados pelo utilizador/);
assert.doesNotMatch(csv, /valores iniciais sao exemplos demonstrativos/);
assert.match(csv, /2026-10-02T10:00:00\.000Z/);
assert.match(csv, /Período do orçamento e dos custos fixos,Mensal/);
assert.match(csv, /saldo decrescente/i);
@@ -0,0 +1,46 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import * as finance from '../../resources/js/lib/financial-calculators.ts';
import * as contract from '../../resources/js/lib/simulation-contract.ts';
import * as fundingContext from '../../resources/js/lib/planning-finance-context.ts';
const require = createRequire(import.meta.url);
const nodes = tree => Array.isArray(tree) ? tree.flatMap(nodes) : tree && typeof tree === 'object' ? [tree, ...nodes(tree.props?.children)] : [];
const text = tree => Array.isArray(tree) ? tree.map(text).join('') : tree?.props ? text(tree.props.children) : typeof tree === 'string' ? tree : '';
function harness(snapshot = '') {
let cursor=0, queue=[], dirty=false, tree;
const memory=[], deps=[];
const hooks={...React, useState(initial) {const id=cursor++;if(!(id in memory))memory[id]=typeof initial==='function'?initial():initial;return[memory[id],next=>{const value=typeof next==='function'?next(memory[id]):next;if(!Object.is(value,memory[id])){memory[id]=value;dirty=true;}}];},useEffect(effect, next) {const id=cursor++;if(!deps[id]||next.some((value,i)=>!Object.is(value,deps[id][i]))){queue.push(effect);deps[id]=next;}}};
const module={exports:{}};
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:require(id),module,module.exports);
const props={currency:'MZN',focus:'funding',loanRelevant:false,snapshot,sourceFunding:{total:'2000000',secured:''},onSnapshotChange(value){props.snapshot=value;dirty=true;},onCurrencyChange(){},onFundingChange(key,value){props.sourceFunding={...props.sourceFunding,[key]:value};dirty=true;}};
const render=()=>{for(let i=0;i<12;i++){cursor=0;queue=[];dirty=false;tree=module.exports.SimulationFinancialTools(props);for(const effect of queue)effect();if(!dirty)return;}throw new Error('Render did not settle');};
render();
return{props,render,text:()=>text(tree),field:label=>nodes(tree).find(node=>node.props?.label===label),button:label=>nodes(tree).find(node=>node.type==='button'&&text(node).startsWith(label))};
}
test('editing canonical mobilised funding updates the attached calculator and snapshot without showing hidden-tool errors',()=>{
const h=harness();
h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
assert.match(h.text(),/1000000.00/);
assert.equal(finance.restoreFinancialToolsSnapshot(h.props.snapshot).funding.secured,'1000000');
assert.doesNotMatch(h.text(),/Empréstimo:|Ponto de equilíbrio:|Orçamento:|valores da calculadora diferem/);
assert.equal(h.button('Exportar resultados'),undefined);
});
test('a known different recovered calculator value is preserved until the user resolves its source',()=>{
const snapshot=finance.serializeFinancialToolsSnapshot({budgetPeriod:'Mensal',loan:{principal:'',rate:'',months:'',rateType:'nominal',periodMonths:'1',gracePeriods:'',upfrontFee:'',recurringFee:''},breakEven:{fixed:'',price:'',variable:''},funding:{total:'2000000',secured:'250000'},incomes:[{label:'Receitas',amount:''}],expenses:[{label:'Custos',amount:''}]});
const h=harness(snapshot);h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
assert.equal(h.field('Montante já mobilizado').props.value,'250000');
assert.match(h.text(),/valores da calculadora diferem/);
h.button('Usar os valores do investimento').props.onClick();h.render();
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
h.props.sourceFunding={total:'2000000',secured:'1500000'};h.render();
assert.equal(h.field('Montante já mobilizado').props.value,'1500000');
assert.match(h.text(),/500000.00/);
});
@@ -0,0 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import { monthlyIvaInput } from '../../resources/js/lib/monthly-iva.ts';
const require = createRequire(import.meta.url);
const module = { exports: {} };
const Choice = () => null;
compileFunction(
ts.transpileModule(
fs.readFileSync(
'resources/js/components/fiscal-operation-picker.tsx',
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText,
['require', 'module', 'exports'],
)(
(id) =>
id === '@/components/catalogue-choice-select'
? { default: Choice }
: require(id),
module,
module.exports,
);
const nodes = (tree) =>
Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
test('additional treatments are not mounted until explicitly selected, and removal preserves their stored data', () => {
const mounted = [];
const state = {
selected: ['irpc:normal'],
saved: 'unchanged-private-snapshot',
};
const props = {
family: 'iva',
selected: state.selected,
operations: ['miners', 'fuel', 'travel'].map((id) => ({
id,
label: `Operação ${id}`,
description: 'Confirmar se aplicável.',
render() {
mounted.push(id);
return React.createElement('div', null, id);
},
})),
onChange(selected) {
state.selected = selected;
props.selected = selected;
},
};
let tree = module.exports.default(props);
assert.deepEqual(
mounted,
[],
'a list of available treatments is not a declaration that they apply',
);
nodes(tree)
.find((node) => node.type === Choice)
.props.onChange('fuel');
assert.deepEqual(state.selected, ['irpc:normal', 'iva:fuel']);
tree = module.exports.default(props);
assert.deepEqual(mounted, ['fuel']);
nodes(tree)
.find((node) => node.type === 'button')
.props.onClick();
assert.deepEqual(state.selected, ['irpc:normal']);
assert.equal(state.saved, 'unchanged-private-snapshot');
});
test('a chosen 2027 period cannot silently use a 2026 monthly IVA projection', () => {
const settings = {
start: '2026-01',
basis: 'net',
declared: true,
auto: false,
};
assert.throws(
() => monthlyIvaInput({ fiscal_period: '2027' }, settings),
/nenhum ano foi alterado/,
);
assert.throws(
() =>
monthlyIvaInput(
{ fiscal_period: '2027' },
{ ...settings, start: '2027-01' },
),
/cobertura apenas para 2026/,
);
assert.equal(settings.start, '2026-01');
});
@@ -0,0 +1,225 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { createRequire } from "node:module";
import { compileFunction } from "node:vm";
import React from "react";
import ts from "typescript";
const require = createRequire(import.meta.url);
const nodes = (tree) =>
Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === "object"
? [tree, ...nodes(tree.props?.children)]
: [];
const text = (tree) =>
Array.isArray(tree)
? tree.map(text).join("")
: tree?.props
? text(tree.props.children)
: typeof tree === "string"
? tree
: "";
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
function harness(filters, errors = {}) {
const memory = [];
let cursor = 0;
const state = (initial) => {
const id = cursor++;
if (!(id in memory)) memory[id] = initial;
return [
memory[id],
(next) => {
memory[id] = typeof next === "function" ? next(memory[id]) : next;
},
];
};
let submitted;
let form;
const TerritoryFields = () => null;
const module = { exports: {} };
const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
compileFunction(
ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText,
["require", "module", "exports"],
)(
(id) => {
if (id === "react")
return {
...React,
useState: state,
useRef(initial) {
const [value] = state({ current: initial });
return value;
},
};
if (id === "@inertiajs/react")
return {
Link: "a",
useForm(initial) {
const [data, set] = state(initial);
form = {
data,
errors: {},
processing: false,
setData(key, value) {
set(typeof key === "string" ? { ...data, [key]: value } : key);
},
get(url) {
submitted = { url, data };
},
};
return form;
},
};
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
if (id === "@/components/funding-classification")
return {
financialCategories: {
banking: "Banca",
insurance_intermediation: "Mediação de seguros",
},
financialTypes: {
commercial_bank: "Banco comercial",
broker: "Corretora",
other: "Outro",
},
};
if (id === "@/components/investment-territory") return { TerritoryFields };
if (id === "@/components/funding-institution") return { InstitutionView: "article" };
if (id === "./shared") return { windowLabels: {} };
return require(id);
},
module,
module.exports,
);
const props = {
filters,
criteriaErrors: errors,
items: { data: [], links: [] },
options: { sectors: [], territories: [] },
kinds: { institution: "Instituição", fund: "Fundo" },
management: false,
categoryTypes: {
banking: ["commercial_bank"],
insurance_intermediation: ["broker"],
},
};
let tree;
function render() {
cursor = 0;
const wrapper = module.exports.default(props);
tree = wrapper.type(wrapper.props);
return tree;
}
const select = (label) =>
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
(n) => n.type === "select",
);
render();
return {
render,
select,
form: () => form,
tree: () => tree,
submitted: () => submitted,
territory: () => nodes(tree).find((n) => n.type === TerritoryFields),
};
}
test("institution category restricts types and removes only an incompatible dependent choice", () => {
const h = harness({
category: "insurance_intermediation",
institution_type: "broker",
sector: "7",
need: "investment",
territory: "district-qa",
});
h.select("Categoria da instituição").props.onChange({
target: { value: "banking" },
});
h.render();
assert.equal(h.form().data.institution_type, "");
for (const [key, value] of Object.entries({
sector: "7",
need: "investment",
territory: "district-qa",
}))
assert.equal(h.form().data[key], value);
assert.deepEqual(
nodes(h.select("Tipo de instituição"))
.filter((n) => n.type === "option")
.map((n) => n.props.value),
["", "commercial_bank", "other"],
);
assert.match(text(h.tree()), /tipo anterior não pertence/);
const results = nodes(h.tree()).find((n) => n.type === "details");
assert.equal(results.props.open, false);
assert.match(text(results), /pesquisa anterior/);
});
test("contradictory record criteria remain explicit until the user chooses a correction", () => {
const h = harness(
{
kind: "fund",
category: "banking",
institution_type: "commercial_bank",
location_mode: "physical",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
},
{ kind: ["Combinação incompatível."] },
);
assert.match(text(h.tree()), /A pesquisa não foi executada/);
assert.equal(h.form().data.kind, "fund");
const action = nodes(h.tree()).find(
(n) => n.type === "button" && /Manter o fundo/.test(text(n)),
);
action.props.onClick();
h.render();
assert.equal(h.form().data.category, "");
assert.equal(h.form().data.institution_type, "");
assert.equal(h.form().data.location_mode, "coverage");
for (const [key, value] of Object.entries({
kind: "fund",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
}))
assert.equal(h.form().data[key], value);
nodes(h.tree())
.find((n) => n.type === "form")
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted().url, "/fundos");
assert.equal(h.submitted().data.province_id, "province-qa");
assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
});
test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
const h = harness({ territory: "district-qa", sector: "7" });
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
h.render();
assert.equal(h.form().data.certainty, "documented");
assert.equal(h.form().data.territory, "district-qa");
assert.equal(h.form().data.sector, "7");
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
h.render();
assert.equal(h.form().data.certainty, "include_unknown");
const resumed = harness({
location_mode: "physical",
territory: "district-qa",
certainty: "include_unknown",
});
assert.equal(resumed.form().data.certainty, "include_unknown");
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
});
@@ -1,31 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
import * as presentation from '../../resources/js/lib/funding-public-presentation.ts';
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { compileFunction } from "node:vm";
import { createRequire } from "node:module";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import ts from "typescript";
import * as presentation from "../../resources/js/lib/funding-public-presentation.ts";
const require = createRequire(import.meta.url),
records = Object.values(
JSON.parse(
fs.readFileSync(
new URL(
'../../database/data/funding-institutions-nov2026.json',
import.meta.url,
),
'utf8',
new URL("../../database/data/funding-institutions-nov2026.json", import.meta.url),
"utf8",
),
).references,
).map((x) => x.draft);
function load(file) {
const module = { exports: {} };
const output = ts.transpileModule(
fs.readFileSync(
new URL('../../resources/js/' + file, import.meta.url),
'utf8',
),
fs.readFileSync(new URL("../../resources/js/" + file, import.meta.url), "utf8"),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
@@ -34,98 +29,89 @@ function load(file) {
},
},
).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
compileFunction(output, ["require", "module", "exports"])(
(name) =>
name === '@/lib/funding-public-presentation'
name === "@/lib/funding-public-presentation"
? presentation
: name === '@/pages/investment/shared'
: name === "@/pages/investment/shared"
? {
Frame: ({ title, children }) =>
React.createElement(
'main',
"main",
null,
React.createElement('h1', null, title),
React.createElement("h1", null, title),
children,
),
card: 'card',
button: 'button',
input: 'input',
card: "card",
button: "button",
input: "input",
}
: name === '@inertiajs/react'
: name === "@inertiajs/react"
? {
Link: ({ children, href }) =>
React.createElement('a', { href }, children),
React.createElement("a", { href }, children),
router: {},
useForm: (data) => ({ data, setData() {}, get() {} }),
useForm: (data) => ({ data, errors: {}, setData() {}, get() {} }),
}
: name === './shared'
: name === "./shared"
? { windowLabels: {} }
: name === '@/lib/portal-api'
: name === "@/lib/portal-api"
? {
portalRequest: () => {
throw Error(
'Read-only rendering must not send requests',
);
throw Error("Read-only rendering must not send requests");
},
}
: name === '@/components/funding-classification'
? load('components/funding-classification.tsx')
: name === '@/components/funding-institution'
? load('components/funding-institution.tsx')
: name === '@/components/funding-dossier-choice'
: name === "@/components/funding-classification"
? load("components/funding-classification.tsx")
: name === "@/components/funding-institution"
? load("components/funding-institution.tsx")
: name === "@/components/funding-dossier-choice"
? { FundingDossierChoice: () => null }
: name ===
'@/components/funding-criteria-assessment'
? load(
'components/funding-criteria-assessment.tsx',
)
: require(name),
: name === "@/components/funding-criteria-assessment"
? load("components/funding-criteria-assessment.tsx")
: resolveLocal(name, file),
module,
module.exports,
);
return module.exports;
}
test('all270 imported institutions get readable descriptions and evidenced services without changing the published payload', () => {
test("all270 imported institutions get readable descriptions and evidenced services without changing the published payload", () => {
assert.equal(records.length, 270);
for (const p of records) {
const original = JSON.stringify(p),
m = presentation.fundingPublicPresentation(p);
assert.ok(m.description);
assert.doesNotMatch(
m.description,
/documento fornecido|ficha|SHA-256|Público\/finalidade/,
);
assert.doesNotMatch(m.description, /documento fornecido|ficha|SHA-256|Público\/finalidade/);
assert.equal(JSON.stringify(p), original);
assert.equal(
m.products.length,
(p.products ?? []).filter((x) => x.availability !== 'closed')
.length,
(p.products ?? []).filter((x) => x.availability !== "closed").length,
);
}
});
test('deliberate editorial descriptions survive and missing products are never fabricated', () => {
test("deliberate editorial descriptions survive and missing products are never fabricated", () => {
const m = presentation.fundingPublicPresentation({
title: 'Example',
kind: 'institution',
summary: 'Apoio especializado ao investimento rural.',
title: "Example",
kind: "institution",
summary: "Apoio especializado ao investimento rural.",
products: [],
institution_types: ['insurer'],
institution_types: ["insurer"],
});
assert.equal(m.description, 'Apoio especializado ao investimento rural.');
assert.equal(m.description, "Apoio especializado ao investimento rural.");
assert.deepEqual(m.products, []);
assert.deepEqual(m.services, []);
});
test('actual public cards and detail lead with description/products and keep import metadata out of the visitor text', () => {
const Index = load('pages/funding/index.tsx').default,
Show = load('pages/funding/show.tsx').default;
test("actual public cards and detail lead with description/products and keep import metadata out of the visitor text", () => {
const Index = load("pages/funding/index.tsx").default,
Show = load("pages/funding/show.tsx").default;
for (const raw of [
records[0],
records.find((p) => p.institution_types.includes('investment_manager')),
records.find((p) => p.institution_types.includes("investment_manager")),
]) {
const p = { ...raw, windows: [], documents: [] },
item = {
id: 'synthetic',
version_id: 'synthetic-version',
id: "synthetic",
version_id: "synthetic-version",
version: 1,
payload: p,
};
@@ -151,23 +137,15 @@ test('actual public cards and detail lead with description/products and keep imp
/ficha|documento fornecido|SHA-256|linha de origem|Instituições financeiras em Moçambique\.docx/i,
);
assert.match(html, /Produtos e serviços/);
assert.match(
html,
new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
);
assert.match(html, new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
}
const out = new URL(
'../../outputs/funding-public-editorial-20261111/',
import.meta.url,
);
const out = new URL("../../outputs/funding-public-editorial-20261111/", import.meta.url);
fs.mkdirSync(out, { recursive: true });
const name = p.products.length
? 'bank-with-products'
: 'investment-manager';
fs.writeFileSync(new URL(name + '-index.html', out), index);
fs.writeFileSync(new URL(name + '-detail.html', out), detail);
const name = p.products.length ? "bank-with-products" : "investment-manager";
fs.writeFileSync(new URL(name + "-index.html", out), index);
fs.writeFileSync(new URL(name + "-detail.html", out), detail);
fs.writeFileSync(
new URL('verification.json', out),
new URL("verification.json", out),
JSON.stringify(
{
publishedSourceRecords: 270,
@@ -188,21 +166,18 @@ test('actual public cards and detail lead with description/products and keep imp
}
});
test('Quorus and Moza use one shared clean profile in both list and detail', () => {
const Index = load('pages/funding/index.tsx').default,
Show = load('pages/funding/show.tsx').default;
const out = new URL(
'../../outputs/funding-uniform-menu-20261111/',
import.meta.url,
);
test("Quorus and Moza use one shared clean profile in both list and detail", () => {
const Index = load("pages/funding/index.tsx").default,
Show = load("pages/funding/show.tsx").default;
const out = new URL("../../outputs/funding-uniform-menu-20261111/", import.meta.url);
fs.mkdirSync(out, { recursive: true });
for (const title of ['Quorus', 'Moza Banco']) {
for (const title of ["Quorus", "Moza Banco"]) {
const raw = records.find((p) => p.title === title);
assert.ok(raw, title);
const p = { ...raw, windows: [], documents: [] },
item = {
id: 'synthetic',
version_id: 'synthetic-version',
id: "synthetic",
version_id: "synthetic-version",
version: 1,
payload: p,
};
@@ -223,8 +198,7 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
}),
);
for (const html of [
index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ??
index,
index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ?? index,
detail,
]) {
assert.doesNotMatch(
@@ -234,65 +208,108 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
assert.equal((html.match(/Produtos e serviços/g) || []).length, 1);
assert.equal((html.match(/Descrição/g) || []).length, 1);
}
if (title === 'Quorus') {
assert.equal(
(detail.match(/Entidade de corretagem de seguros/g) || [])
.length,
1,
);
assert.doesNotMatch(
detail,
/<h3[^>]*>Contactos|<h3[^>]*>Localização/,
);
if (title === "Quorus") {
assert.equal((detail.match(/Entidade de corretagem de seguros/g) || []).length, 1);
assert.doesNotMatch(detail, /<h3[^>]*>Contactos|<h3[^>]*>Localização/);
} else {
assert.equal((detail.match(/21 342 000/g) || []).length, 1);
assert.equal((detail.match(/Rua dos Desportistas/g) || []).length, 1);
assert.equal(
(detail.match(/Rua dos Desportistas/g) || []).length,
1,
);
assert.equal(
(
detail.match(
/Tesouraria, investimento, construção e equipamento/g,
) || []
).length,
(detail.match(/Tesouraria, investimento, construção e equipamento/g) || []).length,
1,
);
assert.doesNotMatch(detail, /500\.000|30\.000\.000|Prime|spread/);
}
fs.writeFileSync(
new URL(title.replaceAll(' ', '-') + '-index.html', out),
index,
);
fs.writeFileSync(
new URL(title.replaceAll(' ', '-') + '-detail.html', out),
detail,
);
fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-index.html", out), index);
fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-detail.html", out), detail);
}
});
test('contact and location deduplication preserves different branches and original records', () => {
const moza = records.find((p) => p.title === 'Moza Banco'),
test("contact and location deduplication preserves different branches and original records", () => {
const moza = records.find((p) => p.title === "Moza Banco"),
original = JSON.stringify(moza);
assert.equal(
presentation
.publicInstitutionContacts(moza.contacts)
.filter((c) => c.kind === 'phone').length,
1,
);
assert.equal(
presentation.publicInstitutionLocations(moza.locations).length,
presentation.publicInstitutionContacts(moza.contacts).filter((c) => c.kind === "phone")
.length,
1,
);
assert.equal(presentation.publicInstitutionLocations(moza.locations).length, 1);
assert.equal(
presentation.publicInstitutionLocations([
...moza.locations,
{
...moza.locations[0],
role: 'branch',
address: 'Rua dos Desportistas, número 714',
role: "branch",
address: "Rua dos Desportistas, número 714",
},
]).length,
2,
);
assert.equal(JSON.stringify(moza), original);
});
function resolveLocal(name, parent) {
if (name === "./territory-geometry-preview") return { default: () => null };
const relative = name.startsWith("@/")
? name.slice(2)
: name.startsWith(".")
? path.posix.join(path.posix.dirname(parent), name)
: null;
if (relative)
for (const candidate of [relative, relative + ".tsx", relative + ".ts"]) {
if (fs.existsSync(new URL("../../resources/js/" + candidate, import.meta.url)))
return load(candidate);
}
return require(name);
}
test("physical presence matches descendants, not a broader province or unknown locations", () => {
const points = [
{
territory_id: "district-a",
territory_path: [
{ id: "province", name: "Province" },
{ id: "district-a", name: "A" },
],
evidence_status: "reported",
},
{
territory_id: "province",
territory_path: [{ id: "province", name: "Province" }],
evidence_status: "reported",
},
{ territory_id: "district-a", evidence_status: "to_confirm" },
{ territory_id: "district-a", evidence_status: "historical" },
{ territory_id: "" },
];
assert.deepEqual(presentation.matchingInstitutionLocations(points, "district-a"), [points[0]]);
assert.deepEqual(
presentation.matchingInstitutionLocations(points, "province"),
points.slice(0, 2),
);
assert.deepEqual(presentation.matchingInstitutionLocations(points, "elsewhere"), []);
});
test("compact institutions show local address and explicitly identify unconfirmed physical presence", () => {
const { InstitutionView } = load("components/funding-institution.tsx");
const value = {
...records[0],
locations: [
{
role: "branch",
address: "Balcão de Tete",
territory_id: "tete",
territory_path: [{ id: "tete", name: "Tete" }],
},
{ role: "headquarters", address: "Sede Maputo", territory_id: "maputo" },
],
};
const render = (territory, compact = true) =>
renderToStaticMarkup(
React.createElement(InstitutionView, { value, compact, physicalTerritory: territory }),
);
assert.match(render("tete"), /Balcão de Tete/);
assert.doesNotMatch(render("tete"), /Sede Maputo|Presença física por confirmar/);
assert.match(render("niassa"), /Presença física por confirmar no local escolhido/);
assert.doesNotMatch(render("niassa"), /Balcão de Tete|Sede Maputo/);
assert.match(render("tete", false), /Sede Maputo/);
assert.match(render("tete", false), /Balcão de Tete/);
});
@@ -212,6 +212,15 @@ export function harness(initial = props()) {
mocks['@/lib/investment-profile-editor'] = load(
'resources/js/lib/investment-profile-editor.ts',
);
mocks['@/lib/catalogue-choice'] = load(
'resources/js/lib/catalogue-choice.ts',
);
mocks['./territory-search-select'] = load(
'resources/js/components/territory-search-select.tsx',
);
mocks['./catalogue-choice-select'] = load(
'resources/js/components/catalogue-choice-select.tsx',
);
mocks['./country-select'] = load(
'resources/js/components/country-select.tsx',
);
@@ -324,17 +333,36 @@ export function harness(initial = props()) {
return nodes(formLabel ? this.form(formLabel) : tree).find(
(n) =>
['input', 'textarea', 'select'].includes(n.type) &&
n.props['aria-label'] === label,
(n.props['aria-label'] === label ||
(n.props.role === 'combobox' &&
n.props['aria-label'] === 'Pesquisar ' + label)),
);
},
value(label, formLabel) {
return this.field(label, formLabel)?.props.value;
const field = this.field(label, formLabel);
// The public control shows the readable label; domain assertions use its ISO code.
return field?.props.role === 'combobox'
? (field.props.value.match(/— ([A-Z]{2})$/)?.[1] ??
field.props.value)
: field?.props.value;
},
change(label, value, formLabel) {
const field = this.field(label, formLabel);
if (!field) throw Error('Missing field ' + label);
field.props.onChange({ target: { value } });
render();
if (field.props.role === 'combobox') {
const option = nodes(
formLabel ? this.form(formLabel) : tree,
).find(
(node) =>
node.props?.role === 'option' &&
text(node).endsWith('— ' + value),
);
if (!option) throw Error('Missing selectable country ' + value);
option.props.onClick();
render();
}
},
button(label, formLabel) {
return nodes(formLabel ? this.form(formLabel) : tree).find(
@@ -70,3 +70,92 @@ await test('blocked browser storage cannot prevent authentication or clearing a
'/participar/entrar?return=%2Foportunidades%2Fteste%3Fsector%3D1',
);
});
test('reused interest hook isolates opportunities, retains deliberate edits and restores after reload', () => {
const source = fs.readFileSync(
new URL(
'../../resources/js/hooks/use-interest-draft.ts',
import.meta.url,
),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}).outputText;
const saved = new Map();
let sequence = 0;
function mount(storage = saved) {
let value, changed, effect;
const module = { exports: {} };
compileFunction(output, [
'require',
'module',
'exports',
'sessionStorage',
'window',
'location',
])(
(name) =>
name === 'react'
? {
useState(init) {
value ??= init();
return [
value,
(next) => {
value =
typeof next === 'function'
? next(value)
: next;
changed = true;
},
];
},
useEffect(callback) {
effect = callback;
},
}
: { newSubmissionKey: () => 'synthetic-' + ++sequence },
module,
module.exports,
{
getItem: (key) => storage.get(key) ?? null,
setItem: (key, data) => storage.set(key, data),
removeItem: (key) => storage.delete(key),
},
{ location: { assign() {} } },
{ pathname: '/negocios/a', search: '?province_id=p' },
);
return (name, initial = { message: 'initial ' + name }) => {
changed = false;
let result = module.exports.useInterestDraft(name, initial);
// React discards a render-phase reset and renders the new scoped state.
if (changed)
result = module.exports.useInterestDraft(name, initial);
effect();
return result;
};
}
const render = mount();
const a = render('business:A');
a.setForm({ message: 'deliberate A' });
render('business:A');
const b = render('business:B');
assert.equal(b.form.message, 'initial business:B');
assert.notEqual(a.key, b.key);
b.setForm({ message: 'deliberate B' });
render('business:B');
assert.equal(render('business:A').form.message, 'deliberate A');
assert.equal(mount()('business:B').form.message, 'deliberate B');
assert.equal(
mount(new Map())('business:A').form.message,
'initial business:A',
);
assert.equal(
JSON.parse(saved.get('investemoz-interest:business:A')).form.message,
'deliberate A',
);
});
@@ -0,0 +1,181 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import ts from 'typescript';
import * as finance from '../../resources/js/lib/financial-calculators.ts';
import * as operating from '../../resources/js/lib/investment-operating-assistance.ts';
const require = createRequire(import.meta.url);
const nodes = (tree) =>
Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
const text = (tree) =>
Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string'
? tree
: '';
function harness(file, snapshot = '') {
let cursor = 0,
tree;
const memory = [],
changes = [];
const module = { exports: {} };
const hooks = {
...React,
useState(initial) {
const id = cursor++;
if (!(id in memory))
memory[id] =
typeof initial === 'function' ? initial() : initial;
return [
memory[id],
(next) => {
memory[id] =
typeof next === 'function' ? next(memory[id]) : next;
},
];
},
};
compileFunction(
ts.transpileModule(
fs.readFileSync('resources/js/components/' + file, 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText,
['require', 'module', 'exports'],
)(
(id) =>
id === 'react'
? hooks
: id === '@/lib/financial-calculators'
? finance
: id === '@/lib/investment-operating-assistance'
? operating
: require(id),
module,
module.exports,
);
const props = {
snapshot,
currency: 'MZN',
onChange(key, value) {
changes.push([key, value]);
},
};
const render = () => {
cursor = 0;
tree = module.exports.default(props);
};
render();
return {
render,
changes,
nodes: () => nodes(tree),
text: () => text(tree),
button: (label) =>
nodes(tree).find(
(node) =>
node.type === 'button' && text(node).startsWith(label),
),
};
}
test('initial budget has no sample amounts and adopts a sum only through the explicit action', () => {
const h = harness('investment-initial-budget.tsx');
const amounts = () =>
h
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
);
assert.deepEqual(
amounts().map((node) => node.props.value),
['', '', '', ''],
);
h.button('Usar a soma').props.onClick();
h.render();
assert.match(h.text(), /montantes em falta/);
assert.equal(
h.changes.some(([key]) => key === 'total_investment'),
false,
);
for (let i = 0; i < 4; i++) {
amounts()[i].props.onChange({
target: { value: String((i + 1) * 1000) },
});
h.render();
}
assert.equal(
h.changes.some(([key]) => key === 'total_investment'),
false,
);
h.button('Usar a soma').props.onClick();
h.render();
assert.deepEqual(h.changes.at(-1), ['total_investment', '10000.00']);
const saved = h.changes
.filter(([key]) => key === 'initial_budget_snapshot')
.at(-1)[1];
const restored = harness('investment-initial-budget.tsx', saved);
assert.deepEqual(
restored
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
)
.map((node) => node.props.value),
['1000', '2000', '3000', '4000'],
);
});
test('hotel estimate is selected deliberately, saved as assumptions, then adopted without replacing another field', () => {
const h = harness('investment-operating-assistance.tsx');
h.nodes()
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'hotel' } });
h.render();
const amounts = () =>
h
.nodes()
.filter(
(node) => node.type === 'input' && node.props.type === 'number',
);
for (const [i, value] of ['10', '5000', '50', '300'].entries()) {
amounts()[i].props.onChange({ target: { value } });
h.render();
}
assert.equal(
h.changes.some(([key]) => key === 'annual_revenue'),
false,
);
h.button('Usar esta estimativa de receitas').props.onClick();
h.render();
assert.deepEqual(h.changes.at(-1), ['annual_revenue', '7500000.00']);
assert.equal(
h.changes.some(
([key]) =>
key === 'total_investment' || key === 'investment_budget_max',
),
false,
);
const saved = h.changes
.filter(([key]) => key === 'planning_assumptions_snapshot')
.at(-1)[1];
const restored = harness('investment-operating-assistance.tsx', saved);
assert.equal(
restored.nodes().find((node) => node.type === 'select').props.value,
'hotel',
);
assert.match(restored.text(), /ocupação/);
});
@@ -0,0 +1,214 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
getSimulationSections,
simulationFieldsForSection,
simulationFieldAvailableAtDetailLevel,
simulationDraftFingerprint,
validateSimulationDraft,
partitionSimulationDraft,
restoreSimulationDraft,
} from '../../resources/js/lib/simulation-form.ts';
import {
emptyOperatingAssumptions,
estimateOperatingRevenue,
estimateOperatingCosts,
restoreOperatingAssumptions,
} from '../../resources/js/lib/investment-operating-assistance.ts';
test('confirmed nullable empty inputs match their HTTP-normalised recovery without accepting changed values', () => {
const local = {
purpose: 'own_investment',
context_opportunity: '',
total_investment: '2000000',
secured_amount: '1000000',
};
const snapshots = partitionSimulationDraft(local);
snapshots.economic_snapshot.context_opportunity = null;
const saved = restoreSimulationDraft(
snapshots.economic_snapshot,
snapshots.personal_snapshot,
);
const versionedLocal = {
...local,
project_questionnaire_version: 'legacy-unversioned',
};
assert.equal(
simulationDraftFingerprint(saved),
simulationDraftFingerprint(versionedLocal),
);
assert.notEqual(
simulationDraftFingerprint(saved),
simulationDraftFingerprint({
...versionedLocal,
secured_amount: '250000',
}),
);
assert.notEqual(
simulationDraftFingerprint(saved),
simulationDraftFingerprint({
...versionedLocal,
context_opportunity: 'another-opportunity',
}),
);
assert.notEqual(
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '' }),
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '0' }),
);
});
test('Hotel and Agronegocio reuse a controlled stage contract without requiring adverts, zones or formal financing facts', () => {
for (const project_title of ['Criar Hotel', 'Agronegócio em Matola Rio']) {
const draft = {
journey_type: 'investor',
detail_level: 'simple',
purpose: 'own_investment',
preferred_language: 'pt-MZ',
project_title,
province_id: 'province-qa',
district_id: 'boane-qa',
locality_id: 'matola-rio-qa',
currency: 'MZN',
investment_budget_min: '1000000',
investment_budget_max: '5000000',
};
const sections = getSimulationSections(draft);
assert.equal(sections.length, 8);
assert.ok(
simulationFieldsForSection(draft, 'purpose').some(
(field) => field.key === 'locality_id',
),
);
for (const stage of [
'market',
'investment',
'financial',
'operating',
'cashflow',
'tax',
])
assert.deepEqual(
validateSimulationDraft(draft, stage),
{},
`${stage} must permit unknown preparation facts`,
);
const finance = simulationFieldsForSection(draft, 'financial').map(
(field) => field.key,
);
assert.ok(finance.includes('secured_amount'));
assert.equal(finance.includes('annual_revenue'), false);
assert.ok(
simulationFieldsForSection(draft, 'operating').some(
(field) => field.key === 'annual_revenue',
),
);
const editableOperating = simulationFieldsForSection(
draft,
'operating',
).filter((field) =>
simulationFieldAvailableAtDetailLevel(
draft,
'operating',
field.key,
),
);
assert.ok(
editableOperating.some((field) => field.key === 'annual_revenue'),
);
assert.ok(
editableOperating.some(
(field) => field.key === 'annual_operating_costs',
),
);
assert.equal(
simulationFieldAvailableAtDetailLevel(draft, 'operating', 'nuit'),
false,
);
const snapshot = JSON.stringify({
version: 1,
data: {
...emptyOperatingAssumptions(),
model: 'hotel',
capacity: '10',
price: '5000',
occupancy: '50',
frequency: '300',
source: 'Synthetic assumptions explicitly entered',
},
});
const original = {
...draft,
preparation_step: 'operating',
planning_assumptions_snapshot: snapshot,
};
const partitioned = partitionSimulationDraft(original);
const recovered = restoreSimulationDraft(
partitioned.economic_snapshot,
partitioned.personal_snapshot,
);
for (const key of [
'locality_id',
'currency',
'investment_budget_min',
'investment_budget_max',
'preparation_step',
'planning_assumptions_snapshot',
])
assert.equal(recovered[key], original[key]);
assert.equal(recovered.total_investment, undefined);
}
});
test('guided estimates require explicit assumptions, preserve the model and do not use population as revenue', () => {
const empty = emptyOperatingAssumptions();
assert.throws(() => estimateOperatingRevenue(empty), /Escolha/);
const hotel = {
...empty,
model: 'hotel',
capacity: '10',
price: '5000',
occupancy: '50',
frequency: '300',
};
assert.equal(estimateOperatingRevenue(hotel), '7500000.00');
assert.throws(
() => estimateOperatingRevenue({ ...hotel, occupancy: '101' }),
/100%/,
);
assert.throws(
() => estimateOperatingRevenue({ ...hotel, price: '' }),
/falta/,
);
assert.equal(
estimateOperatingRevenue({
...hotel,
model: 'agriculture',
capacity: '1200',
price: '25.50',
frequency: '2',
}),
'61200.00',
);
assert.throws(() => estimateOperatingCosts(empty), /não são zero/);
assert.throws(
() =>
estimateOperatingCosts({
...hotel,
costs: [{ label: 'Energia', annual: '' }],
}),
/falta/,
);
const data = {
...hotel,
costs: [
{ label: 'Energia', annual: '100.10' },
{ label: 'Pessoal', annual: '200.20' },
],
};
assert.equal(estimateOperatingCosts(data), '300.30');
assert.deepEqual(
restoreOperatingAssumptions(JSON.stringify({ version: 1, data })),
data,
);
assert.deepEqual(restoreOperatingAssumptions('{broken'), empty);
});
@@ -108,7 +108,7 @@ test('conflict recovery reads current data without applying a write automaticall
});
test('validation shows each field message once and preserves its value', async () => {
const h = harness();
h.change(residence, 'ZZ', account);
h.change(residence, 'ZA', account);
const sent = h.submit(account);
await h.fail(422, sent, {
'payload.residence_country_code': ['SYNTHETIC invalid country'],
@@ -117,7 +117,7 @@ test('validation shows each field message once and preserves its value', async (
text(h.form(account)).split('SYNTHETIC invalid country').length - 1,
1,
);
assert.equal(h.value(residence, account), 'ZZ');
assert.equal(h.value(residence, account), 'ZA');
assert.equal(h.field(residence, account).props['aria-invalid'], true);
});
test('one page leave guard covers multiple dirty profile declarations', () => {
@@ -11,6 +11,59 @@ import {
} from '../../resources/js/lib/project-dossier-report.ts';
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
void test('sector hypotheses preserve their exact passage, provincial scope and edition in the same private report', async () => {
const data = fixture();
data.content_sources = [
{
title: 'SYNTHETIC regional source',
source_url: 'https://example.invalid/source',
analyses: [
{
key: 'synthetic-key',
title: 'SYNTHETIC hypothesis',
quote: 'SYNTHETIC passage <script>private()</script>',
section: 'Supporting passage',
source_sha256: 'a'.repeat(64),
source_version: 7,
source_date: '2026-11-15',
location_label: 'SYNTHETIC province',
location_precision: 'province',
href: '/synthetic-source',
},
],
},
];
const model = createInvestorDossierReport(data, '2026-11-15T00:00:00Z');
const market = model.sections.find((s) => s.id === 'market');
assert.equal(
market.rows.find((r) => r.field.endsWith('SYNTHETIC hypothesis')).value,
data.content_sources[0].analyses[0].quote,
);
assert.match(
market.rows.find((r) => r.classification === 'province').value,
/SYNTHETIC province/,
);
assert.match(
market.rows.find((r) => r.value.startsWith('7; SHA256')).value,
/7; SHA256/,
);
const html = await createProjectDossierPrintHtml(model, [], true);
assert.ok(html.includes('SYNTHETIC hypothesis'));
assert.ok(!html.includes('<script>private()</script>'));
assert.equal(
model.sections.filter((s) => s.id === 'market').length,
1,
'Existing SWOT and source evidence share one market section',
);
assert.equal(
createInvestorDossierReport(fixture()).sections.filter(
(s) => s.id === 'market',
).length,
1,
'Unrelated dossiers retain their original SWOT section',
);
});
function fixture() {
return {
case: {
@@ -138,6 +191,37 @@ function fixture() {
};
}
void test('a planning budget remains an interval in the same dossier report without inventing an investment amount', () => {
const input = fixture();
input.context_opportunity = null;
input.opportunity_options = [];
input.preparation_report.opportunity = null;
Object.assign(input.investment_context.fields, {
investment_budget_min: '1000000',
investment_budget_max: '5000000',
currency: 'MZN',
});
const report = createInvestorDossierReport(input, '2026-11-15T12:00:00Z');
const section = report.sections.find((section) => section.id === 'project');
assert.equal(
section.rows.find(
(row) => row.field === 'Orçamento previsto — mínimo do intervalo',
).value,
'1000000',
);
assert.equal(
section.rows.find(
(row) => row.field === 'Orçamento previsto — máximo do intervalo',
).value,
'5000000',
);
assert.equal(
section.rows.some((row) => row.field === 'Investimento previsto'),
false,
);
assert.equal(input.context_opportunity, null);
});
void test('one dossier groups stage evidence, SWOT, fiscal and all preserved APIEX versions without modifying sources', () => {
const input = fixture();
input.documents.push({ ...input.documents[0], id: 'second-link' });
@@ -202,6 +286,9 @@ void test('financial results from a different opportunity do not enter the conso
id: 'other',
context_opportunity: 'op-b',
financial_snapshot: 'OTHER-PRIVATE-INPUTS',
preparation_snapshot: {
annual_revenue: 'OTHER-PRIVATE-PREPARATION',
},
draft_id: 'other-draft',
draft_version: 8,
recorded_at: '2026-11-13',
@@ -214,6 +301,12 @@ void test('financial results from a different opportunity do not enter the conso
'OTHER-PRIVATE-INPUTS',
),
);
assert.equal(
JSON.stringify(createInvestorDossierReport(input)).includes(
'OTHER-PRIVATE-PREPARATION',
),
false,
);
assert.ok(
!investorDossierReportIndex(input).some(
(entry) => entry.id === 'finance:other',
@@ -249,6 +342,28 @@ void test('the consolidated report reuses loan, break-even, financing and budget
input.results = [
{
id: 'finance-a',
preparation_snapshot: {
total_investment: '100000',
investment_budget_min: '1000000',
investment_budget_max: '5000000',
annual_revenue: '7500000',
planning_assumptions_snapshot: JSON.stringify({
version: 1,
data: {
model: 'hotel',
capacity: '10',
price: '5000',
occupancy: '50',
frequency: '300',
source: 'Synthetic assumptions',
costs: [{ label: 'Energia', annual: '' }],
},
}),
initial_budget_snapshot: JSON.stringify({
version: 1,
rows: [{ label: 'Equipamento', amount: '100000' }],
}),
},
context_opportunity: 'op-a',
context_revision: 2,
context_state: 'review_required',
@@ -287,6 +402,74 @@ void test('the consolidated report reuses loan, break-even, financing and budget
);
assert.match(rows[0].classification, /Histórico/);
assert.equal(input.results[0].financial_snapshot, financial_snapshot);
assert.equal(
rows.find((item) => item.field === 'Receitas anuais estimadas').value,
'7500000 MZN',
);
assert.equal(
rows.find((item) => item.field === 'Quartos disponíveis').value,
'10',
);
assert.equal(
rows.find((item) => item.field === 'Custo anual — Energia').value,
'Por confirmar',
);
assert.equal(
rows.find((item) => item.field === 'Investimento inicial — Equipamento')
.value,
'100000',
);
});
void test('funding remains calculable without presenting an unchosen empty loan or empty comparisons', () => {
const input = fixture();
input.results = [
{
id: 'funding-only',
context_opportunity: 'op-a',
context_revision: 3,
currency: 'MZN',
draft_id: 'draft-a',
draft_version: 1,
recorded_at: '2026-11-15',
engine: 'financial-calculators:v1',
preparation_snapshot: { planning_loan: 'no' },
financial_snapshot: serializeFinancialToolsSnapshot({
budgetPeriod: 'Mensal',
loan: {
principal: '',
rate: '',
months: '',
rateType: 'nominal',
periodMonths: '1',
gracePeriods: '',
upfrontFee: '',
recurringFee: '',
},
breakEven: { fixed: '', price: '', variable: '' },
funding: { total: '1000000', secured: '1000000' },
incomes: [{ label: 'Receita', amount: '' }],
expenses: [{ label: 'Custos', amount: '' }],
}),
},
];
const rows = createInvestorDossierReport(input).sections.find(
(section) => section.id === 'finance',
).rows;
assert.equal(
rows.find(
(row) => row.field === 'Financiamento — Diferença por financiar',
).value,
'0.00 MZN',
);
assert.equal(
rows.some((row) =>
/Empréstimo educativo|Ponto de equilíbrio|Orçamento —/.test(
row.field,
),
),
false,
);
});
void test('the existing Word and print exporters retain dossier identity, pending stages, source and history, escaping active HTML', async () => {
@@ -6,6 +6,7 @@ import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
import * as preparationIntent from '../../resources/js/lib/preparation-intent.ts';
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);
@@ -22,7 +23,9 @@ function load(path, mocks = {}, exportName = 'default', extra = '') {
compileFunction(output + extra, ['require', 'module', 'exports'])(
(name) =>
mocks[name] ??
(name.startsWith('@/') ? { default: () => null } : require(name)),
(name === '@/components/investment-step-help'
? { HelpAtStep: () => null, InvestmentHelpGuide: ({ children }) => children }
: name.startsWith('@/') ? { default: () => null } : require(name)),
module,
module.exports,
);
@@ -57,7 +60,7 @@ function stateHooks() {
const flat = (node) =>
!node || typeof node !== 'object'
? []
: [node, ...React.Children.toArray(node.props?.children).flatMap(flat)];
: [node, ...(node.type?.name === 'InvestmentBudgetRange' ? flat(node.type(node.props)) : React.Children.toArray(node.props?.children).flatMap(flat))];
void test('free navigation keeps every field mounted and reports resource work in the current group', () => {
const state = stateHooks();
const Component = load(
@@ -476,7 +479,7 @@ const preparationMocks = {
},
'@/pages/investment/shared': { card: 'card', input: 'input' },
};
function contextPreviewHarness() {
function contextPreviewHarness(overrides = {}) {
const memory = [];
const effects = [];
let cursor = 0;
@@ -507,7 +510,7 @@ function contextPreviewHarness() {
const pending = [];
const Editor = load('../../resources/js/pages/investor-path/context.tsx', {
react: hooks,
'@inertiajs/react': { Link: () => null, router: {} },
'@inertiajs/react': { usePage: () => ({ props: { auth: { user: { id: 1 } } } }), Link: () => null, router: {} },
'@/components/navigation-context': {
useNavigationContext: () => ({ refresh() {} }),
},
@@ -530,12 +533,15 @@ function contextPreviewHarness() {
input: 'input',
button: 'button',
},
'@/components/investment-budget-range': { default: load('../../resources/js/components/investment-budget-range.tsx', { './currency-select': { default: function CurrencySelect() {} } }) },
'@/lib/preparation-intent': preparationIntent,
'@/components/currency-select': { default: function CurrencySelect() {} },
'@/components/investment-complements': {
default: () => null,
SelectedComplements: () => null,
complementInput: (value) => value,
},
});
}, 'ScopedContextEditor', '\nexports.ScopedContextEditor = ScopedContextEditor;');
const props = {
initial: {
case: { id: 'synthetic', version: 1, title: 'Synthetic' },
@@ -562,7 +568,7 @@ function contextPreviewHarness() {
render() {
cursor = 0;
effects.length = 0;
return Editor(props);
return Editor({ ...props, ...overrides });
},
result: {
preview_hash: 'synthetic-preview',
@@ -598,12 +604,12 @@ async function withDraftTimers(callback) {
}
}
async function readyDraftHarness() {
const harness = contextPreviewHarness();
const harness = contextPreviewHarness({ territorySelection: [{ id: 'synthetic-province', name: 'Synthetic province', location_type: 'province' }] });
harness.render();
harness.effects
.find((effect) => effect.dependencies?.length === 3)
.find((effect) => effect.dependencies?.length === 4)
.callback();
harness.pending[0].resolve({ corridors: [], parks: [] });
if (harness.pending[0]) harness.pending[0].resolve({ corridors: [], parks: [] });
await settlePreview();
harness.render();
return harness;
@@ -615,8 +621,8 @@ const runAutosaveEffect = (harness) =>
const changeDraftCurrency = (harness, value) => {
const tree = harness.render();
flat(tree)
.find((node) => node.type === 'input' && node.props.maxLength === 3)
.props.onChange({ target: { value } });
.find((node) => node.props.label === 'Moeda do orçamento')
.props.onChange(value);
return harness.render();
};
void test('stale autosave timer never sends an old body with a newer draft sequence', async () => {
@@ -689,7 +695,7 @@ void test('large multi-opportunity draft is offered to the transport on exit wit
};
let cleanup;
try {
const harness = contextPreviewHarness();
const harness = contextPreviewHarness({ requestedChoices: [{ opportunity: { key: 'opportunity:1', title: 'Synthetic' }, territory: null }] });
const initial = harness.render();
cleanup = harness.effects
.find(
@@ -743,7 +749,7 @@ void test('successful save followed by failed recovery offers read-only retry an
};
let cleanup;
try {
const harness = contextPreviewHarness();
const harness = contextPreviewHarness({ requestedChoices: [{ opportunity: { key: 'opportunity:1', title: 'Synthetic' }, territory: null }] });
const initial = harness.render();
cleanup = harness.effects
.find(
@@ -803,7 +809,7 @@ void test('successful save followed by failed recovery offers read-only retry an
);
assert.equal(
flat(recovered).find(
(node) => node.type === 'input' && node.props.maxLength === 3,
(node) => node.props.label === 'Moeda do orçamento',
).props.value,
'USD',
);
@@ -845,7 +851,7 @@ void test('failed save retains edits and permits retry without claiming that the
assert.equal(harness.pending.length, 2);
assert.equal(
flat(failed).find(
(node) => node.type === 'input' && node.props.maxLength === 3,
(node) => node.props.label === 'Moeda do orçamento',
).props.value,
'MZN',
);
@@ -883,7 +889,7 @@ void test('context comparison locks declaration and replacement controls until i
);
assert.equal(
flat(ready).find(
(node) => node.type === 'input' && node.props.maxLength === 3,
(node) => node.props.label === 'Moeda do orçamento',
).props.disabled,
false,
);
@@ -897,8 +903,8 @@ void test('context comparison rejects a response for a draft changed while the r
const busy = harness.render();
// Simulate a queued state change, independently of native disabled controls.
flat(busy)
.find((node) => node.type === 'input' && node.props.maxLength === 3)
.props.onChange({ target: { value: 'USD' } });
.find((node) => node.props.label === 'Moeda do orçamento')
.props.onChange('USD');
harness.render();
harness.pending[0].resolve(harness.result);
await settlePreview();
@@ -917,7 +923,7 @@ void test('context comparison rejects a response for a draft changed while the r
);
assert.equal(
flat(stale).find(
(node) => node.type === 'input' && node.props.maxLength === 3,
(node) => node.props.label === 'Moeda do orçamento',
).props.value,
'USD',
);
+132 -87
View File
@@ -1,32 +1,35 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { compileFunction } from "node:vm";
import { createRequire } from "node:module";
import ts from "typescript";
import React from "react";
import { revealPathStage } from "../../resources/js/lib/investor-path-stage.ts";
import { investmentStageHelp } from "../../resources/js/lib/investment-step-help.ts";
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import ts from 'typescript';
import React from 'react';
import { revealPathStage } from '../../resources/js/lib/investor-path-stage.ts';
import { investmentStageHelp } from '../../resources/js/lib/investment-step-help.ts';
const require = createRequire(import.meta.url);
const flatten = (node) =>
Array.isArray(node)
? node.flatMap(flatten)
: node && typeof node === "object"
: node && typeof node === 'object'
? [node, ...flatten(node.props?.children)]
: [];
const text = (node) =>
Array.isArray(node)
? node.map(text).join("")
: node && typeof node === "object"
? node.map(text).join('')
: node && typeof node === 'object'
? text(node.props?.children)
: String(node ?? "");
: String(node ?? '');
function harness(overrides = {}, react = React) {
const requests = [];
let form;
const module = { exports: {} };
const source = fs.readFileSync(
new URL("../../resources/js/pages/investor-path/show.tsx", import.meta.url),
"utf8",
new URL(
'../../resources/js/pages/investor-path/show.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
@@ -34,13 +37,19 @@ function harness(overrides = {}, react = React) {
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code + "\nmodule.exports.Stage = Stage;", ["require", "module", "exports"])(
compileFunction(code + '\nmodule.exports.Stage = Stage;', [
'require',
'module',
'exports',
])(
(name) =>
name === "react"
name === 'react'
? react
: name === "@inertiajs/react"
: name === '@inertiajs/react'
? {
usePage: () => ({ props: { auth: { user: { id: 1 } }, flash: {} } }),
usePage: () => ({
props: { auth: { user: { id: 1 } }, flash: {} },
}),
useForm(initial) {
form ??= {
data: initial,
@@ -53,116 +62,145 @@ function harness(overrides = {}, react = React) {
this.convert = fn;
},
post(url, options) {
requests.push({ url, options, data: this.convert(this.data) });
requests.push({
url,
options,
data: this.convert(this.data),
});
},
};
return form;
},
}
: name === "@/lib/investor-path"
? { pathStates: { preparing: "Em preparação" } }
: name === "@/lib/operation-key" ? { createOperationKey: () => 'qa-key' }
: name === "@/lib/investor-path-stage" ? { revealPathStage }
: name === "@/lib/investment-step-help" ? { investmentStageHelp }
: name === "@/components/proactive-investment" ? { proactiveView: () => null }
: name.startsWith("@/")
? {}
: require(name),
: name === '@/lib/investor-path'
? { pathStates: { preparing: 'Em preparação' } }
: name === '@/lib/operation-key'
? { createOperationKey: () => 'qa-key' }
: name === '@/lib/investor-path-stage'
? { revealPathStage }
: name === '@/lib/investment-step-help'
? { investmentStageHelp }
: name === '@/components/proactive-investment'
? { proactiveView: () => null }
: name.startsWith('@/')
? {}
: require(name),
module,
module.exports,
);
const path = {
case: { id: "dossier-qa", version: 7 },
context_opportunity: "opportunity:42",
case: { id: 'dossier-qa', version: 7 },
context_opportunity: 'opportunity:42',
investment_context: { revision: 3 },
canWrite: true,
canReview: false,
steps: [],
next: { code: "S02" },
documents: [{ document_id: "doc-qa", file_name: "Prova QA", malware_scan_status: "clean" }],
next: { code: 'S02' },
documents: [
{
document_id: 'doc-qa',
file_name: 'Prova QA',
malware_scan_status: 'clean',
},
],
...overrides,
};
const step = {
code: "S08",
title: "Licenciamento prévio",
state: "preparing",
code: 'S08',
title: 'Licenciamento prévio',
state: 'preparing',
preparation_allowed: true,
action_gaps: {},
detail: {},
source_paragraph: 8,
};
return {
render: (changes = {}) => module.exports.Stage({ step: { ...step, ...changes }, path }),
render: (changes = {}) =>
module.exports.Stage({ step: { ...step, ...changes }, path }),
renderPage: () => module.exports.default(path),
requests,
form: () => form,
path,
};
}
test("S08 has one current state, a visible primary save action and no nested disclosure", () => {
test('S08 has one current state, a visible primary save action and no nested disclosure', () => {
const h = harness();
const tree = h.render();
const nodes = flatten(tree);
assert.equal(tree.type, "section");
assert.equal(nodes.filter((n) => n.type === "details").length, 0);
assert.equal(tree.type, 'section');
assert.equal(nodes.filter((n) => n.type === 'details').length, 0);
assert.equal(
nodes.filter((n) => ["h3", "p"].includes(n.type) && text(n).includes("Em preparação"))
.length,
nodes.filter(
(n) =>
['h3', 'p'].includes(n.type) &&
text(n).includes('Em preparação'),
).length,
1,
);
assert.equal(nodes.find((n) => n.type === "button").props.disabled, false);
assert.match(nodes.find((n) => n.type === "button").props.className, /bg-emerald/);
assert.equal(nodes.filter((n) => n.type === "form").length, 1);
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, false);
assert.match(
nodes.find((n) => n.type === 'button').props.className,
/bg-emerald/,
);
assert.equal(nodes.filter((n) => n.type === 'form').length, 1);
assert.equal(tree.props.tabIndex, -1);
});
test("editing and saving retain context, current version, fields and existing endpoint", () => {
test('editing and saving retain context, current version, fields and existing endpoint', () => {
const h = harness({ canReview: true });
let tree = h.render();
const form = h.form();
Object.assign(form.data, {
reason: "Fundamento deliberado",
reference: "REF-QA",
authority: "Entidade QA",
document_id: "doc-qa",
decision_date: "2026-11-10",
reason: 'Fundamento deliberado',
reference: 'REF-QA',
authority: 'Entidade QA',
document_id: 'doc-qa',
decision_date: '2026-11-10',
context_reviewed: true,
});
h.path.case.version = 8;
tree = h.render();
assert.equal(form.data.reason, "Fundamento deliberado");
assert.equal(flatten(tree).filter((n) => n.type === "input").length, 3);
assert.equal(form.data.reason, 'Fundamento deliberado');
assert.equal(flatten(tree).filter((n) => n.type === 'input').length, 3);
flatten(tree)
.find((n) => n.type === "form")
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.deepEqual(h.requests, [
{
url: "/investimentos/dossier-qa/etapas/S08",
url: '/investimentos/dossier-qa/etapas/S08',
options: { preserveScroll: true },
data: { ...form.data, version: 8 },
},
]);
});
test("read-only and inapplicable stages do not acquire write controls; errors and processing remain visible", () => {
test('read-only and inapplicable stages do not acquire write controls; errors and processing remain visible', () => {
const read = harness({ canWrite: false, canReview: false });
assert.equal(flatten(read.render()).filter((n) => n.type === "form").length, 0);
assert.equal(
flatten(read.render()).filter((n) => n.type === 'form').length,
0,
);
const h = harness();
h.render();
assert.equal(
flatten(h.render({ preparation_allowed: false })).filter((n) => n.type === "form").length,
flatten(h.render({ preparation_allowed: false })).filter(
(n) => n.type === 'form',
).length,
0,
);
h.form().processing = true;
h.form().errors = { reason: "Conflito de versão" };
h.form().errors = { reason: 'Conflito de versão' };
const nodes = flatten(h.render());
assert.equal(nodes.find((n) => n.type === "button").props.disabled, true);
assert.equal(text(nodes.find((n) => n.props.role === "alert")), "Conflito de versão");
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, true);
assert.equal(
text(nodes.find((n) => n.props.role === 'alert')),
'Conflito de versão',
);
});
test("other stages keep their existing disclosure and reviewer fields/action choices", () => {
test('other stages keep their existing disclosure and reviewer fields/action choices', () => {
const h = harness({ canWrite: false, canReview: true });
const tree = h.render({ code: "S07" });
assert.equal(tree.type, "details");
assert.equal(flatten(tree).filter((n) => n.type === "details").length, 3);
assert.equal(h.form().data.action, "review");
const tree = h.render({ code: 'S07' });
assert.equal(tree.type, 'details');
assert.equal(flatten(tree).filter((n) => n.type === 'details').length, 3);
assert.equal(h.form().data.action, 'review');
assert.match(text(tree), /Registar acto externo/);
assert.match(text(tree), /Documento de suporte/);
});
@@ -170,46 +208,48 @@ function targetFixture() {
const calls = [];
const root = {
contains: (node) => node === target,
ownerDocument: { getElementById: (id) => (id === "S08" ? target : null) },
ownerDocument: {
getElementById: (id) => (id === 'S08' ? target : null),
},
};
const phase = { tagName: "DETAILS", open: false, parentElement: root };
const phase = { tagName: 'DETAILS', open: false, parentElement: root };
const target = {
tagName: "SECTION",
tagName: 'SECTION',
parentElement: phase,
scrollIntoView: (options) => calls.push(["scroll", options]),
focus: (options) => calls.push(["focus", options]),
scrollIntoView: (options) => calls.push(['scroll', options]),
focus: (options) => calls.push(['focus', options]),
};
return { root, phase, target, calls };
}
test("deep-link opens the containing phase and focuses S08 without navigation or changing fields", () => {
test('deep-link opens the containing phase and focuses S08 without navigation or changing fields', () => {
const f = targetFixture();
assert.equal(revealPathStage(f.root, "#S08", ["S02", "S08"]), true);
assert.equal(revealPathStage(f.root, '#S08', ['S02', 'S08']), true);
assert.equal(f.phase.open, true);
assert.deepEqual(f.calls, [
["scroll", { block: "start" }],
["focus", { preventScroll: true }],
['scroll', { block: 'start' }],
['focus', { preventScroll: true }],
]);
f.phase.open = false;
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), true);
assert.equal(revealPathStage(f.root, '#S08', ['S08']), true);
assert.equal(f.phase.open, true);
});
test("unknown, absent or out-of-scope hash targets have no effect", () => {
test('unknown, absent or out-of-scope hash targets have no effect', () => {
const f = targetFixture();
for (const hash of ["", "#unknown", "#S08%22", "#S07"])
assert.equal(revealPathStage(f.root, hash, ["S08"]), false);
for (const hash of ['', '#unknown', '#S08%22', '#S07'])
assert.equal(revealPathStage(f.root, hash, ['S08']), false);
f.root.contains = () => false;
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), false);
assert.equal(revealPathStage(f.root, '#S08', ['S08']), false);
assert.equal(f.phase.open, false);
assert.deepEqual(f.calls, []);
});
test("page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up", () => {
test('page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up', () => {
const f = targetFixture(),
effects = [],
listeners = new Map();
const previousWindow = globalThis.window;
let previousDependencies;
globalThis.window = {
location: { hash: "#S08" },
location: { hash: '#S08' },
addEventListener: (type, fn) => listeners.set(type, fn),
removeEventListener: (type, fn) => {
assert.equal(listeners.get(type), fn);
@@ -231,19 +271,24 @@ test("page reveals the initial hash and server next-stage updates, listens for h
tools: {},
content_sources: [],
services: [],
steps: [{ code: "S08", preparation_allowed: true }],
steps: [{ code: 'S08', preparation_allowed: true }],
},
{
...React,
useRef: () => ({ current: f.root }),
useEffect: (effect, dependencies) => {
if (!previousDependencies || dependencies.some((value, i) => value !== previousDependencies[i])) {
if (
!previousDependencies ||
dependencies.some(
(value, i) => value !== previousDependencies[i],
)
) {
effects.push(effect);
}
previousDependencies = dependencies;
},
useState: (initial) => [
typeof initial === "function" ? initial() : initial,
typeof initial === 'function' ? initial() : initial,
() => {},
],
},
@@ -253,14 +298,14 @@ test("page reveals the initial hash and server next-stage updates, listens for h
const cleanup = effects[0]();
assert.equal(f.phase.open, true);
f.phase.open = false;
listeners.get("hashchange")();
listeners.get('hashchange')();
assert.equal(f.phase.open, true);
cleanup();
assert.equal(listeners.size, 0);
h.renderPage();
assert.equal(effects.length, 1);
// A saved transition changes the controlled phase's `open` prop.
h.path.next = { code: "S09" };
h.path.next = { code: 'S09' };
f.phase.open = false;
h.renderPage();
assert.equal(effects.length, 2);
@@ -0,0 +1,169 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import ts from 'typescript';
import {
readNavigationFocus,
rememberNavigationFocus,
} from '../../resources/js/lib/navigation-focus.ts';
const require = createRequire(import.meta.url);
const A = '15111500-0000-4000-8000-000000000001';
const B = '15111500-0000-4000-8000-000000000002';
test('dossier provider retains tab focus across navigation/reload, honours explicit URLs and uses the current server version on deliberate change', async () => {
const oldStorage = globalThis.sessionStorage,
oldWindow = globalThis.window;
const storage = new Map(),
calls = [],
visits = [];
globalThis.sessionStorage = {
getItem: (k) => storage.get(k),
setItem: (k, v) => storage.set(k, v),
removeItem: (k) => storage.delete(k),
};
globalThis.window = {
location: { hash: '' },
addEventListener() {},
removeEventListener() {},
};
let pageUrl = '/simulador',
serverFocus = { case_id: B, step_code: null, version: 8 };
rememberNavigationFocus(7, { case_id: A, step_code: 'S08', version: 1 });
const code = ts.transpileModule(
fs.readFileSync(
'resources/js/components/dossier-navigation-context.tsx',
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
function mount() {
const state = [],
dependencies = [],
pending = [];
let cursor = 0,
effectCursor = 0;
const hooks = {
createContext: () => ({ Provider: 'provider' }),
useContext: () => ({}),
useState(initial) {
const i = cursor++;
if (!(i in state))
state[i] =
typeof initial === 'function' ? initial() : initial;
return [
state[i],
(n) =>
(state[i] = typeof n === 'function' ? n(state[i]) : n),
];
},
useEffect(callback, deps) {
const i = effectCursor++;
if (
!dependencies[i] ||
deps.some((v, n) => v !== dependencies[i][n])
) {
dependencies[i] = deps;
pending.push(callback);
}
},
};
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(id) => {
if (id === 'react') return hooks;
if (id === '@inertiajs/react')
return {
usePage: () => ({
url: pageUrl,
props: {
auth: { user: { id: 7 } },
investorPathEnabled: true,
},
}),
router: { visit: (url) => visits.push(url) },
Link: 'a',
};
if (id === '@/lib/navigation-focus')
return { readNavigationFocus, rememberNavigationFocus };
if (id === '@/lib/investor-context')
return {
contextApi: async (url, data, method) => {
calls.push({ url, data, method });
if (url === '/investimentos')
return { contexts: [{ id: A }, { id: B }] };
if (url === '/investimentos/contexto-atual') {
if (method === 'PUT') {
assert.equal(
data.version,
serverFocus.version,
);
serverFocus = {
...data,
version: serverFocus.version + 1,
};
}
return { installed: true, focus: serverFocus };
}
return { case: { id: url.split('/').pop() } };
},
};
return require(id);
},
module,
module.exports,
);
const render = () => {
cursor = effectCursor = 0;
const tree = module.exports.NavigationContextProvider({
children: null,
});
while (pending.length) pending.shift()();
return tree.props.value;
};
return async () => {
render();
await new Promise(setImmediate);
return render();
};
}
try {
let render = mount(),
view = await render();
assert.equal(view.active, A);
assert.equal(view.view.case.id, A);
assert.equal(
calls.some((c) => c.method === 'PUT'),
false,
);
render = mount();
view = await render();
assert.equal(
view.active,
A,
'reload must not adopt the other tab server preference',
);
pageUrl = '/simulador?context=' + B;
view = await render();
assert.equal(view.active, B, 'explicit authorised dossier wins');
assert.equal(readNavigationFocus(7, [A, B]).case_id, B);
serverFocus = { case_id: A, step_code: null, version: 15 };
view.choose(A, 'S02');
await new Promise(setImmediate);
assert.equal(
calls.filter((c) => c.method === 'PUT').at(-1).data.version,
15,
);
assert.equal(visits.at(-1), '/investimentos/' + A + '#S02');
} finally {
globalThis.sessionStorage = oldStorage;
globalThis.window = oldWindow;
}
});
+70
View File
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
readNavigationFocus,
rememberNavigationFocus,
} from '../../resources/js/lib/navigation-focus.ts';
test('tab focus survives reload but is isolated by actor and rechecked against authorised dossiers', () => {
const old = globalThis.sessionStorage,
values = new Map();
globalThis.sessionStorage = {
getItem: (k) => values.get(k),
setItem: (k, v) => values.set(k, v),
removeItem: (k) => values.delete(k),
};
try {
const focus = { case_id: 'synthetic-A', step_code: 'S08', version: 3 };
rememberNavigationFocus(1, focus);
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
assert.equal(readNavigationFocus(2, ['synthetic-A']), null);
assert.equal(readNavigationFocus(1, ['synthetic-B']), null);
const firstTab = globalThis.sessionStorage;
globalThis.sessionStorage = {
getItem: () => null,
setItem: (k, v) => values.set(k, v),
removeItem: (k) => values.delete(k),
};
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
globalThis.sessionStorage = firstTab;
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
rememberNavigationFocus(1, null);
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
} finally {
globalThis.sessionStorage = old;
}
});
test('corrupt, invalid and unavailable browser persistence cannot become authorisation or prevent use', () => {
const old = globalThis.sessionStorage;
try {
for (const value of [
'broken',
'{"case_id":"A","step_code":"S99","version":1}',
'{"case_id":"A","step_code":null,"version":-1}',
]) {
globalThis.sessionStorage = { getItem: () => value };
assert.equal(readNavigationFocus(1, ['A']), null);
}
globalThis.sessionStorage = {
getItem() {
throw Error('blocked');
},
setItem() {
throw Error('blocked');
},
removeItem() {
throw Error('blocked');
},
};
assert.equal(readNavigationFocus(1, ['A']), null);
assert.doesNotThrow(() =>
rememberNavigationFocus(1, {
case_id: 'A',
step_code: null,
version: 1,
}),
);
} finally {
globalThis.sessionStorage = old;
}
});
@@ -110,7 +110,7 @@ void test('sidebar renders every nested authorised destination instead of a firs
'/management/economic-references/lot-01',
])
assert.ok(hrefs.includes(href), href);
assert.match(html, /Área de trabalho/);
assert.match(html, /Administração/);
});
void test('nested current destination is selected without changing its URL or replacing it with a group root', () => {
const { html } = render(
@@ -0,0 +1,94 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, writeFileSync } from 'node:fs';
import JSZip from 'jszip';
import {
calculateBudget,
calculateBreakEven,
restoreFinancialToolsSnapshot,
} from '../../resources/js/lib/financial-calculators.ts';
import { createInvestorDossierReport } from '../../resources/js/lib/investor-dossier-report.ts';
import {
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
await test('persisted synthetic offer crosses the dossier boundary into location assumptions, calculation and private report', async () => {
// Produced by the guarded PHP integration test, never by an operational export.
const directory = new URL(
'../../outputs/offers-investment-continuity-20261114/',
import.meta.url,
);
const { path, saved } = JSON.parse(
readFileSync(
new URL('integrated-report-input.json', directory),
'utf8',
),
);
assert.equal(path.case.title, 'Synthetic acquisition acceptance');
assert.equal(
path.investment_context.fields.project_summary,
saved.project_summary,
);
assert.equal(path.investment_context.fields.province_id, saved.province_id);
const data = restoreFinancialToolsSnapshot(
path.results[0].financial_snapshot,
);
assert.ok(data);
assert.deepEqual(
data,
restoreFinancialToolsSnapshot(saved.financial_tools_snapshot),
);
const budget = calculateBudget(
data.incomes.map((row) => row.amount),
data.expenses.map((row) => row.amount),
);
const breakEven = calculateBreakEven(
data.breakEven.fixed,
data.breakEven.price,
data.breakEven.variable,
);
assert.equal(budget.operatingBalance, '7000.00');
assert.equal(breakEven.breakEvenUnits, '60');
// An explicit alternative location-cost assumption, not an inferred provincial tariff.
const alternative = calculateBudget(
data.incomes.map((row) => row.amount),
['5000', '3000'],
);
assert.equal(alternative.operatingBalance, '2000.00');
assert.deepEqual(
data.expenses.map((row) => row.amount),
['2000', '1000'],
);
const report = createInvestorDossierReport(path, '2026-11-14T12:00:00Z');
const html = await createProjectDossierPrintHtml(report, [], false);
assert.ok(html.includes(saved.project_summary));
assert.ok(html.includes('Synthetic province'));
assert.ok(!html.includes('60000.00'));
assert.ok(!html.includes('Synthetic private contact'));
const docx = await generateProjectDossierDocx(report, [], false);
const bytes = Buffer.from(await docx.arrayBuffer());
const zip = await JSZip.loadAsync(bytes);
const xml = await zip.file('word/document.xml').async('string');
assert.ok(xml.includes(saved.project_summary));
assert.ok(xml.includes('Synthetic province'));
assert.ok(!xml.includes('60000.00'));
writeFileSync(new URL('private-integrated-report.html', directory), html);
writeFileSync(new URL('private-integrated-report.docx', directory), bytes);
writeFileSync(
new URL('location-analysis.json', directory),
JSON.stringify(
{
scope: 'Synthetic investor-declared costs at the selected location; no automatic profitability or fiscal entitlement',
province_id: saved.province_id,
budget,
breakEven,
alternative,
source_offer: path.investment_context.selection.opportunity.key,
case_id: path.case.id,
},
null,
2,
),
);
});
+88
View File
@@ -0,0 +1,88 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { offerListHref } from '../../resources/js/lib/offer-navigation.ts';
import {
portalNavigation,
currentNavigationItem,
currentNavigationGroup,
} from '../../resources/js/lib/portal-navigation.ts';
await test('changing offer state preserves the operational and pending-report filters', () => {
const filters = {
operational: true,
pending_reports: true,
state: 'in_review',
};
const selected = new URL(offerListHref(filters), 'https://qa.invalid');
assert.equal(selected.searchParams.get('operational'), '1');
assert.equal(selected.searchParams.get('pending_reports'), '1');
assert.equal(selected.searchParams.get('state'), 'in_review');
const allStates = new URL(
offerListHref({ ...filters, state: '' }),
selected.origin,
);
assert.equal(allStates.searchParams.has('state'), false);
assert.equal(allStates.searchParams.get('pending_reports'), '1');
assert.equal(offerListHref(), '/minhas-oportunidades/ofertas');
assert.equal(
new URL(
offerListHref({ ...filters, pending_reports: false }),
selected.origin,
).searchParams.has('pending_reports'),
false,
);
});
await test('private offers use the existing work group and do not appear for an ungranted account', () => {
const profile = {
mine: '/minhas-oportunidades',
create: '/minhas-oportunidades/criar',
contexts: [],
request: '/perfil/promotor',
review: null,
administration: null,
};
const groups = portalNavigation({
authenticated: true,
manager: false,
profileAccess: profile,
});
const work = groups.find((group) => group.id === 'work');
const offers = work.children.find((item) => item.id === 'private-offers');
assert.deepEqual(
offers.children.map((item) => item.href),
[
'/minhas-oportunidades/ofertas',
'/minhas-oportunidades/ofertas/criar',
],
);
assert.equal(
currentNavigationItem(groups, '/minhas-oportunidades/ofertas'),
'my-private-offers',
);
assert.equal(
currentNavigationGroup(groups, '/minhas-oportunidades/ofertas/18'),
'work',
);
const reader = portalNavigation({
authenticated: true,
manager: false,
profileAccess: { ...profile, create: null },
});
assert.ok(!JSON.stringify(reader).includes('new-private-offer'));
for (const access of [
{ authenticated: false, manager: false },
{
authenticated: true,
manager: false,
profileAccess: { ...profile, mine: null, create: null },
},
]) {
assert.ok(
!JSON.stringify(portalNavigation(access)).includes(
'/minhas-oportunidades/ofertas',
),
);
}
assert.ok(!groups.some((group) => group.id === 'private-offers'));
});
@@ -0,0 +1,73 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
samePlanningAmount,
fundingDifferences,
draftFundingDifferences,
} from '../../resources/js/lib/planning-finance-context.ts';
import {
serializeFinancialToolsSnapshot,
calculateFundingGap,
} from '../../resources/js/lib/financial-calculators.ts';
import { defaultCashflowDraftInputs } from '../../resources/js/lib/monthly-cashflow.ts';
test('funding reconciliation compares exact decimals without treating unknown as zero', () => {
assert.equal(samePlanningAmount('1000000', '1000000.00'), true);
assert.equal(samePlanningAmount('', '0'), false);
assert.equal(samePlanningAmount('', ''), true);
assert.equal(
samePlanningAmount('9007199254740993', '9007199254740992'),
false,
);
assert.deepEqual(
fundingDifferences(
{ total: '1000000', secured: '1000000' },
{ total: '1000000', secured: '250000' },
),
['secured'],
);
assert.equal(calculateFundingGap('1000000', '1000000').gap, '0.00');
});
test('a recovered snapshot retains deliberate values and reports conflicting funding origins', () => {
const data = {
budgetPeriod: 'Mensal',
loan: {
principal: '',
rate: '',
months: '',
rateType: 'nominal',
periodMonths: '1',
gracePeriods: '',
upfrontFee: '',
recurringFee: '',
},
breakEven: { fixed: '', price: '', variable: '' },
funding: { total: '2000000', secured: '250000' },
incomes: [{ label: 'Receitas', amount: '' }],
expenses: [{ label: 'Custos', amount: '' }],
};
const snapshot = serializeFinancialToolsSnapshot(data);
const draft = {
total_investment: '2000000',
secured_amount: '1000000',
financial_tools_snapshot: snapshot,
};
assert.deepEqual(draftFundingDifferences(draft), ['secured']);
assert.equal(
draft.financial_tools_snapshot,
snapshot,
'a check must not silently replace the restored calculator',
);
assert.deepEqual(
draftFundingDifferences({ ...draft, secured_amount: '250000.00' }),
[],
);
});
test('fresh cashflow assumptions contain no demonstration amounts', () => {
for (const [key, value] of Object.entries(defaultCashflowDraftInputs())) {
if (typeof value === 'string' && /^\d/.test(value))
assert.fail(`Unexpected automatic amount in ${key}`);
}
});
+33 -6
View File
@@ -152,7 +152,7 @@ void test('catalogue detail and return preserve the search inside the local cata
'/zonas',
'/zonas/fixture?catalogue_query=https%3A%2F%2Foutside.invalid',
),
'/zonas?https%3A%2F%2Foutside.invalid=',
'/zonas',
);
});
@@ -226,8 +226,8 @@ void test('work area exposes existing content capability even when the old dashb
},
},
});
const work = groups.find((g) => g.id === 'work');
assert.equal(work.label, 'Área de trabalho');
const work = groups.find((g) => g.id === 'administration').children.find(g => g.id === 'administration-content');
assert.equal(work.label, 'Conteúdos e oportunidades');
assert.ok(
work.children.some(
(i) =>
@@ -238,7 +238,7 @@ void test('work area exposes existing content capability even when the old dashb
);
assert.ok(work.children.some((i) => i.href === '/gestao-conteudos'));
assert.ok(
work.children.some((i) => i.href === '/management/opportunities'),
destinations(groups.find(g => g.id === 'administration').children).includes('/management/opportunities'),
);
});
void test('every previously authorised management/profile destination survives the regrouping exactly once', () => {
@@ -276,7 +276,7 @@ void test('every previously authorised management/profile destination survives t
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(
destinations(groups.find((g) => g.id === 'administration').children).includes(
'/management/economic-references/lot-01',
),
);
@@ -314,7 +314,7 @@ void test('direct analysis and ordinary creation preserve distinct selection sta
groups,
'/minhas-oportunidades/create?analysis=proactive',
),
'work',
'administration',
);
assert.equal(
currentNavigationItem(
@@ -448,3 +448,30 @@ void test('installed concours has its own primary group and preserves public and
);
}
});
void test('administration owns dashboard activities once and remains hidden without authorised destinations', () => {
const dashboardNavigation = [{label: 'Visão geral', href: '/dashboard'}, {label: 'O meu trabalho', href: '/dashboard#meu-trabalho'}, {label: 'Circuito editorial', href: '/management/editorial'}];
const groups = portalNavigation({authenticated: true, manager: true, dashboardNavigation, administrationNavigation: [{label:'Competitividade',href:'/management/clusters'}]});
const admin = groups.find(g => g.id === 'administration');
const dashboard = admin.children.find(g => g.id === 'collaborative-dashboard');
assert.equal(dashboard.label, 'Dashboard');
assert.equal(destinations(dashboard.children).includes('/management/clusters'), false);
assert.equal(currentNavigationItem(groups, '/dashboard#meu-trabalho'), 'dashboard-activity-1');
assert.deepEqual(destinations(dashboard.children), dashboardNavigation.map(i => i.href));
assert.equal(currentNavigationGroup(groups, '/management/editorial'), 'administration');
assert.equal(currentNavigationGroup(groups, '/management/clusters/synthetic/edit'), 'administration');
assert.equal(destinations(groups).filter(h => h === '/management/clusters').length, 1);
assert.equal(portalNavigation({authenticated: false, manager: false, dashboardNavigation}).some(g => g.id === 'administration'), false);
assert.equal(portalNavigation({authenticated: true, manager: false}).some(g => g.id === 'administration'), false);
});
void test('administrative operations are grouped outside Dashboard and removed from More/work', () => {
const groups=portalNavigation({authenticated:true,manager:true,contentManagementHref:'/gestao-conteudos',dashboardNavigation:[{label:'Visão geral',href:'/dashboard'},{label:'O meu trabalho',href:'/dashboard#meu-trabalho'}],administrationNavigation:[{label:'Demografia',href:'/management/demography'}],profileAccess:{contexts:[],request:'/perfil/promotor',administration:'/perfis/gestao',audit:'/perfis/auditoria'},scopedAdministration:[{label:'Atribuições do Balcão',href:'/management/balcao/atribuicoes'}]});
const admin=groups.find(g=>g.id==='administration');
assert.deepEqual(admin.children.map(g=>g.label),['Dashboard','Conteúdos e oportunidades','Cadastros e investimento','Pedidos e acompanhamento','Acessos e configuração']);
assert.deepEqual(destinations(admin.children.find(g=>g.label==='Dashboard').children),['/dashboard','/dashboard#meu-trabalho']);
for(const href of ['/management/projects','/management/demography','/perfis/gestao','/perfis/auditoria','/management/balcao/atribuicoes']) {
assert.equal(destinations(admin.children).filter(h=>h===href).length,1,href);
assert.equal(destinations(groups.filter(g=>g.id!=='administration')).includes(href),false,href);
}
});
@@ -192,3 +192,17 @@ test('actual header has exactly the requested six primary entries on desktop and
),
);
});
test('authorised administration is primary and dashboard is a nested expandable group on desktop and mobile', () => {
for (mobile of [false, true]) {
state = {url: '/management/editorial', props: {auth: {user: {name: 'QA'}, canManagePortal: false}, dashboardNavigation: [{label: 'Visão geral', href: '/management/editorial'}, {label: 'Legislação', href: '/management/editorial?kind=legislation'}]}};
const html = renderToStaticMarkup(React.createElement(module.exports.PortalGroupedMenu));
const nav = html.match(/<nav[^>]*aria-label="Áreas do portal"[\s\S]*?<\/nav>/)?.[0];
assert.ok(nav);
const labels = [...nav.matchAll(/<(?:a|button)[^>]*class="tempo-nav-trigger"[^>]*>([\s\S]*?)<\/(?:a|button)>/g)].map(m => m[1].replace(/<[^>]*>/g, '').replace('Grupo actual', '').trim());
assert.deepEqual(labels, ['Início', 'Descoberta', 'Realização', 'Suporte', 'Administração', 'Sobre nós', 'Mais']);
assert.equal((nav.match(/href="\/management\/editorial"/g) ?? []).length, 1);
assert.match(nav, /Dashboard/);
if (mobile) assert.match(nav, /<summary[^>]*>Dashboard<\/summary>/);
}
});
@@ -0,0 +1,89 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
currencyChoices,
matchesChoice,
} from '../../resources/js/lib/catalogue-choice.ts';
import {
createInvestmentHref,
preparationSearch,
} from '../../resources/js/lib/preparation-intent.ts';
test('an own investment carries explicit sector, geography and an interval, without an advert or corridor', () => {
const path = [
{ id: 'province-qa', location_type: 'province' },
{ id: 'district-qa', location_type: 'district' },
{ id: 'locality-qa', location_type: 'locality' },
];
const url = new URL(
createInvestmentHref(
{
sector: 'agro',
min_amount: '1000000',
max_amount: '5000000',
currency: 'MZN',
q: 'Hotel',
corridor_id: 'unrelated',
opportunities: [42],
},
path,
),
'https://qa.example.test',
);
assert.equal(url.pathname, '/investimentos/iniciar');
assert.equal(url.searchParams.get('investment_budget_min'), '1000000');
assert.equal(url.searchParams.get('investment_budget_max'), '5000000');
assert.equal(url.searchParams.get('currency'), 'MZN');
assert.equal(url.searchParams.get('locality_id'), 'locality-qa');
assert.equal(url.searchParams.get('sector'), 'agro');
for (const key of [
'q',
'project_title',
'corridor_id',
'opportunities',
'total_investment',
])
assert.equal(url.searchParams.has(key), false);
const empty = new URL(createInvestmentHref({ q: 'Criar Hotel' }), url);
assert.equal(
empty.search,
'',
'a title does not assign a definitive activity or sector',
);
});
test('optional opportunity searches use only confirmed criteria and do not carry budget or private declarations', () => {
const query = new URLSearchParams(
preparationSearch('hotel', 'sector:7', [
{ id: 'province-qa', location_type: 'province' },
]),
);
assert.deepEqual(
[...query.entries()],
[
['q', 'hotel'],
['sector_id', '7'],
['province_id', 'province-qa'],
],
);
assert.equal(preparationSearch('', '', []), '');
});
test('country and currency search accepts names, three letters, accents, case and short codes', () => {
for (const query of ['MOC', 'moç', 'MZ', 'mocambique'])
assert.equal(matchesChoice(query, ['Moçambique — MZ']), true);
const metical = currencyChoices().find((choice) => choice.value === 'MZN');
assert.ok(metical);
assert.match(metical.label, /metical/i);
for (const query of ['MET', 'met', 'MZN'])
assert.equal(
matchesChoice(query, [metical.label, ...metical.keywords]),
true,
);
assert.deepEqual(
currencyChoices(['MZN', 'USD']).map((choice) => choice.value),
['MZN', 'USD'],
'preserve a consumer’s approved currency constraints',
);
assert.equal(matchesChoice('euro', [metical.label]), false);
});
@@ -0,0 +1,152 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const file = new URL(
'../../resources/js/components/investment-supply-aggregate.tsx',
import.meta.url,
);
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
},
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (name === '@inertiajs/react') return { router: { reload() {} } };
if (name === '@/lib/investor-context') return { contextApi() {} };
if (name === '@/lib/operation-key')
return { createOperationKey: () => 'SYNTHETIC' };
if (name === './catalogue-choice-select')
return {
default: ({ label, options }) =>
React.createElement(
'label',
null,
label,
React.createElement(
'select',
null,
options.map((o) =>
React.createElement(
'option',
{ key: o.value },
o.label,
),
),
),
),
};
return require(name);
},
module,
module.exports,
);
const Component = module.exports.default;
const fixture = () => ({
privacy_version: 1,
privacy_policy: 'fixed_district_cae_division_v1',
context_revision: 1,
recorded_at: '2026-11-15',
requested_territory: { id: 'local', name: 'Local conhecido' },
scope: { id: 'district', name: 'Distrito conhecido', level: 'district' },
broader_context: true,
entities: 987654321,
repeated: 987654321,
uncertain: 987654321,
source_summary: {
label: 'Originais reservados à equipa',
period: '2020',
incomplete_periods: true,
},
filters: {
sector_id: 1,
activity_id: 'published-activity',
activity_label: 'Agricultura',
division_code: '01',
},
groups: [
{
code: '01',
label: 'Agricultura',
total: 987654321,
entities_band: '5–9',
observations_band: '10–14',
scope: {
id: 'district',
name: 'Distrito conhecido',
level: 'district',
},
first_year: 'PRIVATE-DATE',
last_year: null,
},
],
interpretation: 'Não somar grupos nem inferir procura.',
limitations: 'Cobertura desconhecida.',
privacy_notice: 'Grupos pequenos não divulgados.',
});
const render = (history) =>
renderToStaticMarkup(
React.createElement(Component, {
caseId: 'synthetic',
version: 1,
revision: 2,
history,
protectedMode: true,
activityOptions: [
{
id: 'published-activity',
code: '01110',
label: 'Agricultura',
},
],
}),
);
void test('protected presentation shows documentary identities and observations as separate bands, not raw marginal totals or dates', () => {
const html = render([fixture()]);
assert.match(html, /5–9/);
assert.match(html, /10–14/);
assert.match(html, /Identidades documentais/);
assert.match(html, /Observações consolidadas/);
assert.match(html, /Contexto distrital/);
assert.match(html, /Local conhecido/);
assert.match(html, /2020/);
assert.match(html, /períodos não indicados/);
assert.match(html, /O contexto mudou/);
assert.match(html, /Actividade a comparar/);
assert.ok(!html.includes('987654321'));
assert.ok(!html.includes('PRIVATE-DATE'));
});
void test('suppressed and absent results use the same non-inference message, never zero businesses', () => {
const row = fixture();
row.groups = [];
const html = render([row]);
assert.match(html, /podem faltar registos ou existir grupos protegidos/);
assert.match(html, /não significa ausência de empresas/);
assert.ok(!html.includes('987654321'));
});
void test('legacy exact QA snapshots are not displayed in protected mode and current protected history is recoverable', () => {
const legacy = {
...fixture(),
privacy_version: undefined,
entities: 987654321,
};
const html = render([
legacy,
fixture(),
{ ...fixture(), recorded_at: '2026-11-16' },
]);
assert.match(html, /Análise guardada/);
assert.match(html, /2026-11-16/);
assert.ok(!html.includes('987654321'));
assert.ok(!render([legacy]).includes('Identidades documentais'));
});
+589
View File
@@ -0,0 +1,589 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const root = path.resolve('resources/js');
function load(file, mocks = {}) {
const absolute = path.resolve(root, file);
const module = { exports: {} };
const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(id) => {
if (id in mocks) return mocks[id];
if (id === '@inertiajs/react')
return {
Link: ({ children, ...props }) =>
React.createElement('a', props, children),
usePage: () => ({ url: '/sectores/test', props: { auth: { user: { id: 1 } } } }),
};
if (id.startsWith('.') || id.startsWith('@/')) {
const base = id.startsWith('@/')
? path.resolve(root, id.slice(2))
: path.resolve(path.dirname(absolute), id);
const found = [base, base + '.tsx', base + '.ts'].find(
(p) => fs.existsSync(p) && fs.statSync(p).isFile(),
);
if (found) return load(path.relative(root, found), mocks);
}
return require(id);
},
module,
module.exports,
);
return module.exports;
}
const render = (file, props) =>
renderToStaticMarkup(React.createElement(load(file).default, props));
test('demographic comparison retains four saved places and requires a province before searching districts', () => {
const Page = load('pages/investment/demography.tsx', {
'./shared': {
Frame: ({ children }) =>
React.createElement('main', null, children),
button: '',
},
'@/components/demographic-evidence': { default: () => null },
}).default;
const territories = [
{
id: 'p1',
name: 'Província A',
location_type: 'province',
parent_id: null,
},
{
id: 'p2',
name: 'Província B',
location_type: 'province',
parent_id: null,
},
{
id: 'd1',
name: 'Distrito A',
location_type: 'district',
parent_id: 'p1',
},
{
id: 'd2',
name: 'Distrito B',
location_type: 'district',
parent_id: 'p2',
},
];
const html = renderToStaticMarkup(
React.createElement(Page, {
evidence: { territories: [] },
filters: {
territories: territories.map((t) => t.id),
start_year: 2026,
end_year: 2027,
},
territories,
sectors: { general: 'Geral' },
}),
);
assert.match(html, /aria-label="Pesquisar Província da comparação"/);
assert.match(
html,
/aria-label="Pesquisar Distrito da comparação \(opcional\)"[^>]*disabled/,
);
assert.doesNotMatch(html, /<select[^>]*multiple/);
for (const t of territories)
assert.ok(html.includes(`Retirar ${t.name} —`));
assert.match(html, /disabled=""[^>]*>Acrescentar à comparação/);
assert.match(html, /value="2026"/);
assert.match(html, /value="2027"/);
});
test('the real preparation editor opens an own idea with its budget and no mandatory advert or duplicate reference selector', () => {
const Empty = () => null;
const Editor = load('pages/investor-path/context.tsx', {
'@/components/investment-step-help': { HelpAtStep: Empty, InvestmentHelpGuide: ({ children }) => children },
'@/pages/investment/shared': {
Frame: ({ children }) =>
React.createElement('main', null, children),
card: '',
button: '',
input: '',
},
'@/components/navigation-context': { useNavigationContext: () => ({}) },
'@/components/investment-territory': { TerritoryFields: Empty },
'@/components/private-investment-preparation': {
PreparationEditor: Empty,
PreparationImpact: Empty,
},
'@/components/investment-complements': {
default: Empty,
SelectedComplements: Empty,
complementInput: (value) => value,
},
'@/components/context-documents': { default: Empty },
'@/components/investment-opportunity-choices': { default: Empty },
'@/components/investment-requirements': { default: Empty },
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
}).default;
const html = renderToStaticMarkup(
React.createElement(Editor, {
initial: {
case: {
id: 'synthetic-hotel',
title: 'Criar Hotel',
version: 1,
},
context: {
revision: 0,
fields: { project_title: 'Criar Hotel' },
selection: {},
provenance: {},
opportunity_choices: [],
},
private_investment: null,
can_write: true,
results: [],
requests: [],
preparation_documents: [],
},
source: null,
options: {
countries: [
{ code: 'MZ', name: 'Moçambique', name_en: 'Mozambique' },
],
sectors: [{ id: 7, name: 'Turismo QA' }],
parks: [],
search_limited: false,
opportunities: [
{
key: 'opportunity:2',
title: 'Açúcar sem pertinência',
kind: 'opportunity',
},
],
},
entryIdea: {
sector_id: '7',
currency: 'MZN',
investment_budget_min: '1000000',
investment_budget_max: '5000000',
},
}),
);
assert.match(html, /Criar Hotel/);
assert.match(html, /value="1000000"/);
assert.match(html, /value="5000000"/);
assert.match(html, /value="sector:7" selected=""/);
assert.match(html, /Oportunidades relacionadas \(opcional\)/);
assert.doesNotMatch(html, /Referência individual|Açúcar sem pertinência/);
if (process.env.INVESTMOZ_INTENT_PREVIEW === '1') {
const manifest = JSON.parse(
fs.readFileSync(
'public/build-qa-opportunities/manifest.json',
'utf8',
),
);
const css = fs.readFileSync(
'public/build-qa-opportunities/' +
manifest['resources/css/app.css'].file,
'utf8',
);
fs.writeFileSync(
'outputs/investor-intent-20261115/editor-preview.html',
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz — prévia sintética de preparação</title><style>${css}</style><body><div class="mx-auto max-w-4xl p-4"><p class="rounded border p-3">QA sintético: editor renderizado, sem autenticação, gravação ou consultas. A cartografia foi substituída no ensaio. Esta prévia não demonstra o percurso autenticado.</p>${html}</div></body></html>`,
'utf8',
);
}
});
test('changing the consulted territory remounts its evidence and aborts a late response', async () => {
const state = [],
refs = [];
let cursor = 0,
refCursor = 0,
cleanup;
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in state)) state[index] = initial;
return [
state[index],
(next) => {
state[index] = next;
},
];
},
useRef(initial) {
const index = refCursor++;
refs[index] ??= { current: initial };
return refs[index];
},
useEffect(callback) {
cleanup = callback();
},
};
const Component = load('components/demographic-context.tsx', {
react: hooks,
}).default;
const a = Component({ territoryId: 'synthetic-A' });
const b = Component({ territoryId: 'synthetic-B' });
assert.notEqual(a.key, b.key);
assert.equal(Component({ territoryId: null }), null);
const tree = a.type(a.props);
const nodes = (n) =>
!n || typeof n !== 'object'
? []
: Array.isArray(n)
? n.flatMap(nodes)
: [n, ...nodes(n.props?.children)];
const button = nodes(tree).find((n) => n.type === 'button');
const originalFetch = globalThis.fetch;
let resolve, signal;
globalThis.fetch = (url, options) => {
assert.match(url, /synthetic-A/);
signal = options.signal;
return new Promise((done) => {
resolve = done;
});
};
try {
const pending = button.props.onClick();
cleanup();
assert.equal(signal.aborted, true);
resolve({ ok: true, json: async () => ({ territories: ['old A'] }) });
await pending;
assert.equal(
state[0],
null,
'late evidence must not be attached to another territory',
);
} finally {
globalThis.fetch = originalFetch;
}
});
test('shared evidence is closed by default, preserves content and wraps long references', () => {
const html = render('components/evidence-details.tsx', {
children: 'source-version-hash',
title: 'Fonte',
});
assert.match(html, /<details[^>]*>/);
assert.doesNotMatch(html, /<details[^>]*\bopen/);
assert.match(html, /source-version-hash/);
assert.match(html, /overflow-wrap:anywhere/);
});
test('public document keeps applicability, usage limitations and actions visible, with source metadata in detail', () => {
const { PublicDocumentContent } = load(
'components/public-document-content.tsx',
);
const resource = {
id: 1,
title: 'Diploma QA',
description: 'Objecto documentado',
issuer: null,
document_number: null,
document_date: null,
applicable_from: '2025-01-01',
applicable_until: null,
source_url: null,
source_confirmation: 'unknown',
usage_notice: 'Confirmar o âmbito aplicável',
view_url: null,
download_url: '/documents/1',
context_actions: [],
};
const html = renderToStaticMarkup(
React.createElement(PublicDocumentContent, { resource }),
);
assert.match(html, /2025-01-01/);
assert.match(html, /Confirmar o âmbito aplicável/);
assert.match(html, /href="\/documents\/1"/);
assert.doesNotMatch(html, /Entidade emissora|Consultar ficha/);
assert.ok(html.indexOf('Período indicado') > html.indexOf('</details>'));
});
test('territorial references retain exact citation and provenance without a primary internal-process block', () => {
const source = {
association: 'Corredor QA',
role: 'Ligação',
source_reference: 'Diploma QA §2',
source_quote: 'Relação documentada',
supports: '',
traceability: 'original hash/version',
official_source_accepted: true,
existing_validation: 'validated',
};
const html = render('components/territorial-source-evidence.tsx', {
sources: [source],
});
assert.match(html, /Diploma QA §2/);
assert.match(html, /original hash\/version/);
assert.doesNotMatch(
html,
/não retira a aceitação existente|campo específico/,
);
assert.equal(
render('components/territorial-source-evidence.tsx', { sources: [] }),
'',
);
});
test('empty published catalogue does not claim absent companies, resources or economic potential', () => {
const html = render('components/published-opportunities-empty.tsx', {
href: '/oportunidades?sector=qa',
});
assert.match(html, /Sem anúncios publicados/);
assert.match(
html,
/não indica ausência de empresas, recursos ou potencial/,
);
assert.match(html, /sector=qa/);
});
const value = (
year,
age_group = 'all',
data_kind = 'projected',
unit = 'pessoas',
) => ({
year,
indicator: 'population',
age_group,
residence: 'all',
value: '1234',
original_value: '1 234',
unit,
data_kind,
sheet: 'sheet',
cell: 'B' + year,
validation_status: 'valid',
});
test('demographic highlights never sum dimensions, mix units or silently replace a source/version', () => {
const { demographicHighlights } = load(
'components/demographic-evidence.tsx',
);
const values = [
value(2024),
value(2025),
value(2026, '0-4'),
value(2024, 'all', 'observed'),
value(2023, 'all', 'projected', 'unspecified'),
];
assert.deepEqual(demographicHighlights(values), [
values[1],
values[3],
values[4],
]);
assert.deepEqual(demographicHighlights([value(2025, '0-4')]), []);
});
test('demography shows original latest total, period, projection and decision warning; technical cells remain closed', () => {
const evidence = {
state: 'available',
start_year: 2024,
end_year: 2025,
limitations: ['Não prova procura'],
comparisons: [],
differences: [],
territories: [
{
id: 'qa',
name: 'Território QA',
level: 'province',
factors_to_assess: [],
series: [
{
import_id: 'qa',
source: 'Fonte QA',
version: 'Edição QA',
sha256: '123abc',
file_name: 'QA.xlsx',
missing_years: [],
issue_counts: {},
values: [value(2024), value(2025)],
},
],
},
],
};
const html = render('components/demographic-evidence.tsx', { evidence });
assert.match(html, /1 234/);
assert.match(html, /não demonstram procura ou rentabilidade/);
assert.match(html, /Projecção/);
assert.match(html, /SHA256/);
assert.ok(html.indexOf('SHA256') > html.indexOf('<summary'));
assert.doesNotMatch(html, /<details[^>]*\bopen/);
});
test('cluster analysis omits empty field blocks but keeps documented evidence and uncertainty', () => {
const { forces } = load('lib/cluster-competitiveness.ts');
const rows = Object.fromEntries(
forces.map((f) => [
f,
{
pressure: '',
evidence: 'Facto QA',
source: '',
period: '',
rationale: '',
limitations: 'Por confirmar',
opportunity: '',
},
]),
);
const html = render('components/cluster-competitiveness-public.tsx', {
analysis: {
version: 1,
at: '2026-11-15',
draft: { sector: 'QA', region: 'Local QA', forces: rows },
},
});
assert.match(html, /Facto QA/);
assert.match(html, /Por confirmar/);
assert.doesNotMatch(html, /<dt[^>]*>Fonte e referência/);
});
test('simulator keeps original calculation correspondence and source behind explicit details', () => {
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
const html = renderToStaticMarkup(
React.createElement(SimulationModeloA, { draft: {} }),
);
assert.match(html, /Modelo A/);
assert.match(html, /SHA256/);
assert.ok(
html.indexOf('SHA256') >
html.indexOf('Exemplar e integridade da fonte'),
);
assert.match(html, /não é imposto final/);
});
// Optional visual fixture: the real components with explicit synthetic data,
// not an authenticated application or an operational publication.
if (process.env.INVESTMOZ_RECONCILIATION_PREVIEW === '1') {
const population = (year, age, amount, residence = 'all') => ({
...value(year, age, 'projected', 'pessoas'),
residence,
value: String(amount),
original_value: String(amount),
cell: `${year}-${age}-${residence}`,
});
const values = [
population(2026, 'all', 1000),
population(2028, 'all', 1200),
population(2028, 'all', 480, 'urban'),
population(2028, 'all', 720, 'rural'),
];
for (const age of ['0-4', '5-9', '10-14'])
values.push(population(2028, age, 120));
for (const age of [
'15-19',
'20-24',
'25-29',
'30-34',
'35-39',
'40-44',
'45-49',
'50-54',
'55-59',
'60-64',
])
values.push(population(2028, age, 60));
const evidence = {
state: 'available',
start_year: 2026,
end_year: 2028,
sector: 'general',
limitations: [
'Exclusivamente dados sintéticos. Não representam população real.',
],
comparisons: [],
differences: [],
territories: [
{
id: 'synthetic-qa',
name: 'Território sintético QA',
level: 'district',
factors_to_assess: [],
series: [
{
import_id: 'qa',
source: 'Fonte sintética de ensaio',
version: 'QA 2026',
sha256: 'a'.repeat(64),
file_name: 'exemplo-sintetico.xlsx',
missing_years: [2027],
issue_counts: {},
values,
},
],
},
],
};
const demographicHtml = render('components/demographic-evidence.tsx', {
evidence,
});
const emptyHtml = render('components/published-opportunities-empty.tsx', {
href: '#demografia',
label: 'Estudar a localização',
});
const { PublicDocumentContent } = load(
'components/public-document-content.tsx',
);
const documentHtml = renderToStaticMarkup(
React.createElement(PublicDocumentContent, {
resource: {
id: 1,
title: 'Guia sintético QA',
description:
'Documento de ensaio para conferir a apresentação.',
issuer: 'Entidade sintética',
document_number: 'QA-1',
document_date: '2026-11-15',
applicable_from: '2026-11-15',
applicable_until: null,
source_url: null,
source_confirmation: 'unknown',
usage_notice:
'Exemplo de limitação relevante, conservada junto do documento.',
view_url: null,
download_url: '#documento',
context_actions: [],
},
}),
);
const sourceHtml = render('components/territorial-source-evidence.tsx', {
sources: [
{
association: 'Relação territorial sintética',
role: 'Contexto',
source_reference: 'Fonte sintética §1',
source_quote: 'Relação apenas para ensaio.',
supports: '',
traceability: 'Versão QA e original conservados',
official_source_accepted: false,
existing_validation: null,
},
],
});
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
const simulatorHtml = renderToStaticMarkup(
React.createElement(SimulationModeloA, { draft: {} }),
);
const manifest = JSON.parse(
fs.readFileSync('public/build-qa-opportunities/manifest.json', 'utf8'),
);
const css = fs.readFileSync(
'public/build-qa-opportunities/' +
manifest['resources/css/app.css'].file,
'utf8',
);
fs.writeFileSync(
'outputs/demography-reconciliation-20261115/visual-components.html',
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz QA — conferência de componentes</title><style>${css}</style><body class="bg-slate-50 text-slate-900"><main class="mx-auto max-w-5xl space-y-8 p-4"><header><h1 class="text-2xl font-bold">InvesteMoz — prévia QA</h1><p>Componentes reais com dados sintéticos. Não é uma sessão autenticada nem publicação no portal.</p><nav class="flex flex-wrap gap-4 py-4"><a href="#demografia">Demografia</a><a href="#catalogo">Catálogo</a><a href="#territorio">Território</a><a href="#documento">Biblioteca</a><a href="#simulador">Simulador</a></nav></header><section id="demografia">${demographicHtml}</section><section id="catalogo"><h2 class="text-xl font-semibold">Catálogo — sem anúncios publicados</h2>${emptyHtml}</section><section id="territorio"><h2 class="text-xl font-semibold">Contexto territorial</h2>${sourceHtml}</section><section id="documento">${documentHtml}</section><section id="simulador">${simulatorHtml}</section></main></body></html>`,
'utf8',
);
}
+20 -5
View File
@@ -193,7 +193,7 @@ void test('small business exploratory draft includes idea and finance without ma
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
});
void test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
void test('simple investment preparation separates initial investment and funding and retains the full advanced journey', () => {
const selected = replaceSimulationValue({}, 'journey_type', 'investor');
assert.equal(selected.purpose, 'simulate_only');
const sections = getSimulationSections(selected).map(
@@ -201,14 +201,29 @@ void test('project investment evaluation opens a direct project, location, finan
);
assert.deepEqual(sections, [
'purpose',
'project',
'location',
'market',
'investment',
'financial',
'operating',
'cashflow',
'tax',
'scenarios',
'procedures',
'review',
]);
assert.deepEqual(
getSimulationSections({ ...selected, detail_level: 'advanced' }).map(
(section) => section.id,
),
[
'purpose',
'project',
'location',
'financial',
'tax',
'scenarios',
'procedures',
'review',
],
);
for (const sectionId of [
'project',
'location',
@@ -26,7 +26,10 @@ import { closureFixture } from './fixtures/simulator-closure-fixture.mjs';
void test('S1 saved USD stays USD in report and cannot be reused as MZN for IVA', () => {
const inputs = {
...defaultCashflowDraftInputs(),
monthlyRevenue: '123',
monthlyOperatingCosts: '0', monthlyDebtService: '0',
vatCreditEstimated: '0', vatRefundRequested: '0',
vatRefundRecognized: '0', vatRefundExpectedReceipt: '0',
monthlyRevenue: '123', openingCash: '0',
monthlyTaxAssessed: '0',
};
const snapshot = serializeCashflowDraftSnapshot('fixed', inputs, 'USD');
@@ -67,7 +70,10 @@ void test('S1 saved USD stays USD in report and cannot be reused as MZN for IVA'
assert.equal(restoredProject.cashflow_snapshot, snapshot);
});
void test('S1 legacy amounts remain readable but require explicit origin currency before reuse', () => {
const inputs = { ...defaultCashflowDraftInputs(), monthlyRevenue: '123' };
const inputs = { ...defaultCashflowDraftInputs(),
monthlyOperatingCosts: '0', monthlyDebtService: '0',
vatCreditEstimated: '0', vatRefundRequested: '0',
vatRefundRecognized: '0', vatRefundExpectedReceipt: '0', monthlyRevenue: '123' };
const legacy = serializeCashflowDraftSnapshot('fixed', inputs);
const saved = restoreCashflowDraftSnapshot(legacy);
assert.equal(saved.version, 1);
@@ -14,7 +14,10 @@ import { createProjectDossierReport } from '../../resources/js/lib/project-dossi
void test('cashflow draft recovery preserves unanswered months and invalid editable values without using zero', () => {
const inputs = {
...defaultCashflowDraftInputs(),
openingCash: '77.01',
monthlyOperatingCosts: '0', monthlyDebtService: '0',
vatCreditEstimated: '0', vatRefundRequested: '0',
vatRefundRecognized: '0', vatRefundExpectedReceipt: '0',
openingCash: '77.01', monthlyRevenue: '0',
monthlyTaxSchedule: ['10', '', '20', ...Array(9).fill('0')],
};
const stored = serializeCashflowDraftSnapshot('schedule', inputs, 'MZN');
@@ -0,0 +1,148 @@
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';
const require = createRequire(import.meta.url);
const source = fs.readFileSync(
new URL(
'../../resources/js/pages/management/territorial-editorial.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
let states = [],
index = 0;
const module = { exports: {} };
new Function('require', 'module', 'exports', code)(
(name) => {
if (name === 'react')
return {
...React,
useState: () => [states[index++], () => {}],
useEffect: () => {},
};
if (name === '@inertiajs/react')
return {
Link: ({ href, children }) =>
React.createElement('a', { href }, children),
};
if (name === '@/lib/portal-api')
return {
portalRequest: () => {
throw new Error('No SSR writes');
},
PortalApiError: Error,
};
if (name === './shared')
return {
Management: ({ children }) =>
React.createElement('main', null, children),
Field: ({ label, children }) =>
React.createElement('label', null, label, children),
button: '',
control: '',
};
return require(name);
},
module,
module.exports,
);
const state = {
location: {
id: 'qa',
name: 'Proposta privada',
code: 'QA',
location_type: 'country',
parent_id: null,
version_no: 5,
},
profile: {
source_id: 'qa-source',
valid_from: '2020-01-01',
valid_to: null,
status: 'approved',
editor_id: 1,
reviewer_id: 2,
},
public_version_no: 1,
fresh: true,
baseline_changed: false,
_editorial: { private: true, contributors: [1] },
};
function render({
roles = ['publishers'],
actorId = 3,
changes = {},
dirty = false,
} = {}) {
const working = { ...state, ...changes };
const form = {
name: dirty ? 'Alteração por guardar' : working.location.name,
code: 'QA',
source_id: 'qa-source',
valid_from: '2020-01-01',
valid_to: '',
reason: 'Decisão sintética QA',
confirm_baseline_change: false,
};
states = [
[],
null,
{
working,
public: {
...state,
location: {
...state.location,
name: 'Designação pública original',
},
profile: { ...state.profile, status: 'published' },
},
history: [],
},
form,
[],
false,
'',
{},
];
index = 0;
return renderToStaticMarkup(
React.createElement(module.exports.default, { roles, actorId }),
);
}
test('territorial approval keeps the public reference and requires a separate publisher', () => {
const html = render();
assert.match(html, /Designação pública original/);
assert.match(html, /Publicar versão aprovada/);
assert.match(html, /Versão pública: 1/);
assert.doesNotMatch(render({ actorId: 2 }), /Publicar versão aprovada/);
assert.doesNotMatch(render({ actorId: 1 }), /Publicar versão aprovada/);
assert.doesNotMatch(
render({ roles: ['editors'], actorId: 1 }),
/Retirar publicação actual/,
);
});
test('stale context and unsaved edits cannot silently enter a publication decision', () => {
assert.doesNotMatch(
render({ changes: { fresh: false } }),
/Publicar versão aprovada/,
);
const dirty = render({ roles: ['editors', 'publishers'], dirty: true });
assert.match(
dirty,
/<button[^>]*disabled=""[^>]*>Publicar versão aprovada<\/button>/,
);
assert.match(dirty, /Guarde as alterações antes/);
assert.match(dirty, /Guardar proposta privada/);
});