novas funcionalidades dos formulario
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-02 11:13:37 +02:00
parent a6afb4e97a
commit 4f35313d06
104 changed files with 7653 additions and 178 deletions
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace Tests\Feature;
use App\Jobs\RunSimulation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
class ApiContractTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Queue::fake();
}
public function test_simulation_jobs_follow_simulation_access_scope_and_contract_shape(): void
{
$token = Str::random(48);
$create = $this->postJson('/api/v1/simulations', ['base' => 0, 'rate' => 0], [
'Idempotency-Key' => (string) Str::uuid(),
'X-Simulation-Token' => $token,
])->assertAccepted();
$simulationId = $create->json('data.id');
$this->getJson("/api/v1/simulations/{$simulationId}/jobs", ['X-Simulation-Token' => $token])
->assertOk()
->assertJsonStructure(['data' => [['id', 'simulation_id', 'job_type', 'status', 'attempts', 'available_at']]])
->assertJsonPath('data.0.job_type', 'execute')
->assertJsonPath('data.0.status', 'pending');
$this->getJson("/api/v1/simulations/{$simulationId}/jobs", ['X-Simulation-Token' => Str::random(48)])
->assertNotFound();
}
public function test_public_legislation_lists_only_validated_current_sources_with_etag_and_correlation(): void
{
$owner = User::factory()->create();
$validator = User::factory()->create();
$validId = (string) Str::uuid();
$today = today()->toDateString();
DB::table('investment_legal_sources')->insert([
['id' => $validId, 'title' => 'Lei de teste', 'url' => 'https://example.org/lei', 'diploma' => 'Diploma A',
'article' => 'Artigo 1', 'competent_entity' => 'Entidade A', 'valid_from' => $today, 'valid_until' => null,
'validation_status' => 'validated', 'owner_id' => $owner->id, 'validator_id' => $validator->id,
'validated_at' => now(), 'version_no' => 3, 'created_at' => now(), 'updated_at' => now()],
['id' => (string) Str::uuid(), 'title' => 'Lei pendente', 'url' => 'https://example.org/pendente', 'diploma' => 'Diploma B',
'article' => 'Artigo 2', 'competent_entity' => 'Entidade B', 'valid_from' => $today, 'valid_until' => null,
'validation_status' => 'pending', 'owner_id' => $owner->id, 'validator_id' => null,
'validated_at' => null, 'version_no' => 1, 'created_at' => now(), 'updated_at' => now()],
['id' => (string) Str::uuid(), 'title' => 'Lei expirada', 'url' => 'https://example.org/expirada', 'diploma' => 'Diploma C',
'article' => 'Artigo 3', 'competent_entity' => 'Entidade C', 'valid_from' => today()->subDay()->toDateString(),
'valid_until' => today()->subDay()->toDateString(), 'validation_status' => 'validated', 'owner_id' => $owner->id,
'validator_id' => $validator->id, 'validated_at' => now(), 'version_no' => 2, 'created_at' => now(), 'updated_at' => now()],
]);
$correlationId = (string) Str::uuid();
$response = $this->getJson('/api/v1/legislation/sources?q=Lei&per_page=1', ['X-Correlation-ID' => $correlationId])
->assertOk()
->assertHeader('ETag')
->assertHeader('X-Correlation-ID', $correlationId)
->assertJsonPath('meta.total', 1)
->assertJsonPath('data.0.id', $validId)
->assertJsonPath('data.0.validation_status', 'validated');
$this->assertStringStartsWith('W/"legal-sources-', $response->headers->get('ETag'));
}
public function test_contract_errors_include_correlation_and_required_preconditions(): void
{
$missingKey = $this->postJson('/api/v1/simulations', ['base' => 1, 'rate' => 1])
->assertStatus(428)
->assertJsonStructure(['message'])
->assertHeader('X-Correlation-ID');
$this->assertTrue(Str::isUuid($missingKey->headers->get('X-Correlation-ID')));
$invalidCorrelation = $this->getJson('/api/v1/legislation/sources', ['X-Correlation-ID' => 'invalid'])
->assertUnprocessable()
->assertJsonPath('code', 'invalid_correlation_id')
->assertHeader('X-Correlation-ID');
$this->assertTrue(Str::isUuid($invalidCorrelation->headers->get('X-Correlation-ID')));
}
}
@@ -0,0 +1,94 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class BusinessMarketplacePublicTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
config(['existing-business.enabled' => true]);
}
public function test_public_catalogue_and_detail_exclude_reserved_fields_and_locations(): void
{
$business = $this->publishedBusiness();
$this->getJson('/api/v1/business-opportunities')->assertOk()
->assertJsonPath('data.0.title', 'Public synthetic opportunity')
->assertJsonMissingPath('data.0.owner_user_id')
->assertJsonMissingPath('data.0.payload')
->assertJsonMissingPath('data.0.geom');
$this->getJson('/api/v1/business-opportunities/'.$business['public_slug'])->assertOk()
->assertJsonPath('data.title', 'Public synthetic opportunity')
->assertJsonMissingPath('data.payload')
->assertJsonMissingPath('data.owner_user_id');
}
public function test_interest_is_limited_to_published_business_and_deduplicated_idempotently(): void
{
$business = $this->publishedBusiness();
$payload = [
'existingBusinessId' => $business['id'],
'modality' => 'company_sale',
'fullName' => 'Synthetic investor',
'email' => 'portal-integration-test@gmail.com',
'phone' => '+258 840000000',
'investorType' => 'empresa',
'country' => 'Moçambique',
'sectorInterest' => 'Energia',
'message' => 'Synthetic interest for the published business listing.',
'privacyConsent' => true,
];
$key = (string) Str::uuid();
$first = $this->postJson('/api/v1/interest-requests', $payload, ['Idempotency-Key' => $key])->assertCreated();
$second = $this->postJson('/api/v1/interest-requests', $payload, ['Idempotency-Key' => $key])->assertCreated();
$this->assertSame($first->json(), $second->json());
$this->assertDatabaseHas('interest_requests', [
'existing_business_id' => $business['id'],
'modality' => 'company_sale',
'status' => 'received',
]);
$this->assertDatabaseCount('interest_requests', 1);
$this->assertDatabaseCount('outbox_events', 1);
$this->postJson('/api/v1/interest-requests', [...$payload, 'message' => 'Another valid message for this active interest.'])
->assertStatus(409);
$this->assertDatabaseCount('interest_requests', 1);
}
/** @return array{id:string,public_slug:string} */
private function publishedBusiness(): array
{
$id = (string) Str::uuid();
$slug = 'public-synthetic-'.$id;
$now = now();
DB::table('existing_businesses')->insert([
'id' => $id,
'code' => 'SYN-'.strtoupper(substr(str_replace('-', '', $id), 0, 12)),
'owner_user_id' => User::factory()->create()->id,
'modality' => 'company_sale',
'status' => 'published',
'classification' => 'confidential',
'version_no' => 1,
'payload' => Crypt::encryptString(json_encode(['title' => 'Private synthetic title'], JSON_THROW_ON_ERROR)),
'public_title' => 'Public synthetic opportunity',
'public_slug' => $slug,
'published_at' => $now,
'created_at' => $now,
'updated_at' => $now,
]);
return ['id' => $id, 'public_slug' => $slug];
}
}
+68 -14
View File
@@ -29,6 +29,16 @@ class ExistingBusinessIntakeTest extends TestCase
return $user;
}
private function designated(string $role): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
config(['portal.managers' => [...config('portal.managers', []), $user->email],
'existing-business.'.$role => [...config('existing-business.'.$role, []), strtolower($user->email)]]);
return $user;
}
/** @return array<string,mixed> */
private function draft(): array
{
@@ -41,6 +51,7 @@ class ExistingBusinessIntakeTest extends TestCase
{
$owner = User::factory()->create();
$reviewer = $this->reviewer();
$triager = $this->designated('triagers');
$this->actingAs($owner);
$id = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$url = $this->base.'/'.$id;
@@ -50,17 +61,23 @@ class ExistingBusinessIntakeTest extends TestCase
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested', 'review_consent' => true])->assertOk()->assertJsonPath('version_no', 2);
$this->putJson($url, [...$this->draft(), 'version_no' => 2])->assertForbidden();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Attempted self review'])->assertForbidden();
$this->actingAs($triager)->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'triage', 'note' => 'Synthetic triage completed'])->assertOk()->assertJsonPath('version_no', 3);
$this->actingAs($reviewer)->getJson('/api/v1/existing-business/reviews')->assertOk()->assertJsonPath('records.total', 1);
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertConflict();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk()->assertJsonPath('version_no', 3);
$this->postJson($url.'/transitions', ['version_no' => 3, 'action' => 'needs_information', 'note' => 'Please clarify synthetic source'])->assertOk();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertConflict();
$this->postJson($url.'/transitions', ['version_no' => 3, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk()->assertJsonPath('version_no', 4);
$this->postJson($url.'/transitions', ['version_no' => 4, 'action' => 'needs_information', 'note' => 'Please clarify synthetic source'])->assertOk();
$this->actingAs($owner)->getJson($url)->assertOk()->assertJsonPath('history.0.note', 'Please clarify synthetic source');
$this->postJson($url, [...$this->draft(), '_method' => 'PUT', 'version_no' => 4])->assertOk()->assertJsonPath('version_no', 5);
$this->postJson($url.'/transitions', ['version_no' => 5, 'action' => 'withdrawn', 'note' => 'Synthetic withdrawal requested'])->assertOk();
$this->postJson($url, [...$this->draft(), '_method' => 'PUT', 'version_no' => 5])->assertOk()->assertJsonPath('version_no', 6);
$this->postJson($url.'/transitions', ['version_no' => 6, 'action' => 'withdrawn', 'note' => 'Synthetic withdrawal requested'])->assertOk();
$this->actingAs($reviewer)->getJson($url)->assertForbidden();
$this->getJson('/api/v1/existing-business/reviews')->assertJsonPath('records.total', 0);
$this->assertDatabaseCount('existing_business_reviews', 4);
$this->assertDatabaseCount('existing_business_revisions', 6);
$this->assertDatabaseCount('existing_business_reviews', 5);
$this->assertDatabaseCount('existing_business_revisions', 7);
$this->assertDatabaseCount('business_workflow_transitions', 5);
$this->assertDatabaseCount('outbox_events', 1);
$transition = DB::table('business_workflow_transitions')->where('to_status', 'needs_information')->first();
$this->assertSame('in_review', $transition->from_status);
$this->assertStringNotContainsString('Please clarify', $transition->reason);
$this->assertStringNotContainsString('Please clarify', DB::table('existing_business_reviews')->where('action', 'needs_information')->value('note'));
}
@@ -76,11 +93,14 @@ class ExistingBusinessIntakeTest extends TestCase
'valid_until' => today()->addDay()->toDateString()];
$this->postJson($url.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic review requested', 'review_consent' => true])->assertOk();
$this->postJson($url.'/verifications', $finding)->assertForbidden();
$this->actingAs($reviewer)->postJson($url.'/verifications', [...$finding, 'version_no' => 2])->assertConflict();
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk();
$triager = $this->designated('triagers');
$this->actingAs($triager)->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'triage', 'note' => 'Synthetic triage completed'])->assertOk();
$this->actingAs($reviewer)->postJson($url.'/transitions', ['version_no' => 3, 'action' => 'in_review', 'note' => 'Synthetic review started'])->assertOk();
$this->postJson($url.'/verifications', [...$finding, 'version_no' => 3])->assertConflict();
$finding['version_no'] = 4;
$this->postJson($url.'/verifications', [...$finding, 'valid_until' => null])->assertUnprocessable();
$this->postJson($url.'/verifications', [...$finding, 'object_id' => '00000000-0000-4000-8000-000000000001'])->assertNotFound();
$this->postJson($url.'/verifications', $finding)->assertOk()->assertJsonPath('version_no', 4);
$this->postJson($url.'/verifications', $finding)->assertOk()->assertJsonPath('version_no', 5);
$this->postJson($url.'/verifications', $finding)->assertConflict();
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'confirmed');
$raw = DB::table('existing_business_revisions')->where('business_id', $id)->where('action', 'verification')->value('snapshot');
@@ -88,8 +108,8 @@ class ExistingBusinessIntakeTest extends TestCase
$this->travel(2)->days();
$this->getJson($url)->assertOk()->assertJsonPath('verifications.0.effective_outcome', 'expired');
$this->travelBack();
$this->postJson($url.'/transitions', ['version_no' => 4, 'action' => 'needs_information', 'note' => 'Synthetic clarification requested'])->assertOk();
$this->actingAs($owner)->putJson($url, [...$this->draft(), 'version_no' => 5])->assertOk();
$this->postJson($url.'/transitions', ['version_no' => 5, 'action' => 'needs_information', 'note' => 'Synthetic clarification requested'])->assertOk();
$this->actingAs($owner)->putJson($url, [...$this->draft(), 'version_no' => 6])->assertOk();
$this->getJson($url)->assertJsonPath('verifications.0.effective_outcome', 'stale');
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
}
@@ -114,12 +134,46 @@ class ExistingBusinessIntakeTest extends TestCase
$draft = $this->draft();
$draft['payload']['valid_until'] = today()->subDay()->toDateString();
$id = $this->postJson($this->base, $draft)->assertCreated()->json('id');
foreach (['published', 'approved', 'submitted'] as $action) {
$this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 1, 'action' => $action, 'note' => 'Synthetic invalid transition', 'review_consent' => true])->assertUnprocessable();
foreach (['published', 'approved'] as $action) {
$this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 1, 'action' => $action, 'note' => 'Synthetic invalid transition', 'review_consent' => true])->assertForbidden();
}
$this->postJson($this->base.'/'.$id.'/transitions', ['version_no' => 1, 'action' => 'submitted', 'note' => 'Synthetic invalid transition', 'review_consent' => true])->assertUnprocessable();
$this->assertDatabaseCount('existing_business_reviews', 0);
}
public function test_submission_triage_two_level_approval_and_publication_require_distinct_designations(): void
{
$owner = User::factory()->create();
$triager = $this->designated('triagers');
$reviewer = $this->designated('reviewers');
$levelOne = $this->designated('approvers_l1');
$levelTwo = $this->designated('approvers_l2');
$publisher = $this->designated('publishers');
$sectorId = DB::table('sectors')->insertGetId(['name' => 'Synthetic approval sector', 'slug' => 'synthetic-approval-sector', 'is_active' => true]);
$this->actingAs($owner);
$id = $this->postJson($this->base, $this->draft())->assertCreated()->json('id');
$this->putJson($this->base.'/'.$id, [...$this->draft(), 'version_no' => 1, 'sector_id' => $sectorId,
'public_title' => 'Synthetic public listing'])->assertOk();
$url = $this->base.'/'.$id;
$this->postJson($url.'/transitions', ['version_no' => 2, 'action' => 'submitted', 'note' => 'Synthetic submission for staged approval', 'review_consent' => true])->assertOk();
$this->assertDatabaseHas('tasks', ['existing_business_id' => $id, 'task_type' => 'triage', 'status' => 'open']);
$this->actingAs($triager)->postJson($url.'/transitions', ['version_no' => 3, 'action' => 'triage', 'note' => 'Synthetic initial triage completed'])->assertOk();
$this->actingAs($reviewer)->postJson($url.'/transitions', ['version_no' => 4, 'action' => 'in_review', 'note' => 'Synthetic independent review started'])->assertOk();
$this->postJson($url.'/transitions', ['version_no' => 5, 'action' => 'approval_l1', 'note' => 'Synthetic review checks completed'])->assertOk();
$this->actingAs($levelOne)->postJson($url.'/transitions', ['version_no' => 6, 'action' => 'approval_l2', 'note' => 'Synthetic first level approval'])->assertOk();
config(['existing-business.approvers_l2' => [...config('existing-business.approvers_l2'), strtolower($levelOne->email)]]);
$this->actingAs($levelOne)->postJson($url.'/transitions', ['version_no' => 7, 'action' => 'approved', 'note' => 'Synthetic second level approval attempt'])->assertForbidden();
$this->actingAs($levelTwo)->postJson($url.'/transitions', ['version_no' => 7, 'action' => 'approved', 'note' => 'Synthetic independent second level approval'])->assertOk();
$this->actingAs($publisher)->postJson($url.'/transitions', ['version_no' => 8, 'action' => 'published', 'note' => 'Synthetic independent publication decision'])->assertOk()->assertJsonPath('published_at', fn ($value) => is_string($value));
$this->assertDatabaseHas('business_workflow_transitions', ['existing_business_id' => $id, 'from_status' => 'approval_l2', 'to_status' => 'approved']);
$this->assertDatabaseHas('existing_businesses', ['id' => $id, 'status' => 'published']);
$this->assertDatabaseCount('outbox_events', 1);
}
public function test_reserved_objects_are_scoped_versioned_and_never_verified_by_declaration(): void
{
$this->actingAs(User::factory()->create());
+14
View File
@@ -32,6 +32,9 @@ class InterestSubmissionTest extends TestCase
$this->assertDatabaseCount('interest_requests', 1);
$this->assertDatabaseCount('interest_submission_receipts', 1);
$this->assertDatabaseCount('outbox_events', 1);
$this->assertDatabaseCount('consents', 1);
$this->assertDatabaseHas('consents', ['interest_request_id' => InterestRequest::firstOrFail()->id,
'purpose' => 'respond_to_interest', 'status' => 'granted', 'policy_version' => '2026-09-30']);
$this->assertDatabaseCount('jobs', 1);
$event = DB::table('outbox_events')->first();
$this->assertSame('pending', $event->status);
@@ -51,6 +54,17 @@ class InterestSubmissionTest extends TestCase
$this->assertDatabaseCount('outbox_events', 1);
}
public function test_proponent_sharing_is_a_separate_optional_versioned_consent(): void
{
$this->postJson('/api/v1/interest-requests', [...$this->payload(), 'shareWithProponent' => true])->assertCreated();
$interest = InterestRequest::firstOrFail();
$this->assertDatabaseHas('consents', ['interest_request_id' => $interest->id,
'purpose' => 'respond_to_interest', 'status' => 'granted']);
$this->assertDatabaseHas('consents', ['interest_request_id' => $interest->id,
'purpose' => 'share_contact_with_proponent', 'status' => 'granted', 'policy_version' => '2026-09-30']);
$this->assertSame(2, DB::table('consents')->where('interest_request_id', $interest->id)->count());
}
public function test_old_clients_still_work_and_distinct_keys_create_distinct_submissions(): void
{
$this->postJson('/api/v1/interest-requests', $this->payload())->assertCreated();
+76 -1
View File
@@ -8,6 +8,9 @@ use App\Models\Sector;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia;
use Tests\TestCase;
@@ -120,9 +123,35 @@ class PortalManagementTest extends TestCase
'email' => 'test@example.invalid', 'investor_type' => 'empresa', 'country' => 'Moçambique',
'sector_interest' => 'Energia', 'message' => 'Pedido de informação para teste.', 'privacy_consent' => true]);
$this->actingAs($manager)->get('/management/interests/'.$interest->id)->assertOk();
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review', 'reviewed_by' => 999])->assertRedirect();
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review', 'reviewed_by' => 999,
'next_action' => 'Contactar o investidor', 'next_action_due_at' => now()->addDays(2)->toDateString(), 'assigned_to' => $manager->id,
'note' => 'O pedido foi recebido e encaminhado para análise interna.', 'next_action' => 'Contactar o investidor',
'next_action_due_at' => now()->addDays(2)->toDateString(), 'assigned_to' => $manager->id])->assertRedirect();
$this->assertSame($manager->id, $interest->fresh()->reviewed_by);
$this->assertNotNull($interest->fresh()->reviewed_at);
$transition = DB::table('business_workflow_transitions')->where('interest_request_id', $interest->id)->first();
$this->assertSame('received', $transition->from_status);
$this->assertSame('in_review', $transition->to_status);
$this->assertSame($manager->id, $interest->fresh()->assigned_to);
$this->assertDatabaseHas('tasks', ['interest_request_id' => $interest->id, 'assignee_user_id' => $manager->id,
'title' => 'Contactar o investidor', 'status' => 'open']);
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review', 'next_action' => 'Contactar o investidor',
'next_action_due_at' => now()->addDays(2)->toDateString(), 'assigned_to' => $manager->id])->assertRedirect();
$this->assertSame(1, DB::table('tasks')->where('interest_request_id', $interest->id)->where('status', 'open')->count());
$this->assertDatabaseHas('tasks', ['interest_request_id' => $interest->id, 'assignee_user_id' => $manager->id,
'title' => 'Contactar o investidor', 'status' => 'open']);
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review', 'next_action' => 'Enviar resumo ao investidor',
'next_action_due_at' => now()->addDays(4)->toDateString(), 'assigned_to' => $manager->id])->assertRedirect();
$this->assertDatabaseHas('tasks', ['interest_request_id' => $interest->id, 'title' => 'Contactar o investidor',
'status' => 'cancelled', 'outcome' => 'superseded']);
$this->assertSame(1, DB::table('tasks')->where('interest_request_id', $interest->id)->where('status', 'open')->count());
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review'])->assertRedirect();
$this->assertSame('Enviar resumo ao investidor', $interest->fresh()->next_action);
$this->get('/management/interests?follow_up=upcoming')->assertInertia(fn (AssertableInertia $page) => $page
->component('management/interests')->where('requests.data.0.reference', 'IR-TEST')->where('filters.follow_up', 'upcoming'));
$this->assertSame('O pedido foi recebido e encaminhado para análise interna.', Crypt::decryptString($transition->reason));
$this->assertSame($manager->id, $interest->fresh()->assigned_to);
$this->patch('/management/interests/'.$interest->id, ['status' => 'received'])->assertSessionHasErrors('status');
$this->patch('/management/interests/'.$interest->id, ['status' => 'invalid'])->assertSessionHasErrors('status');
}
@@ -144,6 +173,52 @@ class PortalManagementTest extends TestCase
$this->assertDatabaseCount('interest_requests', 0);
}
public function test_proponent_sharing_consent_can_be_revoked_with_audited_outbox_event(): void
{
$manager = $this->manager();
$interest = InterestRequest::create(['reference' => 'IR-CONSENT', 'full_name' => 'Pessoa de teste',
'email' => 'consent@example.invalid', 'investor_type' => 'empresa', 'country' => 'MZ',
'sector_interest' => 'Energia', 'message' => 'Pedido de partilha para teste.', 'privacy_consent' => true]);
$shareConsentId = (string) Str::uuid();
DB::table('consents')->insert(['id' => $shareConsentId, 'source_system' => 'portal-intake',
'external_id' => 'test-share-consent', 'version_no' => 1, 'data_classification' => 'confidential',
'correlation_id' => (string) Str::uuid(), 'subject_ref' => $interest->reference,
'purpose' => 'share_contact_with_proponent', 'status' => 'granted', 'granted_at' => now(),
'interest_request_id' => $interest->id, 'policy_version' => '2026-09-30', 'created_at' => now(), 'updated_at' => now()]);
$this->actingAs($manager)->patch('/management/interests/'.$interest->id.'/consent/proponent', [
'reason' => 'O titular pediu para não partilhar os seus dados com o proponente.',
])->assertRedirect();
$this->assertDatabaseHas('consents', ['id' => $shareConsentId, 'status' => 'withdrawn']);
$this->assertDatabaseHas('business_workflow_transitions', ['interest_request_id' => $interest->id,
'to_status' => 'received']);
$event = DB::table('outbox_events')->where('event_type', 'InterestConsentWithdrawn')->first();
$this->assertNotNull($event);
$this->assertSame($shareConsentId, $event->aggregate_id);
$this->assertStringNotContainsString('consent@example.invalid', $event->payload);
}
public function test_overdue_task_escalation_is_opt_in_and_idempotent(): void
{
$interest = InterestRequest::create(['reference' => 'IR-SLA', 'full_name' => 'Pessoa de teste',
'email' => 'sla@example.invalid', 'investor_type' => 'empresa', 'country' => 'MZ',
'sector_interest' => 'Energia', 'message' => 'Pedido de teste de escalada.', 'privacy_consent' => true]);
DB::table('tasks')->insert(['source_system' => 'portal-interest', 'external_id' => 'sla-test-task',
'version_no' => 1, 'data_classification' => 'confidential', 'correlation_id' => (string) Str::uuid(),
'interest_request_id' => $interest->id, 'task_type' => 'interest_follow_up', 'title' => 'Contactar',
'status' => 'open', 'priority' => 3, 'due_at' => now()->subHour(), 'created_at' => now(), 'updated_at' => now()]);
config(['existing-business.sla_escalation_enabled' => false]);
$this->artisan('investmoz:escalate-overdue-tasks')->assertSuccessful();
$this->assertDatabaseHas('tasks', ['external_id' => 'sla-test-task', 'priority' => 3]);
config(['existing-business.sla_escalation_enabled' => true]);
$this->artisan('investmoz:escalate-overdue-tasks')->assertSuccessful();
$this->artisan('investmoz:escalate-overdue-tasks')->assertSuccessful();
$this->assertDatabaseHas('tasks', ['external_id' => 'sla-test-task', 'priority' => 1, 'outcome' => 'sla_overdue']);
}
public function test_valid_public_submissions_persist_and_return_distinct_references(): void
{
// DNS validation remains enabled; no mail is sent by this endpoint.
+1 -1
View File
@@ -20,7 +20,7 @@ class PortalServicesTest extends TestCase
public function test_public_sections_render_and_desk_requires_login(): void
{
foreach (['sectores', 'como-investir', 'legislacao', 'documentos', 'apoio', 'parcerias', 'simulador-fiscal', 'formularios/investidor', 'formularios/empresa'] as $path) {
foreach (['sectores', 'como-investir', 'legislacao', 'documentos', 'apoio', 'parcerias', 'simulador-fiscal', 'Simulador', 'formularios/investidor', 'formularios/empresa'] as $path) {
$this->get('/'.$path)->assertOk()->assertInertia(fn (Assert $page) => $page->component('portal/services'));
}
$this->get('/balcao-virtual')->assertRedirect('/login');
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace Tests\Feature;
use Database\Seeders\ReferenceCatalogSeeder;
use Database\Seeders\SectorSeeder;
use Database\Seeders\TerritoryReferenceSeeder;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use RuntimeException;
use Tests\TestCase;
class ReferenceCatalogTest extends TestCase
{
use RefreshDatabase;
public function test_reference_seeds_are_repeatable_and_activity_codes_are_stable(): void
{
$this->seedReferences();
$ids = DB::table('economic_activities')->orderBy('code')->pluck('id', 'code')->all();
$this->seedReferences();
$this->assertCount(6, $ids);
$this->assertSame($ids, DB::table('economic_activities')->orderBy('code')->pluck('id', 'code')->all());
$this->assertSame(6, DB::table('economic_activities')->count());
$this->assertSame(3, DB::table('reference_catalog_versions')->count());
$this->assertDatabaseHas('reference_catalog_versions', [
'catalog_code' => 'economic-activities', 'version_no' => 1, 'locale' => 'pt-MZ', 'status' => 'published',
]);
}
public function test_catalog_search_pagination_and_explicit_version(): void
{
$this->seedReferences();
$this->getJson('/api/v1/catalogs/economic-activities?q=energia&per_page=1')
->assertOk()->assertJsonPath('meta.version', 1)->assertJsonPath('meta.locale', 'pt-MZ')
->assertJsonPath('meta.total', 1)->assertJsonPath('data.0.code', 'energia')
->assertJsonPath('data.0.label', DB::table('sectors')->where('slug', 'energia')->value('name'));
$this->getJson('/api/v1/catalogs/economic-activities?version=1&per_page=2&page=2')
->assertOk()->assertJsonPath('meta.current_page', 2)->assertJsonPath('meta.total', 6)
->assertJsonCount(2, 'data')->assertJsonStructure(['links' => ['next', 'previous']]);
$this->getJson('/api/v1/catalogs/economic-activities?version=999')->assertNotFound();
}
public function test_jurisdiction_dropdown_requires_the_immediate_parent_and_filters_children(): void
{
$this->seedReferences();
$country = DB::table('geo_locations')->where('location_type', 'country')->where('source_system', 'cartografia-workbook')->value('id');
$province = DB::table('geo_locations')->where('location_type', 'province')->where('source_system', 'cartografia-workbook')->orderBy('name')->first();
$this->getJson('/api/v1/catalogs/jurisdictions?type=province&parent_id='.$country.'&per_page=100')
->assertOk()->assertJsonPath('meta.version', 3)->assertJsonPath('meta.locale', 'pt-MZ')->assertJsonPath('meta.total', 11);
$district = DB::table('geo_locations')->where('parent_id', $province->id)->where('location_type', 'district')->first();
$this->getJson('/api/v1/catalogs/jurisdictions?type=district&parent_id='.$province->id.'&q='.$district->name)
->assertOk()->assertJsonPath('data.0.parent_id', $province->id)->assertJsonPath('data.0.name', $district->name)->assertJsonPath('meta.total', 1);
$this->getJson('/api/v1/catalogs/jurisdictions?type=district')->assertUnprocessable()->assertJsonValidationErrors('parent_id');
$this->getJson('/api/v1/catalogs/jurisdictions?type=district&parent_id='.$country)->assertUnprocessable()->assertJsonValidationErrors('parent_id');
}
public function test_economic_activity_dropdown_can_be_filtered_by_sector(): void
{
$this->seedReferences();
$sectorId = DB::table('sectors')->where('slug', 'energia')->value('id');
$this->getJson('/api/v1/catalogs/economic-activities?sector_id='.$sectorId)
->assertOk()->assertJsonPath('meta.total', 1)->assertJsonPath('data.0.code', 'energia');
$this->getJson('/api/v1/catalogs/economic-activities?sector_id=999999999')
->assertUnprocessable()->assertJsonValidationErrors('sector_id');
}
public function test_authorities_are_not_fabricated_before_a_source_is_approved(): void
{
$this->seedReferences();
$this->getJson('/api/v1/catalogs/authorities')->assertOk()->assertJsonPath('data', [])
->assertJsonPath('meta.status', 'not_published')->assertJsonPath('meta.version', null);
}
public function test_published_authority_catalog_only_returns_public_organizations(): void
{
$this->seedReferences();
$versionId = DB::table('reference_catalog_versions')->where('catalog_code', 'authorities')->value('id');
DB::table('reference_catalog_versions')->where('id', $versionId)->update(['status' => 'published']);
foreach ([['Public authority', 'public'], ['Internal authority', 'internal']] as [$name, $classification]) {
$organizationId = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $organizationId, 'name' => $name, 'organization_type' => 'public',
'data_classification' => $classification, 'created_at' => now(), 'updated_at' => now()]);
DB::table('authorities')->insert(['id' => (string) Str::uuid(), 'catalog_version_id' => $versionId,
'organization_id' => $organizationId, 'code' => strtolower(str_replace(' ', '-', $name)),
'authority_type' => 'registry', 'label_pt_mz' => $name, 'source_reference' => 'Synthetic approved source',
'version_no' => 1, 'valid_from' => today()->toDateString(), 'status' => 'published',
'created_at' => now(), 'updated_at' => now()]);
}
$this->getJson('/api/v1/catalogs/authorities')->assertOk()->assertJsonPath('meta.version', 1)
->assertJsonPath('meta.total', 1)->assertJsonPath('data.0.name', 'Public authority');
}
public function test_foreign_keys_and_catalog_migration_rollback_guard(): void
{
$this->seedReferences();
$migration = require database_path('migrations/2026_10_01_000100_create_reference_catalogs.php');
try {
$migration->down();
$this->fail('Rollback must preserve seeded economic activity references.');
} catch (RuntimeException $exception) {
$this->assertStringContainsString('Economic activities exist', $exception->getMessage());
}
$activity = DB::table('economic_activities')->first();
try {
DB::table('economic_activities')->insert([
'id' => (string) Str::uuid(), 'catalog_version_id' => $activity->catalog_version_id, 'sector_id' => 999999999,
'code' => 'invalid-fk', 'label_pt_mz' => 'Inválido', 'version_no' => 1, 'valid_from' => '2026-10-01',
'status' => 'published', 'created_at' => now(), 'updated_at' => now(),
]);
$this->fail('The database accepted an unknown sector reference.');
} catch (QueryException $exception) {
$this->assertSame('23503', $exception->errorInfo[0]);
}
}
public function test_published_catalog_values_are_immutable(): void
{
$this->seedReferences();
$activity = DB::table('economic_activities')->where('code', 'energia')->first();
try {
DB::table('economic_activities')->where('id', $activity->id)->update(['label_pt_mz' => 'Rótulo adulterado']);
$this->fail('Published catalog values must be immutable.');
} catch (QueryException $exception) {
$this->assertSame('42501', $exception->errorInfo[0]);
}
}
public function test_empty_catalog_migration_rolls_back_and_reapplies(): void
{
$migration = require database_path('migrations/2026_10_01_000100_create_reference_catalogs.php');
$migration->down();
$this->assertFalse(Schema::hasTable('economic_activities'));
$this->assertFalse(Schema::hasTable('authorities'));
$this->assertFalse(Schema::hasTable('reference_catalog_versions'));
$migration->up();
$this->assertTrue(Schema::hasTable('economic_activities'));
$this->assertTrue(Schema::hasTable('authorities'));
$this->assertTrue(Schema::hasTable('reference_catalog_versions'));
}
private function seedReferences(): void
{
$this->seed(SectorSeeder::class);
$this->seed(TerritoryReferenceSeeder::class);
$this->seed(ReferenceCatalogSeeder::class);
}
}
+255
View File
@@ -0,0 +1,255 @@
<?php
namespace Tests\Feature;
use App\Jobs\RunSimulation;
use App\Models\User;
use App\Services\SimulationExecution;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Tests\TestCase;
class SimulationExecutionTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Queue::fake();
}
public function test_anonymous_execution_keeps_only_token_hash_and_reconciles_immutable_sources(): void
{
$token = Str::random(48);
$key = (string) Str::uuid();
$response = $this->postJson('/api/v1/simulations', ['base' => '1000', 'rate' => '10', 'reduction' => '50'], [
'Idempotency-Key' => $key, 'X-Simulation-Token' => $token,
])->assertAccepted()->assertJsonPath('data.status', 'queued')->assertJsonPath('access_token', $token);
$queuedEtag = $response->headers->get('ETag');
$simulationId = $response->json('data.id');
$this->assertDatabaseHas('simulations', ['id' => $simulationId, 'anonymous_token_hash' => hash_hmac('sha256', $token, (string) config('app.key'))]);
$this->assertDatabaseMissing('simulations', ['id' => $simulationId, 'anonymous_token_hash' => $token]);
app(RunSimulation::class, ['simulationId' => $simulationId, 'actorId' => null, 'tokenHash' => hash_hmac('sha256', $token, (string) config('app.key'))])
->handle(app(SimulationExecution::class));
$completedResponse = $this->getJson('/api/v1/simulations/'.$simulationId, ['X-Simulation-Token' => $token])
->assertOk()->assertJsonPath('data.status', 'completed');
$this->assertNotSame($queuedEtag, $completedResponse->headers->get('ETag'));
$simulationView = $completedResponse->json('data');
$this->assertEqualsWithDelta(50.0, (float) $simulationView['result_snapshot']['indicative_total'], 0.0000001);
$this->assertDatabaseHas('simulation_result_sources', ['source_type' => 'user_input']);
$this->assertSame(1, DB::table('simulation_reports')->where('simulation_id', $simulationId)->where('status', 'ready')->count());
$simulation = DB::table('simulations')->where('id', $simulationId)->first();
$result = DB::table('simulation_results')->where('simulation_id', $simulationId)->first();
$source = DB::table('simulation_result_sources')->where('result_id', $result->id)->first();
$resultCanonical = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$result->result_snapshot])->canonical;
$sourceCanonical = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$source->source_snapshot])->canonical;
$this->assertSame($result->result_sha256, hash('sha256', $resultCanonical));
$this->assertSame($source->source_sha256, hash('sha256', $sourceCanonical));
$this->assertNotNull($simulation->questionnaire_version_id);
try {
DB::transaction(fn () => DB::table('simulation_audit_events')->where('simulation_id', $simulationId)->update(['action' => 'audit.tampered']));
$this->fail('Simulation audit events must be append-only.');
} catch (QueryException) {
$this->assertDatabaseMissing('simulation_audit_events', ['simulation_id' => $simulationId, 'action' => 'audit.tampered']);
}
}
public function test_execution_requires_an_explicit_user_supplied_reduction(): void
{
$this->postJson('/api/v1/simulations', ['base' => '500', 'rate' => '5'], [
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
])->assertUnprocessable()->assertJsonValidationErrors('reduction');
}
public function test_idempotency_replays_same_payload_and_rejects_key_reuse_with_different_payload(): void
{
$token = Str::random(48);
$key = (string) Str::uuid();
$headers = ['Idempotency-Key' => $key, 'X-Simulation-Token' => $token];
$first = $this->postJson('/api/v1/simulations', ['base' => '500', 'rate' => '5', 'reduction' => '0'], $headers)->assertAccepted();
$id = $first->json('data.id');
$this->postJson('/api/v1/simulations', ['base' => '500', 'rate' => '5', 'reduction' => '0'], $headers)
->assertOk()->assertJsonPath('data.id', $id)->assertJsonPath('replayed', true);
$this->postJson('/api/v1/simulations', ['base' => '500', 'rate' => '6', 'reduction' => '0'], $headers)->assertConflict();
$this->assertSame(1, DB::table('simulations')->where('id', $id)->count());
}
public function test_if_match_is_required_and_stale_versions_return_412_then_success_advances_version(): void
{
$token = Str::random(48);
$response = $this->postJson('/api/v1/simulations', ['base' => '1000', 'rate' => '10', 'reduction' => '0'], [
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
])->assertAccepted();
$id = $response->json('data.id');
$scenarioId = $response->json('data.scenarios.0.id');
app(RunSimulation::class, ['simulationId' => $id, 'actorId' => null, 'tokenHash' => hash_hmac('sha256', $token, (string) config('app.key'))])
->handle(app(SimulationExecution::class));
$response = $this->getJson('/api/v1/simulations/'.$id, ['X-Simulation-Token' => $token])->assertOk();
$payload = ['label' => 'Cenário revisto', 'base' => '2000', 'rate' => '8', 'reduction' => '25'];
$url = "/api/v1/simulations/{$id}/scenarios/{$scenarioId}";
$headers = ['X-Simulation-Token' => $token];
$this->patchJson($url, $payload, $headers)->assertStatus(428);
$this->patchJson($url, $payload, $headers + ['If-Match' => '"sim-'.$id.'-v999"'])->assertStatus(412);
$etag = $response->headers->get('ETag');
$updated = $this->patchJson($url, $payload, $headers + ['If-Match' => $etag])->assertAccepted();
$updated->assertHeader('ETag', '"sim-'.$id.'-v3"')->assertJsonPath('data.status', 'queued');
$tokenHash = hash_hmac('sha256', $token, (string) config('app.key'));
app(RunSimulation::class, ['simulationId' => $id, 'actorId' => null, 'tokenHash' => $tokenHash])->handle(app(SimulationExecution::class));
$this->assertSame(2, DB::table('simulation_results')->where('simulation_id', $id)->count());
$this->assertSame(2, DB::table('simulation_reports')->where('simulation_id', $id)->count());
$this->patchJson($url, $payload, $headers + ['If-Match' => $etag])->assertStatus(412);
}
public function test_rls_hides_rows_without_context_and_from_an_unrelated_actor(): void
{
$owner = User::factory()->create(['email_verified_at' => now()]);
$other = User::factory()->create(['email_verified_at' => now()]);
$this->actingAs($owner)->postJson('/api/v1/simulations', ['base' => '10', 'rate' => '1', 'reduction' => '0'], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
$id = DB::table('simulations')->where('owner_user_id', $owner->id)->value('id');
$execution = app(SimulationExecution::class);
DB::unprepared('DO $$ BEGIN CREATE ROLE simulation_rls_test NOLOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$');
DB::statement('GRANT USAGE ON SCHEMA public TO simulation_rls_test');
DB::statement('GRANT SELECT ON public.simulations, public.memberships TO simulation_rls_test');
try {
DB::statement('SET ROLE simulation_rls_test');
$execution->setContext($other->id, null);
$this->assertSame(0, (int) DB::scalar('select count(*) from public.simulations where id = ?', [$id]));
$execution->setContext($owner->id, null);
$this->assertSame(1, (int) DB::scalar('select count(*) from public.simulations where id = ?', [$id]));
} finally {
DB::statement('RESET ROLE');
DB::statement('DROP OWNED BY simulation_rls_test');
DB::statement('DROP ROLE IF EXISTS simulation_rls_test');
}
$this->actingAs($other)->getJson('/api/v1/simulations/'.$id)->assertNotFound();
}
public function test_terminal_job_failure_is_reconciled_without_exposing_exception_text(): void
{
$owner = User::factory()->create(['email_verified_at' => now()]);
$this->actingAs($owner)->postJson('/api/v1/simulations', ['base' => '10', 'rate' => '1', 'reduction' => '0'], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
$simulation = DB::table('simulations')->where('owner_user_id', $owner->id)->first();
$job = new RunSimulation($simulation->id, $owner->id, null);
$job->failed(new \RuntimeException('sensitive internal detail'));
$this->assertDatabaseHas('simulation_jobs', ['simulation_id' => $simulation->id, 'status' => 'failed', 'error_code' => 'execution_failed']);
$this->assertDatabaseHas('simulations', ['id' => $simulation->id, 'status' => 'failed', 'error_code' => 'execution_failed']);
$this->assertDatabaseMissing('simulation_audit_events', ['simulation_id' => $simulation->id, 'action' => 'sensitive internal detail']);
}
public function test_organization_membership_scopes_simulation_reads(): void
{
$owner = User::factory()->create(['email_verified_at' => now()]);
$member = User::factory()->create(['email_verified_at' => now()]);
$outsider = User::factory()->create(['email_verified_at' => now()]);
$organizationId = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $organizationId, 'name' => 'Test organization', 'organization_type' => 'private',
'data_classification' => 'internal', 'created_at' => now(), 'updated_at' => now()]);
DB::table('memberships')->insert([
['id' => (string) Str::uuid(), 'user_id' => $owner->id, 'organization_id' => $organizationId, 'role' => 'admin', 'created_at' => now(), 'updated_at' => now()],
['id' => (string) Str::uuid(), 'user_id' => $member->id, 'organization_id' => $organizationId, 'role' => 'viewer', 'created_at' => now(), 'updated_at' => now()],
]);
$this->actingAs($owner)->postJson('/api/v1/simulations', ['base' => '100', 'rate' => '2', 'reduction' => '0', 'organization_id' => $organizationId],
['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
$id = DB::table('simulations')->where('owner_user_id', $owner->id)->value('id');
$this->actingAs($member)->getJson('/api/v1/simulations/'.$id)->assertOk();
$this->actingAs($outsider)->getJson('/api/v1/simulations/'.$id)->assertNotFound();
DB::unprepared('DO $$ BEGIN CREATE ROLE simulation_rls_test NOLOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$');
DB::statement('GRANT USAGE ON SCHEMA public TO simulation_rls_test');
DB::statement('GRANT SELECT, UPDATE ON public.simulations TO simulation_rls_test');
DB::statement('GRANT SELECT ON public.memberships TO simulation_rls_test');
try {
DB::statement('SET ROLE simulation_rls_test');
$execution = app(SimulationExecution::class);
$execution->setContext($member->id, null);
$this->assertSame(1, (int) DB::scalar('select count(*) from public.simulations where id = ?', [$id]));
$this->assertSame(0, DB::affectingStatement('update public.simulations set version_no = version_no + 1 where id = ?', [$id]));
} finally {
DB::statement('RESET ROLE');
DB::statement('DROP OWNED BY simulation_rls_test');
DB::statement('DROP ROLE IF EXISTS simulation_rls_test');
}
DB::table('memberships')->where('user_id', $owner->id)->where('organization_id', $organizationId)->delete();
$this->actingAs($owner)->getJson('/api/v1/simulations/'.$id)->assertNotFound();
}
public function test_postgres_rls_uses_anonymous_token_hmac_not_plain_token(): void
{
$token = Str::random(48);
$response = $this->postJson('/api/v1/simulations', ['base' => '40', 'rate' => '10', 'reduction' => '0'], [
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
])->assertAccepted();
$id = $response->json('data.id');
$tokenHash = hash_hmac('sha256', $token, (string) config('app.key'));
DB::unprepared('DO $$ BEGIN CREATE ROLE simulation_rls_test NOLOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$');
DB::statement('GRANT USAGE ON SCHEMA public TO simulation_rls_test');
DB::statement('GRANT SELECT ON public.simulations, public.memberships TO simulation_rls_test');
try {
DB::statement('SET ROLE simulation_rls_test');
$execution = app(SimulationExecution::class);
$execution->setContext(null, hash_hmac('sha256', 'wrong-token', (string) config('app.key')));
$this->assertSame(0, (int) DB::scalar('select count(*) from public.simulations where id = ?', [$id]));
$execution->setContext(null, $tokenHash);
$this->assertSame(1, (int) DB::scalar('select count(*) from public.simulations where id = ?', [$id]));
} finally {
DB::statement('RESET ROLE');
DB::statement('DROP OWNED BY simulation_rls_test');
DB::statement('DROP ROLE IF EXISTS simulation_rls_test');
}
}
public function test_retry_budget_is_bounded_and_failed_attempt_is_reconciled(): void
{
$owner = User::factory()->create(['email_verified_at' => now()]);
$this->actingAs($owner)->postJson('/api/v1/simulations', ['base' => '10', 'rate' => '1', 'reduction' => '0'], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
$simulation = DB::table('simulations')->where('owner_user_id', $owner->id)->first();
$execution = app(SimulationExecution::class);
DB::transaction(function () use ($execution, $owner, $simulation): void {
$execution->setContext($owner->id, null);
DB::table('simulation_scenarios')->where('simulation_id', $simulation->id)->delete();
});
$job = new RunSimulation($simulation->id, $owner->id, null);
try {
$job->handle($execution);
$this->fail('A simulation without a scenario must fail and remain retryable.');
} catch (\RuntimeException $exception) {
$this->assertSame('Simulation has no scenario.', $exception->getMessage());
}
$this->assertSame(3, $job->tries);
$this->assertSame([10, 60], $job->backoff());
$this->assertDatabaseHas('simulation_jobs', ['simulation_id' => $simulation->id, 'status' => 'running', 'attempts' => 1]);
$job->failed(new \RuntimeException('do not persist this detail'));
$this->assertDatabaseHas('simulation_jobs', ['simulation_id' => $simulation->id, 'status' => 'failed', 'attempts' => 3]);
}
public function test_empty_schema_rolls_back_and_reapplies_with_questionnaire_seed(): void
{
$migration = require database_path('migrations/2026_10_01_000200_create_simulation_execution_core.php');
$migration->down();
$this->assertFalse(Schema::hasTable('simulations'));
$migration->up();
$this->assertTrue(Schema::hasTable('simulation_results'));
$this->assertDatabaseHas('questionnaire_versions', ['id' => '61000100-0000-4000-8000-000000000001', 'status' => 'published']);
}
public function test_questionnaire_endpoint_exposes_only_published_version_with_etag(): void
{
$this->getJson('/api/v1/questionnaires/user-entered-arithmetic')->assertOk()
->assertHeader('ETag', '"questionnaire-61000100-0000-4000-8000-000000000001-v1"')
->assertJsonPath('data.locale', 'pt-MZ')->assertJsonPath('data.schema_snapshot.rate_origin', 'user_input');
$this->getJson('/api/v1/questionnaires/unknown')->assertNotFound();
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class SimulationFormDraftTest extends TestCase
{
use RefreshDatabase;
public function test_anonymous_draft_is_encrypted_scoped_and_restorable(): void
{
$token = Str::random(48);
$key = (string) Str::uuid();
$payload = $this->payload();
$created = $this->postJson('/api/v1/simulation-drafts', $payload, [
'Idempotency-Key' => $key, 'X-Simulation-Token' => $token,
])->assertCreated()->assertJsonPath('data.version_no', 1);
$id = $created->json('data.id');
$stored = DB::table('simulation_form_drafts')->where('id', $id)->first();
$this->assertNotSame(json_encode($payload['personal_snapshot']), $stored->personal_snapshot);
$this->assertNotSame(json_encode($payload['economic_snapshot']), $stored->economic_snapshot);
$this->getJson('/api/v1/simulation-drafts/current', ['X-Simulation-Token' => $token])
->assertOk()->assertJsonPath('data.personal_snapshot.legal_name', 'Entidade de teste')
->assertJsonPath('data.economic_snapshot.base', '1200');
$this->getJson('/api/v1/simulation-drafts/'.$id, ['X-Simulation-Token' => Str::random(48)])->assertNotFound();
}
public function test_creation_is_idempotent_and_rejects_key_reuse_with_changed_data(): void
{
$token = Str::random(48);
$key = (string) Str::uuid();
$headers = ['Idempotency-Key' => $key, 'X-Simulation-Token' => $token];
$payload = $this->payload();
$first = $this->postJson('/api/v1/simulation-drafts', $payload, $headers)->assertCreated();
$id = $first->json('data.id');
$this->postJson('/api/v1/simulation-drafts', $payload, $headers)
->assertOk()->assertJsonPath('data.id', $id)->assertJsonPath('data.replayed', true);
$payload['economic_snapshot']['base'] = '1300';
$this->postJson('/api/v1/simulation-drafts', $payload, $headers)->assertConflict();
}
public function test_updates_require_a_current_etag_and_delete_is_reversible_until_expiry(): void
{
$token = Str::random(48);
$headers = ['Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token];
$payload = $this->payload();
$created = $this->postJson('/api/v1/simulation-drafts', $payload, $headers)->assertCreated();
$id = $created->json('data.id');
$url = '/api/v1/simulation-drafts/'.$id;
$this->putJson($url, $payload, ['X-Simulation-Token' => $token])->assertStatus(428);
$this->putJson($url, $payload, ['X-Simulation-Token' => $token, 'If-Match' => '"sfd-'.$id.'-v99"'])->assertStatus(412);
$updated = $this->putJson($url, $payload, ['X-Simulation-Token' => $token, 'If-Match' => $created->headers->get('ETag')])
->assertOk()->assertJsonPath('data.version_no', 2);
$this->deleteJson($url, [], ['X-Simulation-Token' => $token, 'If-Match' => $updated->headers->get('ETag')])->assertNoContent();
$this->assertDatabaseHas('simulation_form_drafts', ['id' => $id]);
$this->assertDatabaseMissing('simulation_form_drafts', ['id' => $id, 'deleted_at' => null]);
}
public function test_server_rejects_invalid_rates_and_unlisted_snapshot_fields(): void
{
$token = Str::random(48);
$payload = $this->payload();
$payload['economic_snapshot']['rate'] = '101';
$this->postJson('/api/v1/simulation-drafts', $payload, [
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot.rate');
$payload = $this->payload();
$payload['economic_snapshot']['unapproved_field'] = 'not accepted';
$this->postJson('/api/v1/simulation-drafts', $payload, [
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot');
}
/** @return array{personal_snapshot: array<string,string>, economic_snapshot: array<string,string>} */
private function payload(): array
{
return [
'personal_snapshot' => ['legal_name' => 'Entidade de teste', 'email' => 'teste@example.com'],
'economic_snapshot' => ['purpose' => 'simulate_only', 'tax_calculation' => 'yes', 'base' => '1200', 'rate' => '8', 'reduction' => '0'],
];
}
}
+4 -2
View File
@@ -37,7 +37,8 @@ class SchemaLifecycleTest extends TestCase
// additive upgrades are exercised by their feature/migration tests.
$baselinePaths = array_values(array_filter(glob(database_path('migrations/*.php')),
fn ($path) => strcmp(basename($path), '2026_09_25') < 0));
$this->artisan('migrate:fresh', ['--seed' => true, '--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
// This historical baseline predates several tables required by DatabaseSeeder.
$this->artisan('migrate:fresh', ['--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
$manifest = json_decode(file_get_contents(base_path('docs/investmoz/schema.json')), true, 512, JSON_THROW_ON_ERROR);
$legacy = json_decode(file_get_contents(base_path('docs/investmoz/legacy-schema.json')), true, 512, JSON_THROW_ON_ERROR);
@@ -154,7 +155,8 @@ class SchemaLifecycleTest extends TestCase
$this->assertTrue(Schema::hasTable('users'));
$this->assertTrue(Schema::hasTable('opportunities'));
$this->assertCount(2, DB::select("SELECT extname FROM pg_extension WHERE extname IN ('postgis','pgcrypto')"));
$this->artisan('migrate', ['--seed' => true, '--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
// Reapplying the partial baseline must not invoke seeders for later schemas.
$this->artisan('migrate', ['--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
// This is a separate upgrade batch: ordinary rollback must now revert it.
$this->artisan('migrate:rollback', ['--force' => true])->assertExitCode(0);
$this->assertFalse(Schema::hasTable('projects'));
+10
View File
@@ -20,6 +20,16 @@ abstract class TestCase extends BaseTestCase
&& (string) $db->getConfig('port') === '55441'
&& in_array($db->getConfig('host'), ['127.0.0.1', 'localhost'], true)) {
$db->statement('DROP SCHEMA IF EXISTS skills_edu CASCADE');
if ($db->selectOne("SELECT to_regclass('public.complementary_project_links') AS id")->id !== null) {
$db->statement('DROP TRIGGER IF EXISTS project_dependency_check ON public.complementary_project_links');
$db->statement('DROP TRIGGER IF EXISTS project_dependency_lock ON public.complementary_project_links');
}
$db->statement('DROP FUNCTION IF EXISTS public.check_project_dependency_graph() RESTRICT');
$db->statement('DROP FUNCTION IF EXISTS public.lock_project_dependency_graph() RESTRICT');
if ($db->selectOne("SELECT to_regclass('public.existing_business_locations') AS id")->id !== null) {
$db->statement('DROP TRIGGER IF EXISTS existing_business_locations_hierarchy_trigger ON public.existing_business_locations');
}
$db->statement('DROP FUNCTION IF EXISTS public.enforce_existing_business_location_hierarchy() RESTRICT');
}
}
+67
View File
@@ -0,0 +1,67 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
getAutosaveSnapshot,
partitionSimulationDraft,
replaceSimulationValue,
restoreSimulationDraft,
simulationDraftFingerprint,
validateSimulationDraft,
} from "../../resources/js/lib/simulation-form.ts";
test("changing territorial or sector parents clears every dependent value", () => {
assert.deepEqual(
replaceSimulationValue({
province_id: "p1", district_id: "d1", admin_post_id: "a1", locality_id: "l1",
}, "province_id", "p2"),
{ province_id: "p2" },
);
assert.deepEqual(
replaceSimulationValue({ sector_id: "s1", activity_id: "a1", activity_id_label: "A" }, "sector_id", "s2"),
{ sector_id: "s2" },
);
});
test("switching to anonymous simulation clears formal identity and project data", () => {
const next = replaceSimulationValue({
purpose: "own_investment", legal_name: "Empresa", email: "a@b.co", project_title: "Projecto",
total_investment: "10", total_investment_label: "10",
}, "purpose", "simulate_only");
assert.deepEqual(next, { purpose: "simulate_only" });
});
test("client validation rejects absent arithmetic inputs and out-of-range rates", () => {
assert.deepEqual(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes" }, "tax"), {
base: "Este campo é obrigatório.",
rate: "Este campo é obrigatório.",
reduction: "Este campo é obrigatório.",
});
assert.equal(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes", base: "0", rate: "101", reduction: "0" }, "tax").rate,
"O valor não pode exceder 100.");
});
test("financial reconciliation reports a mismatch without inventing a fiscal value", () => {
const errors = validateSimulationDraft({
currency: "USD", total_investment: "100", own_capital: "20", domestic_debt: "20", foreign_debt: "20", grants: "20",
}, "financial");
assert.match(errors.total_investment, /corresponder ao investimento total/);
assert.equal(validateSimulationDraft({}, "financial").currency, "Este campo é obrigatório.");
});
test("autosave omits identity and contact fields from browser storage", () => {
assert.deepEqual(getAutosaveSnapshot({
total_investment: "50", legal_name: "Nome", email: "person@example.com", nuit: "123",
project_title: "Projecto", legal_name_label: "Nome",
}), { total_investment: "50", project_title: "Projecto" });
});
test("server draft snapshots split private identity from economic values", () => {
assert.deepEqual(partitionSimulationDraft({ purpose: "simulate_only", legal_name: "Nome", base: "10", rate: "2", province_id_label: "Tete", person_type: "collective", person_type_label: "Pessoa colectiva" }), {
personal_snapshot: { legal_name: "Nome", person_type: "collective", selection_labels: { person_type: "Pessoa colectiva" } },
economic_snapshot: { purpose: "simulate_only", base: "10", rate: "2", selection_labels: { province_id: "Tete" } },
});
assert.deepEqual(restoreSimulationDraft({ activity_id: "uuid", infrastructure_needs: ["energia", "água"], selection_labels: { activity_id: "Energia", infrastructure_needs: ["Energia", "Água"] } }, {}), {
activity_id: "uuid", activity_id_label: "Energia", infrastructure_needs: ["energia", "água"], infrastructure_needs_label: ["Energia", "Água"],
});
assert.equal(simulationDraftFingerprint({ base: "10", purpose: "simulate_only" }), simulationDraftFingerprint({ purpose: "simulate_only", base: "10" }));
});
+17
View File
@@ -0,0 +1,17 @@
import assert from "node:assert/strict";
import test from "node:test";
import { replaceTerritoryPath } from "../../resources/js/lib/territory-path.js";
test("changing a parent replaces its value and clears every descendant", () => {
const path = ["province-a", "district-a", "post-a", "locality-a"];
assert.deepEqual(replaceTerritoryPath(path, 0, "province-b"), ["province-b"]);
assert.deepEqual(replaceTerritoryPath(path, 1, "district-b"), ["province-a", "district-b"]);
});
test("clearing a level also clears that level and all descendants", () => {
const path = ["province-a", "district-a", "post-a", "locality-a"];
assert.deepEqual(replaceTerritoryPath(path, 0), []);
assert.deepEqual(replaceTerritoryPath(path, 2, null), ["province-a", "district-a"]);
});