This commit is contained in:
2026-11-02 20:31:15 +02:00
parent 8ddfa93f45
commit 1da273f1f3
131 changed files with 14802 additions and 526 deletions
@@ -111,7 +111,8 @@ class BusinessMarketplacePublicTest extends TestCase
->where('filters.modality', 'real_estate')->has('results.data', 1));
$this->get('/negocios/'.$business['public_slug'])->assertOk()
->assertInertia(fn ($page) => $page->component('investment/business-opportunity')
->where('record.modality', 'real_estate'));
->where('record.modality', 'real_estate')
->where('similarCatalogueUrl', '/negocios?modality=real_estate'));
$this->get('/negocios/'.$business['public_slug'].'/manifestar-interesse')->assertOk()
->assertInertia(fn ($page) => $page->component('investment/business-interest')
->where('record.modality', 'real_estate'));
@@ -138,6 +139,45 @@ class BusinessMarketplacePublicTest extends TestCase
$this->assertDatabaseHas('interest_requests', ['existing_business_id' => $business['id'], 'modality' => 'real_estate', 'status' => 'received']);
}
public function test_similar_catalogue_uses_only_disclosed_primary_province_and_preserves_publication_limits(): void
{
$this->withoutVite();
$country = (string) Str::uuid();
$province = (string) Str::uuid();
DB::table('geo_locations')->insert([
['id' => $country, 'name' => 'Synthetic country', 'code' => $country, 'location_type' => 'country', 'parent_id' => null],
['id' => $province, 'name' => 'Synthetic province', 'code' => $province, 'location_type' => 'province', 'parent_id' => $country],
]);
foreach ([$country, $province] as $location) {
DB::table('geo_locations')->where('id', $location)->update([
'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$location,
]);
}
$origin = $this->publishedBusiness();
$match = $this->publishedBusiness();
$reserved = $this->publishedBusiness();
$expired = $this->publishedBusiness();
foreach ([$origin, $match, $reserved, $expired] as $business) {
DB::table('existing_business_locations')->insert([
'id' => (string) Str::uuid(), 'existing_business_id' => $business['id'],
'province_id' => $province, 'precision_level' => 'province',
'is_primary' => true, 'is_public' => $business['id'] !== $reserved['id'],
]);
}
DB::table('existing_businesses')->where('id', $expired['id'])->update(['expires_at' => now()->subDay()]);
$url = '/negocios?modality=company_sale&province_id='.$province;
$this->get('/negocios/'.$origin['public_slug'])->assertInertia(fn (Assert $page) => $page
->where('similarCatalogueUrl', $url)->where('record.province', 'Synthetic province'));
$this->get('/negocios/'.$reserved['public_slug'])->assertInertia(fn (Assert $page) => $page
->where('similarCatalogueUrl', '/negocios?modality=company_sale')->where('record.province', null));
$this->getJson('/api/v1/business-opportunities?modality=company_sale&province_id='.$province)->assertOk()
->assertJsonCount(2, 'data')->assertJsonMissing(['id' => $reserved['id']])->assertJsonMissing(['id' => $expired['id']]);
DB::table('geo_locations')->where('id', $province)->update(['source_system' => 'unpublished-synthetic']);
$this->get('/negocios/'.$origin['public_slug'])->assertInertia(fn (Assert $page) => $page
->where('similarCatalogueUrl', '/negocios?modality=company_sale'));
}
/** @return array{id:string,public_slug:string} */
private function publishedBusiness(string $modality = 'company_sale'): array
{
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class DeskFormAnalysisScopeTest extends TestCase
{
use RefreshDatabase;
private User $manager;
private User $investor;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->manager = User::factory()->create();
$this->investor = User::factory()->create();
config(['portal.managers' => [$this->manager->email]]);
}
private function publish(string $code, array $definition, int $version = 0): string
{
return $this->actingAs($this->manager)->putJson('/management/balcao/servicos/'.$code, [
'base_version' => $version, 'definition' => $definition, 'confirm' => true,
'reason' => 'Synthetic QA analysis scope, without actual applicants.',
])->assertCreated()->json('id');
}
private function requestUrl(string $service): string
{
$case = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', [
'title' => 'Synthetic analysis scope', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true,
])->assertCreated()->json('id');
$id = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', [
'service_version_id' => $service, 'client_key' => (string) Str::uuid(),
])->assertCreated()->json('id');
return '/balcao-virtual/pedidos/'.$id;
}
public function test_checks_do_not_ask_for_finance_or_location_fields_absent_from_the_form(): void
{
$definition = config('virtual-desk.services.project-change');
unset($definition['fields']['territory_id'], $definition['fields']['location_source']);
$url = $this->requestUrl($this->publish('project-change', $definition));
$view = $this->getJson($url)->assertOk()->json();
$codes = array_column($view['findings'], 'code');
$this->assertNotContains('finance_unknown', $codes);
$this->assertNotContains('finance_difference', $codes);
$this->assertNotContains('location_unknown', $codes);
$this->assertContains('official_form_pending', $codes);
}
public function test_inactive_answers_are_preserved_without_blocking_submission_and_receipt_distinguishes_their_scope(): void
{
$definition = config('virtual-desk.services.project-preparation');
$definition['fields']['financial_branch'] = ['label' => 'Synthetic branch', 'type' => 'select', 'required' => true,
'options' => ['no' => 'No', 'yes' => 'Yes']];
foreach (['investment_amount', 'own_finance', 'other_finance', 'currency', 'territory_id', 'location_source'] as $key) {
$definition['fields'][$key]['when'] = ['field' => 'financial_branch', 'equals' => 'yes'];
}
$definition['fields']['investment_amount']['label'] = 'Valor sintético preservado';
$url = $this->requestUrl($this->publish('project-preparation', $definition));
$answers = ['title' => 'Synthetic investment', 'description' => 'Synthetic description', 'regime' => 'unknown',
'financial_branch' => 'no', 'investment_amount' => '100.00', 'own_finance' => '20.00', 'other_finance' => '30.00',
'currency' => 'MZN', 'location_source' => 'Synthetic stored source'];
$this->putJson($url, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertOk()->assertJsonPath('status', 'submitted');
$view = $this->getJson($url)->assertOk()->json();
$this->assertSame($answers, $view['request']['payload']);
$this->assertNotContains('finance_difference', array_column($view['findings'], 'code'));
$this->assertNotContains('finance_unknown', array_column($view['findings'], 'code'));
$this->assertNotContains('location_unknown', array_column($view['findings'], 'code'));
$id = basename($url);
$snapshot = DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot');
$definition['fields']['investment_amount']['label'] = 'A later version must not relabel old receipts';
$this->publish('project-preparation', $definition, 1);
$this->actingAs($this->investor);
$html = $this->get($url.'/recibo?format=html')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
->assertSee('Respostas conservadas de perguntas não aplicáveis')->assertSee('Valor sintético preservado')
->assertDontSee('A later version must not relabel old receipts')->getContent();
[$applicable, $preserved] = explode('Respostas conservadas de perguntas não aplicáveis', $html, 2);
$this->assertStringNotContainsString('Valor sintético preservado', $applicable);
$this->assertStringContainsString('Valor sintético preservado', $preserved);
$this->assertStringContainsString('100,00 MZN', $preserved);
$technical = $this->get($url.'/recibo')->assertOk()->streamedContent();
$this->assertStringContainsString('100.00', $technical);
$this->assertSame($snapshot, DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot'));
$this->actingAs(User::factory()->create())->get($url.'/recibo?format=html')->assertForbidden();
$active = $this->requestUrl(DB::table('desk_service_versions')->where('code', 'project-preparation')->where('version', 2)->value('id'));
$answers['financial_branch'] = 'yes';
$this->putJson($active, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertUnprocessable()->assertJsonValidationErrors('payload.investment_amount');
$answers['own_finance'] = '40.00';
$answers['other_finance'] = '60.00';
$this->putJson($active, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertOk()->assertJsonPath('status', 'submitted');
}
}
@@ -0,0 +1,40 @@
<?php
namespace Tests\Feature;
use App\Services\InvestmentGeography;
use App\Services\VirtualDesk;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
final class DeskLocationApplicabilityTest extends TestCase
{
use RefreshDatabase;
public function test_a_preserved_inactive_location_does_not_require_a_hidden_source_but_an_active_location_still_does(): void
{
$this->seed(TerritoryReferenceSeeder::class);
$territory = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->value('id');
$this->assertNotEmpty($territory);
$definition = ['fields' => [
'branch' => ['label' => 'Synthetic branch', 'type' => 'select', 'required' => true, 'options' => ['yes' => 'Yes', 'no' => 'No']],
'territory_id' => ['label' => 'Location', 'type' => 'territory', 'required' => false, 'when' => ['field' => 'branch', 'equals' => 'yes']],
'location_source' => ['label' => 'Source', 'type' => 'text', 'required' => false, 'when' => ['field' => 'branch', 'equals' => 'yes']],
]];
$desk = app(VirtualDesk::class);
$payload = ['branch' => 'no', 'territory_id' => $territory];
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
$payload['branch'] = 'yes';
try {
$desk->validateFields($payload, $definition, true);
$this->fail('An applicable selected location must retain its source requirement.');
} catch (ValidationException $error) {
$this->assertArrayHasKey('payload.location_source', $error->errors());
}
$payload['location_source'] = 'Synthetic QA use of the packaged reference';
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
$this->assertSame(['branch' => 'yes'], $desk->validateFields(['branch' => 'yes'], $definition, true));
}
}
@@ -0,0 +1,28 @@
<?php
namespace Tests\Feature;
use Tests\TestCase;
final class DeskReceiptCompatibilityTest extends TestCase
{
public function test_existing_direct_receipt_consumers_keep_their_contract_and_escape_preserved_answers(): void
{
$definition = ['title' => 'Synthetic receipt', 'fields' => [
'branch' => ['label' => 'Synthetic branch', 'type' => 'select', 'options' => ['no' => 'No', 'yes' => 'Yes']],
'detail' => ['label' => 'Synthetic preserved detail', 'type' => 'text', 'when' => ['field' => 'branch', 'equals' => 'yes']],
]];
$payload = ['branch' => 'no', 'detail' => '<script>alert("synthetic")</script>'];
$record = (object) ['id' => 'synthetic-id', 'protocol' => 'SYNTHETIC-QA', 'submitted_at' => '2026-11-02 10:00:00', 'version' => 2];
$html = view('desk.receipt', ['record' => $record, 'snapshot' => ['payload' => $payload], 'definition' => $definition])->render();
[$active, $preserved] = explode('Respostas conservadas de perguntas não aplicáveis', $html, 2);
$this->assertStringNotContainsString('Synthetic preserved detail', $active);
$this->assertStringContainsString('Synthetic preserved detail', $preserved);
$this->assertStringContainsString('&lt;script&gt;', $preserved);
$this->assertStringNotContainsString('<script>', $html);
$payload['branch'] = 'yes';
$html = view('desk.receipt', ['record' => $record, 'snapshot' => ['payload' => $payload], 'definition' => $definition])->render();
$this->assertStringNotContainsString('Respostas conservadas de perguntas não aplicáveis', $html);
$this->assertStringContainsString('Synthetic preserved detail', $html);
}
}
+214
View File
@@ -0,0 +1,214 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\VirtualDesk;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
final class DeskServiceEditorTest extends TestCase
{
use RefreshDatabase;
private User $manager;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->manager = User::factory()->create();
config(['portal.managers' => [$this->manager->email]]);
}
/** @return array<string,mixed> */
private function input(int $version = 0): array
{
return ['base_version' => $version, 'definition' => config('virtual-desk.services.project-change'),
'reason' => 'Synthetic QA definition change; no actual service or applicant.', 'confirm' => true];
}
public function test_numeric_choice_values_do_not_bypass_conditional_requirements(): void
{
$definition = ['fields' => [
'choice' => ['label' => 'Choice', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes']],
'detail' => ['label' => 'Detail', 'type' => 'text', 'required' => true, 'when' => ['field' => 'choice', 'equals' => '1']],
]];
$desk = app(VirtualDesk::class);
try {
$desk->validateFields(['choice' => 1], $definition, true);
$this->fail('A numeric option identifier must not bypass the required dependent answer.');
} catch (ValidationException $error) {
$this->assertArrayHasKey('payload.detail', $error->errors());
}
$valid = $desk->validateFields(['choice' => 1, 'detail' => 'Synthetic detail'], $definition, true);
$this->assertSame('1', $valid['choice']);
$this->assertSame('Synthetic detail', $valid['detail']);
}
public function test_hidden_parent_answers_do_not_activate_nested_required_questions(): void
{
// Children deliberately precede parents: field order must not change applicability.
$definition = ['fields' => [
'detail' => ['label' => 'Deep detail', 'type' => 'text', 'required' => true, 'when' => ['field' => 'branch', 'equals' => '1']],
'branch' => ['label' => 'Branch', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes'], 'when' => ['field' => 'root', 'equals' => '1']],
'root' => ['label' => 'Root', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes']],
]];
$desk = app(VirtualDesk::class);
$inactive = $desk->validateFields(['root' => '0', 'branch' => '1'], $definition, true);
$this->assertSame('1', $inactive['branch'], 'Keep previous answers without making their descendants applicable.');
$this->assertArrayNotHasKey('detail', $inactive);
$saved = $desk->validateFields(['root' => '0', 'branch' => '1', 'detail' => 'Preserved answer'], $definition, true);
$this->assertSame('Preserved answer', $saved['detail']);
$draft = $desk->validateFields(['root' => '1', 'branch' => 1], $definition, false);
$this->assertSame('1', $draft['branch']);
try {
$desk->validateFields(['root' => '1', 'branch' => 1], $definition, true);
$this->fail('An applicable nested question must still be required on submission.');
} catch (ValidationException $error) {
$this->assertArrayHasKey('payload.detail', $error->errors());
}
$active = $desk->validateFields(['root' => '1', 'branch' => '1', 'detail' => 'Applicable answer'], $definition, true);
$this->assertSame('Applicable answer', $active['detail']);
}
public function test_published_versions_preserve_existing_request_schema_payload_and_source_and_retry_without_duplicates(): void
{
$url = '/management/balcao/servicos/project-change';
$v1 = $this->actingAs($this->manager)->putJson($url, $this->input())->assertCreated()->assertJsonPath('version', 1)->json('id');
$before = DB::table('desk_service_versions')->where('id', $v1)->first();
$investor = User::factory()->create();
$case = $this->actingAs($investor)->postJson('/balcao-virtual/dossiers', ['title' => 'Synthetic schema preservation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
$request = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
$answers = ['title' => 'Existing synthetic answer', 'description' => 'Synthetic description of the proposed change',
'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'Synthetic justification for version preservation'];
$this->putJson('/balcao-virtual/pedidos/'.$request, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk()->assertJsonPath('status', 'submitted');
$saved = DB::table('desk_requests')->where('id', $request)->first();
$input = $this->input(1);
$input['definition']['fields']['extra_question'] = ['label' => 'Additional email', 'type' => 'email', 'required' => true];
$v2 = $this->actingAs($this->manager)->putJson($url, $input)->assertCreated()->assertJsonPath('version', 2)->json('id');
$this->putJson($url, $input)->assertCreated()->assertJsonPath('id', $v2);
$this->assertSame(2, DB::table('desk_service_versions')->where('code', 'project-change')->count());
$this->assertSame($before->definition, DB::table('desk_service_versions')->where('id', $v1)->value('definition'));
$this->assertSame($before->source, DB::table('desk_service_versions')->where('id', $v2)->value('source'));
$after = DB::table('desk_requests')->where('id', $request)->first();
$this->assertSame($saved->payload, $after->payload);
$this->assertSame($saved->submitted_snapshot, $after->submitted_snapshot);
$this->assertSame('submitted', $after->status);
$this->assertSame($v1, $after->service_version_id);
$this->actingAs($investor)->getJson('/balcao-virtual/pedidos/'.$request)->assertOk()->assertJsonMissingPath('definition.fields.extra_question');
$next = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v2, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
$this->getJson('/balcao-virtual/pedidos/'.$next)->assertOk()->assertJsonPath('definition.fields.extra_question.required', true);
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertUnprocessable()->assertJsonValidationErrors('payload.extra_question');
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => [...$answers, 'extra_question' => 'invalid-email'], 'submit' => true, 'consent' => true])
->assertUnprocessable()->assertJsonValidationErrors('payload.extra_question');
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => [...$answers, 'extra_question' => 'synthetic@example.invalid'], 'submit' => true, 'consent' => true])
->assertOk()->assertJsonPath('status', 'submitted');
$this->assertSame(2, DB::table('audit_events')->where('action', 'service_definition_version_published')->count());
$history = '/management/balcao/servicos/project-change/versoes';
$this->getJson($history)->assertForbidden();
$this->actingAs($this->manager)->getJson($history)->assertOk()->assertJsonPath('total', 2)
->assertJsonPath('data.0.id', $v2)->assertJsonPath('data.1.id', $v1)
->assertJsonPath('data.0.reason', $input['reason'])->assertJsonPath('data.0.author_id', $this->manager->id)
->assertJsonPath('data.0.definition.fields.extra_question.type', 'email')
->assertJsonMissingPath('data.1.definition.fields.extra_question')->assertJsonMissingPath('data.0.payload')
->assertDontSee('Existing synthetic answer', false);
$this->assertSame($saved->submitted_snapshot, DB::table('desk_requests')->where('id', $request)->value('submitted_snapshot'));
}
public function test_authority_conflicts_conditions_reserved_keys_and_stage_changes_are_checked_on_server(): void
{
$url = '/management/balcao/servicos/project-change';
$this->actingAs(User::factory()->create())->getJson('/management/balcao/servicos')->assertForbidden();
$this->putJson($url, $this->input())->assertForbidden();
$this->actingAs($this->manager)->getJson('/management/balcao/servicos')->assertOk()->assertJsonCount(3, 'services');
$this->putJson($url, $this->input())->assertCreated();
$this->putJson($url, $this->input(1))->assertUnprocessable()->assertJsonValidationErrors('definition');
$stale = $this->input();
$stale['definition']['title'] = 'Stale alternative';
$this->putJson($url, $stale)->assertConflict();
$invalid = $this->input(1);
$invalid['definition']['fields']['regime']['type'] = 'text';
unset($invalid['definition']['fields']['regime']['options']);
$this->putJson($url, $invalid)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.regime.type');
$invalid = $this->input(1);
$invalid['definition']['stage'] = 'E1';
$this->putJson($url, $invalid)->assertUnprocessable()->assertJsonValidationErrors('definition.stage');
$invalid = $this->input(1);
$invalid['definition']['fields']['context_reuse'] = ['label' => 'Reserved', 'type' => 'text', 'required' => false];
$this->putJson($url, $invalid)->assertUnprocessable();
$invalid = $this->input(1);
$invalid['definition']['fields']['title']['when'] = ['field' => 'description', 'equals' => 'x'];
$invalid['definition']['fields']['description']['when'] = ['field' => 'title', 'equals' => 'x'];
$this->putJson($url, $invalid)->assertUnprocessable();
$invalid = $this->input(1);
$invalid['definition']['fields']['description']['when'] = ['field' => 'regime', 'equals' => 'missing-option'];
$this->putJson($url, $invalid)->assertUnprocessable();
$invalid = $this->input(1);
$invalid['definition']['fields']['regime']['options'] = [];
$this->putJson($url, $invalid)->assertUnprocessable();
$this->assertSame(1, DB::table('desk_service_versions')->where('code', 'project-change')->count());
}
public function test_history_pagination_is_bounded_and_does_not_mix_service_definitions(): void
{
$definition = config('virtual-desk.services.project-change');
for ($version = 1; $version <= 12; $version++) {
DB::table('desk_service_versions')->insert(['id' => (string) Str::uuid(), 'code' => 'project-change', 'version' => $version,
'status' => 'published', 'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')),
'author_id' => $this->manager->id, 'published_by' => $this->manager->id, 'published_at' => now()]);
}
$url = '/management/balcao/servicos/project-change/versoes';
$this->actingAs($this->manager)->getJson($url)->assertOk()->assertJsonCount(10, 'data')->assertJsonPath('total', 12)
->assertJsonPath('data.0.version', 12)->assertJsonPath('data.9.version', 3);
$this->getJson($url.'?page=2')->assertOk()->assertJsonCount(2, 'data')->assertJsonPath('data.0.version', 2)->assertJsonPath('data.1.version', 1);
$this->getJson($url.'?page=999999999')->assertOk()->assertJsonPath('page', 2)->assertJsonCount(2, 'data');
$this->getJson($url.'?page=0')->assertUnprocessable();
$this->getJson('/management/balcao/servicos/project-follow-up/versoes')->assertOk()->assertJsonCount(0, 'data')->assertJsonPath('total', 0);
$this->getJson('/management/balcao/servicos/missing-service/versoes')->assertNotFound();
$this->assertSame(12, DB::table('desk_service_versions')->count());
DB::table('desk_service_versions')->insert(['id' => (string) Str::uuid(), 'code' => 'historical-service', 'version' => 1,
'status' => 'published', 'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $this->manager->id]);
$this->getJson('/management/balcao/servicos/historical-service/versoes')->assertOk()->assertJsonCount(1, 'data');
$this->getJson('/management/balcao/servicos')->assertOk()->assertJsonPath('services.3.code', 'historical-service')->assertJsonPath('services.3.editable', false);
$this->putJson('/management/balcao/servicos/historical-service', $this->input(1))->assertNotFound();
$this->assertSame(13, DB::table('desk_service_versions')->count());
}
public function test_location_source_remains_available_whenever_a_configured_location_applies(): void
{
$url = '/management/balcao/servicos/project-change';
$this->actingAs($this->manager);
$missing = $this->input();
unset($missing['definition']['fields']['location_source']);
$this->putJson($url, $missing)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.location_source');
$narrower = $this->input();
$narrower['definition']['fields']['location_source']['when'] = ['field' => 'regime', 'equals' => 'special'];
$this->putJson($url, $narrower)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.location_source.when');
$this->assertDatabaseCount('desk_service_versions', 0);
// The source can have broader applicability than the location, including ancestor conditions.
$broader = $this->input();
$broader['definition']['fields']['branch'] = ['label' => 'Synthetic branch', 'type' => 'select', 'required' => false,
'options' => ['yes' => 'Yes', 'no' => 'No'], 'when' => ['field' => 'regime', 'equals' => 'special']];
$broader['definition']['fields']['territory_id']['when'] = ['field' => 'branch', 'equals' => 'yes'];
$broader['definition']['fields']['location_source']['when'] = ['field' => 'regime', 'equals' => 'special'];
$this->putJson($url, $broader)->assertCreated();
$same = $broader;
$same['base_version'] = 1;
$same['definition']['fields']['location_source']['when'] = ['field' => 'branch', 'equals' => 'yes'];
$this->putJson($url, $same)->assertCreated();
$unconditional = $same;
$unconditional['base_version'] = 2;
unset($unconditional['definition']['fields']['location_source']['when']);
$this->putJson($url, $unconditional)->assertCreated();
$withoutLocation = $this->input(3);
unset($withoutLocation['definition']['fields']['territory_id'], $withoutLocation['definition']['fields']['location_source']);
$this->putJson($url, $withoutLocation)->assertCreated();
$this->assertDatabaseCount('desk_service_versions', 4);
}
}
@@ -0,0 +1,67 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class DeskServiceSchemaPrefillTest extends TestCase
{
use RefreshDatabase;
public function test_new_requests_reuse_only_fields_and_default_options_present_in_their_own_definition(): void
{
$this->withoutVite();
$manager = User::factory()->create();
$investor = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$url = '/management/balcao/servicos/project-change';
$definition = config('virtual-desk.services.project-change');
$publish = fn (int $base, array $schema) => $this->actingAs($manager)->putJson($url, [
'base_version' => $base, 'definition' => $schema, 'confirm' => true,
'reason' => 'Synthetic QA schema configuration, without actual applicants.',
])->assertCreated()->json('id');
$v1 = $publish(0, $definition);
$case = $this->actingAs($investor)->postJson('/balcao-virtual/dossiers', [
'title' => 'Synthetic project title', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true,
])->assertCreated()->json('id');
$create = fn (string $version) => $this->actingAs($investor)->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', [
'service_version_id' => $version, 'client_key' => (string) Str::uuid(),
])->assertCreated()->json('id');
$old = $create($v1);
$oldPayload = DB::table('desk_requests')->where('id', $old)->value('payload');
$this->getJson('/balcao-virtual/pedidos/'.$old)->assertOk()->assertJsonPath('request.payload.title', 'Synthetic project title')
->assertJsonPath('request.payload.regime', 'unknown');
unset($definition['fields']['title'], $definition['fields']['description'], $definition['fields']['regime']);
$v2 = $publish(1, $definition);
$next = $create($v2);
$requestUrl = '/balcao-virtual/pedidos/'.$next;
$view = $this->getJson($requestUrl)->assertOk()->assertJsonMissingPath('request.payload.title')
->assertJsonMissingPath('request.payload.description')->assertJsonMissingPath('request.payload.regime')->json();
$answers = [...$view['request']['payload'], 'original_reference' => 'SYNTHETIC-REFERENCE', 'change_reason' => 'Synthetic reason'];
$this->putJson($requestUrl, ['version' => 1, 'payload' => [...$answers, 'unconfigured' => 'not allowed']])
->assertUnprocessable()->assertJsonValidationErrors('payload');
$this->putJson($requestUrl, ['version' => 1, 'payload' => $answers])->assertOk()->assertJsonPath('status', 'draft');
$this->putJson($requestUrl, ['version' => 2, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertOk()->assertJsonPath('status', 'submitted');
$this->assertSame($oldPayload, DB::table('desk_requests')->where('id', $old)->value('payload'));
$this->getJson('/balcao-virtual/pedidos/'.$old)->assertOk()->assertJsonPath('request.payload.title', 'Synthetic project title')
->assertJsonPath('request.payload.regime', 'unknown')->assertJsonPath('definition.fields.title.required', true);
$definition['fields']['regime'] = ['label' => 'Synthetic configured choice', 'type' => 'select', 'required' => true,
'options' => ['configured' => 'Synthetic configured option']];
$v3 = $publish(2, $definition);
$configured = $create($v3);
$configuredUrl = '/balcao-virtual/pedidos/'.$configured;
$view = $this->getJson($configuredUrl)->assertOk()->assertJsonMissingPath('request.payload.regime')->json();
$answers = [...$view['request']['payload'], 'original_reference' => 'SYNTHETIC-REFERENCE', 'change_reason' => 'Synthetic reason'];
$this->putJson($configuredUrl, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
->assertUnprocessable()->assertJsonValidationErrors('payload.regime');
$this->putJson($configuredUrl, ['version' => 1, 'payload' => [...$answers, 'regime' => 'configured'], 'submit' => true, 'consent' => true])
->assertOk()->assertJsonPath('status', 'submitted');
$this->assertSame(3, DB::table('desk_service_versions')->count());
}
}
+3 -1
View File
@@ -19,7 +19,9 @@ class ExistingBusinessIntakeTest extends TestCase
protected function setUp(): void
{
parent::setUp();
config(['existing-business.enabled' => true]);
// This suite exercises the explicit legacy designation lists, not profile grants.
config(['existing-business.enabled' => true, 'portal.profile_access_enabled' => false,
'portal.profile_administration_enabled' => false]);
}
private function reviewer(): User
+269
View File
@@ -0,0 +1,269 @@
<?php
namespace Tests\Feature;
use App\Models\Sector;
use App\Models\User;
use App\Services\FundingProgrammeReferences;
use App\Services\FundingProgrammes;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
final class FundingProgrammesTest extends TestCase
{
use RefreshDatabase;
private function draft(): array
{
return ['title' => 'SINTÉTICO QA — Fundo de ensaio', 'kind' => 'fund', 'summary' => 'Referência fictícia para validação técnica.',
'manager_name' => 'Entidade sintética', 'source_url' => 'https://example.invalid/fund', 'source_reference' => 'Documento sintético QA',
'source_checked_on' => today()->toDateString(), 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'unknown',
'criteria' => [['code' => 'registration', 'question' => 'A entidade tem registo?', 'applies_to' => 'entity', 'expected' => 'yes',
'source_reference' => 'Critério sintético 1', 'explanation' => 'Exigência fictícia para ensaio.']],
'windows' => [['code' => 'closed-call', 'title' => 'Chamada histórica sintética', 'mode' => 'dated',
'end_on' => today()->subDay()->toDateString(), 'coverage' => 'programme', 'source_url' => 'https://example.invalid/call',
'source_reference' => 'Chamada fictícia QA', 'checked_on' => today()->toDateString()]]];
}
private function publishDraft(User $editor, string $code, array $draft): string
{
$service = app(FundingProgrammes::class);
$id = $service->save($editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
$plan = $service->preview($editor, $id);
$service->publish($editor, $id, ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true]);
return $id;
}
public function test_packaged_official_reference_prepares_only_a_draft_and_reuses_existing_fiche_without_overwriting(): void
{
$this->withoutVite();
$this->travelTo(Carbon::parse('2026-11-02 12:00:00'));
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$this->actingAs($editor)->get('/management/fundos/referencias/fdel')->assertOk()
->assertInertia(fn ($page) => $page->component('funding/reference')->where('reference.draft.coverage', 'national')
->where('reference.draft.windows.0.end_on', '2025-10-20')->where('reference.draft.windows.0.coverage', 'unknown'));
$references = app(FundingProgrammeReferences::class);
$plan = $references->preview($editor, 'fdel');
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => str_repeat('0', 64)])->assertConflict();
$this->assertSame(0, DB::table('funding_programmes')->count());
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertRedirect();
$row = DB::table('funding_programmes')->where('code', 'fdel')->first();
$this->assertNotNull($row);
$this->assertNull($row->published_version_id);
$this->assertSame(0, DB::table('funding_programme_versions')->count());
$service = app(FundingProgrammes::class);
$publication = $service->preview($editor, $row->id);
$this->assertSame('closed', $service->windowState($publication['payload']['windows'][0]));
$this->assertSame([], $publication['payload']['windows'][0]['territory_ids']);
$this->assertSame([], $publication['payload']['resource_ids']);
$audit = DB::table('audit_events')->where('entity_id', $row->id)->where('action', 'reference_prepared')->first();
$this->assertSame($plan['package_sha256'], json_decode($audit->after_data, true)['package_sha256']);
$draft = json_decode($row->draft, true);
$draft['summary'] = 'Alteração editorial deliberada de ensaio; preservar sem substituição pela referência.';
$service->save($editor, $row->id, ['version' => 1, 'code' => 'fdel', 'reason' => 'Actualização deliberada de ensaio antes de repetir.', 'draft' => $draft]);
$before = DB::table('funding_programmes')->where('id', $row->id)->first();
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertRedirect('/management/fundos/'.$row->id);
$this->assertSame($before->draft, DB::table('funding_programmes')->where('id', $row->id)->value('draft'));
$this->assertSame(1, DB::table('funding_programmes')->count());
$this->assertSame(1, DB::table('audit_events')->where('entity_id', $row->id)->where('action', 'reference_prepared')->count());
$this->actingAs(User::factory()->create())->get('/management/fundos/referencias/fdel')->assertForbidden();
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertForbidden();
$this->travelBack();
}
public function test_download_is_pinned_to_published_library_version_and_rechecks_rights_scan_and_actual_bytes(): void
{
$this->withoutVite();
Storage::fake('local');
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$document = (string) Str::uuid();
$bytes = 'SINTÉTICO QA — Condições fictícias, versão um.';
$key = 'funding-qa/'.$document.'.txt';
Storage::disk('local')->put($key, $bytes);
DB::table('documents')->insert(['id' => $document, 'source_system' => 'synthetic-funding-test', 'file_name' => 'funding-qa.txt', 'media_type' => 'text/plain',
'storage_key' => $key, 'size_bytes' => strlen($bytes), 'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes),
'malware_scan_status' => 'clean', 'status' => 'active', 'rights_status' => 'authorized', 'data_classification' => 'public', 'version_no' => 1]);
$resource = DB::table('portal_resources')->insertGetId(['document_id' => $document, 'title' => 'SINTÉTICO QA — Condições', 'category' => 'funding-qa', 'topic' => 'Ensaio sintético de financiamento',
'published' => true, 'rights_status' => 'authorized', 'source_url' => 'https://example.invalid/funding-qa', 'source_reference' => 'Referência sintética QA', 'metadata_version' => 1]);
$id = $this->publishDraft($editor, 'qa-document', [...$this->draft(), 'resource_ids' => [$resource]]);
$service = app(FundingProgrammes::class);
$published = $service->published($id);
$url = '/fundos/'.$id.'/versoes/'.$published['version_id'].'/documentos/'.$resource;
$this->get($url)->assertOk()->assertDownload('funding-qa.txt');
$this->assertTrue($published['payload']['documents'][0]['available']);
Storage::disk('local')->put($key, 'SINTÉTICO QA — Ficheiro alterado sem nova análise.');
$this->get($url)->assertNotFound();
Storage::disk('local')->put($key, $bytes);
foreach ([['malware_scan_status' => 'pending'], ['rights_status' => 'restricted'], ['data_classification' => 'confidential'], ['malware_scanned_sha256' => str_repeat('0', 64)]] as $patch) {
DB::table('documents')->where('id', $document)->update($patch);
$this->get($url)->assertNotFound();
$this->assertFalse($service->published($id)['payload']['documents'][0]['available']);
DB::table('documents')->where('id', $document)->update(['malware_scan_status' => 'clean', 'rights_status' => 'authorized', 'data_classification' => 'public', 'malware_scanned_sha256' => hash('sha256', $bytes)]);
}
$oldPlan = $service->preview($editor, $id);
DB::table('documents')->where('id', $document)->update(['version_no' => 2]);
$this->get($url)->assertNotFound();
$this->assertFalse($service->published($id)['payload']['documents'][0]['available']);
$newPlan = $service->preview($editor, $id);
$this->assertNotSame($oldPlan['hash'], $newPlan['hash']);
$this->actingAs($editor)->post('/management/fundos/'.$id.'/publicar', ['version' => 1, 'hash' => $oldPlan['hash'], 'reason' => 'Publicação sintética para ensaio de versão.', 'confirm' => true])->assertConflict();
$version = $service->publish($editor, $id, ['version' => 1, 'hash' => $newPlan['hash'], 'reason' => 'Publicação sintética para ensaio de versão.', 'confirm' => true]);
$this->get('/fundos/'.$id.'/versoes/'.$version.'/documentos/'.$resource)->assertOk();
$this->get($url)->assertNotFound();
DB::table('portal_resources')->where('id', $resource)->update(['published' => false]);
$this->get('/fundos/'.$id.'/versoes/'.$version.'/documentos/'.$resource)->assertNotFound();
$this->assertSame(1, json_decode(DB::table('funding_programme_versions')->where('id', $published['version_id'])->value('payload'), true)['document_snapshots'][0]['version']);
}
public function test_filters_explain_unknown_and_partial_coverage_preserve_scopes_and_distinguish_window_dates(): void
{
$this->withoutVite();
$this->seed(TerritoryReferenceSeeder::class);
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$sector = Sector::create(['name' => 'SINTÉTICO QA — Agricultura', 'slug' => 'qa-funding-agriculture', 'is_active' => true, 'published_at' => now()]);
$otherSector = Sector::create(['name' => 'SINTÉTICO QA — Indústria', 'slug' => 'qa-funding-industry', 'is_active' => true, 'published_at' => now()]);
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Tete')->value('id');
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
$national = $this->publishDraft($editor, 'qa-national', [...$this->draft(), 'sectors_scope' => 'all', 'windows' => []]);
$unknown = $this->publishDraft($editor, 'qa-unknown', [...$this->draft(), 'coverage' => 'unknown', 'windows' => []]);
$window = [...$this->draft()['windows'][0], 'mode' => 'dated', 'start_on' => today()->toDateString(), 'end_on' => today()->toDateString()];
$local = $this->publishDraft($editor, 'qa-local', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$province], 'sectors_scope' => 'selected', 'sector_ids' => [$sector->id], 'windows' => [$window]]);
$outside = $this->publishDraft($editor, 'qa-outside', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$otherProvince], 'sectors_scope' => 'selected', 'sector_ids' => [$sector->id]]);
$partial = $this->publishDraft($editor, 'qa-district', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$district], 'sectors_scope' => 'selected', 'sector_ids' => [$otherSector->id],
'windows' => [[...$window, 'start_on' => today()->addDay()->toDateString(), 'end_on' => today()->addWeek()->toDateString()]]]);
$get = fn (array $filters) => $this->get('/fundos?'.http_build_query($filters))->assertOk();
$filters = ['sector' => $sector->id, 'territory' => $province];
$get($filters)->assertInertia(fn ($page) => $page->has('items.data', 3)->where('items.data', fn ($rows) => collect($rows)->pluck('id')->sort()->values()->all() === collect([$national, $unknown, $local])->sort()->values()->all()));
$get([...$filters, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
$get([...$filters, 'territory' => $district, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
$get(['sector' => $otherSector->id, 'territory' => $province, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2)
->where('items.data', fn ($rows) => str_contains(collect($rows)->firstWhere('id', $partial)['filter_explanation']['territory'], 'uma parte')));
$get(['state' => 'open'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $local));
$get(['state' => 'closed'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $outside));
$get(['state' => 'upcoming'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $partial));
$get(['state' => 'unknown'])->assertInertia(fn ($page) => $page->has('items.data', 2));
$get(['territory' => $otherProvince, 'sector' => $sector->id, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
$this->getJson('/fundos?territory='.Str::uuid())->assertUnprocessable();
$snapshot = app(FundingProgrammes::class)->published($local);
DB::table('geo_locations')->where('id', $province)->update(['name' => 'SINTÉTICO QA — Nome alterado']);
$this->assertSame($snapshot['payload']['territory_paths'], app(FundingProgrammes::class)->published($local)['payload']['territory_paths']);
}
public function test_public_versions_and_private_interests_preserve_the_original_snapshot(): void
{
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$service = app(FundingProgrammes::class);
$input = ['version' => 0, 'code' => 'synthetic-fund', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $this->draft()];
$id = $service->save($editor, null, $input);
$plan = $service->preview($editor, $id);
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true];
$first = $service->publish($editor, $id, $publication);
$this->withoutVite();
$this->get('/fundos')->assertOk();
$this->get('/fundos/'.$id)->assertOk();
$this->get('/fundos?q=sem-correspondencia')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
$this->put('/fundos/'.$id.'/interesse', ['version_id' => $first, 'consent' => true])->assertRedirect('/login');
$this->postJson('/fundos/'.$id.'/criterios', ['version_id' => $first, 'applicant_kind' => 'entity', 'answers' => ['registration' => 'no']])
->assertOk()->assertJsonPath('criteria.0.status', 'does_not_match');
$this->assertSame($first, $service->publish($editor, $id, $publication));
$this->assertSame(1, DB::table('funding_programme_versions')->count());
$this->assertSame('closed', $service->published($id)['payload']['windows'][0]['state']);
$person = User::factory()->create();
$service->saveInterest($person, $id, $first, true);
$this->actingAs($person)->get('/fundos/guardados')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.saved_version', 1));
$this->actingAs(User::factory()->create())->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
$input['version'] = 1;
$input['draft']['summary'] = 'Descrição sintética actualizada.';
$service->save($editor, $id, $input);
$this->assertSame($first, $service->published($id)['version_id']);
$plan = $service->preview($editor, $id);
$second = $service->publish($editor, $id, [...$publication, 'version' => 2, 'hash' => $plan['hash']]);
$this->assertNotSame($first, $second);
$service->saveInterest($person, $id, $second, true);
$this->assertSame($first, DB::table('funding_programme_interests')->where('user_id', $person->id)->value('version_id'));
$service->removeInterest(User::factory()->create(), $id);
$this->assertNull(DB::table('funding_programme_interests')->where('user_id', $person->id)->value('removed_at'));
$result = $service->assess($id, ['version_id' => $second, 'applicant_kind' => 'unknown', 'answers' => ['registration' => 'yes']]);
$this->assertSame('unknown', $result['criteria'][0]['status']);
$result = $service->assess($id, ['version_id' => $second, 'applicant_kind' => 'individual', 'answers' => []]);
$this->assertSame('not_applicable', $result['criteria'][0]['status']);
$service->withdraw($editor, $id, 2, 'Retirada sintética para verificar conservação privada.');
$this->actingAs($person)->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page
->has('items.data', 1)->where('items.data.0.available', false)->where('items.data.0.saved_version', 1));
$this->get('/fundos/'.$id)->assertNotFound();
$this->delete('/fundos/'.$id.'/interesse')->assertRedirect();
$this->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
}
public function test_example_content_cannot_be_published_as_an_actual_programme(): void
{
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$service = app(FundingProgrammes::class);
$draft = [...$this->draft(), 'source_status' => 'example'];
$id = $service->save($editor, null, ['version' => 0, 'code' => 'synthetic-example', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
$this->expectException(ValidationException::class);
$service->preview($editor, $id);
}
public function test_editor_routes_enforce_authority_preview_and_stale_versions_independently_of_procurement(): void
{
$this->withoutVite();
$editor = User::factory()->create();
$outsider = User::factory()->create();
config(['portal.managers' => [$editor->email], 'procurement.enabled' => false]);
$this->actingAs($outsider)->get('/management/fundos')->assertForbidden();
$this->post('/management/fundos', [])->assertForbidden();
$this->actingAs($editor)->get('/management/fundos/novo')->assertOk();
$input = ['version' => 0, 'code' => 'synthetic-http-editor', 'reason' => 'Preparação sintética de ensaio editorial.', 'draft' => $this->draft()];
$this->post('/management/fundos', $input)->assertRedirect();
$id = DB::table('funding_programmes')->where('code', $input['code'])->value('id');
$this->get('/management/fundos/'.$id)->assertOk();
$this->get('/management/fundos')->assertOk();
$plan = $this->postJson('/management/fundos/'.$id.'/previa')->assertOk()->json();
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética de ensaio editorial.', 'confirm' => true];
$this->post('/management/fundos/'.$id.'/publicar', [...$publication, 'hash' => str_repeat('0', 64)])->assertConflict();
$this->post('/management/fundos/'.$id.'/publicar', $publication)->assertRedirect();
$this->put('/management/fundos/'.$id, $input)->assertConflict();
$this->actingAs($outsider)->post('/management/fundos/'.$id.'/retirar', ['version' => 1, 'reason' => $input['reason']])->assertForbidden();
$this->postJson('/management/fundos/'.$id.'/previa')->assertForbidden();
$this->get('/management/fundos/'.$id)->assertForbidden();
$this->assertSame(1, DB::table('funding_programme_versions')->count());
}
public function test_changed_master_reference_invalidates_preview_and_publishes_a_distinct_snapshot_without_overwriting_history(): void
{
$editor = User::factory()->create();
config(['portal.managers' => [$editor->email]]);
$organization = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $organization, 'name' => 'SINTÉTICO QA — Gestor original', 'organization_type' => 'private']);
$service = app(FundingProgrammes::class);
$draft = [...$this->draft(), 'manager_organization_id' => $organization];
$id = $service->save($editor, null, ['version' => 0, 'code' => 'synthetic-master-change', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
$plan = $service->preview($editor, $id);
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true];
$first = $service->publish($editor, $id, $publication);
DB::table('organizations')->where('id', $organization)->update(['name' => 'SINTÉTICO QA — Gestor actualizado']);
$newPlan = $service->preview($editor, $id);
$this->assertNotSame($plan['hash'], $newPlan['hash']);
$this->assertSame('SINTÉTICO QA — Gestor original', $service->published($id)['payload']['manager_name']);
$second = $service->publish($editor, $id, [...$publication, 'hash' => $newPlan['hash']]);
$this->assertNotSame($first, $second);
$this->assertSame(2, $service->published($id)['version']);
$this->assertSame('SINTÉTICO QA — Gestor original', json_decode(DB::table('funding_programme_versions')->where('id', $first)->value('payload'), true)['manager_name']);
$this->assertSame(2, DB::table('funding_programme_versions')->count());
}
}
@@ -0,0 +1,198 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\FundingProgrammes;
use App\Services\InvestmentOpportunityAlerts;
use App\Services\InvestmentWorkspace;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Tests\TestCase;
final class InvestmentFundingAlertsTest extends TestCase
{
use RefreshDatabase;
private User $actor;
private User $editor;
private Sector $sector;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->actor = User::factory()->create();
$this->editor = User::factory()->create();
config(['portal.managers' => [$this->editor->email]]);
$this->sector = Sector::create(['name' => 'SYNTHETIC funding sector', 'slug' => 'synthetic-funding-sector', 'is_active' => true, 'published_at' => now()]);
$this->actingAs($this->actor);
}
private function preferences(array $sources = ['funding'], array $criteria = [], int $version = 0): array
{
return ['version' => $version, 'enabled' => true, 'frequency' => 'as_available', 'channel' => 'in_app', 'consent' => true, 'sources' => $sources, 'criteria' => $criteria];
}
private function draft(array $patch = []): array
{
return [...['title' => 'SYNTHETIC funding QA', 'kind' => 'fund', 'summary' => 'SYNTHETIC QA only, not a real financing offer.',
'manager_name' => 'Synthetic manager', 'source_url' => 'https://example.invalid/funding', 'source_reference' => 'Synthetic edition QA',
'source_checked_on' => today()->toDateString(), 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'selected',
'sector_ids' => [$this->sector->id], 'criteria' => [], 'windows' => []], ...$patch];
}
private function publish(array $draft = [], ?string $id = null): array
{
$service = app(FundingProgrammes::class);
$row = $id ? DB::table('funding_programmes')->where('id', $id)->firstOrFail() : null;
$id = $service->save($this->editor, $id, ['code' => $row->code ?? 'synthetic-'.Str::uuid(), 'version' => $row->version ?? 0,
'reason' => 'Synthetic preparation for isolated funding alert QA.', 'draft' => $this->draft($draft)]);
$plan = $service->preview($this->editor, $id);
$version = $service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'reason' => 'Synthetic publication for isolated funding alert QA.', 'confirm' => true]);
return ['id' => $id, 'version_id' => $version];
}
private function opportunity(): void
{
Opportunity::create(['sector_id' => $this->sector->id, 'title' => 'SYNTHETIC opportunity QA', 'slug' => 'qa-'.Str::uuid(), 'reference' => 'QA-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subMinute()]);
}
public function test_opt_in_baselines_existing_publications_and_matches_only_selected_public_scope(): void
{
$this->publish();
$criteria = ['sector' => $this->sector->slug, 'funding_certainty' => 'documented', 'category' => 'irrelevant', 'tender_regime' => 'irrelevant'];
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: $criteria))->assertOk()
->assertJsonMissingPath('criteria.category')->assertJsonMissingPath('criteria.tender_regime');
$match = $this->publish(['title' => 'SYNTHETIC matching publication']);
$this->publish(['sectors_scope' => 'unknown', 'sector_ids' => []]);
$this->opportunity();
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$notification = DB::table('investment_notifications')->sole();
$this->assertSame($match['version_id'], $notification->funding_version_id);
$this->assertNull($notification->opportunity_id);
$this->assertNull($notification->tender_version_id);
$payload = json_decode(Crypt::decryptString($notification->payload), true);
$this->assertSame($match['id'], $payload['programme_id']);
$this->assertArrayNotHasKey('criteria_answers', $payload);
$this->assertArrayNotHasKey('documents', $payload);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('notifications.data.0.kind', 'funding_match');
$this->assertDatabaseCount('funding_programme_interests', 0);
}
public function test_all_three_sources_can_be_selected_explicitly_without_opt_in_by_migration(): void
{
config(['procurement.enabled' => true]);
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'tenders', 'funding']))->assertOk()
->assertJsonPath('sources', ['funding', 'opportunities', 'tenders']);
$this->assertDatabaseCount('investment_notifications', 0);
$this->assertSame(['funding', 'opportunities', 'tenders'], json_decode(DB::table('investment_alert_preferences')->sole()->sources, true));
}
public function test_window_state_filter_uses_documented_dates_without_treating_unknown_windows_as_open(): void
{
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: ['funding_state' => 'open']))->assertOk();
$this->publish();
$window = ['code' => 'synthetic-window', 'title' => 'Synthetic dated window', 'mode' => 'dated', 'coverage' => 'programme',
'source_url' => 'https://example.invalid/window', 'source_reference' => 'Synthetic window edition', 'checked_on' => today()->toDateString(), 'end_on' => today()->toDateString(), 'criteria' => []];
$match = $this->publish(['windows' => [$window]]);
$this->publish(['windows' => [[...$window, 'end_on' => today()->subDay()->toDateString()]]]);
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$notice = DB::table('investment_notifications')->sole();
$this->assertSame($match['version_id'], $notice->funding_version_id);
$this->assertSame('open', json_decode(Crypt::decryptString($notice->payload), true)['window_states'][0]['state']);
}
public function test_unknown_scope_is_explicit_and_new_versions_preserve_old_notices_until_withdrawal(): void
{
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: ['sector' => $this->sector->slug, 'funding_certainty' => 'include_unknown']))->assertOk();
$first = $this->publish(['sectors_scope' => 'unknown', 'sector_ids' => []]);
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(1, $alerts->dispatchDue());
$old = DB::table('investment_notifications')->sole();
$payload = json_decode(Crypt::decryptString($old->payload), true);
$this->assertStringContainsString('por confirmar', $payload['scope_explanation']['sector']);
$this->publish(['title' => 'SYNTHETIC changed title'], $first['id']);
$this->travel(5)->minutes();
$this->assertSame(1, $alerts->dispatchDue());
$this->assertSame($old->payload, DB::table('investment_notifications')->where('id', $old->id)->value('payload'));
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertOk();
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
$this->actingAs($this->actor);
app(FundingProgrammes::class)->withdraw($this->editor, $first['id'], 2, 'Synthetic withdrawal for historical notice QA.');
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data');
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
$this->assertDatabaseCount('investment_notifications', 2);
}
public function test_funding_unavailability_does_not_block_other_sources_or_cancellation(): void
{
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'funding']))->assertOk();
Schema::rename('investment_funding_alert_seen', 'investment_funding_alert_seen_unavailable_qa');
$this->opportunity();
$this->publish();
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.source_statuses.funding', false);
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false, 'criteria' => ['funding_state' => 'retired']])->assertOk()->assertJsonPath('enabled', false);
Schema::rename('investment_funding_alert_seen_unavailable_qa', 'investment_funding_alert_seen');
}
public function test_batch_is_bounded_per_source_and_funding_failure_rolls_back_all_deliveries(): void
{
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'funding']))->assertOk();
$sample = $this->publish();
$payload = DB::table('funding_programme_versions')->where('id', $sample['version_id'])->value('payload');
for ($index = 0; $index < 200; $index++) {
$id = (string) Str::uuid();
$version = (string) Str::uuid();
DB::table('funding_programmes')->insert(['id' => $id, 'code' => 'batch-'.$index, 'draft' => $payload, 'created_by' => $this->editor->id]);
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => 1, 'payload' => $payload, 'reason' => 'Synthetic batch fixture only', 'actor_id' => $this->editor->id]);
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version]);
}
$this->opportunity();
$mock = \Mockery::mock(InvestmentWorkspace::class)->makePartial();
$mock->shouldReceive('notifyFunding')->andThrow(new \RuntimeException('Synthetic delivery failure'));
$this->app->instance(InvestmentWorkspace::class, $mock);
try {
app(InvestmentOpportunityAlerts::class)->dispatchDue();
$this->fail('Delivery failure must escape and roll back.');
} catch (\RuntimeException $error) {
$this->assertSame('Synthetic delivery failure', $error->getMessage());
}
$this->assertDatabaseCount('investment_notifications', 0);
$this->assertDatabaseCount('investment_funding_alert_seen', 0);
$this->assertDatabaseCount('investment_alert_seen', 0);
$this->app->instance(InvestmentWorkspace::class, new InvestmentWorkspace);
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(201, $alerts->dispatchDue());
$this->assertSame(1, $alerts->dispatchDue());
$this->assertSame(0, $alerts->dispatchDue());
$this->assertDatabaseCount('investment_notifications', 202);
}
public function test_upgrade_preserves_preferences_and_rollback_refuses_funding_history(): void
{
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities']))->assertOk();
$before = (array) DB::table('investment_alert_preferences')->sole();
$migration = require database_path('migrations/2026_11_02_220000_investment_funding_alerts.php');
$migration->down();
$migration->up();
$this->assertSame($before, (array) DB::table('investment_alert_preferences')->sole());
$this->assertSame(['opportunities'], app(InvestmentOpportunityAlerts::class)->preferences($this->actor->id)['sources']);
$this->putJson('/investidor/alert-preferences', $this->preferences(['funding'], version: 1))->assertOk();
$this->publish();
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Preserve funding');
$migration->down();
}
}
@@ -0,0 +1,225 @@
<?php
namespace Tests\Feature;
use App\Models\InvestmentSubmission;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\InvestmentOpportunityAlerts;
use App\Services\InvestmentWorkspace;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class InvestmentOpportunityAlertsTest extends TestCase
{
use RefreshDatabase;
private User $actor;
private Sector $sector;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->actor = User::factory()->create();
$this->sector = Sector::create(['name' => 'Synthetic alert sector', 'slug' => 'synthetic-alert-sector', 'is_active' => true, 'published_at' => now()]);
$this->actingAs($this->actor);
}
private function input(array $criteria = [], string $frequency = 'as_available', int $version = 0): array
{
return ['version' => $version, 'enabled' => true, 'channel' => 'in_app', 'frequency' => $frequency, 'consent' => true, 'criteria' => $criteria];
}
private function opportunity(array $attributes = []): Opportunity
{
$record = new Opportunity;
$record->forceFill([...['sector_id' => $this->sector->id, 'title' => 'Synthetic public alert opportunity', 'slug' => 'synthetic-'.Str::uuid(),
'reference' => 'SYNTHETIC-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subDay(), 'opportunity_category' => 'investment_project'], ...$attributes])->save();
return $record;
}
public function test_opt_in_is_private_validated_versioned_and_idempotent_and_cancellation_does_not_need_retired_choices(): void
{
$url = '/investidor/alert-preferences';
Sector::create(['name' => 'Synthetic unpublished private sector', 'slug' => 'synthetic-unpublished', 'is_active' => true]);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.enabled', false)->assertJsonPath('alertPreferences.version', 0);
$this->getJson('/investidor/notifications')->assertOk()->assertDontSee('Synthetic unpublished private sector');
$this->putJson($url, $this->input(['sector' => 'synthetic-unpublished']))->assertUnprocessable();
$this->putJson($url, [...$this->input(), 'consent' => false])->assertUnprocessable()->assertJsonValidationErrors('consent');
$this->putJson($url, [...$this->input(), 'channel' => 'email'])->assertUnprocessable()->assertJsonValidationErrors('channel');
$this->putJson($url, $this->input(['sector' => 'unknown']))->assertUnprocessable();
$this->putJson($url, $this->input(['province_id' => (string) Str::uuid()]))->assertUnprocessable();
$input = $this->input(['sector' => $this->sector->slug]);
$this->putJson($url, $input)->assertOk()->assertJsonPath('version', 1)->assertJsonPath('enabled', true);
$this->putJson($url, $input)->assertOk()->assertJsonPath('version', 1);
$this->assertDatabaseCount('investment_alert_preferences', 1);
$this->assertDatabaseCount('audit_events', 1);
$this->putJson($url, $this->input([], 'weekly', 0))->assertConflict();
$raw = DB::table('investment_alert_preferences')->value('criteria');
$this->assertStringNotContainsString($this->sector->slug, $raw);
$this->sector->update(['is_active' => false]);
$this->putJson($url, ['version' => 1, 'enabled' => false, 'frequency' => 'retired-choice', 'channel' => 'retired-channel',
'criteria' => ['sector' => 'retired-sector', 'category' => 'retired-category']])->assertOk()->assertJsonPath('version', 2)
->assertJsonPath('enabled', false)->assertJsonPath('frequency', 'as_available')->assertJsonPath('channel', 'in_app')
->assertJsonPath('criteria.sector', $this->sector->slug);
$this->actingAs(User::factory()->create())->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.version', 0);
$this->actingAs(User::factory()->unverified()->create())->putJson($url, $this->input())->assertForbidden();
}
public function test_matching_reuses_catalogue_geography_and_excludes_old_private_future_and_incompatible_records(): void
{
$this->seed(TerritoryReferenceSeeder::class);
$province = DB::table('geo_locations')->where('location_type', 'province')->first();
$district = DB::table('geo_locations')->where('parent_id', $province->id)->where('location_type', 'district')->first();
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('id', '<>', $province->id)->first();
$old = $this->opportunity(['primary_territory_id' => $district->id]);
$input = $this->input(['sector' => $this->sector->slug, 'province_id' => $province->id, 'category' => 'investment_project']);
$this->putJson('/investidor/alert-preferences', $input)->assertOk();
$match = $this->opportunity(['primary_territory_id' => $district->id]);
$other = Sector::create(['name' => 'Other synthetic sector', 'slug' => 'other-synthetic', 'is_active' => true]);
$this->opportunity(['sector_id' => $other->id, 'primary_territory_id' => $district->id]);
$this->opportunity(['primary_territory_id' => $otherProvince->id]);
$this->opportunity(['primary_territory_id' => $district->id, 'opportunity_category' => 'financing']);
$this->opportunity(['primary_territory_id' => $district->id, 'status' => 'draft']);
$future = $this->opportunity(['primary_territory_id' => $district->id, 'published_at' => now()->addDay()]);
$this->opportunity(['primary_territory_id' => $district->id, 'owner_user_id' => $this->actor->id, 'workflow_context' => ['publication' => ['visibility' => 'private']]]);
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(1, $alerts->dispatchDue());
$this->assertSame(0, $alerts->dispatchDue());
$notification = DB::table('investment_notifications')->sole();
$this->assertSame($match->id, $notification->opportunity_id);
$this->assertNull($notification->submission_id);
$payload = json_decode(Crypt::decryptString($notification->payload), true);
$this->assertSame(1, $payload['preference_version']);
$this->assertSame($input['criteria']['province_id'], $payload['criteria']['province_id']);
$this->assertArrayNotHasKey('workflow_context', $payload);
$this->assertNotSame($old->id, $notification->opportunity_id);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('unread', 1)->assertJsonPath('notifications.data.0.payload.title', $match->title);
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
$this->actingAs($this->actor);
$match->update(['status' => 'draft']);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data')->assertJsonPath('unread', 0);
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
$this->assertDatabaseCount('investment_notifications', 1);
$this->travel(25)->hours();
$this->assertSame(1, $alerts->dispatchDue());
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $future->id]);
}
public function test_frequency_cancellation_and_reactivation_preserve_history_without_backlog_or_duplicates(): void
{
$this->putJson('/investidor/alert-preferences', $this->input([], 'daily'))->assertOk();
$first = $this->opportunity();
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(0, $alerts->dispatchDue());
$this->travel(24)->hours();
$this->assertSame(1, $alerts->dispatchDue());
$second = $this->opportunity();
$this->assertSame(0, $alerts->dispatchDue());
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk();
$this->travel(8)->days();
$this->assertSame(0, $alerts->dispatchDue());
$this->putJson('/investidor/alert-preferences', $this->input([], 'weekly', 2))->assertOk();
$third = $this->opportunity();
$this->travel(6)->days();
$this->assertSame(0, $alerts->dispatchDue());
$this->travel(1)->days();
$this->assertSame(1, $alerts->dispatchDue());
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $first->id]);
$this->assertDatabaseMissing('investment_notifications', ['opportunity_id' => $second->id]);
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $third->id]);
$this->assertDatabaseCount('investment_notifications', 2);
}
public function test_failed_delivery_rolls_back_seen_marker_and_next_run_and_can_be_retried(): void
{
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
$record = $this->opportunity();
$before = DB::table('investment_alert_preferences')->value('next_run_at');
$workspace = \Mockery::mock(InvestmentWorkspace::class);
$workspace->shouldReceive('notifyOpportunity')->once()->andThrow(new \RuntimeException('Synthetic delivery failure'));
$this->app->instance(InvestmentWorkspace::class, $workspace);
try {
app(InvestmentOpportunityAlerts::class)->dispatchDue();
$this->fail('Delivery failure must propagate without consuming the opportunity.');
} catch (\RuntimeException $error) {
$this->assertSame('Synthetic delivery failure', $error->getMessage());
}
$this->assertDatabaseMissing('investment_alert_seen', ['opportunity_id' => $record->id]);
$this->assertDatabaseCount('investment_notifications', 0);
$this->assertSame($before, DB::table('investment_alert_preferences')->value('next_run_at'));
$this->app->forgetInstance(InvestmentWorkspace::class);
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->artisan('investmoz:dispatch-opportunity-alerts')->assertSuccessful();
$this->assertDatabaseCount('investment_notifications', 1);
}
public function test_a_retired_reference_does_not_block_other_subscribers_or_prevent_cancellation(): void
{
$this->seed(TerritoryReferenceSeeder::class);
$province = DB::table('geo_locations')->where('location_type', 'province')->value('id');
$this->putJson('/investidor/alert-preferences', $this->input(['province_id' => $province]))->assertOk();
$other = User::factory()->create();
$this->actingAs($other)->putJson('/investidor/alert-preferences', $this->input())->assertOk();
$record = $this->opportunity();
DB::table('geo_locations')->where('id', $province)->update(['data_classification' => 'internal']);
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->assertDatabaseHas('investment_notifications', ['user_id' => $other->id, 'opportunity_id' => $record->id]);
$this->assertDatabaseMissing('investment_notifications', ['user_id' => $this->actor->id]);
$this->actingAs($this->actor)->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.criteria_available', false)
->assertJsonPath('alertPreferences.criteria.province_id', $province);
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk()->assertJsonPath('enabled', false);
}
public function test_a_batch_larger_than_one_run_is_drained_without_losing_or_repeating_notifications(): void
{
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
for ($index = 0; $index < 201; $index++) {
$this->opportunity();
}
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(200, $alerts->dispatchDue());
$this->assertSame(1, $alerts->dispatchDue());
$this->assertSame(0, $alerts->dispatchDue());
$this->assertDatabaseCount('investment_notifications', 201);
$this->assertDatabaseCount('investment_alert_seen', 201);
}
public function test_upgrade_preserves_legacy_notifications_and_rollback_refuses_to_destroy_preferences(): void
{
$submission = $this->postJson('/api/v1/investment/submissions')->assertCreated()->json('id');
app(InvestmentWorkspace::class)->notify($this->actor->id, InvestmentSubmission::findOrFail($submission), 'status', 'synthetic-upgrade', ['status' => 'draft']);
$original = (array) DB::table('investment_notifications')->sole();
$migration = require database_path('migrations/2026_11_02_190000_investment_opportunity_alerts.php');
$tenderMigration = require database_path('migrations/2026_11_02_200000_investment_tender_alerts.php');
$fundingMigration = require database_path('migrations/2026_11_02_220000_investment_funding_alerts.php');
$fundingMigration->down();
$tenderMigration->down();
$migration->down();
$this->assertFalse(app(InvestmentOpportunityAlerts::class)->installed());
$migration->up();
$tenderMigration->up();
$fundingMigration->up();
$this->assertSame($original, (array) DB::table('investment_notifications')->sole());
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
try {
$migration->down();
$this->fail('Preferences and notification history must be preserved before rollback.');
} catch (\RuntimeException $error) {
$this->assertStringContainsString('Preserve alert preferences', $error->getMessage());
}
$this->assertTrue(app(InvestmentOpportunityAlerts::class)->installed());
$this->assertDatabaseCount('investment_notifications', 1);
$this->assertDatabaseCount('investment_alert_preferences', 1);
}
}
@@ -0,0 +1,224 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\InvestmentOpportunityAlerts;
use App\Services\InvestmentWorkspace;
use App\Services\Procurement;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class InvestmentTenderAlertsTest extends TestCase
{
use RefreshDatabase;
private User $actor;
private User $editor;
private Sector $sector;
private string $organization;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->actor = User::factory()->create();
$this->editor = User::factory()->create();
config(['procurement.enabled' => true, 'portal.managers' => [$this->editor->email]]);
$this->sector = Sector::create(['name' => 'Synthetic tender sector', 'slug' => 'synthetic-tender', 'is_active' => true, 'published_at' => now()]);
$this->organization = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SINTÉTICO QA — Entidade de ensaio', 'organization_type' => 'private']);
$this->actingAs($this->actor);
}
private function input(array $sources = ['tenders'], array $criteria = [], int $version = 0): array
{
return ['version' => $version, 'enabled' => true, 'frequency' => 'as_available', 'channel' => 'in_app', 'consent' => true, 'sources' => $sources, 'criteria' => $criteria];
}
private function payload(array $overrides = []): array
{
return [...['title' => 'SINTÉTICO QA — Concurso de ensaio', 'reference' => 'QA-'.Str::uuid(), 'organization_id' => $this->organization,
'sector_id' => $this->sector->id, 'regime' => 'private', 'modality' => 'Modalidade documentada de ensaio',
'object' => 'Objecto sintético de ensaio; sem contratação real.', 'instrument' => 'Regras sintéticas documentadas', 'edition' => 'QA-2026',
'rule_source' => 'https://example.invalid/synthetic-rules', 'origin_published_at' => now()->subDay()->format('Y-m-d\TH:i'),
'deadline' => now()->addMonth()->format('Y-m-d\TH:i'), 'timezone' => 'Africa/Maputo', 'delivery_channel' => 'Canal externo documentado de ensaio',
'public_reason' => 'Publicação sintética de ensaio, sem contratação ou proposta real.',
'internal_notes' => 'SECRET-SYNTHETIC-DRAFT', 'public_contact' => 'synthetic-private@example.invalid', 'contact_authorized' => false,
'attachments' => [], 'lots' => []], ...$overrides];
}
/** @return array{id:string,version_id:string,payload:array} */
private function publish(array $payload = [], ?string $id = null, string $act = 'initial'): array
{
$service = app(Procurement::class);
$payload = $payload ?: $this->payload();
$id = $service->save($this->editor, $id, ['version' => $id ? DB::table('portal_tenders')->where('id', $id)->value('version') : 0,
'reason' => 'Preparação sintética documentada para ensaio QA.', 'draft' => $payload]);
$plan = $service->preview($this->editor, $id, $act);
$service->publish($this->editor, $id, ['act' => $act, 'hash' => $plan['hash'], 'reason' => $plan['payload']['public_reason']]);
return ['id' => $id, 'version_id' => DB::table('portal_tenders')->where('id', $id)->value('published_version_id'), 'payload' => $payload];
}
private function opportunity(): Opportunity
{
return Opportunity::create(['sector_id' => $this->sector->id, 'title' => 'Synthetic opportunity', 'slug' => 'synthetic-'.Str::uuid(),
'reference' => 'SYNTHETIC-'.Str::uuid(), 'status' => 'published', 'published_at' => now()]);
}
public function test_new_tenders_match_public_sector_province_and_regime_without_drafts_or_private_data(): void
{
$this->seed(TerritoryReferenceSeeder::class);
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('id', '<>', $province)->value('id');
$this->publish($this->payload(['territory_id' => $district]));
$criteria = ['sector' => $this->sector->slug, 'province_id' => $province, 'tender_regime' => 'private', 'category' => 'not-applicable-to-tenders'];
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], $criteria))->assertOk()->assertJsonPath('sources', ['tenders'])->assertJsonMissingPath('criteria.category');
$match = $this->publish($this->payload(['territory_id' => $district]));
$this->publish($this->payload(['territory_id' => $otherProvince]));
$this->publish($this->payload(['territory_id' => $district, 'regime' => 'external']));
$otherSector = Sector::create(['name' => 'Other synthetic sector', 'slug' => 'other-synthetic-tender', 'is_active' => true]);
$this->publish($this->payload(['territory_id' => $district, 'sector_id' => $otherSector->id]));
app(Procurement::class)->save($this->editor, null, ['version' => 0, 'reason' => 'Rascunho sintético sem publicação de ensaio.', 'draft' => $this->payload(['territory_id' => $district])]);
$this->opportunity();
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$notification = DB::table('investment_notifications')->sole();
$this->assertSame($match['version_id'], $notification->tender_version_id);
$this->assertNull($notification->submission_id);
$this->assertNull($notification->opportunity_id);
$payload = json_decode(Crypt::decryptString($notification->payload), true);
$this->assertSame($match['id'], $payload['tender_id']);
$this->assertSame('initial', $payload['act']);
$this->assertSame(1, $payload['preference_version']);
$this->assertArrayNotHasKey('internal_notes', $payload);
$this->assertArrayNotHasKey('public_contact', $payload);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('notifications.data.0.kind', 'tender_match')->assertDontSee('SECRET-SYNTHETIC-DRAFT');
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
$this->assertDatabaseCount('portal_tender_watches', 0);
}
public function test_new_published_acts_preserve_old_alerts_and_draft_edits_do_not_generate_alerts(): void
{
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
$initial = $this->publish($this->payload());
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(1, $alerts->dispatchDue());
$old = DB::table('investment_notifications')->sole();
$changed = $initial['payload'];
$changed['deadline'] = now()->addMonths(2)->format('Y-m-d\TH:i');
$service = app(Procurement::class);
$service->save($this->editor, $initial['id'], ['version' => 2, 'reason' => 'Alteração sintética de prazo ainda em preparação.', 'draft' => $changed]);
$this->travel(5)->minutes();
$this->assertSame(0, $alerts->dispatchDue());
$plan = $service->preview($this->editor, $initial['id'], 'extension');
$service->publish($this->editor, $initial['id'], ['act' => 'extension', 'hash' => $plan['hash'], 'reason' => $plan['payload']['public_reason']]);
$this->travel(5)->minutes();
$this->assertSame(1, $alerts->dispatchDue());
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(2, 'notifications.data');
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertOk();
$this->assertSame($old->payload, DB::table('investment_notifications')->where('id', $old->id)->value('payload'));
DB::table('portal_tenders')->where('id', $initial['id'])->update(['published_version_id' => null]);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data');
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
$this->assertDatabaseCount('investment_notifications', 2);
}
public function test_temporary_unavailability_only_pauses_tenders_and_cancellation_never_depends_on_that_catalogue(): void
{
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
$this->publish();
$opportunity = $this->opportunity();
config(['procurement.enabled' => false]);
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(1, $alerts->dispatchDue());
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $opportunity->id]);
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.source_statuses.opportunities', true)
->assertJsonPath('alertPreferences.source_statuses.tenders', false);
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], [], 1))->assertUnprocessable()->assertJsonValidationErrors('sources');
config(['procurement.enabled' => true]);
$this->travel(5)->minutes();
$this->assertSame(1, $alerts->dispatchDue());
config(['procurement.enabled' => false]);
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk()->assertJsonPath('enabled', false);
$this->travel(8)->days();
$this->assertSame(0, $alerts->dispatchDue());
$this->assertDatabaseCount('investment_notifications', 2);
}
public function test_delivery_failure_rolls_back_both_sources_and_retry_delivers_each_once(): void
{
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
$this->opportunity();
$this->publish();
$before = DB::table('investment_alert_preferences')->value('next_run_at');
$workspace = \Mockery::mock(InvestmentWorkspace::class)->makePartial();
$workspace->shouldReceive('notifyTender')->once()->andThrow(new \RuntimeException('Synthetic tender delivery failure'));
$this->app->instance(InvestmentWorkspace::class, $workspace);
try {
app(InvestmentOpportunityAlerts::class)->dispatchDue();
$this->fail('The shared delivery transaction must fail atomically.');
} catch (\RuntimeException $error) {
$this->assertSame('Synthetic tender delivery failure', $error->getMessage());
}
$this->assertDatabaseCount('investment_notifications', 0);
$this->assertDatabaseCount('investment_alert_seen', 0);
$this->assertDatabaseCount('investment_tender_alert_seen', 0);
$this->assertSame($before, DB::table('investment_alert_preferences')->value('next_run_at'));
$this->app->forgetInstance(InvestmentWorkspace::class);
$this->assertSame(2, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->assertDatabaseCount('investment_notifications', 2);
}
public function test_source_selection_is_explicit_and_migration_preserves_existing_preferences_and_history(): void
{
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities']))->assertOk();
$before = (array) DB::table('investment_alert_preferences')->sole();
$migration = require database_path('migrations/2026_11_02_200000_investment_tender_alerts.php');
$migration->down();
$this->assertFalse(app(InvestmentOpportunityAlerts::class)->tendersInstalled());
$migration->up();
$this->assertSame($before, (array) DB::table('investment_alert_preferences')->sole());
$this->publish();
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], [], 1))->assertOk();
$this->publish();
$this->travel(5)->minutes();
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
try {
$migration->down();
$this->fail('Tender preferences and history must be preserved before rollback.');
} catch (\RuntimeException $error) {
$this->assertStringContainsString('Preserve tender alert preferences', $error->getMessage());
}
$this->assertDatabaseCount('investment_notifications', 1);
}
public function test_opportunity_backlog_does_not_starve_tenders_or_lose_the_remaining_batch(): void
{
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
for ($index = 0; $index < 201; $index++) {
$this->opportunity();
}
$this->publish();
$alerts = app(InvestmentOpportunityAlerts::class);
$this->assertSame(201, $alerts->dispatchDue(), 'One tender is delivered alongside the bounded opportunity batch.');
$this->assertDatabaseCount('investment_tender_alert_seen', 1);
$this->assertSame(1, $alerts->dispatchDue(), 'The unconsumed opportunity remains due for the next run.');
$this->assertSame(0, $alerts->dispatchDue());
$this->assertDatabaseCount('investment_notifications', 202);
$this->assertDatabaseCount('investment_alert_seen', 201);
}
}
@@ -0,0 +1,89 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
final class QuickOpportunitySearchTest extends TestCase
{
use RefreshDatabase;
private Sector $sector;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
$this->sector = Sector::create(['name' => 'Agronegócio sintético QA', 'slug' => 'agronegocio-synthetic', 'is_active' => true, 'published_at' => now()]);
}
private function record(string $title, string $summary, array $attributes = []): Opportunity
{
return Opportunity::create([...['sector_id' => $this->sector->id, 'title' => $title, 'summary' => $summary,
'reference' => 'SYNTHETIC-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subMinute()], ...$attributes]);
}
public function test_plantio_de_algodao_finds_cultivation_variants_without_relabelling_processing_and_combines_province_and_sector(): void
{
$this->seed(TerritoryReferenceSeeder::class);
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
$this->assertNotEmpty($district);
$crop = $this->record('SINTÉTICO QA — exploração agrícola', 'Cultivo comercial de algodão, exemplo fictício para ensaio.', ['primary_territory_id' => $district]);
$processing = $this->record('SINTÉTICO QA — unidade de transformação', 'Descaroçamento, fiação e produção de óleo de algodão.', ['primary_territory_id' => $district]);
$this->record('SINTÉTICO QA — outra cultura', 'Cultivo de milho, sem relação com a pesquisa solicitada.');
$this->record('SINTÉTICO QA — privado', 'Cultivo de algodão.', ['status' => 'draft']);
$this->record('SINTÉTICO QA — futuro', 'Cultivo de algodão.', ['published_at' => now()->addDay()]);
$deleted = $this->record('SINTÉTICO QA — eliminado', 'Cultivo de algodão.');
$deleted->delete();
$before = DB::table('opportunities')->orderBy('id')->get()->toJson();
foreach (['plantio de algodao', 'PLANTIO DE ALGODÃO', 'algodao cultivo', 'plantação de algodão Nampula'] as $text) {
foreach (['/api/v1/investment/search', '/api/v1/opportunities/search'] as $endpoint) {
$this->getJson($endpoint.'?'.http_build_query(['q' => $text]))->assertOk()
->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $crop->id);
}
}
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'AGRONEGOCIO, NAMPULA']))->assertOk()->assertJsonPath('total', 2);
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertInertia(fn (Assert $page) => $page
->component('investment/catalogue')->where('filters.q', 'plantio de algodao')->where('results.total', 1)
->where('results.data.0.id', $crop->id)->where('relatedSearch', null));
$this->getJson('/api/v1/investment/map?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertJsonCount(1, 'unlocated');
$csv = $this->get('/api/v1/investment/export?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->streamedContent();
$this->assertStringContainsString($crop->title, $csv);
$this->assertStringNotContainsString($processing->title, $csv);
$this->assertSame($before, DB::table('opportunities')->orderBy('id')->get()->toJson());
}
public function test_if_only_processing_exists_related_fiches_are_separate_and_never_widen_other_filters(): void
{
$processing = $this->record('SINTÉTICO QA — transformação de algodão', 'Descaroçamento e transformação de algodão.');
$this->record('SINTÉTICO QA — privado', 'Descaroçamento de algodão.', ['status' => 'draft']);
$this->record('SINTÉTICO QA — outra cadeia', 'Cultivo de milho.');
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('results.total', 0)->where('relatedSearch.query', 'plantio de algodao')->where('relatedSearch.subject', 'algodao')
->has('relatedSearch.items', 1)->where('relatedSearch.items.0.id', $processing->id)
->where('relatedSearch.href', '/oportunidades?q=algodao'));
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao', 'category' => 'financing']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('results.total', 0)->has('relatedSearch.items', 0)->where('filters.category', 'financing')
->where('relatedSearch.href', '/oportunidades?category=financing&q=algodao'));
}
public function test_literal_wildcards_and_unmatched_words_do_not_return_unrelated_records(): void
{
$literal = $this->record('SINTÉTICO QA — 100% algodão', 'Referência sintética.', ['reference' => 'SYNTHETIC_REF_ABC']);
$this->record('SINTÉTICO QA — 1000 algodão', 'Referência sintética.', ['reference' => 'SYNTHETICXREFXABC']);
foreach (['100%', 'SYNTHETIC_REF_ABC'] as $query) {
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => $query]))->assertOk()
->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $literal->id);
}
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'de e em']))->assertOk()->assertJsonPath('total', 0);
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'palavra-inexistente-synthetic']))->assertOk()->assertJsonPath('total', 0);
}
}
@@ -0,0 +1,454 @@
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);
function load(file, mocks) {
const output = ts.transpileModule(
fs
.readFileSync(
new URL(
'../../resources/js/components/' + file,
import.meta.url,
),
'utf8',
)
.replaceAll('import.meta.env.VITE_MAP_TILE_URL', 'undefined'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const polygon = (x, y) => ({
type: 'Polygon',
coordinates: [
[
[x, y],
[x + 1, y],
[x + 1, y + 1],
[x, y + 1],
[x, y],
],
],
});
const boundary = {
geometry: polygon(30, -20),
title: 'Província sintética',
purpose: 'administrative_boundary',
selected_territory: true,
location_type: 'province',
url: '/territorio',
source_reference: 'Fonte sintética',
source_date: '2026-01-01',
};
const point = {
geometry: { coordinates: [40, -10] },
properties: {
id: 1,
title: 'Investimento sintético',
url: '/oportunidades/1',
location: 'Local confirmado',
},
};
const flatten = (node) =>
!node || typeof node !== 'object'
? []
: [
node,
...React.Children.toArray(node.props.children).flatMap(flatten),
];
await test('catalogue composes one map with the same opportunity data and separate administrative context, including no selected territory', () => {
const Map = () => null,
Info = () => null;
const requests = [];
const Component = load('catalogue-investment-map.tsx', {
'./interactive-investment-map': { default: Map },
'./territory-geometry-preview': { TerritoryGeometryDetails: Info },
'./use-territory-geometry': {
useTerritoryGeometry: (id) => {
requests.push(id);
return { context: { areas: [boundary] }, error: '' };
},
},
}).default;
const points = [point],
areas = [];
const tree = Component({ points, areas, territoryId: 'province-1' });
assert.equal(tree.type, Map);
assert.equal(tree.props.points, points);
assert.equal(tree.props.areas, areas);
assert.deepEqual(tree.props.administrativeAreas, [boundary]);
assert.equal(tree.props.layerControls, true);
assert.equal(tree.props.administrativeInfo.type, Info);
assert.deepEqual(requests, ['province-1']);
assert.equal(
Component({ points: [], areas }).props.administrativeInfo,
undefined,
);
});
await test('territorial request changes discard old boundaries immediately and ignore late responses; clearing selection removes context', async () => {
const previousFetch = globalThis.fetch;
const pending = [],
memory = [];
let cursor = 0,
effect;
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in memory)) memory[index] = initial;
return [memory[index], (value) => (memory[index] = value)];
},
useEffect(fn) {
effect = fn;
},
};
globalThis.fetch = (url, options) =>
new Promise((resolve) => pending.push({ url, options, resolve }));
try {
const { useTerritoryGeometry } = load('use-territory-geometry.ts', {
react: hooks,
});
const render = (id) => {
cursor = 0;
return useTerritoryGeometry(id);
};
render('a');
const cleanup = effect();
cleanup();
render('b');
effect();
pending[0].resolve({
ok: true,
json: async () => ({ areas: [boundary] }),
});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(render('b').context, null);
pending[1].resolve({
ok: true,
json: async () => ({ areas: [{ ...boundary, title: 'B' }] }),
});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(render('b').context.areas[0].title, 'B');
assert.equal(render('c').context, null);
assert.equal(render(undefined).context, null);
assert.equal(pending[0].options.signal.aborted, true);
assert.equal(pending.length, 2);
} finally {
globalThis.fetch = previousFetch;
}
});
await test('Leaflet uses one instance, independent layers and selected boundary bounds; restoring hidden points from the list never creates positions', async () => {
const previousDocument = globalThis.document,
previousObserver = globalThis.ResizeObserver;
let effect, overlayOptions, overlayEvents, fitted;
const refs = [],
instances = [],
groups = [];
globalThis.document = {
createElement: () => ({ append() {}, textContent: '', style: {} }),
};
globalThis.ResizeObserver = class {
observe() {}
disconnect() {}
};
const instance = {
setView() {
return this;
},
fitBounds(value) {
fitted = value;
},
on(_event, fn) {
overlayEvents = fn;
return this;
},
addLayer(group) {
group.visible = true;
return this;
},
invalidateSize() {},
remove() {},
};
const layer = () => ({
addTo(group) {
group.items.push(this);
return this;
},
bindPopup() {
return this;
},
on() {
return this;
},
getLatLng() {
return [
point.geometry.coordinates[1],
point.geometry.coordinates[0],
];
},
openPopup() {},
});
const L = {
map() {
instances.push(instance);
return instance;
},
tileLayer: () => ({
on() {
return this;
},
addTo() {},
}),
layerGroup() {
const group = {
items: [],
addTo() {
this.visible = true;
return this;
},
};
groups.push(group);
return group;
},
control: {
scale: () => ({ addTo() {} }),
layers(_base, overlays) {
overlayOptions = overlays;
return { addTo() {} };
},
},
geoJSON(geometry) {
const item = layer();
const coords = geometry.coordinates[0];
item.getBounds = () => ({
isValid: () => true,
getSouth: () => Math.min(...coords.map((c) => c[1])),
getNorth: () => Math.max(...coords.map((c) => c[1])),
getWest: () => Math.min(...coords.map((c) => c[0])),
getEast: () => Math.max(...coords.map((c) => c[0])),
});
return item;
},
divIcon: (value) => value,
marker: () => layer(),
};
const hooks = {
...React,
useMemo: (fn) => fn(),
useState: (initial) => [initial, () => {}],
useRef(initial) {
const ref = { current: refs.length === 0 ? {} : initial };
refs.push(ref);
return ref;
},
useEffect(fn) {
effect = fn;
},
};
try {
const Component = load('interactive-investment-map.tsx', {
react: hooks,
leaflet: L,
'leaflet/dist/leaflet.css': {},
}).default;
const area = {
...boundary,
title: 'Área sintética',
purpose: 'investment_area',
selected_territory: false,
};
const tree = Component({
points: [point],
areas: [area, boundary],
administrativeAreas: [boundary],
layerControls: true,
});
const cleanup = effect();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(instances.length, 1);
assert.equal(groups[0].items.length, 1);
assert.equal(groups[1].items.length, 1);
assert.equal(groups[2].items.length, 1); // Same boundary from both APIs is not doubled.
assert.deepEqual(fitted, [
[-20, 30],
[-19, 31],
]); // No national parent/outside point overrides the selection.
assert.equal(Object.keys(overlayOptions).length, 3);
overlayEvents({ layer: groups[0], type: 'overlayremove' });
assert.equal(refs[4].current.points, false);
const button = flatten(tree).find((n) => n.type === 'button');
button.props.onClick();
assert.equal(groups[0].visible, true);
assert.equal(refs[4].current.points, true);
assert(
flatten(tree).some(
(n) => n.type === 'a' && n.props.href === '/territorio',
),
);
assert(flatten(tree).some((n) => n.type === 'details'));
cleanup();
refs.length = 0;
groups.length = 0;
Component({
points: [],
areas: [],
administrativeAreas: [
{ ...boundary, selected_territory: false },
{
...boundary,
geometry: polygon(0, 0),
selected_territory: false,
location_type: 'country',
title: 'País sintético',
},
],
layerControls: true,
});
const cleanupEmpty = effect();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(groups[0].items.length, 0);
assert.deepEqual(fitted, [
[-20, 30],
[-19, 31],
]);
cleanupEmpty();
} finally {
globalThis.document = previousDocument;
globalThis.ResizeObserver = previousObserver;
}
});
await test('administrative failure does not remove investment results or add another map', () => {
const Map = () => null,
Info = () => null;
const Component = load('catalogue-investment-map.tsx', {
'./interactive-investment-map': { default: Map },
'./territory-geometry-preview': { TerritoryGeometryDetails: Info },
'./use-territory-geometry': {
useTerritoryGeometry: () => ({
context: null,
error: 'Limites indisponíveis',
}),
},
}).default;
const points = [point];
const tree = Component({ points, areas: [], territoryId: 'a' });
assert.equal(tree.type, Map);
assert.equal(tree.props.points, points);
assert.equal(tree.props.administrativeAreas, undefined);
assert(flatten(tree.props.notice).some((n) => n.props.role === 'alert'));
});
await test('declared parcels and documented source locations are never labelled as administrative boundaries or investments', () => {
const hooks = {
...React,
useMemo: (fn) => fn(),
useState: (value) => [value, () => {}],
useRef: (value) => ({ current: value }),
useEffect: () => {},
};
const Component = load('interactive-investment-map.tsx', {
react: hooks,
'leaflet/dist/leaflet.css': {},
}).default;
const parcel = renderToStaticMarkup(
Component({
points: [],
areas: [
{
...boundary,
purpose: 'declared_parcel',
title: 'Parcela sintética',
},
],
contextOnly: true,
mapKind: 'declared_parcel',
}),
);
assert.match(parcel, />Perímetro declarado pelo Promotor<\/h2>/);
assert.match(parcel, /não é limite administrativo/);
assert.doesNotMatch(
parcel,
/>Contexto administrativo<\/h2>|limites administrativos disponíveis/,
);
const documented = renderToStaticMarkup(
Component({
points: [],
areas: [],
mapKind: 'documented_locations',
layerControls: true,
}),
);
assert.match(documented, />Mapa dos locais documentados<\/h2>/);
assert.match(documented, /Local documentado com coordenadas/);
assert.doesNotMatch(documented, /Oportunidade com coordenadas confirmadas/);
const administrative = renderToStaticMarkup(
Component({ points: [], areas: [boundary], contextOnly: true }),
);
assert.match(administrative, />Contexto administrativo<\/h2>/);
});
await test('partnership catalogue has one contextual map and keeps the applied territory while filter edits are pending', () => {
let draft;
const hooks = {
...React,
useState(initial) {
draft ??= initial;
return [
draft,
(value) => {
draft = value;
},
];
},
};
const Map = () => null;
const Page = load('../pages/partnerships/catalogue.tsx', {
react: hooks,
'@inertiajs/react': { Link: 'a', router: { get() {} } },
'@/components/catalogue-investment-map': { default: Map },
'./shared': { Frame: 'main', Field: 'label', control: '', button: '' },
}).default;
const props = {
types: {},
sectors: [],
territories: [{ id: 'a', name: 'A', location_type: 'province' }],
filters: { territory_id: 'a' },
mapPoints: [point],
results: {
data: [],
total: 0,
prev_page_url: null,
next_page_url: null,
},
};
let tree = Page(props);
const maps = () => flatten(tree).filter((node) => node.type === Map);
assert.equal(maps().length, 1);
assert.equal(maps()[0].props.mapKind, 'documented_locations');
assert.equal(maps()[0].props.points, props.mapPoints);
flatten(tree)
.find((node) => node.type === 'select' && node.props.value === 'a')
.props.onChange({ target: { value: 'b' } });
tree = Page(props);
assert.equal(maps()[0].props.territoryId, 'a');
assert.equal(maps()[0].props.points, props.mapPoints);
});
@@ -0,0 +1,147 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url);
function source(name) {
return fs.readFileSync(
new URL('../../resources/js/pages/investment/' + name, import.meta.url),
'utf8',
);
}
function compile(source) {
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
require,
module,
module.exports,
);
return module.exports;
}
const shared = ts.createSourceFile(
'shared.tsx',
source('shared.tsx'),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const apiNode = shared.statements.find(
(node) => ts.isFunctionDeclaration(node) && node.name?.text === 'api',
);
const { api } = compile(apiNode.getText(shared));
await test('API preserves JSON validation messages and handles empty and non-JSON responses', async () => {
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async () =>
new Response(JSON.stringify({ message: 'Campo obrigatorio' }), {
status: 422,
});
await assert.rejects(api('/synthetic'), /Campo obrigatorio/);
globalThis.fetch = async () =>
new Response('<html>proxy error</html>', { status: 502 });
await assert.rejects(api('/synthetic'), /concluir a opera/);
globalThis.fetch = async () =>
new Response('<html>expired</html>', { status: 419 });
await assert.rejects(api('/synthetic'), /sess.*expirou/);
globalThis.fetch = async () => new Response('', { status: 200 });
await assert.rejects(api('/synthetic'), /concluir a opera/);
globalThis.fetch = async () => new Response(null, { status: 204 });
assert.equal(await api('/synthetic'), null);
} finally {
globalThis.fetch = originalFetch;
}
});
await test('public GET ignores malformed CSRF cookie; writes preserve CSRF and multipart transport', async () => {
const originalFetch = globalThis.fetch;
const originalDocument = Object.getOwnPropertyDescriptor(
globalThis,
'document',
);
let request;
try {
Object.defineProperty(globalThis, 'document', {
value: { cookie: 'XSRF-TOKEN=%broken' },
configurable: true,
});
globalThis.fetch = async (url, options) => {
request = options;
return new Response('{"ok":true}');
};
assert.deepEqual(await api('/synthetic'), { ok: true });
await assert.rejects(api('/synthetic', {}), /validada/);
globalThis.document.cookie = 'XSRF-TOKEN=synthetic%3D';
const body = new FormData();
body.set('name', 'synthetic');
await api('/synthetic', body);
assert.equal(request.method, 'POST');
assert.equal(request.credentials, 'same-origin');
assert.equal(request.headers['X-XSRF-TOKEN'], 'synthetic=');
assert.equal(request.headers['Content-Type'], undefined);
assert.equal(request.body, body);
} finally {
globalThis.fetch = originalFetch;
if (originalDocument)
Object.defineProperty(globalThis, 'document', originalDocument);
else delete globalThis.document;
}
});
await test('catalogue pagination exposes applied links only after a successful search', () => {
const file = ts.createSourceFile(
'catalogue.tsx',
source('catalogue.tsx'),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let nav;
function visit(node) {
if (
ts.isJsxElement(node) &&
node.openingElement.tagName.getText(file) === 'nav' &&
node.getText(file).includes('results.prev_page_url')
)
nav = node;
ts.forEachChild(node, visit);
}
visit(file);
assert.ok(nav);
const { Pagination } = compile(
`const Link='a'; export function Pagination({searchLoading,searchError,results,view}) {return (${nav.getText(file)});}`,
);
const props = {
view: 'list',
results: {
prev_page_url: '/previous?page=1',
next_page_url: '/previous?page=3',
},
};
for (const state of [
{ searchLoading: true, searchError: '' },
{ searchLoading: false, searchError: 'failure' },
]) {
const html = renderToStaticMarkup(
React.createElement(Pagination, { ...props, ...state }),
);
assert.doesNotMatch(html, /href=/);
}
const html = renderToStaticMarkup(
React.createElement(Pagination, {
...props,
searchLoading: false,
searchError: '',
}),
);
assert.match(html, /href="\/previous\?page=1"/);
assert.match(html, /href="\/previous\?page=3"/);
});
@@ -0,0 +1,129 @@
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 { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, overrides = {}) {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => overrides[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function render(payload) {
const empty = () => null;
const page = load('../../resources/js/pages/desk/request.tsx', {
'@inertiajs/react': {
Link: ({ href, children }) =>
createElement('a', { href }, children),
useForm: (data) => ({ data, errors: {}, processing: false }),
},
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
'@/lib/desk-field-visibility': load(
'../../resources/js/lib/desk-field-visibility.ts',
),
'@/components/dossier-prefill': { DossierPrefill: empty },
'@/components/country-select': { __esModule: true, default: empty },
'@/components/investment-territory': { TerritoryFields: empty },
'@/components/desk-internal-operations': {
DocumentReview: empty,
RequestOperations: empty,
},
'@/pages/investment/shared': {
Frame: ({ children }) => createElement('main', null, children),
card: '',
input: '',
button: '',
},
}).default;
return renderToStaticMarkup(
page({
request: {
id: 'synthetic-request',
version: 1,
status: 'draft',
payload,
protocol: null,
editable_fields: [],
analyst_id: null,
due_at: null,
},
case: { id: 'synthetic-case', title: 'Synthetic dossier' },
definition: {
title: 'Synthetic form',
result: 'Synthetic result',
fields: {
detail: {
label: 'Deep detail',
type: 'text',
required: true,
when: { field: 'branch', equals: '1' },
},
branch: {
label: 'Branch question',
type: 'select',
required: true,
options: { 0: 'No', 1: 'Yes' },
when: { field: 'root', equals: '1' },
},
root: {
label: 'Root question',
type: 'select',
required: true,
options: { 0: 'No', 1: 'Yes' },
},
},
},
owner: true,
manager: false,
analyst: false,
fieldsEditable: true,
states: { draft: 'Draft' },
transitions: [],
findings: [],
messages: [],
analysts: [],
territoryPaths: {},
events: [],
documents: [],
payments: [],
caseVersion: 1,
countries: [],
toolPrefill: null,
}),
);
}
await test('hidden parent answers never reveal nested questions, while reopening the branch restores their answers', () => {
const payload = { root: '0', branch: '1', detail: 'Preserved detail' };
const hidden = render(payload);
assert.ok(hidden.includes('Root question'));
assert.ok(!hidden.includes('Branch question'));
assert.ok(!hidden.includes('Deep detail'));
assert.ok(!hidden.includes('Preserved detail'));
const visible = render({ ...payload, root: '1' });
assert.ok(visible.includes('Branch question'));
assert.ok(visible.includes('Deep detail'));
assert.ok(visible.includes('Preserved detail'));
assert.deepEqual(payload, {
root: '0',
branch: '1',
detail: 'Preserved detail',
});
});
+117
View File
@@ -0,0 +1,117 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('service editor retains the source, invalidates confirmation after edits and compares old/new values before publishing a remembered draft', () => {
const service = {
code: 'project-change',
version: 1,
definition: {
title: 'Synthetic service',
theme: 'Synthetic',
profile: 'Investor',
entity: 'Internal team',
result: 'Preparation',
stage: 'E10',
fields: {
question: {
label: 'Original question',
type: 'text',
required: false,
},
},
},
};
const before = JSON.stringify(service);
let form, rememberedKey, sent;
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/pages/desk/service-editor.tsx',
import.meta.url,
),
'utf8',
) + '\nexport { Editor };',
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === 'react'
? { useState: (initial) => [initial, () => {}] }
: name === '@inertiajs/react'
? {
Link: 'a',
useForm(key, initial) {
rememberedKey = key;
form ??= {
data: initial,
errors: {},
processing: false,
setData(value, next) {
this.data =
typeof value === 'function'
? value(this.data)
: { ...this.data, [value]: next };
},
put(url) {
sent = {
url,
data: structuredClone(this.data),
};
},
};
return form;
},
}
: name === '@/pages/investment/shared'
? { Frame: 'main', card: '', button: '', input: '' }
: name === '@/components/desk-service-history'
? { default: () => null, __esModule: true }
: require(name),
module,
module.exports,
);
const render = () => module.exports.Editor({ service });
let tree = render();
assert.equal(rememberedKey, 'desk-service-editor:project-change:1');
form.data.confirm = true;
const question = nodes(tree).find(
(node) =>
node.type === 'input' && node.props.value === 'Original question',
);
question.props.onChange({ target: { value: 'Revised question' } });
assert.equal(form.data.confirm, false);
tree = render();
const html = renderToStaticMarkup(tree);
assert.match(html, /Versão anterior/);
assert.match(html, /Original question/);
assert.match(html, /Revised question/);
assert.match(html, /pedidos.*definição original/is);
assert.equal(JSON.stringify(service), before);
form.data.confirm = true;
tree.props.onSubmit({ preventDefault() {} });
assert.equal(sent.url, '/management/balcao/servicos/project-change');
assert.equal(sent.data.base_version, 1);
assert.equal(
sent.data.definition.fields.question.label,
'Revised question',
);
});
@@ -0,0 +1,186 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
function harness() {
const values = [],
requests = [];
let cursor = 0,
effect;
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in values)) values[index] = initial;
return [
values[index],
(value) => {
values[index] =
typeof value === 'function'
? value(values[index])
: value;
},
];
},
useEffect(callback) {
effect = callback;
},
};
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/desk-service-history.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === 'react'
? hooks
: name === '@/lib/portal-api'
? {
portalRequest: (url, options) =>
new Promise((resolve, reject) =>
requests.push({
url,
options,
resolve,
reject,
}),
),
}
: require(name),
module,
module.exports,
);
return {
requests,
start: () => effect(),
render(code = 'project-change') {
cursor = 0;
return module.exports.default({
code,
formatField: (field) =>
field.label +
(field.required ? ' — Obrigatório' : ' — Opcional'),
});
},
};
}
const version = {
id: 'v1',
version: 1,
status: 'published',
author_id: 21,
published_by: 22,
published_at: null,
reason: 'Synthetic publication reason',
source: { identifier: 'Synthetic source', edition: 'Synthetic edition' },
definition: {
title: 'Old form',
theme: 'Theme',
profile: 'Investor',
entity: 'Internal team',
stage: 'E10',
result: 'Internal preparation',
fields: {
title: { label: 'Original question', type: 'text', required: true },
},
},
payload: 'PRIVATE-ANSWER',
};
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('history renders immutable definitions and provenance without applicant answers, then paginates using the same authorised endpoint', async () => {
const h = harness();
h.render();
h.start();
assert.equal(
h.requests[0].url,
'/management/balcao/servicos/project-change/versoes?page=1',
);
h.requests[0].resolve({ page: 1, pages: 2, total: 11, data: [version] });
await flush();
const tree = h.render(),
html = renderToStaticMarkup(tree);
assert.match(html, /Original question — Obrigatório/);
assert.match(html, /Synthetic publication reason/);
assert.match(html, /Synthetic source · Synthetic edition/);
assert.doesNotMatch(html, /PRIVATE-ANSWER|<input|<form|<textarea/);
nodes(tree)
.find(
(node) =>
node.type === 'button' && node.props.children === 'Seguinte',
)
.props.onClick();
assert.match(renderToStaticMarkup(h.render()), /A recuperar/);
h.start();
assert.equal(
h.requests[1].url,
'/management/balcao/servicos/project-change/versoes?page=2',
);
h.requests[1].resolve({
page: 2,
pages: 2,
total: 11,
data: [
{
...version,
id: 'older',
version: 0,
definition: { ...version.definition, title: 'Previous page' },
},
],
});
await flush();
assert.match(renderToStaticMarkup(h.render()), /Previous page/);
});
await test('failed history differs from an empty history and stale service responses never replace the selected service', async () => {
const h = harness();
h.render();
const cleanup = h.start();
cleanup();
h.render('project-follow-up');
h.start();
h.requests[0].resolve({ page: 1, pages: 1, total: 1, data: [version] });
await flush();
assert.doesNotMatch(
renderToStaticMarkup(h.render('project-follow-up')),
/Original question/,
);
h.requests[1].reject(new Error('Network unavailable'));
await flush();
const failed = h.render('project-follow-up');
assert.match(renderToStaticMarkup(failed), /Tentar novamente/);
assert.doesNotMatch(renderToStaticMarkup(failed), /Ainda não existem/);
nodes(failed)
.find((node) => node.type === 'button')
.props.onClick();
h.render('project-follow-up');
h.start();
h.requests[2].resolve({ page: 1, pages: 1, total: 0, data: [] });
await flush();
assert.match(
renderToStaticMarkup(h.render('project-follow-up')),
/Ainda não existem/,
);
});
@@ -0,0 +1,72 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
await test('blocked browser storage cannot prevent authentication or clearing a submitted interest', () => {
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 module = { exports: {} };
let destination;
const storage = {
getItem() {
throw new Error('blocked');
},
setItem() {
throw new Error('blocked');
},
removeItem() {
throw new Error('blocked');
},
};
compileFunction(output, [
'require',
'module',
'exports',
'sessionStorage',
'window',
'location',
])(
(name) =>
name === 'react'
? {
useState: (init) => [init(), () => {}],
useEffect: (effect) => effect(),
}
: { newSubmissionKey: () => 'synthetic-key' },
module,
module.exports,
storage,
{
location: {
assign: (url) => {
destination = url;
},
},
},
{ pathname: '/oportunidades/teste', search: '?sector=1' },
);
const draft = module.exports.useInterestDraft('synthetic', {
name: 'Synthetic',
email: 'synthetic@example.invalid',
});
assert.equal(draft.key, 'synthetic-key');
assert.doesNotThrow(() => draft.clear());
assert.doesNotThrow(() => draft.authenticate());
assert.equal(
destination,
'/participar/entrar?return=%2Foportunidades%2Fteste%3Fsector%3D1',
);
});
+20 -18
View File
@@ -110,7 +110,7 @@ void test('map coverage distinguishes returned counts, missing provenance and tr
assert.doesNotMatch(empty, /As fichas continuam disponíveis abaixo/);
assert.doesNotMatch(empty, /Resultados limitados/);
});
void test('map layer choices preserve received records, coverage, unlocated links and filters without another request', async () => {
void test('one layered map preserves records, coverage, unlocated links and applied filters without a duplicate map or nonadministrative inference', async () => {
const previousFetch = globalThis.fetch;
let resolve;
const requests = [];
@@ -149,7 +149,7 @@ void test('map layer choices preserve received records, coverage, unlocated link
{
react: hooks,
'@/components/search-state': { default: SearchState },
'./territory-geometry-preview': { default: () => null },
'./catalogue-investment-map': { default: MapView },
'./interactive-investment-map': { default: MapView },
'./investment-map-coverage': { default: Coverage },
},
@@ -180,34 +180,36 @@ void test('map layer choices preserve received records, coverage, unlocated link
const map = () => flat(tree).find((node) => node.type === MapView);
assert.equal(map().props.points.length, 2);
assert.equal(map().props.areas.length, 1);
flat(tree)
.filter((node) => node.type === 'input')[0]
.props.onChange({ target: { checked: false } });
tree = render();
assert.deepEqual(map().props.points, []);
assert.equal(map().props.areas.length, 1);
flat(tree)
.filter((node) => node.type === 'input')[1]
.props.onChange({ target: { checked: false } });
tree = render();
assert.deepEqual(map().props.areas, []);
assert.equal(
flat(tree).filter((node) => node.type === MapView).length,
1,
);
assert.equal(
flat(tree).filter((node) => node.type === 'input').length,
0,
);
assert.equal(map().props.territoryId, 'synthetic-province');
const html = renderToStaticMarkup(tree);
assert.match(html, /Camadas ocultas/);
assert.match(html, /incluindo camadas ocultas/);
assert.match(html, /href="\/synthetic\/3"/);
assert.match(
html,
/<th scope="row">Marcadores de investimento<\/th><td>2<\/td>/,
);
for (const checkbox of flat(tree).filter(
(node) => node.type === 'input',
))
checkbox.props.onChange({ target: { checked: true } });
tree = render();
assert.equal(map().props.points, data.features);
assert.equal(map().props.areas, data.areas);
assert.equal(requests.length, 1);
assert.match(requests[0].url, /province_id=synthetic-province/);
cursor = 0;
const changed = Panel({
filters: { geo_location_id: 'synthetic-park' },
});
const changedMap = flat(changed).find((node) => node.type === MapView);
assert.equal(changedMap.props.territoryId, undefined);
assert.equal(changedMap.props.points, null);
assert.deepEqual(changedMap.props.areas, []);
assert(!flat(changed).some((node) => node.type === Coverage));
} finally {
cleanup?.();
globalThis.fetch = previousFetch;
@@ -3,6 +3,32 @@ import assert from 'node:assert/strict';
import { contextApi } from '../../resources/js/lib/investor-context.ts';
const success = { ok: true, json: async () => ({ saved: true }) };
await test('context handles compact CSRF cookies and rejects malformed writes before transport', async () => {
let calls = 0;
await withTransport(
async (_url, options) => {
calls++;
if (options.method !== 'GET')
assert.equal(
options.headers['X-XSRF-TOKEN'],
'synthetic/token',
);
return success;
},
async () => {
globalThis.document.cookie = 'other=x;XSRF-TOKEN=synthetic%2Ftoken';
await contextApi('/synthetic', {});
globalThis.document.cookie = 'XSRF-TOKEN=%broken';
await assert.rejects(
contextApi('/synthetic', {}, 'POST', true),
/sessão/,
);
assert.equal(calls, 1);
await contextApi('/synthetic');
assert.equal(calls, 2);
},
);
});
async function withTransport(fetch, callback) {
const previousFetch = globalThis.fetch;
const previousDocument = globalThis.document;
@@ -134,3 +160,37 @@ void test('ordinary context writes and reads retain their existing method and er
},
);
});
void test('invalid successful context response remains a failure and releases keepalive budget', async () => {
let calls = 0;
await withTransport(
async (_url, options) => {
calls++;
assert.equal(options.keepalive, true);
return calls === 1
? new Response('<html>unexpected</html>', { status: 200 })
: success;
},
async () => {
await assert.rejects(
contextApi(
'/synthetic',
{ text: 'a'.repeat(40000) },
'POST',
true,
),
/HTTP 200/,
);
assert.equal(calls, 1);
assert.deepEqual(
await contextApi(
'/synthetic',
{ text: 'a'.repeat(40000) },
'POST',
true,
),
{ saved: true },
);
},
);
});
@@ -0,0 +1,454 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(path, mocks) {
const output = ts.transpileModule(
fs.readFileSync(new URL(path, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports.default;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('preferences submit their own version and chosen criteria, with explicit opt-in and an independent cancellation action', () => {
let form, sent;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
transform(fn) {
this.apply = fn;
},
put(url, options) {
sent = {
url,
options,
data: this.apply(this.data),
};
},
};
return form;
},
},
'@/components/opportunity-search-filters': {
modalityLabels: {
investment_project: 'Projecto de investimento',
},
},
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 7,
enabled: true,
frequency: 'daily',
channel: 'in_app',
next_run_at: null,
criteria: {
sector: 'qa',
province_id: 'province',
category: 'investment_project',
},
};
const render = () =>
Component({
preferences,
options: {
frequencies: { daily: 'Daily' },
sectors: [{ slug: 'qa', name: 'Synthetic sector' }],
provinces: [{ id: 'province', name: 'Synthetic province' }],
categories: ['investment_project'],
},
});
let tree = render();
assert.equal(form.data.consent, false);
assert.ok(
renderToStaticMarkup(tree).includes('Não são enviados emails ou SMS'),
);
const criteria = nodes(tree).find(
(node) => node.type === 'select' && node.props.value === 'qa',
);
criteria.props.onChange({ target: { value: '' } });
tree = render();
assert.equal(form.data.criteria.province_id, 'province');
nodes(tree)
.find(
(node) =>
node.type === 'input' && node.props.name === 'alert-consent',
)
.props.onChange({ target: { checked: true } });
tree = render();
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(sent.url, '/investidor/alert-preferences');
assert.equal(sent.data.version, 7);
assert.equal(sent.data.channel, 'in_app');
assert.equal(sent.data.enabled, true);
assert.equal(sent.data.consent, true);
assert.equal(sent.data.criteria.sector, '');
nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Cancelar estes alertas',
)
.props.onClick();
assert.equal(sent.data.enabled, false);
assert.equal(sent.data.consent, false);
assert.equal(preferences.enabled, true);
const unavailable = renderToStaticMarkup(
Component({
preferences: { ...preferences, criteria_available: false },
options: {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: [],
},
}),
);
assert.ok(
unavailable.includes(
'O acompanhamento das selecções indisponíveis fica suspenso',
),
);
assert.ok(unavailable.includes('Província anterior indisponível'));
assert.ok(unavailable.includes('Cancelar estes alertas'));
assert.equal(form.data.criteria.province_id, 'province');
});
await test('opportunity notifications preserve the legacy manifestation action and link to the public fiche', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 2,
notifications: {
data: [
{
id: 'alert',
opportunity_id: 12,
submission_id: null,
kind: 'opportunity_match',
payload: {
title: 'Synthetic public opportunity',
slug: 'synthetic-fiche',
source: 'Synthetic catalogue',
preference_version: 7,
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
{
id: 'legacy',
submission_id: 'synthetic-submission',
kind: 'received',
payload: { reference: 'SYNTHETIC-REF' },
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/oportunidades/synthetic-fiche'));
assert.ok(html.includes('/investidor/manifestacoes/synthetic-submission'));
assert.ok(html.includes('versão 7'));
assert.ok(html.includes('Manifestação recebida'));
assert.ok(!html.includes('/manifestacoes/null'));
});
await test('tender alerts require an explicit source choice and show only their applicable form controls', () => {
let form, sent;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
transform(fn) {
this.apply = fn;
},
put(url) {
sent = { url, data: this.apply(this.data) };
},
};
return form;
},
},
'@/components/opportunity-search-filters': {
modalityLabels: {
investment_project: 'Projecto de investimento',
},
},
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 3,
enabled: true,
frequency: 'daily',
channel: 'in_app',
next_run_at: null,
criteria: { category: 'investment_project' },
};
const options = {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: ['investment_project'],
tendersAvailable: true,
tenderRegimes: { private: 'Concurso privado' },
};
const render = (currentOptions = options) =>
Component({ preferences, options: currentOptions });
let tree = render();
assert.deepEqual(form.data.sources, ['opportunities']);
assert.equal(
nodes(tree).find((node) => node.props?.name === 'source-tenders').props
.checked,
false,
);
form.setData('consent', true);
nodes(tree)
.find((node) => node.props?.name === 'source-tenders')
.props.onChange({ target: { checked: true } });
assert.equal(form.data.consent, false);
tree = render();
nodes(tree)
.find((node) => node.props?.name === 'source-opportunities')
.props.onChange({ target: { checked: false } });
tree = render();
const html = renderToStaticMarkup(tree);
assert.ok(html.includes('Regime do concurso'));
assert.ok(!html.includes('Todas as modalidades'));
assert.ok(html.includes('Concurso privado'));
form.setData('consent', true);
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.deepEqual(sent.data.sources, ['tenders']);
tree = render({ ...options, tendersAvailable: false });
const unavailable = nodes(tree).find(
(node) => node.props?.name === 'source-tenders',
);
assert.equal(
unavailable.props.disabled,
false,
'An unavailable selected source must remain removable.',
);
unavailable.props.onChange({ target: { checked: false } });
assert.deepEqual(form.data.sources, []);
});
await test('published tender acts retain their identity and use the tender action rather than a manifestation URL', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 1,
alertOptions: { tenderActs: { extension: 'Prorrogação' } },
notifications: {
data: [
{
id: 'synthetic-alert',
submission_id: null,
tender_version_id: 'synthetic-version',
kind: 'tender_match',
payload: {
title: 'Synthetic public tender',
tender_id: 'synthetic-tender',
act: 'extension',
publication_version: 4,
source: 'Synthetic catalogue',
preference_version: 3,
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/concursos/synthetic-tender'));
assert.ok(html.includes('Consultar concurso'));
assert.ok(html.includes('Prorrogação'));
assert.ok(html.includes('versão 4'));
assert.ok(html.includes('não apresenta uma proposta'));
assert.ok(!html.includes('/manifestacoes/null'));
});
await test('funding preferences require opt-in and expose scope and window choices only for that source', () => {
let form;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
processing: false,
errors: {},
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
};
return form;
},
},
'@/components/opportunity-search-filters': { modalityLabels: {} },
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 1,
enabled: true,
frequency: 'daily',
criteria: {},
channel: 'in_app',
next_run_at: null,
};
const options = {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: [],
fundingAvailable: true,
};
let tree = Component({ preferences, options });
assert.deepEqual(form.data.sources, ['opportunities']);
assert.equal(
renderToStaticMarkup(tree).includes('Estado de uma janela'),
false,
);
form.setData('consent', true);
nodes(tree)
.find((node) => node.props?.name === 'source-funding')
.props.onChange({ target: { checked: true } });
assert.equal(form.data.consent, false);
tree = Component({ preferences, options });
assert.ok(
renderToStaticMarkup(tree).includes(
'Incluir e assinalar informação por confirmar',
),
);
assert.ok(renderToStaticMarkup(tree).includes('Estado de uma janela'));
assert.equal(form.data.criteria.funding_certainty, 'documented');
const unavailable = nodes(
Component({
preferences,
options: { ...options, fundingAvailable: false },
}),
).find((node) => node.props?.name === 'source-funding');
assert.equal(unavailable.props.disabled, false);
unavailable.props.onChange({ target: { checked: false } });
assert.deepEqual(form.data.sources, ['opportunities']);
});
await test('funding notice links to its programme and qualifies historical window states', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 1,
notifications: {
data: [
{
id: 'qa',
submission_id: null,
kind: 'funding_match',
payload: {
title: 'Synthetic fund',
programme_id: 'qa-fund',
source_url:
'https://example.invalid/funding-source',
source_reference: 'Synthetic source edition',
source_checked_on: '2026-11-02',
publication_version: 2,
scope_explanation: {
sector: 'Âmbito por confirmar',
},
window_states: [
{
title: 'Synthetic historical window',
state: 'closed',
end_on: '2025-10-20',
},
],
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/fundos/qa-fund'));
assert.ok(html.includes('https://example.invalid/funding-source'));
assert.ok(html.includes('Synthetic source edition'));
assert.ok(html.includes('não confirma uma candidatura aberta'));
assert.ok(html.includes('estado na data do aviso'));
assert.ok(html.includes('encerrada'));
assert.ok(html.includes('Âmbito por confirmar'));
assert.ok(!html.includes('/manifestacoes/null'));
});
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
readOpportunitySelection,
persistOpportunitySelection,
} from '../../resources/js/lib/opportunity-selection.ts';
await test('selection accepts only unique positive safe integer identifiers', () => {
const old = globalThis.sessionStorage;
try {
for (const value of ['null', '{}', '"123"', 'invalid', 'false']) {
globalThis.sessionStorage = { getItem: () => value };
assert.deepEqual(readOpportunitySelection(), []);
}
globalThis.sessionStorage = {
getItem: () => '[1,2,1,"3",null,-1,0,1.5,9007199254740992]',
};
assert.deepEqual(readOpportunitySelection(), [1, 2]);
} finally {
globalThis.sessionStorage = old;
}
});
await test('blocked storage never prevents reading, selecting or clearing and reports persistence failure', () => {
const old = globalThis.sessionStorage;
try {
globalThis.sessionStorage = {
getItem() {
throw Error('blocked');
},
setItem() {
throw Error('quota');
},
removeItem() {
throw Error('blocked');
},
};
assert.deepEqual(readOpportunitySelection(), []);
assert.equal(persistOpportunitySelection([1]), false);
assert.equal(persistOpportunitySelection([]), false);
} finally {
globalThis.sessionStorage = old;
}
});
await test('selection persists and clears the existing key without altering other browser data', () => {
const old = globalThis.sessionStorage;
const memory = new Map([['unrelated', 'preserved']]);
try {
globalThis.sessionStorage = {
getItem: (k) => memory.get(k) ?? null,
setItem: (k, v) => memory.set(k, v),
removeItem: (k) => memory.delete(k),
};
assert.equal(persistOpportunitySelection([12, 4]), true);
assert.deepEqual(readOpportunitySelection(), [12, 4]);
assert.equal(persistOpportunitySelection([]), true);
assert.deepEqual(readOpportunitySelection(), []);
assert.equal(memory.get('unrelated'), 'preserved');
} finally {
globalThis.sessionStorage = old;
}
});
+39 -1
View File
@@ -148,7 +148,7 @@ await test('browser writes preserve the CSRF cookie header', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: { cookie: 'other=x; XSRF-TOKEN=qa%2Ftoken' },
value: { cookie: 'other=x;XSRF-TOKEN=qa%2Ftoken' },
});
try {
t.mock.method(globalThis, 'fetch', async (_url, options) => {
@@ -201,3 +201,41 @@ await test('invalid JSON and network errors remain failures', async (t) => {
});
await assert.rejects(portalRequest('/api/v1/home'), TypeError);
});
await test('malformed CSRF cookie prevents writes with a readable session error but permits reads', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: { cookie: 'XSRF-TOKEN=%broken' },
});
let calls = 0;
t.mock.method(globalThis, 'fetch', async () => {
calls++;
return new Response('{"success":true}');
});
try {
await assert.rejects(
portalRequest('/synthetic', { method: 'POST' }),
(error) =>
error instanceof PortalApiError && /sessão/.test(error.message),
);
assert.equal(calls, 0);
await portalRequest('/synthetic');
assert.equal(calls, 1);
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
});
await test('nullable validation errors never crash field rendering', async (t) => {
t.mock.method(
globalThis,
'fetch',
async () => new Response('{"errors":null}', { status: 422 }),
);
await assert.rejects(portalRequest('/synthetic'), (error) => {
assert.deepEqual(fieldErrors(error), {});
return error instanceof PortalApiError;
});
});
+76
View File
@@ -325,3 +325,79 @@ void test('direct analysis and ordinary creation preserve distinct selection sta
'new-my-opportunity',
);
});
void test('investment entry belongs to realization exactly once', () => {
const groups = portalNavigation({ authenticated: false, manager: false });
const realization = groups.find((g) => g.id === 'realization');
assert.ok(
realization.children.some(
(i) => i.id === 'start' && i.href === '/investimentos/iniciar',
),
);
assert.equal(
destinations(groups).filter((href) => href === '/investimentos/iniciar')
.length,
1,
);
assert.equal(
currentNavigationGroup(groups, '/investimentos/iniciar'),
'realization',
);
});
void test('portfolio and zone fiche return keeps the applied catalogue page and filters', () => {
for (const base of [
'/carteira',
'/zonas',
'/management/portfolio',
'/management/investment/zones',
]) {
const href = catalogueDetailHref(
base + '/synthetic',
'q=energia&province_id=p',
base + '?q=energia&province_id=p&page=3&unrelated=private',
);
const returned = new URL(
catalogueReturnHref(base, href),
'https://portal.invalid',
);
assert.equal(returned.searchParams.get('page'), '3');
assert.equal(returned.searchParams.get('q'), 'energia');
assert.equal(returned.searchParams.get('province_id'), 'p');
assert.equal(returned.searchParams.has('unrelated'), false);
}
});
void test('catalogue pagination inheritance rejects invalid page values', () => {
for (const page of ['0', '-1', '1.5', 'invalid', '9007199254740992']) {
const href = catalogueDetailHref(
'/carteira/synthetic',
'kind=project',
'/carteira?page=' + page,
);
const query = new URLSearchParams(
new URL(href, 'https://portal.invalid').searchParams.get(
'catalogue_query',
),
);
assert.equal(query.has('page'), false);
}
});
void test('funding links require installation and saved list requires authentication', () => {
const base = { authenticated: false, manager: false };
assert.equal(
JSON.stringify(portalNavigation(base)).includes('/fundos'),
false,
);
const publicMenu = JSON.stringify(
portalNavigation({ ...base, funding: true }),
);
assert.equal(publicMenu.includes('/fundos'), true);
assert.equal(publicMenu.includes('/fundos/guardados'), false);
assert.equal(
JSON.stringify(
portalNavigation({ ...base, funding: true, authenticated: true }),
).includes('/fundos/guardados'),
true,
);
});
+140
View File
@@ -0,0 +1,140 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import { compileFunction } from 'node:vm';
const source = fs.readFileSync(
new URL('../../resources/js/lib/profile-json.ts', import.meta.url),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}).outputText;
const module = { exports: {} };
compileFunction(output, ['exports'])(module.exports);
const { profileJson, ProfileValidationError } = module.exports;
async function transport(response, run) {
const fetch = globalThis.fetch,
document = globalThis.document;
let count = 0;
globalThis.document = { cookie: 'XSRF-TOKEN=synthetic' };
globalThis.fetch = async () => {
count++;
return response;
};
try {
await run();
assert.equal(count, 1);
} finally {
globalThis.fetch = fetch;
globalThis.document = document;
}
}
await test('profile HTML failures retain reauthentication without JSON parser errors or automatic retry', async () => {
await transport(
new Response('<html>authentication required</html>', {
status: 403,
headers: { 'X-Portal-Reauthentication': 'required' },
}),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
e.reauthenticate &&
Object.keys(e.fields).length === 0,
);
},
);
});
await test('profile validation preserves field errors and server message', async () => {
await transport(
new Response(
JSON.stringify({
message: 'Invalid synthetic field',
errors: { name: ['Required', 'Too short'] },
}),
{ status: 422 },
),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
e.message === 'Invalid synthetic field' &&
e.fields.name === 'Required Too short',
);
},
);
});
await test('profile rejects invalid successful response and explains expired sessions', async () => {
for (const status of [200, 419])
await transport(
new Response('<html>unexpected</html>', { status }),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
(status !== 419 || /expirou/.test(e.message)),
);
},
);
});
await test('profile accepts no-content success', async () => {
await transport(new Response(null, { status: 204 }), async () =>
assert.equal(await profileJson('/synthetic'), null),
);
});
await test('profile reads ignore malformed CSRF while writes fail before transport with a useful error', async () => {
const oldFetch = globalThis.fetch,
oldDocument = globalThis.document;
let calls = 0;
try {
globalThis.document = { cookie: 'other=1;XSRF-TOKEN=%broken' };
globalThis.fetch = async (_url, options) => {
calls++;
assert.equal(options.method, 'GET');
assert.equal(options.headers['X-XSRF-TOKEN'], undefined);
assert.equal(options.credentials, 'same-origin');
return new Response('{"ok":true}');
};
assert.deepEqual(await profileJson('/synthetic', {}, 'GET'), {
ok: true,
});
await assert.rejects(
profileJson('/synthetic', {}),
(e) =>
e instanceof ProfileValidationError &&
/validada/.test(e.message),
);
assert.equal(calls, 1);
} finally {
globalThis.fetch = oldFetch;
globalThis.document = oldDocument;
}
});
await test('profile writes decode CSRF cookies regardless of separator spacing', async () => {
const oldFetch = globalThis.fetch,
oldDocument = globalThis.document;
try {
globalThis.document = { cookie: 'other=1;XSRF-TOKEN=synthetic%3D' };
globalThis.fetch = async (_url, options) => {
assert.equal(options.headers['X-XSRF-TOKEN'], 'synthetic=');
assert.equal(options.credentials, 'same-origin');
assert.equal(options.body, JSON.stringify({ name: 'synthetic' }));
return new Response('{"saved":true}');
};
assert.deepEqual(
await profileJson('/synthetic', { name: 'synthetic' }),
{ saved: true },
);
} finally {
globalThis.fetch = oldFetch;
globalThis.document = oldDocument;
}
});
@@ -0,0 +1,127 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
publicBusinessOfflineHtml,
downloadPublicBusinessOffline,
} from '../../resources/js/lib/public-business-offline.ts';
const savedAt = new Date('2026-11-02T15:00:00.000Z');
const record = {
slug: 'synthetic',
title: 'Negócio sintético',
modality: 'company_sale',
amount_min: '9007199254740993.25',
currency: 'MZN',
province: 'Província sintética',
payload: { private: 'RESERVED' },
owner_user_id: 73,
};
await test('offline fiche is self-contained, preserves exact public values and identifies capture versus publication', () => {
const html = publicBusinessOfflineHtml(
record,
'Venda da empresa',
'https://portal.example.invalid',
savedAt,
);
assert.match(html, /9007199254740993\.25 MZN/);
assert.match(html, /2026-11-02T15:00:00\.000Z/);
assert.match(html, /Publicação no portal<\/dt><dd>Não indicado/);
assert.match(html, /Província sintética/);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/negocios\/synthetic"/,
);
assert.doesNotMatch(
html,
/RESERVED|owner_user_id|<script|<link|<img|<iframe|<form|src=/,
);
assert.match(html, /default-src 'none'/);
assert.match(html, /<html lang="pt-MZ">/);
});
await test('untrusted text and slugs cannot create executable markup or an external source link', () => {
const html = publicBusinessOfflineHtml(
{
...record,
slug: '//external.invalid/"',
title: '<script>alert(1)</script>',
objective: '<img src=x onerror=alert(1)> & "value"',
},
'"malicious"',
'https://portal.example.invalid',
savedAt,
);
assert.doesNotMatch(html, /<script|<img/);
assert.match(html, /&lt;script&gt;/);
assert.match(
html,
/&lt;img src=x onerror=alert\(1\)&gt; &amp; &quot;value&quot;/,
);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/negocios\/%2F%2Fexternal/,
);
assert.throws(
() =>
publicBusinessOfflineHtml(
record,
'Venda',
'javascript:alert(1)',
savedAt,
),
/inválida/,
);
});
await test('download creates a standalone HTML file and releases its temporary URL', () => {
const previousWindow = globalThis.window,
previousDocument = globalThis.document;
const previousCreate = URL.createObjectURL.bind(URL),
previousRevoke = URL.revokeObjectURL.bind(URL);
let clicked = false,
removed = false,
revoked,
blob,
release;
const link = {
click() {
clicked = true;
},
remove() {
removed = true;
},
};
try {
globalThis.window = {
location: { origin: 'https://portal.example.invalid' },
setTimeout(fn) {
release = fn;
},
};
globalThis.document = {
createElement: () => link,
body: { appendChild() {} },
};
URL.createObjectURL = (value) => {
blob = value;
return 'blob:synthetic';
};
URL.revokeObjectURL = (value) => {
revoked = value;
};
downloadPublicBusinessOffline(record, 'Venda da empresa');
assert.equal(clicked, true);
assert.equal(removed, true);
assert.equal(link.download, 'negocio-synthetic.html');
assert.equal(blob.type, 'text/html;charset=utf-8');
assert.equal(revoked, undefined);
release();
assert.equal(revoked, 'blob:synthetic');
} finally {
globalThis.window = previousWindow;
globalThis.document = previousDocument;
URL.createObjectURL = previousCreate;
URL.revokeObjectURL = previousRevoke;
}
});
@@ -0,0 +1,75 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { publicOpportunityOfflineHtml } from '../../resources/js/lib/public-opportunity-offline.ts';
import { publicRecordOfflineHtml } from '../../resources/js/lib/public-record-offline.ts';
await test('opportunity offline projection keeps public content, precise values and source while excluding private context and attachments', () => {
const html = publicOpportunityOfflineHtml(
{
title: 'Synthetic opportunity',
slug: 'synthetic',
reference: 'SYN-1',
summary: 'Summary',
description: '<img src=x onerror=alert(1)>',
expected_impact: 'Expected jobs, not measured results',
estimated_investment_amount: '9007199254740993.25',
estimated_investment_currency: 'MZN',
district: 'Synthetic district',
province: 'Synthetic province',
last_validated_at: '2026-10-01',
payload: 'PRIVATE-PAYLOAD',
context: 'PRIVATE-CONTEXT',
documents: ['PRIVATE-FILE'],
},
'https://portal.example.invalid',
new Date('2026-11-02T12:00:00Z'),
);
assert.match(html, /9007199254740993\.25 MZN/);
assert.match(html, /SYN-1/);
assert.match(html, /2026-10-01/);
assert.match(html, /Synthetic district, Synthetic province/);
assert.match(html, /Contexto territorial/);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/oportunidades\/synthetic"/,
);
assert.doesNotMatch(html, /PRIVATE-|<(?:img|script|iframe|link)\b/);
assert.match(html, /&lt;img/);
assert.match(html, /não confirma a implantação/);
});
await test('shared offline renderer rejects source paths outside the portal and preserves unknown fields as unknown', () => {
const content = {
title: 'Synthetic',
kind: 'Ficha',
sourcePath: '//external.invalid',
rows: [],
sections: [],
notice: '',
};
assert.throws(
() =>
publicRecordOfflineHtml(
content,
'https://portal.example.invalid',
new Date(),
),
/inválida/,
);
assert.throws(
() =>
publicRecordOfflineHtml(
{ ...content, sourcePath: '/\\external.invalid' },
'https://portal.example.invalid',
new Date(),
),
/inválida/,
);
const html = publicOpportunityOfflineHtml(
{ title: 'Unknown', slug: 'unknown', reference: 'SYN-2' },
'https://portal.example.invalid',
new Date(),
);
assert.match(html, /Investimento estimado<\/dt><dd>Não indicado/);
assert.doesNotMatch(html, /<dd>0/);
});
@@ -0,0 +1,133 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks) {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports.default;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('the quick search has a native GET destination and submits the actual input value even after browser autofill', () => {
let sent, edited;
const Hero = load('../../resources/js/components/portal-hero.tsx', {
react: { useState: (initial) => [initial, () => {}], useEffect() {} },
'@inertiajs/react': {
Link: 'a',
router: {
get: (url, data) => {
sent = { url, data };
},
},
},
'lucide-react': { ArrowRight: () => null, Search: () => null },
});
const tree = Hero({
query: 'stale rendered value',
setQuery: (value) => {
edited = value;
},
});
const form = nodes(tree).find((node) => node.type === 'form');
const input = nodes(tree).find(
(node) => node.type === 'input' && node.props.name === 'q',
);
assert.equal(form.props.action, '/oportunidades');
assert.equal(form.props.method, 'get');
assert.equal(input.props.maxLength, 120);
input.props.onChange({ target: { value: 'plantio de algodao' } });
assert.equal(edited, 'plantio de algodao');
const original = globalThis.FormData;
try {
globalThis.FormData = class {
constructor(element) {
this.element = element;
}
get(key) {
assert.equal(key, 'q');
return this.element.value;
}
};
let prevented = false;
form.props.onSubmit({
preventDefault() {
prevented = true;
},
currentTarget: { value: ' plantio de algodao ' },
});
assert.equal(prevented, true);
assert.deepEqual(sent, {
url: '/oportunidades',
data: { q: 'plantio de algodao' },
});
} finally {
globalThis.FormData = original;
}
const html = renderToStaticMarkup(tree);
assert.ok(html.includes('Pesquisa rápida de oportunidades'));
assert.ok(html.includes('action="/oportunidades"'));
assert.ok(html.includes('Pesquisar'));
});
await test('related processing fiches are explicitly distinct from the requested cultivation and disappear during pending or failed searches', () => {
const Related = load(
'../../resources/js/components/opportunity-related-results.tsx',
{ '@inertiajs/react': { Link: 'a' } },
);
const related = {
query: 'plantio de algodao',
subject: 'algodao',
href: '/oportunidades?sector=qa&q=algodao',
items: [
{
id: 1,
slug: 'synthetic-processing',
title: 'Synthetic processing',
summary: 'Descaroçamento e transformação de algodão.',
},
],
};
const props = { related, loading: false, error: '', total: 0 };
const html = renderToStaticMarkup(Related(props));
assert.ok(
html.includes('não correspond') ||
html.includes(
'Não encontrámos fichas que correspondam a todos os termos',
),
);
assert.ok(html.includes('outras etapas da cadeia'));
assert.ok(html.includes('Descaroçamento e transformação de algodão'));
assert.ok(html.includes('q=plantio+de+algodao'));
assert.ok(html.includes('Ver a pesquisa relacionada'));
for (const state of [
{ loading: true },
{ error: 'failure' },
{ total: 1 },
{ related: null },
]) {
assert.equal(Related({ ...props, ...state }), null);
}
});
+225
View File
@@ -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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function harness() {
let cursor = 0,
effect;
const state = [],
requests = [];
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in state)) state[index] = initial;
return [
state[index],
(value) => {
state[index] =
typeof value === 'function'
? value(state[index])
: value;
},
];
},
useEffect(fn) {
effect = fn;
},
};
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/similar-businesses.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === 'react'
? hooks
: name === '@inertiajs/react'
? { Link: 'a' }
: name === '@/lib/portal-api'
? {
portalRequest: (url, options) =>
new Promise((resolve, reject) =>
requests.push({
url,
options,
resolve,
reject,
}),
),
}
: require(name),
module,
module.exports,
);
const render = (props) => {
cursor = 0;
return module.exports.default(props);
};
return { render, start: () => effect(), requests };
}
const props = {
currentId: 'current',
catalogueUrl: '/negocios?sector=4&modality=company_sale',
criteria: ['Venda da empresa', 'Agricultura'],
};
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('explicit public classification changes matching criteria and is cleared when the source record changes', async () => {
const h = harness();
const row = {
target_type: 'chain',
target_id: 'synthetic-chain',
purpose: 'coverage',
purpose_label: 'Abrangencia documentada',
label: 'Cadeia sintética',
source_reference: 'Fonte sintética divulgada',
};
const scoped = {
...props,
classifications: [
row,
row,
{ ...row, purpose: 'location', purpose_label: 'Localização' },
],
};
let tree = h.render(scoped);
const chooser = tree.props.children.find((child) => child?.type === 'label')
.props.children[1];
chooser.props.onChange({
target: { value: 'chain:synthetic-chain:coverage' },
});
tree = h.render(scoped);
h.start();
const url = new URL(h.requests[0].url, 'https://portal.invalid');
assert.equal(url.searchParams.get('association_type'), 'chain');
assert.equal(url.searchParams.get('association_target'), 'synthetic-chain');
assert.equal(url.searchParams.get('association_purpose'), 'coverage');
assert.match(renderToStaticMarkup(tree), /Fonte sintética divulgada/);
assert.match(
renderToStaticMarkup(tree),
/value="chain:synthetic-chain:location"/,
);
assert.equal(
(
renderToStaticMarkup(tree).match(
/value="chain:synthetic-chain:coverage"/g,
) ?? []
).length,
1,
);
h.requests[0].resolve({ data: [] });
await flush();
const changed = { ...scoped, currentId: 'other-record' };
const next = renderToStaticMarkup(h.render(changed));
assert.doesNotMatch(next, /Fonte sintética divulgada/);
assert.match(next, /A consultar/);
h.start();
assert.equal(
new URL(h.requests[1].url, 'https://portal.invalid').searchParams.has(
'association_target',
),
false,
);
});
await test('similar businesses reuse public criteria, exclude self and duplicates, bound the preview and preserve filters in detail links', async () => {
const h = harness();
assert.match(renderToStaticMarkup(h.render(props)), /A consultar/);
h.start();
assert.equal(
h.requests[0].url,
'/api/v1/business-opportunities?sector=4&modality=company_sale&per_page=7&page=1',
);
h.requests[0].resolve({
data: [
{ id: 'current', slug: 'self', title: 'Self' },
{
id: 'a',
slug: 'a',
title: 'A',
published_at: '2026-11-01T12:00:00Z',
},
{ id: 'a', slug: 'duplicate', title: 'Duplicate' },
...Array.from({ length: 8 }, (_, i) => ({
id: `b${i}`,
slug: `b${i}`,
title: `Business ${i}`,
})),
],
});
await flush();
const html = renderToStaticMarkup(h.render(props));
assert.doesNotMatch(html, />Self<|>Duplicate<|Business 7/);
assert.equal((html.match(/<li>/g) ?? []).length, 6);
assert.match(html, /\/negocios\/a\?sector=4&amp;modality=company_sale/);
assert.match(html, /Agricultura/);
assert.match(html, /proximidade geográfica/);
assert.match(html, /Fonte: catálogo público/);
assert.match(html, /datetime="2026-11-01T12:00:00Z"/i);
assert.match(html, /Data de publicação não indicada/);
});
await test('malformed catalogue records are a recoverable error, never proof of no matching businesses', async () => {
const h = harness();
h.render(props);
h.start();
h.requests[0].resolve({
data: [{ id: 'a', slug: null, title: 'Malformed' }],
});
await flush();
const html = renderToStaticMarkup(h.render(props));
assert.match(html, /Tentar novamente/);
assert.doesNotMatch(html, /Não foram encontrados/);
});
await test('empty catalogue differs from failed lookup; changing context hides old rows and ignores late responses', async () => {
const h = harness();
h.render(props);
const cleanup = h.start();
cleanup();
const next = { ...props, catalogueUrl: '/negocios?modality=real_estate' };
assert.match(renderToStaticMarkup(h.render(next)), /A consultar/);
h.start();
h.requests[0].resolve({
data: [{ id: 'old', slug: 'old', title: 'Old response' }],
});
await flush();
assert.doesNotMatch(renderToStaticMarkup(h.render(next)), /Old response/);
h.requests[1].resolve({ data: [] });
await flush();
assert.match(
renderToStaticMarkup(h.render(next)),
/não demonstra ausência/,
);
h.render(props);
h.start();
h.requests[2].reject(new Error('network'));
await flush();
const tree = h.render(props);
const html = renderToStaticMarkup(tree);
assert.match(html, /Tentar novamente/);
assert.doesNotMatch(html, /não demonstra ausência/);
const button = tree.props.children[2].props.children[1];
button.props.onClick();
assert.match(renderToStaticMarkup(h.render(props)), /A consultar/);
h.start();
assert.equal(h.requests.length, 4);
});