@@ -49,7 +49,9 @@ class AiGatewayTest extends TestCase
|
||||
Storage::disk('local')->put($key, $text);
|
||||
$this->beforeApplicationDestroyed(fn () => Storage::disk('local')->delete($key));
|
||||
DB::table('documents')->insert(['id' => $id, 'file_name' => $key, 'media_type' => 'text/plain', 'storage_key' => $key,
|
||||
'sha256' => hash('sha256', $text), 'status' => 'active', 'data_classification' => $classification]);
|
||||
'sha256' => hash('sha256', $text), 'status' => 'active', 'data_classification' => $classification,
|
||||
'malware_scan_status' => 'clean', 'malware_scanned_sha256' => hash('sha256', $text), 'malware_engine' => 'ClamAV-Test-Double',
|
||||
'malware_engine_version' => 'fixture', 'malware_scanned_at' => now(), 'malware_signatures_at' => now()]);
|
||||
$response = $this->postJson('/api/v1/ai/sources', ['document_id' => $id, 'title' => 'Fonte sintética', 'language' => $language,
|
||||
'nature' => 'illustrative', 'source_url' => 'https://example.org/synthetic', 'source_owner' => 'Entidade de teste',
|
||||
'evidence_reference' => 'Autorização exclusivamente sintética.', 'source_date' => now()->toDateString(),
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\RunSimulation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -23,7 +22,7 @@ class ApiContractTest extends TestCase
|
||||
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], [
|
||||
$create = $this->postJson('/api/v1/simulations', ['base' => 0, 'rate' => 0, 'reduction' => 0], [
|
||||
'Idempotency-Key' => (string) Str::uuid(),
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertAccepted();
|
||||
@@ -31,9 +30,12 @@ class ApiContractTest extends TestCase
|
||||
$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']]])
|
||||
->assertJsonStructure(['data' => [['id', 'simulation_id', 'job_type', 'status', 'attempts', 'available_at', 'started_at', 'finished_at', 'error_code']]])
|
||||
->assertJsonPath('data.0.job_type', 'execute')
|
||||
->assertJsonPath('data.0.status', 'pending');
|
||||
->assertJsonPath('data.0.status', 'pending')
|
||||
->assertJsonPath('data.0.started_at', null)
|
||||
->assertJsonPath('data.0.finished_at', null)
|
||||
->assertJsonPath('data.0.error_code', null);
|
||||
|
||||
$this->getJson("/api/v1/simulations/{$simulationId}/jobs", ['X-Simulation-Token' => Str::random(48)])
|
||||
->assertNotFound();
|
||||
@@ -74,7 +76,7 @@ class ApiContractTest extends TestCase
|
||||
|
||||
public function test_contract_errors_include_correlation_and_required_preconditions(): void
|
||||
{
|
||||
$missingKey = $this->postJson('/api/v1/simulations', ['base' => 1, 'rate' => 1])
|
||||
$missingKey = $this->postJson('/api/v1/simulations', ['base' => 1, 'rate' => 1, 'reduction' => 0])
|
||||
->assertStatus(428)
|
||||
->assertJsonStructure(['message'])
|
||||
->assertHeader('X-Correlation-ID');
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ClamDQueueWorkerIntegrationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_database_queue_worker_processes_a_private_document_and_does_not_publish_it(): void
|
||||
{
|
||||
$scanner = app(MalwareScanner::class);
|
||||
$health = $scanner->health();
|
||||
Storage::fake('local');
|
||||
config(['queue.default' => 'database', 'portal.managers' => []]);
|
||||
$manager = User::factory()->create(['email_verified_at' => now()]);
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('queue-worker-qa.txt', 'Harmless private queue worker integration test.'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->where('file_name', 'queue-worker-qa.txt')->firstOrFail();
|
||||
$this->assertSame('pending', $document->malware_scan_status);
|
||||
$this->assertSame('quarantined', $document->status);
|
||||
|
||||
ScanDocumentForMalware::dispatch($document->id)->onConnection('database')->onQueue('default');
|
||||
Artisan::call('queue:work', ['connection' => 'database', '--once' => true, '--tries' => 3, '--timeout' => 150, '--queue' => 'default']);
|
||||
$document = DB::table('documents')->where('id', $document->id)->firstOrFail();
|
||||
|
||||
if ($health['available']) {
|
||||
$this->assertSame('clean', $document->malware_scan_status);
|
||||
$this->assertSame('active', $document->status);
|
||||
$this->assertSame($document->sha256, $document->malware_scanned_sha256);
|
||||
} else {
|
||||
$this->assertSame('inconclusive', $document->malware_scan_status);
|
||||
$this->assertSame('quarantined', $document->status);
|
||||
}
|
||||
$this->assertSame('internal', $document->data_classification);
|
||||
$this->assertSame(0, DB::table('portal_resources')->count());
|
||||
$this->assertDatabaseHas('document_malware_scans', ['document_id' => $document->id,
|
||||
'result' => $health['available'] ? 'clean' : 'inconclusive']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ClamDScannerIntegrationTest extends TestCase
|
||||
{
|
||||
private ?string $temporaryFile = null;
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if ($this->temporaryFile && is_file($this->temporaryFile)) {
|
||||
unlink($this->temporaryFile);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_real_clamd_scans_a_harmless_document_and_honours_the_file_limit(): void
|
||||
{
|
||||
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1', 'services.malware.port' => 3310]);
|
||||
$scanner = app(MalwareScanner::class);
|
||||
$health = $scanner->health();
|
||||
if (! $health['available']) {
|
||||
$this->markTestSkipped('A local ClamD with current signatures is required for this integration test.');
|
||||
}
|
||||
|
||||
$root = storage_path('app/private');
|
||||
$directory = $root.'/malware-integration-tests';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
$this->temporaryFile = $directory.'/'.Str::uuid().'.txt';
|
||||
file_put_contents($this->temporaryFile, 'Harmless InvestMoz malware scanner integration test document.');
|
||||
|
||||
$result = $scanner->scan($this->temporaryFile, filesize($this->temporaryFile), $root);
|
||||
$this->assertSame('clean', $result['result']);
|
||||
$this->assertSame($health['engine_version'], $result['engine_version']);
|
||||
$this->assertNotNull($result['signatures_at']);
|
||||
|
||||
config(['services.malware.max_file_bytes' => 1]);
|
||||
$limited = $scanner->scan($this->temporaryFile, filesize($this->temporaryFile), $root);
|
||||
$this->assertSame('inconclusive', $limited['result']);
|
||||
$this->assertSame('file_scan_limit_exceeded', $limited['reason_code']);
|
||||
}
|
||||
|
||||
public function test_unavailable_clamd_is_indeterminate_and_never_an_approval(): void
|
||||
{
|
||||
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1', 'services.malware.port' => 1]);
|
||||
$result = app(MalwareScanner::class)->scan(__FILE__, filesize(__FILE__), dirname(__DIR__, 2));
|
||||
|
||||
$this->assertSame('inconclusive', $result['result']);
|
||||
$this->assertSame('scanner_unavailable', $result['reason_code']);
|
||||
}
|
||||
|
||||
public function test_clamd_response_timeout_is_inconclusive(): void
|
||||
{
|
||||
$root = storage_path('app/private');
|
||||
$directory = $root.'/malware-integration-tests';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
$this->temporaryFile = $directory.'/'.Str::uuid().'.txt';
|
||||
file_put_contents($this->temporaryFile, 'Harmless timeout fixture.');
|
||||
|
||||
$fixture = __DIR__.'/../Fixtures/ClamDStallServer.php';
|
||||
$process = proc_open([PHP_BINARY, $fixture], [0=>['pipe','r'], 1=>['pipe','w'], 2=>['pipe','w']], $pipes);
|
||||
$this->assertIsResource($process);
|
||||
fclose($pipes[0]);
|
||||
$address = trim((string) fgets($pipes[1]));
|
||||
$port = (int) substr($address, strrpos($address, ':') + 1);
|
||||
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1',
|
||||
'services.malware.port' => $port, 'services.malware.timeout_seconds' => 1]);
|
||||
|
||||
try {
|
||||
$result = app(MalwareScanner::class)->scan($this->temporaryFile, filesize($this->temporaryFile), $root);
|
||||
} finally {
|
||||
proc_terminate($process);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
proc_close($process);
|
||||
}
|
||||
|
||||
$this->assertSame('inconclusive', $result['result']);
|
||||
$this->assertSame('scanner_timeout', $result['reason_code']);
|
||||
}
|
||||
|
||||
public function test_real_clamd_keeps_a_password_protected_archive_inconclusive(): void
|
||||
{
|
||||
$this->requireRealClamd();
|
||||
if (! class_exists(\ZipArchive::class) || ! defined('ZipArchive::EM_AES_256')) {
|
||||
$this->markTestSkipped('PHP ZipArchive with AES support is required to create the harmless encrypted fixture.');
|
||||
}
|
||||
|
||||
$root = storage_path('app/private');
|
||||
$directory = $root.'/malware-integration-tests';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
$this->temporaryFile = $directory.'/'.Str::uuid().'.zip';
|
||||
$archive = new \ZipArchive;
|
||||
$this->assertSame(true, $archive->open($this->temporaryFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE));
|
||||
$this->assertTrue($archive->addFromString('readme.txt', 'Harmless encrypted archive fixture.'));
|
||||
$this->assertTrue($archive->setPassword('local-test-password'));
|
||||
$this->assertTrue($archive->setEncryptionName('readme.txt', \ZipArchive::EM_AES_256));
|
||||
$archive->close();
|
||||
|
||||
$result = app(MalwareScanner::class)->scan($this->temporaryFile, filesize($this->temporaryFile), $root);
|
||||
|
||||
$this->assertSame('inconclusive', $result['result']);
|
||||
$this->assertSame('encrypted_or_password_protected', $result['reason_code']);
|
||||
}
|
||||
|
||||
public function test_zip_beyond_the_decompression_limit_is_inconclusive(): void
|
||||
{
|
||||
$this->requireRealClamd();
|
||||
if (! class_exists(\ZipArchive::class)) {
|
||||
$this->markTestSkipped('PHP ZipArchive is required to create the harmless compressed fixture.');
|
||||
}
|
||||
|
||||
$root = storage_path('app/private');
|
||||
$directory = $root.'/malware-integration-tests';
|
||||
if (! is_dir($directory)) {
|
||||
mkdir($directory, 0700, true);
|
||||
}
|
||||
$this->temporaryFile = $directory.'/'.Str::uuid().'.zip';
|
||||
$archive = new \ZipArchive;
|
||||
$this->assertSame(true, $archive->open($this->temporaryFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE));
|
||||
$this->assertTrue($archive->addFromString('expanded.txt', str_repeat('A', 110 * 1024 * 1024)));
|
||||
$archive->close();
|
||||
|
||||
$result = app(MalwareScanner::class)->scan($this->temporaryFile, filesize($this->temporaryFile), $root);
|
||||
|
||||
$this->assertSame('inconclusive', $result['result']);
|
||||
$this->assertSame('archive_decompression_limit', $result['reason_code']);
|
||||
}
|
||||
|
||||
private function requireRealClamd(): void
|
||||
{
|
||||
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1', 'services.malware.port' => 3310]);
|
||||
if (! app(MalwareScanner::class)->health()['available']) {
|
||||
$this->markTestSkipped('A local ClamD with current signatures is required for this integration test.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CrmIntakeTest extends TestCase
|
||||
@@ -27,8 +28,17 @@ class CrmIntakeTest extends TestCase
|
||||
|
||||
private function interest(string $reference = 'IR-CRM-1'): InterestRequest
|
||||
{
|
||||
return InterestRequest::create(['reference' => $reference, 'full_name' => 'Contacto fictício', 'email' => 'CONTACT@example.invalid',
|
||||
$interest = InterestRequest::create(['reference' => $reference, 'full_name' => 'Contacto fictício', 'email' => 'CONTACT@example.invalid',
|
||||
'investor_type' => 'empresa', 'country' => 'Moçambique', 'sector_interest' => 'Energia', 'message' => 'Mensagem do pedido de teste.', 'privacy_consent' => true]);
|
||||
DB::table('consents')->insert([
|
||||
'id' => (string) Str::uuid(), 'source_system' => 'portal-intake', 'external_id' => 'CrmTestConsent:'.$reference,
|
||||
'version_no' => 1, 'data_classification' => 'confidential', 'subject_ref' => $interest->reference,
|
||||
'purpose' => 'respond_to_interest', 'status' => 'granted', 'granted_at' => now(),
|
||||
'interest_request_id' => $interest->id, 'policy_version' => 'test-policy-v1',
|
||||
'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
return $interest;
|
||||
}
|
||||
|
||||
private function data(User $user): array
|
||||
@@ -72,6 +82,30 @@ class CrmIntakeTest extends TestCase
|
||||
$this->assertDatabaseCount('leads', 2);
|
||||
}
|
||||
|
||||
public function test_conversion_rechecks_the_canonical_contact_consent_record(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$interest = $this->interest();
|
||||
DB::table('consents')->where('interest_request_id', $interest->id)
|
||||
->where('purpose', 'respond_to_interest')
|
||||
->update(['status' => 'withdrawn', 'withdrawn_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
$this->post('/management/crm/convert/'.$interest->id, $this->data($user))
|
||||
->assertSessionHasErrors('investor_id');
|
||||
|
||||
$this->assertDatabaseCount('leads', 0);
|
||||
$this->assertDatabaseCount('investors', 0);
|
||||
$this->assertDatabaseCount('contacts', 0);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
|
||||
DB::table('consents')->where('interest_request_id', $interest->id)->update([
|
||||
'status' => 'granted', 'withdrawn_at' => null, 'deleted_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
$this->post('/management/crm/convert/'.$interest->id, $this->data($user))
|
||||
->assertSessionHasErrors('investor_id');
|
||||
$this->assertDatabaseCount('leads', 0);
|
||||
}
|
||||
|
||||
public function test_unauthorised_users_cannot_convert_and_input_requires_owner_and_future_action(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DatabaseErrorRedactionTest extends TestCase
|
||||
{
|
||||
public function test_public_html_database_errors_do_not_expose_sql_or_connection_details(): void
|
||||
{
|
||||
config(['app.debug' => true]);
|
||||
Route::get('/_test/database-error-redaction', fn () => \DB::select('select missing_column from private_test_table'));
|
||||
|
||||
$response = $this->get('/_test/database-error-redaction');
|
||||
|
||||
$response->assertStatus(503)
|
||||
->assertSee('Serviço temporariamente indisponível')
|
||||
->assertDontSee('missing_column')
|
||||
->assertDontSee('private_test_table')
|
||||
->assertDontSee('investemoz_test')
|
||||
->assertDontSee('127.0.0.1')
|
||||
->assertDontSee('QueryException')
|
||||
->assertDontSee('C:\\laragon');
|
||||
}
|
||||
|
||||
public function test_api_database_errors_return_a_safe_reference_without_sql(): void
|
||||
{
|
||||
config(['app.debug' => true]);
|
||||
Route::get('/api/_test/database-error-redaction', fn () => \DB::select('select missing_column from private_test_table'));
|
||||
|
||||
$response = $this->getJson('/api/_test/database-error-redaction');
|
||||
|
||||
$response->assertStatus(503)
|
||||
->assertJsonPath('message', 'Serviço temporariamente indisponível. Tente novamente mais tarde.')
|
||||
->assertJsonStructure(['message', 'reference']);
|
||||
$this->assertStringNotContainsString('missing_column', $response->getContent());
|
||||
$this->assertStringNotContainsString('private_test_table', $response->getContent());
|
||||
}
|
||||
|
||||
public function test_connection_errors_do_not_expose_host_or_database_name(): void
|
||||
{
|
||||
config(['app.debug' => true, 'database.connections.pgsql.host' => '127.0.0.1',
|
||||
'database.connections.pgsql.port' => 1]);
|
||||
DB::purge('pgsql');
|
||||
Route::get('/_test/database-connection-error', fn () => DB::select('select 1'));
|
||||
|
||||
$response = $this->get('/_test/database-connection-error');
|
||||
|
||||
$response->assertStatus(503)->assertSee('Serviço temporariamente indisponível')
|
||||
->assertDontSee('127.0.0.1')->assertDontSee('investemoz_test');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DocumentLibrarySchemaCompatibilityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_schema_check_accepts_the_complete_library_and_security_schema(): void
|
||||
{
|
||||
$this->assertSame(0, Artisan::call('portal:check-document-library-schema'));
|
||||
$this->assertStringContainsString('Esquema da biblioteca compatível', Artisan::output());
|
||||
}
|
||||
|
||||
public function test_schema_check_rejects_missing_security_columns_without_weakening_queries(): void
|
||||
{
|
||||
Schema::table('portal_resources', fn ($table) => $table->dropColumn('rights_status'));
|
||||
|
||||
$this->assertSame(1, Artisan::call('portal:check-document-library-schema'));
|
||||
$this->assertStringContainsString('portal_resources.rights_status', Artisan::output());
|
||||
$this->assertStringNotContainsString('documents.malware_scan_status', Artisan::output());
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,14 @@ class EducationTest extends TestCase
|
||||
|
||||
private function declaration(): array
|
||||
{
|
||||
$country = (string) Str::uuid();
|
||||
$province = (string) Str::uuid();
|
||||
$territory = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $territory, 'name' => 'Território sintético', 'code' => $territory, 'location_type' => 'district']);
|
||||
DB::table('geo_locations')->insert(['id' => $country, 'name' => 'País sintético', 'code' => $country, 'location_type' => 'country']);
|
||||
DB::table('geo_locations')->insert(['id' => $province, 'name' => 'Província sintética', 'code' => $province,
|
||||
'location_type' => 'province', 'parent_id' => $country]);
|
||||
DB::table('geo_locations')->insert(['id' => $territory, 'name' => 'Distrito sintético', 'code' => $territory,
|
||||
'location_type' => 'district', 'parent_id' => $province]);
|
||||
|
||||
return [
|
||||
'project_id' => Project::create(['code' => (string) Str::uuid(), 'name' => 'Projecto sintético', 'status' => 'draft'])->id,
|
||||
@@ -68,7 +74,7 @@ class EducationTest extends TestCase
|
||||
|
||||
public function test_educational_proposal_requires_review_and_is_a_single_unpublished_canonical_opportunity(): void
|
||||
{
|
||||
$this->manager();
|
||||
$manager = $this->manager();
|
||||
$demandData = $this->declaration();
|
||||
$this->post('/management/education/demands', $demandData)->assertSessionHasNoErrors();
|
||||
$demand = LabourDemand::where('project_id', $demandData['project_id'])->firstOrFail();
|
||||
@@ -76,6 +82,8 @@ class EducationTest extends TestCase
|
||||
$data = ['demand_version' => 1, 'sector_id' => $sector->id, 'title' => 'Oficina sintética',
|
||||
'intervention' => 'Resposta formativa sintética para verificação do fluxo.', 'risks' => 'Custos e viabilidade por confirmar.',
|
||||
'source' => 'Fonte sintética identificada no teste.', 'currency' => 'MZN'];
|
||||
$data['district_id'] = $demandData['geo_location_id'];
|
||||
$data['province_id'] = DB::table('geo_locations')->where('id', $demandData['geo_location_id'])->value('parent_id');
|
||||
$url = '/management/education/demands/'.$demand->id.'/investment';
|
||||
$this->post($url, $data)->assertUnprocessable();
|
||||
$this->manager();
|
||||
@@ -121,6 +129,33 @@ class EducationTest extends TestCase
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_provider_and_course_catalogues_follow_documented_capacity_territory(): void
|
||||
{
|
||||
$manager = $this->manager();
|
||||
$first = $this->declaration();
|
||||
$firstCourse = $this->course();
|
||||
$capacity = $first;
|
||||
unset($capacity['project_id'], $capacity['employer']);
|
||||
TrainingCapacity::create([...$capacity, 'course_id' => $firstCourse->id, 'submitted_by' => $manager->id]);
|
||||
|
||||
$otherProvince = (string) Str::uuid();
|
||||
$otherDistrict = (string) Str::uuid();
|
||||
$country = DB::table('geo_locations')->where('id', $first['geo_location_id'])->value('parent_id');
|
||||
$country = DB::table('geo_locations')->where('id', $country)->value('parent_id');
|
||||
DB::table('geo_locations')->insert(['id' => $otherProvince, 'name' => 'Província de teste B', 'code' => $otherProvince,
|
||||
'location_type' => 'province', 'parent_id' => $country]);
|
||||
DB::table('geo_locations')->insert(['id' => $otherDistrict, 'name' => 'Distrito de teste B', 'code' => $otherDistrict,
|
||||
'location_type' => 'district', 'parent_id' => $otherProvince]);
|
||||
$otherCourse = $this->course();
|
||||
TrainingCapacity::create([...$capacity, 'geo_location_id' => $otherDistrict, 'course_id' => $otherCourse->id, 'submitted_by' => $manager->id]);
|
||||
|
||||
$this->get('/management/education?geo_location_id='.$first['geo_location_id'])
|
||||
->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('filters.geo_location_id', $first['geo_location_id'])
|
||||
->has('providers', 1)->where('providers.0.id', $firstCourse->provider_id)
|
||||
->has('courses', 1)->where('courses.0.id', $firstCourse->id));
|
||||
}
|
||||
|
||||
public function test_access_requires_verified_manager_and_enabled_feature(): void
|
||||
{
|
||||
$this->get('/management/education')->assertRedirect('/login');
|
||||
@@ -150,6 +185,12 @@ class EducationTest extends TestCase
|
||||
$this->assertStringNotContainsString($data['source'], $audit->after_data);
|
||||
$this->post('/management/education/demands', [...$data, 'quantity' => -1])->assertSessionHasErrors('quantity');
|
||||
$this->post('/management/education/demands', [...$data, 'period_end' => now()->toDateString()])->assertSessionHasErrors('period_end');
|
||||
$country = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert([
|
||||
'id' => $country, 'name' => 'País fora do escopo', 'code' => $country, 'location_type' => 'country',
|
||||
]);
|
||||
$this->post('/management/education/demands', [...$data, 'geo_location_id' => $country])
|
||||
->assertSessionHasErrors('geo_location_id');
|
||||
Skill::findOrFail($data['skill_id'])->delete();
|
||||
$this->post('/management/education/demands', $data)->assertSessionHasErrors('skill_id');
|
||||
}
|
||||
|
||||
@@ -88,10 +88,16 @@ class ExistingBusinessFoundationTest extends TestCase
|
||||
{
|
||||
$migration = require database_path('migrations/2026_09_28_130000_existing_business_foundation.php');
|
||||
$intake = require database_path('migrations/2026_09_28_140000_existing_business_intake.php');
|
||||
$marketplace = require database_path('migrations/2026_09_30_120000_extend_existing_business_marketplace.php');
|
||||
$draftContinuity = require database_path('migrations/2026_10_04_120000_add_simulation_draft_continuity.php');
|
||||
$draftContinuity->down();
|
||||
$marketplace->down();
|
||||
$intake->down();
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
$intake->up();
|
||||
$marketplace->up();
|
||||
$draftContinuity->up();
|
||||
app(ExistingBusinessDrafts::class)->save(User::factory()->create(), $this->draft());
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('destructive rollback refused');
|
||||
|
||||
@@ -6,12 +6,26 @@ use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ExistingBusinessWizardTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function publicLocation(string $type, ?string $parent = null): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert([
|
||||
'id' => $id, 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id,
|
||||
'version_no' => 1, 'data_classification' => 'public', 'name' => 'Synthetic '.$type.' '.$id,
|
||||
'location_type' => $type, 'parent_id' => $parent, 'code' => $id,
|
||||
]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_sector_migration_reverses_empty_and_refuses_data_loss(): void
|
||||
{
|
||||
$migration = require database_path('migrations/2026_09_29_200000_existing_business_form_sector.php');
|
||||
@@ -58,7 +72,8 @@ class ExistingBusinessWizardTest extends TestCase
|
||||
$this->putJson($url, [...$save, 'version_no' => 3, 'payload' => $payload, 'modality' => 'real_estate'])->assertOk();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 4])->assertUnprocessable()->assertJsonValidationErrors('objects');
|
||||
$this->putJson($url, [...$save, 'version_no' => 4, 'payload' => $payload])->assertOk();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 5, 'confirmation_code' => 'wrong'])->assertUnprocessable();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 5, 'confirmation_code' => 'wrong'])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('confirmation_code');
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 5])->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 5])->assertConflict();
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertForbidden();
|
||||
@@ -66,4 +81,87 @@ class ExistingBusinessWizardTest extends TestCase
|
||||
$raw = DB::table('existing_businesses')->where('id', $record['id'])->value('payload');
|
||||
$this->assertStringNotContainsString('synthetic@example.test', $raw);
|
||||
}
|
||||
|
||||
public function test_multiple_locations_require_distinct_public_paths_from_the_same_hierarchy(): void
|
||||
{
|
||||
config(['existing-business.enabled' => true]);
|
||||
$owner = User::factory()->create();
|
||||
$sector = DB::table('sectors')->insertGetId(['name' => 'Synthetic locations', 'slug' => 'synthetic-locations', 'is_active' => true]);
|
||||
$country = $this->publicLocation('country');
|
||||
$provinceA = $this->publicLocation('province', $country);
|
||||
$provinceB = $this->publicLocation('province', $country);
|
||||
$districtA = $this->publicLocation('district', $provinceA);
|
||||
$districtB = $this->publicLocation('district', $provinceB);
|
||||
$this->actingAs($owner);
|
||||
|
||||
$payload = [
|
||||
'title' => 'Synthetic multiple-location opportunity', 'wizard_version' => '2', 'wizard_step' => '8',
|
||||
'proponent_type' => 'organization', 'proponent_name' => 'Synthetic proponent', 'country' => 'MZ',
|
||||
'contact_name' => 'Synthetic contact', 'contact_email' => 'locations@example.test',
|
||||
'acting_capacity' => 'holder', 'legitimacy_declaration' => 'yes',
|
||||
'opportunity_type' => 'company_sale',
|
||||
'description' => 'Synthetic description with sufficient detail for review.',
|
||||
'project_stage' => 'study', 'availability' => 'available', 'value_status' => 'unknown',
|
||||
'geography_scope' => 'multiple', 'source_reference' => 'Synthetic source reference',
|
||||
'source_provider' => 'Synthetic information provider', 'source_date' => today()->toDateString(),
|
||||
'asset_deal_kind' => 'whole_business', 'confirm_information' => 'yes',
|
||||
'confirm_disclosure_authority' => 'yes', 'confirm_no_publication_guarantee' => 'yes',
|
||||
'locations_json' => json_encode([['province_id' => $provinceA]], JSON_THROW_ON_ERROR),
|
||||
];
|
||||
$id = $this->postJson('/api/v1/existing-business/listings', [
|
||||
'modality' => 'company_sale', 'classification' => 'confidential', 'reason' => 'Synthetic multiple-location draft',
|
||||
'sector_id' => $sector, 'payload' => $payload,
|
||||
])->assertCreated()->json('id');
|
||||
$url = '/api/v1/existing-business/listings/'.$id;
|
||||
$transition = ['action' => 'submitted', 'version_no' => 1, 'note' => 'Synthetic multiple-location submission',
|
||||
'review_consent' => true, 'confirmation_code' => DB::table('existing_businesses')->where('id', $id)->value('code')];
|
||||
|
||||
$this->postJson($url.'/transitions', $transition)->assertUnprocessable()->assertJsonValidationErrors('locations');
|
||||
$overlapping = [
|
||||
['province_id' => $provinceA],
|
||||
['province_id' => $provinceA, 'district_id' => $districtA],
|
||||
];
|
||||
$this->putJson($url, ['modality' => 'company_sale', 'classification' => 'confidential',
|
||||
'reason' => 'Synthetic overlapping location update', 'version_no' => 1, 'sector_id' => $sector,
|
||||
'payload' => [...$payload, 'locations_json' => json_encode($overlapping, JSON_THROW_ON_ERROR)]])->assertOk();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 2])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('locations_json');
|
||||
|
||||
$wrongParent = [
|
||||
['province_id' => $provinceA, 'district_id' => $districtA],
|
||||
['province_id' => $provinceA, 'district_id' => $districtB],
|
||||
];
|
||||
$this->putJson($url, ['modality' => 'company_sale', 'classification' => 'confidential',
|
||||
'reason' => 'Synthetic invalid hierarchy update', 'version_no' => 2, 'sector_id' => $sector,
|
||||
'payload' => [...$payload, 'locations_json' => json_encode($wrongParent, JSON_THROW_ON_ERROR)]])->assertOk();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 3])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('district_id');
|
||||
|
||||
$valid = [
|
||||
['province_id' => $provinceA, 'district_id' => $districtA],
|
||||
['province_id' => $provinceB, 'district_id' => $districtB],
|
||||
];
|
||||
$this->putJson($url, ['modality' => 'company_sale', 'classification' => 'confidential',
|
||||
'reason' => 'Synthetic distinct location update', 'version_no' => 3, 'sector_id' => $sector,
|
||||
'payload' => [...$payload, 'locations_json' => json_encode($valid, JSON_THROW_ON_ERROR)]])->assertOk();
|
||||
$this->postJson($url.'/transitions', [...$transition, 'version_no' => 4])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('record.payload.locations_json', json_encode($valid, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function test_public_territory_search_matches_names_with_or_without_accents(): void
|
||||
{
|
||||
$country = $this->publicLocation('country');
|
||||
$province = $this->publicLocation('province', $country);
|
||||
DB::table('geo_locations')->where('id', $province)->update([
|
||||
'name' => 'Província de Mapúto', 'code' => 'MPT-ACCENT',
|
||||
]);
|
||||
|
||||
$this->getJson('/api/v1/investment/territory-options?type=province&q=maputo')
|
||||
->assertOk()->assertJsonPath('data.0.id', $province);
|
||||
$this->getJson('/api/v1/investment/territory-options?type=province&q=provincia')
|
||||
->assertOk()->assertJsonPath('data.0.id', $province);
|
||||
$this->getJson('/api/v1/investment/territory-options?type=province&q=Mapúto')
|
||||
->assertOk()->assertJsonPath('data.0.id', $province);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ImportLegalSourceArchiveTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->app->bind(MalwareScanner::class, fn () => new class implements MalwareScanner
|
||||
{
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
return ['result' => 'clean', 'reason_code' => null, 'engine' => 'ClamAV-Test-Double', 'engine_version' => 'fixture',
|
||||
'signatures_at' => new \DateTimeImmutable('2026-10-06T00:00:00Z'), 'duration_ms' => 1, 'detail' => null];
|
||||
}
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
return ['available' => true, 'engine' => 'ClamAV-Test-Double', 'engine_version' => 'fixture',
|
||||
'signatures_at' => new \DateTimeImmutable('2026-10-06T00:00:00Z'), 'signature_age_hours' => 0.0, 'reason_code' => null];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function test_preview_has_no_storage_or_database_side_effects(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
|
||||
$this->artisan('documents:import-legal-source-archive')->assertSuccessful();
|
||||
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
$this->assertDatabaseCount('portal_resources', 0);
|
||||
$this->assertDatabaseCount('portal_resource_links', 0);
|
||||
$this->assertSame([], Storage::disk('local')->allFiles('portal-documents'));
|
||||
}
|
||||
|
||||
public function test_import_creates_private_unapproved_records_and_reimport_does_not_duplicate(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
|
||||
$this->artisan('documents:import-legal-source-archive', ['--apply' => true])->assertSuccessful();
|
||||
|
||||
$expectedResources = file_exists(storage_path('app/private/geo-ine-source-20260928/original.pdf')) ? 4 : 3;
|
||||
$this->assertDatabaseCount('documents', $expectedResources);
|
||||
$this->assertDatabaseCount('portal_resources', $expectedResources);
|
||||
$this->assertDatabaseCount('portal_resource_links', 19);
|
||||
$this->assertDatabaseCount('portal_resource_links', 8, ['target_type' => 'requirement']);
|
||||
$this->assertDatabaseCount('portal_resource_revisions', $expectedResources);
|
||||
$this->assertCount($expectedResources, Storage::disk('local')->allFiles('portal-documents'));
|
||||
$this->assertSame($expectedResources, DB::table('documents')->where('source_system', 'legal-source-archive')
|
||||
->where('status', 'active')->where('data_classification', 'internal')->where('rights_status', 'unconfirmed')
|
||||
->where('malware_scan_status', 'clean')->whereColumn('sha256', 'malware_scanned_sha256')->count());
|
||||
$this->assertDatabaseHas('portal_resources', ['published' => false, 'approved_by' => null, 'rights_status' => 'unconfirmed']);
|
||||
$this->assertDatabaseHas('portal_resource_links', [
|
||||
'target_type' => 'module', 'target_key' => 'simulator', 'applicability' => 'evidence',
|
||||
]);
|
||||
$this->assertDatabaseHas('portal_resources', [
|
||||
'document_number' => 'Lei n.º 22/2022', 'source_confirmation' => 'official_confirmed', 'legal_status' => 'amended',
|
||||
]);
|
||||
$this->assertDatabaseHas('portal_resources', [
|
||||
'document_number' => 'BR n.º 89/2017', 'source_confirmation' => 'identified', 'legal_status' => 'unknown',
|
||||
]);
|
||||
$this->assertDatabaseHas('portal_resource_links', [
|
||||
'target_type' => 'requirement', 'target_key' => 'fiscal.iva.lei_22_2022', 'review_status' => 'confirmed',
|
||||
]);
|
||||
$this->assertDatabaseHas('portal_resource_links', [
|
||||
'target_type' => 'theme', 'target_key' => 'iva', 'review_status' => 'pending',
|
||||
]);
|
||||
$this->assertDatabaseHas('portal_resource_links', [
|
||||
'target_type' => 'requirement', 'target_key' => 'fiscal.iva.lei_13_2016_rectification_2017', 'review_status' => 'pending',
|
||||
]);
|
||||
if ($expectedResources === 4) {
|
||||
$this->assertDatabaseHas('portal_resources', [
|
||||
'document_number' => 'Codificador DPA 2012', 'document_type' => 'reference_data', 'legislation' => false,
|
||||
'source_confirmation' => 'official_confirmed', 'rights_status' => 'unconfirmed', 'published' => false,
|
||||
]);
|
||||
}
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
$this->get('/documentos/'.DB::table('portal_resources')->value('id').'/download')->assertNotFound();
|
||||
|
||||
$this->artisan('documents:import-legal-source-archive', ['--apply' => true])->assertSuccessful();
|
||||
|
||||
$this->assertDatabaseCount('documents', $expectedResources);
|
||||
$this->assertDatabaseCount('portal_resources', $expectedResources);
|
||||
$this->assertDatabaseCount('portal_resource_links', 19);
|
||||
$this->assertDatabaseCount('portal_resource_links', 8, ['target_type' => 'requirement']);
|
||||
$this->assertDatabaseCount('portal_resource_revisions', $expectedResources);
|
||||
$this->assertCount($expectedResources, Storage::disk('local')->allFiles('portal-documents'));
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,8 @@ class InvestmentPortfolioTest extends TestCase
|
||||
{
|
||||
$this->seed(InvestmentPortfolioSeeder::class);
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$reviewer = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email, $reviewer->email]]);
|
||||
$dossier = InvestmentDossier::firstOrFail();
|
||||
$url = '/management/portfolio/'.$dossier->id;
|
||||
$payload = ['version_no' => $dossier->version_no, 'title' => 'Revisao mais recente', 'source' => $dossier->source, 'content' => $dossier->content];
|
||||
@@ -50,7 +51,8 @@ class InvestmentPortfolioTest extends TestCase
|
||||
$this->assertSame('Revisao mais recente', $dossier->fresh()->title);
|
||||
$this->assertSame('draft', $dossier->fresh()->publication_status);
|
||||
$this->assertSame(2, $dossier->fresh()->version_no);
|
||||
$this->post($url.'/publish', [...$approval, 'version_no' => 2])->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->post($url.'/publish', [...$approval, 'version_no' => 2])->assertForbidden();
|
||||
$this->actingAs($reviewer)->post($url.'/publish', [...$approval, 'version_no' => 2])->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->assertSame(3, $dossier->fresh()->version_no);
|
||||
$this->assertSame('published', $dossier->fresh()->publication_status);
|
||||
$this->postJson($url.'/publish', [...$approval, 'version_no' => 2])->assertStatus(409);
|
||||
@@ -71,9 +73,9 @@ class InvestmentPortfolioTest extends TestCase
|
||||
$this->actingAs($editor)->put('/management/portfolio/'.$dossier->id,
|
||||
['version_no' => $dossier->version_no, 'title' => $dossier->title, 'source' => $dossier->source, 'content' => $dossier->content])->assertSessionHasNoErrors();
|
||||
$evidence = ['approval_evidence' => 'Autorização fictícia apenas para teste'];
|
||||
$this->post('/management/portfolio/'.$dossier->id.'/publish', [...$evidence, 'version_no' => $dossier->fresh()->version_no])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->assertSame($editor->id, $dossier->fresh()->reviewer_id);
|
||||
$this->post('/management/portfolio/'.$dossier->id.'/publish', [...$evidence, 'version_no' => $dossier->fresh()->version_no])->assertForbidden();
|
||||
$this->actingAs($reviewer)->post('/management/portfolio/'.$dossier->id.'/publish', [...$evidence, 'version_no' => $dossier->fresh()->version_no])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->assertSame($reviewer->id, $dossier->fresh()->reviewer_id);
|
||||
|
||||
return $dossier->fresh();
|
||||
}
|
||||
@@ -89,23 +91,28 @@ class InvestmentPortfolioTest extends TestCase
|
||||
$this->post('/management/portfolio/'.$dossier->id.'/publish', ['approval_evidence' => 'Tentativa sem privilégios de gestão'])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_owner_approval_publishes_document_once_and_preserves_later_edits(): void
|
||||
public function test_import_keeps_documentary_dossiers_private_and_preserves_later_edits(): void
|
||||
{
|
||||
$approval = 'Aprovação expressa do proprietário para executar a carteira v4.';
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->assertSame(29, InvestmentDossier::where('publication_status', 'published')->count());
|
||||
$this->assertSame(29, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$this->artisan('portfolio:import')->assertSuccessful();
|
||||
$this->assertSame(0, InvestmentDossier::where('publication_status', 'published')->count());
|
||||
$this->assertSame(29, InvestmentDossier::where('publication_status', 'draft')->count());
|
||||
$this->assertSame(0, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$dossier = InvestmentDossier::firstOrFail();
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (Assert $page) => $page
|
||||
->missing('record.approval_evidence')->missing('record.approval_basis'));
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->assertSame(29, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portfolio/'.$dossier->id.'/publish', [
|
||||
'version_no' => $dossier->version_no, 'approval_evidence' => 'Synthetic owner approval is not an editor assignment',
|
||||
])->assertStatus(422);
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
$this->artisan('portfolio:import')->assertSuccessful();
|
||||
$this->assertSame(0, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$this->actingAs($editor)->put('/management/portfolio/'.$dossier->id, [
|
||||
'version_no' => $dossier->version_no, 'title' => 'Alteração posterior', 'source' => $dossier->source, 'content' => $dossier->content,
|
||||
])->assertSessionHasNoErrors();
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->artisan('portfolio:import')->assertSuccessful();
|
||||
$this->assertSame('draft', $dossier->fresh()->publication_status);
|
||||
$this->assertSame('Alteração posterior', $dossier->fresh()->title);
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
@@ -147,6 +154,36 @@ class InvestmentPortfolioTest extends TestCase
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
}
|
||||
|
||||
public function test_private_manifestation_link_requires_authentication_and_preserves_the_public_dossier(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
$this->app['auth']->forgetGuards();
|
||||
$dossierId = $dossier->id;
|
||||
$owner = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
|
||||
$this->postJson('/api/v1/investment/submissions', ['dossier_id' => $dossierId])->assertUnauthorized();
|
||||
$this->assertDatabaseCount('investment_submissions', 0);
|
||||
|
||||
$this->actingAs($owner)->get('/carteira/'.$dossierId)
|
||||
->assertInertia(fn (Assert $page) => $page->component('portfolio/show')->has('existingSubmissions', 0));
|
||||
$submissionId = $this->postJson('/api/v1/investment/submissions', ['dossier_id' => $dossierId])
|
||||
->assertCreated()->json('id');
|
||||
|
||||
$this->assertDatabaseHas('investment_submissions', [
|
||||
'id' => $submissionId,
|
||||
'user_id' => $owner->id,
|
||||
'dossier_id' => $dossierId,
|
||||
'status' => 'draft',
|
||||
]);
|
||||
$this->assertSame('published', $dossier->fresh()->publication_status);
|
||||
$this->actingAs($owner)->get('/carteira/'.$dossierId)
|
||||
->assertInertia(fn (Assert $page) => $page->has('existingSubmissions', 1)->where('existingSubmissions.0.id', $submissionId));
|
||||
$this->actingAs($other)->get('/investidor/manifestacoes/'.$submissionId)->assertNotFound();
|
||||
$this->assertDatabaseCount('investment_submissions', 1);
|
||||
$this->assertDatabaseCount('investment_dossiers', 29);
|
||||
}
|
||||
|
||||
public function test_unpublished_and_deleted_entities_cannot_start_journeys(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
@@ -163,6 +200,11 @@ class InvestmentPortfolioTest extends TestCase
|
||||
$origin = InvestmentDossier::where('corridor_id', $corridorId)->firstOrFail();
|
||||
$origin->update(['editor_id' => $project->editor_id, 'reviewer_id' => $project->reviewer_id,
|
||||
'publication_status' => 'published', 'published_at' => now(), 'approval_evidence' => 'Teste de contexto autorizado']);
|
||||
$this->actingAs(User::factory()->create())->post('/investidor/guardar/'.$project->id, ['origin_id' => $origin->id])->assertStatus(422);
|
||||
DB::table('corridor_projects')->where('project_id', $project->project_id)->where('corridor_id', $corridorId)->update([
|
||||
'validation_status' => 'validated', 'source_reference' => 'Fixture de teste com fonte identificada',
|
||||
'evidence_reference' => 'fixture:test:association', 'valid_from' => today()->toDateString(),
|
||||
]);
|
||||
$other = InvestmentDossier::whereNotNull('project_id')->where('id', '!=', $project->id)->firstOrFail();
|
||||
$other->update(['editor_id' => $project->editor_id, 'reviewer_id' => $project->reviewer_id,
|
||||
'publication_status' => 'published', 'published_at' => now(), 'approval_evidence' => 'Teste de contexto autorizado']);
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\DevelopmentCorridor;
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\Project;
|
||||
use App\Models\User;
|
||||
use App\Models\ValueChain;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentStructureTest extends TestCase
|
||||
@@ -47,11 +49,16 @@ class InvestmentStructureTest extends TestCase
|
||||
$cluster = EconomicCluster::firstOrFail();
|
||||
$project = Project::factory()->create();
|
||||
$url = '/management/clusters/'.$cluster->id.'/projects';
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasNoErrors();
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasNoErrors();
|
||||
$association = ['project_id' => $project->id, 'version_no' => 0, 'role' => 'anchor', 'association_type' => 'potential',
|
||||
'source_reference' => 'Referencia de planeamento sintético', 'evidence_reference' => 'fixture:test:cluster-link',
|
||||
'valid_from' => today()->toDateString()];
|
||||
$this->post($url, $association)->assertSessionHasNoErrors();
|
||||
$this->post($url, $association)->assertStatus(409);
|
||||
$this->assertDatabaseCount('cluster_projects', 1);
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'supporting'])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('cluster_projects', ['project_id' => $project->id, 'role' => 'supporting']);
|
||||
$this->post($url, [...$association, 'version_no' => 1])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('cluster_projects', ['project_id' => $project->id, 'version_no' => 1]);
|
||||
$this->post($url, [...$association, 'version_no' => 1, 'role' => 'supporting'])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('cluster_projects', ['project_id' => $project->id, 'role' => 'supporting', 'version_no' => 2, 'validation_status' => 'pending']);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('entity_type', 'cluster_projects')->count());
|
||||
$project->delete();
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasErrors('project_id');
|
||||
@@ -80,6 +87,52 @@ class InvestmentStructureTest extends TestCase
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->get('/management/projects')->assertForbidden();
|
||||
$this->post('/management/clusters', [])->assertForbidden();
|
||||
$this->get('/management/corridors')->assertForbidden();
|
||||
$this->post('/management/corridors', [])->assertForbidden();
|
||||
$this->assertDatabaseCount('economic_clusters', 0);
|
||||
$this->assertDatabaseCount('development_corridors', 0);
|
||||
}
|
||||
|
||||
public function test_development_corridors_have_private_crud_with_supported_fields_and_statuses(): void
|
||||
{
|
||||
$this->manager();
|
||||
$data = ['code' => 'COR-TEST', 'name' => 'Corredor de teste', 'status' => 'proposed',
|
||||
'description' => 'Descrição sintética para validar o cadastro administrativo.'];
|
||||
$this->post('/management/corridors', $data)->assertSessionHasNoErrors()->assertRedirect();
|
||||
|
||||
$corridor = DevelopmentCorridor::firstOrFail();
|
||||
$this->assertSame('internal', $corridor->data_classification);
|
||||
$this->assertDatabaseHas('development_corridors', ['id' => $corridor->id, 'status' => 'proposed']);
|
||||
$this->get('/management/corridors')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->component('structures/index')->where('structure', 'corridors')->has('records.data', 1));
|
||||
$this->get('/management/corridors/'.$corridor->id.'/edit')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->component('structures/editor')->where('structure', 'corridors')->where('record.id', $corridor->id));
|
||||
|
||||
$this->put('/management/corridors/'.$corridor->id, [...$data, 'status' => 'active', 'description' => 'Descrição actualizada.'])
|
||||
->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('development_corridors', ['id' => $corridor->id, 'status' => 'active', 'description' => 'Descrição actualizada.']);
|
||||
}
|
||||
|
||||
public function test_structure_relations_require_sources_and_independent_review(): void
|
||||
{
|
||||
$editor = User::factory()->create();
|
||||
$reviewer = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email, $reviewer->email]]);
|
||||
$cluster = EconomicCluster::create(['code' => 'REL-C1', 'name' => 'Cluster relacional', 'sector' => 'Energia', 'status' => 'planned']);
|
||||
$project = Project::factory()->create();
|
||||
$url = '/management/structure-relations/cluster-project';
|
||||
$payload = ['cluster_id' => $cluster->id, 'project_id' => $project->id, 'role' => 'anchor',
|
||||
'association_type' => 'official', 'source_reference' => 'Diploma oficial, artigo 4, secao 2',
|
||||
'evidence_reference' => 'fixture:test:evidence-01', 'valid_from' => today()->toDateString()];
|
||||
|
||||
$this->actingAs($editor)->post($url, [...$payload, 'source_reference' => 'curta'])->assertSessionHasErrors('source_reference');
|
||||
$this->post($url, $payload)->assertSessionHasNoErrors();
|
||||
$relation = DB::table('cluster_projects')->where('cluster_id', $cluster->id)->where('project_id', $project->id)->first();
|
||||
$this->assertSame('pending', $relation->validation_status);
|
||||
$this->assertSame($editor->id, $relation->editor_id);
|
||||
$this->post('/management/structure-relations/cluster-project/'.$relation->id.'/validate', ['version_no' => 1])->assertForbidden();
|
||||
$this->actingAs($reviewer)->post('/management/structure-relations/cluster-project/'.$relation->id.'/validate', ['version_no' => 1])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('cluster_projects', ['id' => $relation->id, 'validation_status' => 'validated', 'validator_id' => $reviewer->id, 'version_no' => 2]);
|
||||
$this->post('/management/structure-relations/cluster-project/'.$relation->id.'/revoke', ['version_no' => 1])->assertStatus(409);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentCatalogue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use Database\Seeders\InvestmentAreaSeeder;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
@@ -25,7 +28,10 @@ class InvestmentTerritoryTest extends TestCase
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$sector = Sector::create(['name' => 'Synthetic map', 'slug' => 'synthetic-map', 'is_active' => true]);
|
||||
$record = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'MAP-COORD', 'slug' => 'map-coord', 'title' => 'Synthetic marker', 'status' => 'published', 'published_at' => now()->subMinute()]);
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('matched_count', 1)->assertJsonPath('complete', false)->assertJsonCount(1, 'unlocated');
|
||||
$this->getJson('/api/v1/investment/search')->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $record->id);
|
||||
$this->get('/oportunidades')->assertInertia(fn (AssertableInertia $page) => $page->where('results.total', 1)->where('results.data.0.id', $record->id));
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('matched_count', 1)
|
||||
->assertJsonPath('georeferenced_count', 0)->assertJsonPath('complete', false)->assertJsonCount(1, 'unlocated');
|
||||
$this->actingAs($manager);
|
||||
$url = '/management/opportunities/'.$record->id.'/coordinates';
|
||||
$payload = ['version' => 0, 'latitude' => -25.9, 'longitude' => 32.5, 'source_reference' => 'Synthetic coordinates for automated tests only', 'confirmed_site' => true];
|
||||
@@ -33,9 +39,16 @@ class InvestmentTerritoryTest extends TestCase
|
||||
$this->postJson($url, [...$payload, 'confirmed_site' => false])->assertUnprocessable();
|
||||
$this->postJson($url, $payload)->assertOk()->assertJsonPath('version', 1);
|
||||
$this->postJson($url, $payload)->assertConflict();
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('complete', true)->assertJsonPath('features.0.properties.id', $record->id)->assertJsonPath('features.0.geometry.coordinates.0', 32.5);
|
||||
$this->getJson('/api/v1/investment/search')->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $record->id);
|
||||
$this->get('/oportunidades')->assertInertia(fn (AssertableInertia $page) => $page->where('results.total', 1)->where('results.data.0.id', $record->id));
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('matched_count', 1)
|
||||
->assertJsonPath('georeferenced_count', 1)->assertJsonPath('complete', true)
|
||||
->assertJsonPath('features.0.properties.id', $record->id)->assertJsonPath('features.0.geometry.coordinates.0', 32.5);
|
||||
$record->update(['status' => 'draft']);
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonCount(0, 'features')->assertJsonCount(0, 'unlocated');
|
||||
$this->getJson('/api/v1/investment/search')->assertOk()->assertJsonPath('total', 0)->assertJsonCount(0, 'data');
|
||||
$this->get('/oportunidades')->assertInertia(fn (AssertableInertia $page) => $page->where('results.total', 0)->has('results.data', 0));
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonPath('matched_count', 0)->assertJsonPath('complete', true)
|
||||
->assertJsonCount(0, 'features')->assertJsonCount(0, 'unlocated');
|
||||
}
|
||||
|
||||
public function test_public_cascade_filters_saved_locations_and_hides_unapproved_references(): void
|
||||
@@ -78,6 +91,126 @@ class InvestmentTerritoryTest extends TestCase
|
||||
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$province)->assertOk()->assertJsonCount(0, 'data');
|
||||
}
|
||||
|
||||
public function test_opportunities_match_hierarchical_and_multiple_public_locations_without_expanding(): void
|
||||
{
|
||||
$country = $this->location('country');
|
||||
$provinceA = $this->location('province', $country);
|
||||
$districtA = $this->location('district', $provinceA);
|
||||
$postA = $this->location('admin_post', $districtA);
|
||||
$localityA = $this->location('locality', $postA);
|
||||
$provinceB = $this->location('province', $country);
|
||||
$districtB = $this->location('district', $provinceB);
|
||||
$postB = $this->location('admin_post', $districtB);
|
||||
$localityB = $this->location('locality', $postB);
|
||||
$ids = [$country, $provinceA, $districtA, $postA, $localityA, $provinceB, $districtB, $postB, $localityB];
|
||||
foreach ($ids as $id) {
|
||||
DB::table('geo_locations')->where('id', $id)->update([
|
||||
'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id,
|
||||
'data_classification' => 'public',
|
||||
]);
|
||||
}
|
||||
$sector = Sector::create(['name' => 'Territorial test', 'slug' => 'territorial-test', 'is_active' => true]);
|
||||
$make = function (string $code, ?string $primary, string $scope = 'specific') use ($sector): Opportunity {
|
||||
return Opportunity::create(['sector_id' => $sector->id, 'reference' => $code, 'slug' => strtolower($code), 'title' => $code,
|
||||
'status' => 'published', 'published_at' => now()->subMinute(), 'primary_territory_id' => $primary, 'geography_scope' => $scope]);
|
||||
};
|
||||
$a = $make('AREA-A', $districtA);
|
||||
$a->update(['estimated_investment_amount' => '1234.50', 'estimated_investment_currency' => 'USD']);
|
||||
$multi = $make('AREA-MULTI', $localityB);
|
||||
DB::table('opportunity_locations')->insert(['opportunity_id' => $multi->id, 'geo_location_id' => $localityA]);
|
||||
$b = $make('AREA-B', $localityB);
|
||||
$national = $make('AREA-NATIONAL', null, 'national');
|
||||
$unlocated = $make('AREA-UNKNOWN', null, 'unspecified');
|
||||
|
||||
$service = app(InvestmentCatalogue::class);
|
||||
$this->assertEqualsCanonicalizing([$a->id, $multi->id], $service->query(['province_id' => $provinceA])->pluck('id')->all());
|
||||
$this->assertEqualsCanonicalizing([$a->id, $multi->id], $service->query(['province_id' => $provinceA, 'district_id' => $districtA])->pluck('id')->all());
|
||||
$this->assertEqualsCanonicalizing([$multi->id], $service->query(['province_id' => $provinceA, 'district_id' => $districtA,
|
||||
'admin_post_id' => $postA, 'locality_id' => $localityA])->pluck('id')->all());
|
||||
$this->assertEqualsCanonicalizing([$a->id, $multi->id, $national->id], $service->query(['province_id' => $provinceA, 'include_national' => true])->pluck('id')->all());
|
||||
$this->assertSame([], $service->query(['province_id' => $provinceB, 'sector' => 'no-such-sector'])->pluck('id')->all());
|
||||
$this->assertEqualsCanonicalizing([$a->id, $multi->id, $b->id, $unlocated->id], $service->query([])->pluck('id')->all());
|
||||
$this->assertSame(2, $service->query(['province_id' => $provinceA])->reorder()->count());
|
||||
$map = $this->getJson('/api/v1/investment/map?province_id='.$provinceA)->assertOk()->assertJsonPath('matched_count', 2);
|
||||
$this->assertEqualsCanonicalizing([$a->id, $multi->id], array_column($map->json('unlocated'), 'id'));
|
||||
$export = $this->get('/api/v1/investment/export?province_id='.$provinceA)->assertOk();
|
||||
$csv = $export->streamedContent();
|
||||
$this->assertStringContainsString('Referência;Título;', $csv);
|
||||
$this->assertStringContainsString('AREA-A', $csv);
|
||||
$this->assertStringContainsString('AREA-MULTI', $csv);
|
||||
$this->assertStringNotContainsString('AREA-B', $csv);
|
||||
$this->assertStringContainsString('1234.50', $csv);
|
||||
$this->get('/oportunidades?province_id='.$provinceA.'&page=1')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('results.total', 2)->has('results.data', 2)->where('filters.province_id', $provinceA));
|
||||
$this->getJson('/api/v1/investment/search?province_id='.$provinceA)->assertOk()->assertJsonPath('total', 2);
|
||||
$this->assertNotContains($national->id, $service->query(['province_id' => $provinceA])->pluck('id')->all());
|
||||
$this->assertNotContains($unlocated->id, $service->query(['province_id' => $provinceA])->pluck('id')->all());
|
||||
$this->assertNotContains($national->id, $service->query([])->pluck('id')->all());
|
||||
}
|
||||
|
||||
public function test_cluster_territory_uses_only_public_validated_project_links_and_project_locations(): void
|
||||
{
|
||||
$country = $this->location('country');
|
||||
$provinceA = $this->location('province', $country);
|
||||
$provinceB = $this->location('province', $country);
|
||||
foreach ([$country, $provinceA, $provinceB] as $id) {
|
||||
DB::table('geo_locations')->where('id', $id)->update([
|
||||
'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id,
|
||||
'data_classification' => 'public',
|
||||
]);
|
||||
}
|
||||
|
||||
$clusterIds = [];
|
||||
foreach ([['MATCH', $provinceA, 'validated'], ['PENDING', $provinceB, 'pending']] as [$code, $province, $status]) {
|
||||
$clusterId = (string) Str::uuid();
|
||||
$projectId = Project::create(['code' => 'TERR-'.$code, 'name' => 'Project '.$code, 'status' => 'active'])->id;
|
||||
DB::table('project_locations')->insert(['project_id' => $projectId, 'geo_location_id' => $province,
|
||||
'role' => 'primary', 'data_classification' => 'public']);
|
||||
DB::table('economic_clusters')->insert(['id' => $clusterId, 'code' => 'TERR-'.$code, 'name' => 'Cluster '.$code,
|
||||
'sector' => 'Teste', 'status' => 'active']);
|
||||
DB::table('cluster_projects')->insert(['cluster_id' => $clusterId, 'project_id' => $projectId, 'role' => 'anchor',
|
||||
'data_classification' => 'public', 'association_type' => 'potential', 'source_reference' => 'Fonte de teste para ligação territorial',
|
||||
'evidence_reference' => 'fixture:territory:'.$code, 'valid_from' => today()->toDateString(), 'validation_status' => $status]);
|
||||
InvestmentDossier::create(['cluster_id' => $clusterId, 'title' => 'Dossier '.$code, 'content' => '{}', 'source' => 'fixture de teste']);
|
||||
$clusterIds[] = $clusterId;
|
||||
}
|
||||
|
||||
$ids = app(InvestmentGeography::class)->descendants($provinceA);
|
||||
$matches = app(InvestmentGeography::class)->constrainDossiersToTerritories(InvestmentDossier::query(), $ids)
|
||||
->pluck('cluster_id')->all();
|
||||
$this->assertSame([$clusterIds[0]], $matches);
|
||||
}
|
||||
|
||||
public function test_opportunity_pagination_retains_the_selected_territory(): void
|
||||
{
|
||||
$country = $this->location('country');
|
||||
$province = $this->location('province', $country);
|
||||
foreach ([$country, $province] as $id) {
|
||||
DB::table('geo_locations')->where('id', $id)->update([
|
||||
'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id,
|
||||
'data_classification' => 'public',
|
||||
]);
|
||||
}
|
||||
$sector = Sector::create(['name' => 'Pagination area', 'slug' => 'pagination-area', 'is_active' => true]);
|
||||
$ids = [];
|
||||
for ($index = 1; $index <= 13; $index++) {
|
||||
$record = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'PAGE-'.$index,
|
||||
'slug' => 'page-'.$index, 'title' => 'Page opportunity '.$index, 'status' => 'published',
|
||||
'published_at' => now()->subMinute(), 'primary_territory_id' => $province, 'geography_scope' => 'specific']);
|
||||
$ids[] = $record->id;
|
||||
}
|
||||
|
||||
$this->get('/oportunidades?province_id='.$province.'&page=2')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('results.total', 13)->has('results.data', 1)->where('results.data.0.id', $ids[0])
|
||||
->where('filters.province_id', $province)
|
||||
->where('results.prev_page_url', fn ($url) => str_contains($url, 'province_id='.$province)));
|
||||
$this->getJson('/api/v1/investment/search?province_id='.$province.'&page=2')->assertOk()
|
||||
->assertJsonPath('total', 13)->assertJsonCount(1, 'data')->assertJsonPath('data.0.id', $ids[0]);
|
||||
}
|
||||
|
||||
public function test_cascade_assignment_persists_and_rejects_mismatched_parent_and_stale_write(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
@@ -146,9 +146,18 @@ class InvestmentUnificationTest extends TestCase
|
||||
|
||||
public function test_territorial_filters_intersect_and_hide_withdrawn_relations(): void
|
||||
{
|
||||
$this->artisan('portfolio:import', ['--approval' => 'Autorização sintética exclusivamente para teste.'])->assertSuccessful();
|
||||
$this->artisan('portfolio:import')->assertSuccessful();
|
||||
$clusters = InvestmentDossier::whereNotNull('cluster_id')->limit(2)->get();
|
||||
$corridor = InvestmentDossier::whereNotNull('corridor_id')->firstOrFail();
|
||||
// Explicitly published synthetic fixtures; import itself keeps all dossiers private.
|
||||
$editor = User::factory()->create();
|
||||
$reviewer = User::factory()->create();
|
||||
$publishFixture = fn (InvestmentDossier $dossier) => $dossier->update([
|
||||
'publication_status' => 'published', 'published_at' => now(), 'editor_id' => $editor->id,
|
||||
'reviewer_id' => $reviewer->id, 'approval_evidence' => 'Synthetic independent review fixture', 'approval_basis' => 'manager',
|
||||
]);
|
||||
$clusters->each($publishFixture);
|
||||
$publishFixture($corridor);
|
||||
$opportunity = $this->opportunity();
|
||||
foreach ($clusters as $cluster) {
|
||||
DB::table('opportunity_clusters')->insert(['opportunity_id' => $opportunity->id, 'cluster_id' => $cluster->cluster_id]);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentZoneAttachmentTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_upload_is_private_until_administrative_review_and_explicit_public_selection(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = $this->manager(true);
|
||||
$zoneId = $this->draft($manager);
|
||||
$response = $this->actingAs($manager)->post('/api/v2/investment/admin/zones/'.$zoneId.'/attachments', [
|
||||
'file' => UploadedFile::fake()->createWithContent('decreto.pdf', "%PDF-1.7\nconteudo sintetico de ensaio\n"),
|
||||
'kind' => 'legal_instrument', 'caption' => 'Diploma de ensaio', 'source_reference' => 'Arquivo oficial, referência sintética',
|
||||
'source_date' => '2026-01-01', 'rights_status' => 'pending', 'rights_basis' => '',
|
||||
], ['Accept' => 'application/json'])->assertCreated();
|
||||
$attachment = $response->json();
|
||||
|
||||
$this->assertSame('pending', $attachment['review_status']);
|
||||
$this->assertFalse($attachment['publicly_selected']);
|
||||
$this->assertSame($manager->id, $attachment['uploaded_by']);
|
||||
$document = DB::table('documents')->where('id', $attachment['document_id'])->first();
|
||||
$this->assertSame('active', $document->status);
|
||||
$this->assertSame('clean', $document->malware_scan_status);
|
||||
$this->assertSame($document->sha256, $document->malware_scanned_sha256);
|
||||
$this->assertSame('confidential', $document->data_classification);
|
||||
$this->assertDatabaseHas('investment_zone_attachment_events', ['attachment_id' => $attachment['id'], 'action' => 'uploaded']);
|
||||
$this->get('/zonas/'.$zoneId.'/anexos/'.$attachment['id'])->assertNotFound();
|
||||
$this->actingAs($manager)->get('/management/investment/zones/'.$zoneId.'/attachments/'.$attachment['id'])->assertOk();
|
||||
|
||||
$this->actingAs($manager)->postJson('/api/v2/investment/admin/zone-attachments/'.$attachment['id'].'/review', [
|
||||
'version_no' => 1, 'decision' => 'reviewed', 'rights_status' => 'confirmed', 'rights_basis' => 'Permissão documentada para o ensaio',
|
||||
'personal_data_status' => 'none',
|
||||
])->assertOk()->assertJsonPath('independent_review', false)->assertJsonPath('review_status', 'reviewed');
|
||||
$this->assertDatabaseHas('investment_zone_attachment_events', ['attachment_id' => $attachment['id'], 'action' => 'review']);
|
||||
|
||||
$this->makeVisibleWithoutOperator($zoneId, $manager);
|
||||
$this->actingAs($manager)->postJson('/api/v2/investment/admin/zone-attachments/'.$attachment['id'].'/select-public', ['version_no' => 2])->assertOk()->assertJsonPath('publicly_selected', true);
|
||||
$this->getJson('/api/v2/investment/zones/'.$zoneId)->assertOk()
|
||||
->assertJsonPath('attachments.0.caption', 'Diploma de ensaio')
|
||||
->assertJsonMissingPath('attachments.0.uploaded_by')
|
||||
->assertJsonMissingPath('attachments.0.rights_basis');
|
||||
$this->get('/zonas/'.$zoneId.'/anexos/'.$attachment['id'])->assertOk();
|
||||
|
||||
$this->actingAs($manager)->postJson('/api/v2/investment/admin/zone-attachments/'.$attachment['id'].'/withdraw-public', ['version_no' => 3])->assertOk()->assertJsonPath('publicly_selected', false);
|
||||
$this->get('/zonas/'.$zoneId.'/anexos/'.$attachment['id'])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_public_selection_rejects_unknown_rights_or_personal_data_and_invalid_file_content(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = $this->manager(true);
|
||||
$zoneId = $this->draft($manager);
|
||||
$this->actingAs($manager)->post('/api/v2/investment/admin/zones/'.$zoneId.'/attachments', [
|
||||
'file' => UploadedFile::fake()->createWithContent('bad.pdf', 'not a PDF document'),
|
||||
'kind' => 'study', 'caption' => 'Invalid test file', 'source_reference' => 'Synthetic test source', 'rights_status' => 'pending',
|
||||
], ['Accept' => 'application/json'])->assertUnprocessable();
|
||||
$this->actingAs($manager)->post('/api/v2/investment/admin/zones/'.$zoneId.'/attachments', [
|
||||
'file' => UploadedFile::fake()->create('large.pdf', 20481, 'application/pdf'),
|
||||
'kind' => 'study', 'caption' => 'Oversized test file', 'source_reference' => 'Synthetic test source', 'rights_status' => 'pending',
|
||||
], ['Accept' => 'application/json'])->assertUnprocessable();
|
||||
|
||||
$attachment = $this->actingAs($manager)->post('/api/v2/investment/admin/zones/'.$zoneId.'/attachments', [
|
||||
'file' => UploadedFile::fake()->createWithContent('study.pdf', "%PDF-1.7\nsynthetic test\n"),
|
||||
'kind' => 'study', 'caption' => 'Study under review', 'source_reference' => 'Synthetic test source', 'rights_status' => 'pending',
|
||||
], ['Accept' => 'application/json'])->assertCreated()->json();
|
||||
$this->actingAs($manager)->postJson('/api/v2/investment/admin/zone-attachments/'.$attachment['id'].'/review', [
|
||||
'version_no' => 1, 'decision' => 'reviewed', 'rights_status' => 'pending', 'personal_data_status' => 'unknown',
|
||||
])->assertOk()->assertJsonPath('review_status', 'reviewed')->assertJsonPath('independent_review', false);
|
||||
$this->makeVisibleWithoutOperator($zoneId, $manager);
|
||||
$this->actingAs($manager)->postJson('/api/v2/investment/admin/zone-attachments/'.$attachment['id'].'/select-public', ['version_no' => 2])->assertUnprocessable();
|
||||
$this->get('/zonas/'.$zoneId.'/anexos/'.$attachment['id'])->assertNotFound();
|
||||
}
|
||||
|
||||
private function manager(bool $publisher): User
|
||||
{
|
||||
$user = User::factory()->create(['email_verified_at' => now()]);
|
||||
$user->forceFill(['two_factor_secret' => Crypt::encryptString('synthetic-test-secret'), 'two_factor_confirmed_at' => now()])->save();
|
||||
config(['portal.managers' => [...config('portal.managers', []), $user->email]]);
|
||||
if ($publisher) {
|
||||
config(['investment-zones.publishers' => [...config('investment-zones.publishers', []), $user->email]]);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function draft(User $manager): string
|
||||
{
|
||||
return $this->actingAs($manager)->postJson('/api/v2/investment/admin/zones', [
|
||||
'code' => 'ATTACHMENT-TEST-'.Str::uuid(), 'category' => 'zee', 'physical_category' => 'economic_zone',
|
||||
'legal_regime' => 'zee', 'name' => 'Zona de ensaio', 'description' => 'Descrição de ensaio para anexo.',
|
||||
])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function makeVisibleWithoutOperator(string $zoneId, User $editor): void
|
||||
{
|
||||
$reviewer = $this->manager(false);
|
||||
$sourceId = (string) Str::uuid();
|
||||
DB::table('investment_legal_sources')->insert([
|
||||
'id' => $sourceId, 'title' => 'Fonte de ensaio', 'url' => 'https://example.test/zone-source', 'diploma' => 'Documento sintético',
|
||||
'article' => 'Artigo de ensaio', 'competent_entity' => 'Entidade sintética', 'valid_from' => today()->toDateString(),
|
||||
'validation_status' => 'validated', 'owner_id' => $editor->id, 'validator_id' => $reviewer->id,
|
||||
'validated_at' => now(), 'version_no' => 1, 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
DB::table('investment_zones')->where('id', $zoneId)->update([
|
||||
'legal_source_id' => $sourceId, 'publication_status' => 'published', 'validation_status' => 'validated',
|
||||
'reviewer_id' => $reviewer->id, 'published_at' => now(), 'version_no' => 2,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ class InvestmentZoneTest extends TestCase
|
||||
$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]]);
|
||||
foreach (['legal_reviewers', 'gis_reviewers', 'publishers'] as $role) {
|
||||
foreach (['legal_reviewers', 'gis_reviewers', 'territory_reviewers', 'publishers'] as $role) {
|
||||
config(['investment-zones.'.$role => [...config('investment-zones.'.$role, []), $user->email]]);
|
||||
}
|
||||
|
||||
@@ -72,16 +72,40 @@ class InvestmentZoneTest extends TestCase
|
||||
$geometryMigration = require database_path('migrations/2026_09_28_110000_zone_geometry_review.php');
|
||||
$businessMigration = require database_path('migrations/2026_09_28_130000_existing_business_foundation.php');
|
||||
$intakeMigration = require database_path('migrations/2026_09_28_140000_existing_business_intake.php');
|
||||
$marketplaceMigration = require database_path('migrations/2026_09_30_120000_extend_existing_business_marketplace.php');
|
||||
$taxGovernanceMigration = require database_path('migrations/2026_10_03_170000_create_simulation_tax_rule_governance.php');
|
||||
$draftContinuityMigration = require database_path('migrations/2026_10_04_120000_add_simulation_draft_continuity.php');
|
||||
$zoneExtensionMigration = require database_path('migrations/2026_10_04_130000_extend_investment_zone_records.php');
|
||||
$zoneAttachmentsMigration = require database_path('migrations/2026_10_04_140000_create_investment_zone_attachments.php');
|
||||
$zonePublicationMigration = require database_path('migrations/2026_10_04_150000_relax_zone_operator_publication_requirement.php');
|
||||
$zoneDevelopmentMigration = require database_path('migrations/2026_10_04_160000_extend_zone_development_and_area_scopes.php');
|
||||
$primaryTerritoryMigration = require database_path('migrations/2026_09_28_160000_investment_primary_territory.php');
|
||||
$zoneDevelopmentMigration->down();
|
||||
$zonePublicationMigration->down();
|
||||
$zoneAttachmentsMigration->down();
|
||||
$zoneExtensionMigration->down();
|
||||
$draftContinuityMigration->down();
|
||||
$taxGovernanceMigration->down();
|
||||
$marketplaceMigration->down();
|
||||
$intakeMigration->down();
|
||||
$businessMigration->down();
|
||||
$originMigration->down();
|
||||
$geometryMigration->down();
|
||||
$primaryTerritoryMigration->down();
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
$taxGovernanceMigration->up();
|
||||
$geometryMigration->up();
|
||||
$originMigration->up();
|
||||
$businessMigration->up();
|
||||
$intakeMigration->up();
|
||||
$marketplaceMigration->up();
|
||||
$primaryTerritoryMigration->up();
|
||||
$zoneExtensionMigration->up();
|
||||
$zoneAttachmentsMigration->up();
|
||||
$zonePublicationMigration->up();
|
||||
$zoneDevelopmentMigration->up();
|
||||
$draftContinuityMigration->up();
|
||||
foreach ($skillsMigrations as $file) {
|
||||
(require $file)->up();
|
||||
}
|
||||
@@ -96,6 +120,152 @@ class InvestmentZoneTest extends TestCase
|
||||
$this->assertDatabaseCount('investment_zones', 1);
|
||||
}
|
||||
|
||||
public function test_documented_general_industrial_park_can_publish_without_special_regime_or_operator_and_filters_match_csv(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
$publisher = $this->manager();
|
||||
config(['investment-zones.publishers' => [$publisher->email]]);
|
||||
$country = $this->geoNode('country', 'Synthetic country for park', null);
|
||||
$province = $this->geoNode('province', 'Synthetic province for park', $country);
|
||||
$evidence = [['title' => 'Synthetic municipal project page', 'url' => 'https://example.test/munhava', 'source_type' => 'institutional',
|
||||
'supports' => 'Existence and project status only; no availability claim.', 'source_date' => null]];
|
||||
$id = $this->actingAs($editor)->postJson('/api/v2/investment/admin/zones', [
|
||||
'code' => 'QA-GENERAL-PARK', 'name' => 'Synthetic planned industrial park', 'category' => 'industrial_park',
|
||||
'physical_category' => 'industrial_logistics_park', 'legal_regime' => 'pending', 'development_status' => 'planned',
|
||||
'availability_status' => 'not_informed', 'description' => 'A planned informational park record.', 'province_id' => $province,
|
||||
'source_evidence' => $evidence, 'area_components' => [['type' => 'pilot', 'value' => 50, 'unit' => 'ha', 'status' => 'reported',
|
||||
'source_reference' => 'Synthetic source reports pilot area; not available land.', 'source_date' => null]],
|
||||
])->assertCreated()->json('id');
|
||||
$this->actingAs($publisher)->postJson('/api/v2/investment/admin/zones/'.$id.'/publish', ['version_no' => 1])->assertOk();
|
||||
$this->getJson('/api/v2/investment/zones?development_status=planned')->assertOk()->assertJsonPath('records.total', 1)
|
||||
->assertJsonPath('records.data.0.id', $id)->assertJsonPath('records.data.0.availability_status', 'not_informed');
|
||||
$csv = $this->get('/api/v2/investment/zones/export.csv?development_status=planned')->assertOk()->assertHeader('content-type', 'text/csv; charset=UTF-8');
|
||||
$this->assertStringStartsWith("\xEF\xBB\xBF", $csv->streamedContent());
|
||||
$this->assertStringContainsString('Regime;Desenvolvimento;Disponibilidade', $csv->streamedContent());
|
||||
$this->assertStringContainsString('Synthetic planned industrial park', $csv->streamedContent());
|
||||
$this->assertStringContainsString('https://example.test/munhava', $csv->streamedContent());
|
||||
$this->getJson('/api/v2/investment/zones?availability_status=confirmed')->assertJsonPath('records.total', 0);
|
||||
$this->assertDatabaseHas('investment_zones', ['id' => $id, 'operator_id' => null, 'legal_source_id' => null, 'publication_status' => 'published']);
|
||||
}
|
||||
|
||||
public function test_zone_record_separates_physical_type_and_legal_regime_and_searches_multiple_reviewed_territories_once(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
$legalReviewer = $this->manager();
|
||||
$territoryReviewer = $this->manager();
|
||||
$publisher = $this->manager();
|
||||
config(['investment-zones.legal_reviewers' => [$legalReviewer->email], 'investment-zones.territory_reviewers' => [$territoryReviewer->email], 'investment-zones.publishers' => [$publisher->email]]);
|
||||
$country = $this->geoNode('country', 'Synthetic Mozambique', null);
|
||||
$province = $this->geoNode('province', 'Synthetic Zambézia', $country);
|
||||
$districtA = $this->geoNode('district', 'Synthetic Mocuba', $province);
|
||||
$districtB = $this->geoNode('district', 'Synthetic Lugela', $province);
|
||||
$source = $this->actingAs($editor)->postJson('/api/v2/investment/admin/legal-sources', [
|
||||
'title' => 'Synthetic zone creation act', 'url' => 'https://example.test/zone-act', 'diploma' => 'Synthetic act',
|
||||
'article' => 'Article 1', 'competent_entity' => 'Synthetic authority', 'valid_from' => today()->toDateString(),
|
||||
])->assertCreated()->json('id');
|
||||
$this->actingAs($legalReviewer)->postJson('/api/v2/investment/admin/legal-sources/'.$source.'/validate', ['version_no' => 1])->assertOk();
|
||||
$zoneId = $this->actingAs($editor)->postJson('/api/v2/investment/admin/zones', [
|
||||
'code' => 'SYNTHETIC-MULTI-ZEE', 'category' => 'zee', 'physical_category' => 'economic_zone', 'legal_regime' => 'zee',
|
||||
'name' => 'Synthetic Mocuba scope', 'name_en' => 'Synthetic Mocuba scope', 'description' => 'Synthetic test record.', 'description_en' => 'Synthetic test record.',
|
||||
'legal_source_id' => $source, 'province_id' => $province,
|
||||
'activities' => [['name' => 'Agriculture', 'status' => 'potential', 'source_reference' => 'Synthetic test source']],
|
||||
'locations' => [
|
||||
['geo_location_id' => $districtA, 'scope_type' => 'legal_scope', 'source_reference' => 'Synthetic legal territory source', 'legal_source_id' => $source],
|
||||
['geo_location_id' => $districtB, 'scope_type' => 'legal_scope', 'source_reference' => 'Synthetic legal territory source', 'legal_source_id' => $source],
|
||||
],
|
||||
])->assertCreated()->json('id');
|
||||
$links = DB::table('investment_zone_locations')->where('zone_id', $zoneId)->orderBy('geo_location_id')->get(['id', 'version_no']);
|
||||
$this->assertCount(2, $links);
|
||||
foreach ($links as $link) {
|
||||
$this->actingAs($territoryReviewer)->postJson('/api/v2/investment/admin/zone-locations/'.$link->id.'/validate', ['version_no' => $link->version_no])->assertOk();
|
||||
}
|
||||
$this->actingAs($publisher)->postJson('/api/v2/investment/admin/zones/'.$zoneId.'/publish', ['version_no' => 1])->assertOk();
|
||||
$this->getJson('/api/v2/investment/zones?province_id='.$province)->assertOk()->assertJsonPath('records.total', 1)->assertJsonPath('records.data.0.id', $zoneId);
|
||||
$this->getJson('/api/v2/investment/zones?province_id='.$province.'&district_id='.$districtA)->assertOk()->assertJsonPath('records.total', 1);
|
||||
$this->getJson('/api/v2/investment/zones?province_id='.$province.'&district_id='.$districtB)->assertOk()->assertJsonPath('records.total', 1);
|
||||
$this->getJson('/api/v2/investment/zones?province_id='.$province.'&activity=Agriculture')->assertOk()->assertJsonPath('records.total', 1);
|
||||
$this->assertDatabaseHas('investment_zones', ['id' => $zoneId, 'operator_id' => null, 'publication_status' => 'published']);
|
||||
$this->assertDatabaseHas('investment_zones', ['id' => $zoneId, 'physical_category' => 'economic_zone', 'legal_regime' => 'zee']);
|
||||
$this->assertDatabaseCount('investment_zone_locations', 2);
|
||||
}
|
||||
|
||||
public function test_initial_zone_import_is_idempotent_and_keeps_records_private_until_review(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$country = $this->geoNode('country', 'Synthetic Mozambique import', null);
|
||||
$maputo = $this->geoNode('province', 'Synthetic Maputo', $country);
|
||||
$nampula = $this->geoNode('province', 'Synthetic Nampula', $country);
|
||||
$sofala = $this->geoNode('province', 'Synthetic Sofala', $country);
|
||||
$zambezia = $this->geoNode('province', 'Synthetic Zambézia import', $country);
|
||||
$districts = [
|
||||
'BOANE' => $this->geoNode('district', 'BOANE', $maputo),
|
||||
'MOSSURIL' => $this->geoNode('district', 'MOSSURIL', $nampula),
|
||||
'CIDADE DA BEIRA' => $this->geoNode('district', 'CIDADE DA BEIRA', $sofala),
|
||||
'MOCUBA' => $this->geoNode('district', 'MOCUBA', $zambezia),
|
||||
'LUGELA' => $this->geoNode('district', 'LUGELA', $zambezia),
|
||||
'NACALA-PORTO' => $this->geoNode('district', 'NACALA-PORTO', $nampula),
|
||||
'NACALA-VELHA' => $this->geoNode('district', 'NACALA-VELHA', $nampula),
|
||||
];
|
||||
$this->geoNode('admin_post', 'MATOLA RIO', $districts['BOANE']);
|
||||
$this->geoNode('admin_post', 'MATIBANE', $districts['MOSSURIL']);
|
||||
$this->geoNode('admin_post', 'MUNHAMADE', $districts['LUGELA']);
|
||||
$this->geoNode('admin_post', 'CIDADE DE MOCUBA', $districts['MOCUBA']);
|
||||
|
||||
$this->artisan('investment-zones:import-initial', ['--apply' => true, '--actor' => $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_zones', 7);
|
||||
$this->assertDatabaseCount('investment_zone_locations', 9);
|
||||
$this->assertDatabaseCount('investment_legal_sources', 6);
|
||||
$this->assertSame(7, DB::table('investment_zones')->where('publication_status', 'draft')->where('validation_status', 'pending')->count());
|
||||
$this->assertDatabaseCount('investment_zones', 7);
|
||||
$this->artisan('investment-zones:import-initial', ['--apply' => true, '--actor' => $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_zones', 7);
|
||||
$this->assertDatabaseCount('investment_zone_locations', 9);
|
||||
}
|
||||
|
||||
public function test_industrial_candidate_import_is_exact_idempotent_keeps_ambiguity_and_revubue_single(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$country = $this->geoNode('country', 'Synthetic country industrial candidates', null);
|
||||
$nampulaProvince = $this->geoNode('province', 'NAMPULA', $country);
|
||||
$cabo = $this->geoNode('province', 'Synthetic Cabo Delgado', $country);
|
||||
$tete = $this->geoNode('province', 'Synthetic Tete', $country);
|
||||
$sofala = $this->geoNode('province', 'Synthetic Sofala industrial', $country);
|
||||
$this->geoNode('district', 'LARDE', $nampulaProvince);
|
||||
$this->geoNode('district', 'NAMPULA', $nampulaProvince);
|
||||
foreach (['MONTEPUEZ', 'BALAMA', 'ANCUABE', 'PALMA'] as $name) {
|
||||
$this->geoNode('district', $name, $cabo);
|
||||
}
|
||||
$chiuta = $this->geoNode('district', 'CHIUTA', $tete);
|
||||
$moatize = $this->geoNode('district', 'MOATIZE', $tete);
|
||||
$this->geoNode('district', 'CIDADE DA BEIRA', $sofala);
|
||||
|
||||
$this->artisan('investment-zones:import-industrial-candidates')->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_zones', 0);
|
||||
$this->artisan('investment-zones:import-industrial-candidates', ['--apply' => true, '--actor' => $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_zones', 9);
|
||||
$this->assertDatabaseCount('investment_zone_locations', 10);
|
||||
$this->assertDatabaseCount('investment_legal_sources', 0);
|
||||
$revubue = DB::table('investment_zones')->where('code', 'MOZ-REVUBUE-ZFI')->first();
|
||||
$this->assertSame('draft', $revubue->publication_status);
|
||||
$this->assertSame('planned', $revubue->development_status);
|
||||
$this->assertSame(2, DB::table('investment_zone_locations')->where('zone_id', $revubue->id)->whereIn('geo_location_id', [$chiuta, $moatize])->count());
|
||||
$this->assertSame('reported', DB::table('investment_zones')->where('code', 'MOZ-TOPUITO-ZFI')->value('area_components->0->status'));
|
||||
$this->artisan('investment-zones:import-industrial-candidates', ['--apply' => true, '--actor' => $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_zones', 9);
|
||||
$this->assertDatabaseCount('investment_zone_locations', 10);
|
||||
$this->assertDatabaseCount('investment_zone_revisions', 9);
|
||||
}
|
||||
|
||||
private function geoNode(string $type, string $name, ?string $parent): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$id,
|
||||
'version_no' => 1, 'data_classification' => 'public', 'name' => $name, 'location_type' => $type, 'parent_id' => $parent,
|
||||
'code' => $id, 'source_code' => null, 'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_validated_relations_filter_the_same_opportunity_and_revoked_sources_disappear(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
@@ -111,11 +281,14 @@ class InvestmentZoneTest extends TestCase
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'Synthetic operator', 'organization_type' => 'private']);
|
||||
$sector = Sector::create(['slug' => 'qa-zone-sector', 'name' => 'Synthetic sector', 'is_active' => true]);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'QA-ZONE', 'slug' => 'qa-zone', 'title' => 'Synthetic investment', 'status' => 'published', 'published_at' => now()->subMinute()]);
|
||||
$zoneCountry = $this->geoNode('country', 'Synthetic Country for zone link', null);
|
||||
$zoneProvince = $this->geoNode('province', 'Synthetic Province for zone link', $zoneCountry);
|
||||
$zoneIds = [];
|
||||
foreach (['zee', 'zfi'] as $category) {
|
||||
$this->actingAs($editor);
|
||||
$zoneId = $this->postJson('/api/v2/investment/admin/zones', ['code' => 'QA-'.$category, 'name' => 'Synthetic '.$category,
|
||||
'category' => $category, 'name_en' => 'Synthetic zone', 'description' => 'Synthetic description', 'description_en' => 'Synthetic description',
|
||||
'category' => $category, 'physical_category' => $category === 'zfi' ? 'industrial_free_zone' : 'economic_zone', 'legal_regime' => $category,
|
||||
'province_id' => $zoneProvince, 'name_en' => 'Synthetic zone', 'description' => 'Synthetic description', 'description_en' => 'Synthetic description',
|
||||
'operator_id' => $organization, 'legal_source_id' => $source])->assertCreated()->json('id');
|
||||
$linkPayload = ['opportunity_id' => $opportunity->id, 'association_type' => 'potential', 'role' => 'potential',
|
||||
'source_reference' => 'Synthetic relationship evidence', 'justification' => 'Synthetic potential investment', 'valid_from' => today()->toDateString()];
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\LandAssistanceCase;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LandAssistanceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_public_guide_and_blank_form_are_available_without_claiming_official_status(): void
|
||||
{
|
||||
$this->get('/terra-duat')->assertOk()->assertInertia(fn (Assert $page) => $page->component('land-assistance/guide'));
|
||||
$this->get('/terra-duat/formulario-em-branco')->assertOk()->assertInertia(fn (Assert $page) => $page->component('land-assistance/blank'));
|
||||
}
|
||||
|
||||
public function test_private_draft_and_support_are_versioned_and_create_one_crm_receipt(): void
|
||||
{
|
||||
$owner = User::factory()->create(['email_verified_at' => now()]);
|
||||
$payload = [
|
||||
'support_kind' => 'investment', 'request_description' => 'Preciso de orientação para preparar um pedido de apoio sobre um terreno.',
|
||||
'applicant_category' => 'individual', 'full_name' => 'Pessoa de Teste', 'email' => 'terra@example.test',
|
||||
'phone' => null, 'preferred_contact' => 'email', 'country' => 'Moçambique', 'area_status' => 'identified',
|
||||
'purpose' => 'Projecto agrícola exploratório', 'parcels' => [], 'contact_consent' => true,
|
||||
'truth_declaration' => true,
|
||||
];
|
||||
|
||||
$this->actingAs($owner)->postJson('/investidor/terra-duat', ['payload' => $payload])->assertCreated();
|
||||
$case = LandAssistanceCase::firstOrFail();
|
||||
$this->assertSame(1, $case->version);
|
||||
$this->assertSame('draft', $case->status);
|
||||
$this->assertDatabaseCount('land_assistance_revisions', 1);
|
||||
|
||||
$this->postJson("/investidor/terra-duat/{$case->id}/solicitar-apoio", ['version' => 1, 'payload' => $payload])->assertAccepted();
|
||||
$case->refresh();
|
||||
$this->assertSame('support_requested', $case->status);
|
||||
$this->assertSame(2, $case->version);
|
||||
$this->assertNotNull($case->interest_request_id);
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('interest_submission_receipts', 1);
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
$this->assertDatabaseCount('consents', 1);
|
||||
$this->assertSame('Terra e DUAT', InterestRequest::firstOrFail()->sector_interest);
|
||||
|
||||
$this->actingAs(User::factory()->create(['email_verified_at' => now()]))
|
||||
->getJson("/investidor/terra-duat/{$case->id}")->assertNotFound();
|
||||
$this->actingAs($owner)->postJson("/investidor/terra-duat/{$case->id}/solicitar-apoio", ['version' => 2, 'payload' => $payload])->assertStatus(409);
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
}
|
||||
|
||||
public function test_phone_only_support_still_requires_contact_consent(): void
|
||||
{
|
||||
$owner = User::factory()->create(['email_verified_at' => now()]);
|
||||
$payload = [
|
||||
'support_kind' => 'investment', 'request_description' => 'Preciso de orientação sobre os passos de preparação do pedido.',
|
||||
'applicant_category' => 'individual', 'full_name' => 'Pessoa de Teste', 'phone' => '840000000',
|
||||
'preferred_contact' => 'phone', 'area_status' => 'identified', 'purpose' => 'Projecto exploratório',
|
||||
'contact_consent' => false, 'truth_declaration' => true,
|
||||
];
|
||||
$this->actingAs($owner)->postJson('/investidor/terra-duat', ['payload' => $payload])->assertCreated();
|
||||
$case = LandAssistanceCase::firstOrFail();
|
||||
$this->postJson("/investidor/terra-duat/{$case->id}/solicitar-apoio", ['version' => 1, 'payload' => $payload])
|
||||
->assertUnprocessable()->assertJsonValidationErrors(['payload.contact_consent']);
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
}
|
||||
|
||||
public function test_phone_only_support_is_saved_without_a_synthetic_email(): void
|
||||
{
|
||||
$owner = User::factory()->create(['email_verified_at' => now()]);
|
||||
$payload = [
|
||||
'support_kind' => 'investment', 'request_description' => 'Preciso de orientação sobre a preparação do pedido.',
|
||||
'applicant_category' => 'individual', 'full_name' => 'Pessoa de Teste', 'email' => '', 'phone' => '840000000',
|
||||
'preferred_contact' => 'phone', 'area_status' => 'identified', 'purpose' => 'Projecto exploratório',
|
||||
'contact_consent' => true, 'truth_declaration' => true,
|
||||
];
|
||||
$this->actingAs($owner)->postJson('/investidor/terra-duat', ['payload' => $payload])->assertCreated();
|
||||
$case = LandAssistanceCase::firstOrFail();
|
||||
|
||||
$this->postJson("/investidor/terra-duat/{$case->id}/solicitar-apoio", ['version' => 1, 'payload' => $payload])
|
||||
->assertAccepted();
|
||||
$interest = InterestRequest::firstOrFail();
|
||||
$this->assertNull($interest->email);
|
||||
$this->assertSame('840000000', $interest->phone);
|
||||
$this->assertSame('support_requested', $case->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_email_nullable_migration_can_be_reversed_when_no_email_is_missing(): void
|
||||
{
|
||||
$migration = require base_path('database/migrations/2026_10_03_210000_make_interest_request_email_nullable.php');
|
||||
|
||||
$migration->down();
|
||||
$this->assertSame('NO', DB::table('information_schema.columns')
|
||||
->where('table_schema', 'public')->where('table_name', 'interest_requests')->where('column_name', 'email')
|
||||
->value('is_nullable'));
|
||||
|
||||
$migration->up();
|
||||
$this->assertSame('YES', DB::table('information_schema.columns')
|
||||
->where('table_schema', 'public')->where('table_name', 'interest_requests')->where('column_name', 'email')
|
||||
->value('is_nullable'));
|
||||
}
|
||||
|
||||
public function test_email_nullable_migration_refuses_rollback_with_phone_only_requests(): void
|
||||
{
|
||||
DB::table('interest_requests')->insert([
|
||||
'reference' => 'AP-QA-PHONE-ONLY-ROLLBACK', 'full_name' => 'Pessoa de Teste', 'email' => null,
|
||||
'phone' => '840000000', 'investor_type' => 'individual', 'country' => 'MZ',
|
||||
'sector_interest' => 'Terra e DUAT', 'message' => 'Pedido sintético de teste.',
|
||||
'privacy_consent' => true, 'status' => 'received', 'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
$migration = require base_path('database/migrations/2026_10_03_210000_make_interest_request_email_nullable.php');
|
||||
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Rollback must preserve phone-only requests.');
|
||||
} catch (\RuntimeException $exception) {
|
||||
$this->assertStringContainsString('phone-only', $exception->getMessage());
|
||||
}
|
||||
|
||||
$this->assertSame('YES', DB::table('information_schema.columns')
|
||||
->where('table_schema', 'public')->where('table_name', 'interest_requests')->where('column_name', 'email')
|
||||
->value('is_nullable'));
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,23 @@ class PortalManagementTest extends TestCase
|
||||
$this->getJson('/management/opportunities?page=-1')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_unspecified_geography_has_a_private_review_filter_without_assigning_a_location(): void
|
||||
{
|
||||
$this->actingAs($this->manager());
|
||||
$sector = $this->sector();
|
||||
$pending = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'GEO-PENDING', 'slug' => 'geo-pending',
|
||||
'title' => 'Pendência territorial', 'status' => 'published', 'published_at' => now()->subMinute(),
|
||||
'geography_scope' => 'unspecified', 'primary_territory_id' => null]);
|
||||
$specific = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'GEO-SPECIFIC', 'slug' => 'geo-specific',
|
||||
'title' => 'Território específico', 'status' => 'published', 'published_at' => now()->subMinute(), 'geography_scope' => 'specific']);
|
||||
|
||||
$this->get('/management/opportunities?geography_scope=unspecified')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('geographyReviewCount', 1)->where('records.total', 1)
|
||||
->where('records.data.0.id', $pending->id)->where('records.data.0.geography_scope', 'unspecified'));
|
||||
$this->assertNull($pending->fresh()->primary_territory_id);
|
||||
$this->assertSame('specific', $specific->fresh()->geography_scope);
|
||||
}
|
||||
|
||||
protected function beforeRefreshingDatabase(): void
|
||||
{
|
||||
$this->assertSame('testing', app()->environment());
|
||||
@@ -199,6 +216,55 @@ class PortalManagementTest extends TestCase
|
||||
$this->assertStringNotContainsString('consent@example.invalid', $event->payload);
|
||||
}
|
||||
|
||||
public function test_contact_consent_revocation_blocks_conversion_and_emits_no_duplicate_events(): void
|
||||
{
|
||||
$manager = $this->manager();
|
||||
$interest = InterestRequest::create(['reference' => 'IR-CONTACT-CONSENT', 'integration_id' => (string) Str::uuid(),
|
||||
'full_name' => 'Pessoa de teste', 'email' => 'contact-consent@example.invalid', 'investor_type' => 'empresa',
|
||||
'country' => 'MZ', 'sector_interest' => 'Energia', 'message' => 'Pedido de contacto para teste.',
|
||||
'privacy_consent' => true]);
|
||||
$consentId = (string) Str::uuid();
|
||||
DB::table('consents')->insert(['id' => $consentId, 'source_system' => 'portal-intake',
|
||||
'external_id' => 'test-contact-consent', 'version_no' => 1, 'data_classification' => 'confidential',
|
||||
'correlation_id' => (string) Str::uuid(), 'subject_ref' => $interest->reference,
|
||||
'purpose' => 'respond_to_interest', 'status' => 'granted', 'granted_at' => now(),
|
||||
'interest_request_id' => $interest->id, 'policy_version' => '2026-09-30',
|
||||
'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
$this->actingAs($manager)->get('/management/interests/'.$interest->id)
|
||||
->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('consents.0.purpose', 'respond_to_interest')->where('consents.0.status', 'granted'));
|
||||
$this->actingAs(User::factory()->create())
|
||||
->patch('/management/interests/'.$interest->id.'/consent/contact', [
|
||||
'reason' => 'O titular pediu para cessar o contacto sobre o pedido.',
|
||||
])->assertForbidden();
|
||||
$this->actingAs($manager);
|
||||
$this->patch('/management/interests/'.$interest->id.'/consent/contact', [
|
||||
'reason' => 'O titular pediu para cessar o contacto sobre o pedido.',
|
||||
])->assertRedirect();
|
||||
$this->patch('/management/interests/'.$interest->id.'/consent/contact', [
|
||||
'reason' => 'O titular pediu para cessar o contacto sobre o pedido.',
|
||||
])->assertRedirect();
|
||||
$this->post('/management/crm/convert/'.$interest->id, [
|
||||
'legal_name' => 'Empresa de teste', 'investor_type' => 'domestic', 'owner_user_id' => $manager->id,
|
||||
'title' => 'Lead de teste', 'next_action' => 'Rever pedido', 'due_at' => now()->addDay()->toIso8601String(),
|
||||
])->assertSessionHasErrors('investor_id');
|
||||
|
||||
$this->assertDatabaseHas('consents', ['id' => $consentId, 'status' => 'withdrawn']);
|
||||
$this->assertDatabaseHas('business_workflow_transitions', ['interest_request_id' => $interest->id,
|
||||
'to_status' => 'received']);
|
||||
$event = DB::table('outbox_events')->where('event_type', 'InterestConsentWithdrawn')
|
||||
->where('aggregate_id', $consentId)->first();
|
||||
$this->assertNotNull($event);
|
||||
$this->assertStringNotContainsString('contact-consent@example.invalid', $event->payload);
|
||||
$this->assertStringContainsString('respond_to_interest', $event->payload);
|
||||
$this->assertSame(1, DB::table('outbox_events')->where('event_type', 'InterestConsentWithdrawn')
|
||||
->where('aggregate_id', $consentId)->count());
|
||||
$this->assertSame(1, DB::table('business_workflow_transitions')
|
||||
->where('interest_request_id', $interest->id)->count());
|
||||
$this->assertDatabaseCount('leads', 0);
|
||||
}
|
||||
|
||||
public function test_overdue_task_escalation_is_opt_in_and_idempotent(): void
|
||||
{
|
||||
$interest = InterestRequest::create(['reference' => 'IR-SLA', 'full_name' => 'Pessoa de teste',
|
||||
|
||||
@@ -6,7 +6,9 @@ use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
@@ -18,6 +20,25 @@ class PortalServicesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->app->bind(MalwareScanner::class, fn () => new class implements MalwareScanner
|
||||
{
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
return ['result' => 'clean', 'reason_code' => null, 'engine' => 'ClamAV-Test-Double', 'engine_version' => 'fixture',
|
||||
'signatures_at' => new \DateTimeImmutable('2026-10-05T00:00:00Z'), 'duration_ms' => 1, 'detail' => null];
|
||||
}
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
return ['available' => true, 'engine' => 'ClamAV-Test-Double', 'engine_version' => 'fixture',
|
||||
'signatures_at' => new \DateTimeImmutable('2026-10-05T00:00:00Z'), 'signature_age_hours' => 0.0, 'reason_code' => null];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function test_public_sections_render_and_desk_requires_login(): void
|
||||
{
|
||||
foreach (['sectores', 'como-investir', 'legislacao', 'documentos', 'apoio', 'parcerias', 'simulador-fiscal', 'Simulador', 'formularios/investidor', 'formularios/empresa'] as $path) {
|
||||
@@ -43,6 +64,16 @@ class PortalServicesTest extends TestCase
|
||||
$this->post('/apoio', $payload)->assertStatus(409);
|
||||
}
|
||||
|
||||
public function test_home_remains_available_when_document_catalogue_schema_is_incompatible(): void
|
||||
{
|
||||
DB::shouldReceive('table')->once()->with('portal_resources as r')
|
||||
->andThrow(new QueryException('pgsql', 'select missing catalogue columns', [], new \PDOException('SQLSTATE[42703]')));
|
||||
|
||||
$this->get('/')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component('PortalInvestidor')
|
||||
->has('essentialResources', 0));
|
||||
}
|
||||
|
||||
public function test_partnership_requires_moderation_and_hides_owner_identity(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
@@ -64,14 +95,36 @@ class PortalServicesTest extends TestCase
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('exemplo.txt', 'Documento sintético de teste.'),
|
||||
'publication_consent' => true])->assertSessionHasNoErrors();
|
||||
'issuer' => 'Entidade sintética de QA', 'original_source' => 'https://example.gov.mz/source'])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->first();
|
||||
$this->post('/management/portal-services/resources', ['document_id' => $document->id, 'title' => 'Guia de teste', 'category' => 'Guia', 'topic' => 'Investimento',
|
||||
'source_reference' => 'Fonte sintética apenas para testes', 'legislation' => true, 'essential' => true, 'published' => true])->assertSessionHasNoErrors();
|
||||
$id = DB::table('portal_resources')->value('id');
|
||||
$this->assertSame('active', $document->status);
|
||||
$this->assertSame('clean', $document->malware_scan_status);
|
||||
$this->assertSame($document->sha256, $document->malware_scanned_sha256);
|
||||
$this->assertSame('internal', $document->data_classification);
|
||||
$this->assertSame($manager->id, $document->uploaded_by);
|
||||
$this->assertSame(strlen('Documento sintético de teste.'), (int) $document->size_bytes);
|
||||
$this->get('/management/documents/'.$document->id.'/download')->assertOk()->assertDownload('exemplo.txt');
|
||||
auth()->logout();
|
||||
$this->get('/management/documents/'.$document->id.'/download')->assertRedirect('/login');
|
||||
$this->actingAs($manager);
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
$id = $this->registerDocumentResource($document->id, 'Guia de teste');
|
||||
$this->assertDatabaseHas('portal_resources', ['id' => $id, 'published' => false, 'rights_status' => 'authorized']);
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertUnprocessable();
|
||||
// A malware scan releases technical quarantine without changing privacy or editorial publication.
|
||||
DB::table('documents')->where('id', $document->id)->update(['status' => 'active', 'data_classification' => 'public']);
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/documentos/'.$id.'/download')->assertOk()->assertDownload('exemplo.txt');
|
||||
$this->get('/documentos/'.$id.'?back=%2Fdocumentos%3Ftopic%3DInvestimento')->assertInertia(fn (Assert $page) => $page
|
||||
->component('portal/document')->where('resource.title', 'Guia de teste')->where('backUrl', '/documentos?topic=Investimento')
|
||||
->has('resource.links', 3)->missing('resource.storage_key')->missing('resource.sha256'));
|
||||
$this->get('/')->assertInertia(fn (Assert $page) => $page->has('essentialResources', 1));
|
||||
$this->get('/legislacao')->assertInertia(fn (Assert $page) => $page->has('resources.data', 1)->missing('resources.data.0.storage_key'));
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 1)->where('resources.data.0.title', 'Guia de teste')->missing('resources.data.0.storage_key'));
|
||||
$this->getJson('/api/v1/documents/recommendations?module=simulator&activity_id=CAE-TEST&stage=review')->assertOk()->assertJsonPath('data.0.title', 'Guia de teste');
|
||||
$this->put('/management/portal-services/resources/'.$id, [...$this->documentResourcePayload($document->id, 'Guia de teste revisto'), 'metadata_version' => 2, 'description' => 'Resumo editado pelo gestor.'])
|
||||
->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('portal_resources', ['id' => $id, 'published' => true, 'title' => 'Guia de teste revisto']);
|
||||
$this->assertDatabaseHas('portal_resource_revisions', ['resource_id' => $id, 'revision_no' => 3, 'change_type' => 'metadata_updated']);
|
||||
DB::table('documents')->where('id', $document->id)->update(['data_classification' => 'internal']);
|
||||
$this->get('/documentos/'.$id.'/download')->assertNotFound();
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
@@ -81,6 +134,243 @@ class PortalServicesTest extends TestCase
|
||||
$this->get('/documentos/'.$id.'/download')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_document_search_combines_exact_activity_and_territory_filters_without_duplicates(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager);
|
||||
$provinceA = (string) Str::uuid();
|
||||
$provinceB = (string) Str::uuid();
|
||||
foreach ([[$provinceA, 'Província QA A'], [$provinceB, 'Província QA B']] as [$id, $name]) {
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'name' => $name, 'location_type' => 'province', 'code' => strtoupper(Str::random(4)),
|
||||
'data_classification' => 'public', 'version_no' => 1, 'source_system' => 'qa', 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
$districtA = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $districtA, 'name' => 'Distrito QA A1', 'location_type' => 'district', 'parent_id' => $provinceA,
|
||||
'code' => strtoupper(Str::random(4)), 'data_classification' => 'public', 'version_no' => 1, 'source_system' => 'qa', 'created_at' => now(), 'updated_at' => now()]);
|
||||
$records = [];
|
||||
foreach ([['A', $provinceA, 'provincial'], ['District', $districtA, 'district'], ['B', $provinceB, 'provincial'], ['National', null, 'national'], ['Unknown', null, 'unknown']] as [$suffix, $territory, $scope]) {
|
||||
$file = UploadedFile::fake()->createWithContent('doc-'.$suffix.'.txt', 'document content '.$suffix);
|
||||
$this->post('/management/portal-services/upload', ['file' => $file])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->where('file_name', 'doc-'.$suffix.'.txt')->first();
|
||||
$id = $this->registerDocumentResource($document->id, 'Document '.$suffix, [
|
||||
'territory_id' => $territory, 'territorial_scope' => $scope,
|
||||
'associations' => [
|
||||
['target_type' => 'module', 'target_key' => 'simulator', 'relationship' => 'supports', 'applicability' => 'evidence', 'basis_reference' => 'Registo documental QA, secção 1.'],
|
||||
['target_type' => 'module', 'target_key' => 'project_dossier', 'relationship' => 'supports', 'applicability' => 'evidence', 'basis_reference' => 'Registo documental QA, secção 2.'],
|
||||
['target_type' => 'activity', 'target_key' => 'CAE-TEST', 'relationship' => 'applies_to', 'applicability' => 'evidence', 'basis_reference' => 'Registo documental QA, secção 3.'],
|
||||
['target_type' => 'stage', 'target_key' => 'review', 'relationship' => 'supports', 'applicability' => 'evidence', 'basis_reference' => 'Registo documental QA, secção 4.'],
|
||||
],
|
||||
]);
|
||||
DB::table('documents')->where('id', $document->id)->update(['status' => 'active', 'data_classification' => 'public']);
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$records[$suffix] = $id;
|
||||
}
|
||||
$query = '/documentos?'.http_build_query(['territory_id' => $provinceA, 'activity' => ['CAE-TEST'], 'module' => ['simulator'], 'stage' => ['review']]);
|
||||
$this->get($query)->assertOk()->assertInertia(fn (Assert $page) => $page->has('resources.data', 3)
|
||||
->where('resources.data.0.id', $records['A'])->where('resources.data.1.id', $records['District'])->where('resources.data.2.id', $records['National']));
|
||||
$this->get('/documentos?'.http_build_query(['territory_id' => $provinceA, 'activity' => ['NOT-FOUND']]))
|
||||
->assertInertia(fn (Assert $page) => $page->has('resources.data', 0)->where('resources.total', 0));
|
||||
$this->assertDatabaseCount('portal_resource_links', 20);
|
||||
}
|
||||
|
||||
public function test_document_publication_marks_proposals_and_requires_a_confirmed_source(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('proposal.txt', 'Proposal document content.')])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->first();
|
||||
$payload = [...$this->documentResourcePayload($document->id, 'Proposta legislativa QA'), 'document_type' => 'legislation',
|
||||
'legislation' => true, 'source_confirmation' => 'identified', 'legal_status' => 'proposed'];
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$id = (int) DB::table('portal_resources')->value('id');
|
||||
DB::table('documents')->where('id', $document->id)->update(['status' => 'active', 'data_classification' => 'public']);
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertUnprocessable();
|
||||
$this->put('/management/portal-services/resources/'.$id, [...$payload, 'metadata_version' => 1, 'source_confirmation' => 'official_confirmed'])
|
||||
->assertSessionHasNoErrors();
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/legislacao')->assertInertia(fn (Assert $page) => $page->where('resources.data.0.legal_status', 'proposed')
|
||||
->where('resources.data.0.source_confirmation', 'official_confirmed'));
|
||||
}
|
||||
|
||||
public function test_manager_classifies_a_reviewed_document_public_before_separate_publication(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('public-guide.txt', 'A guide whose source and rights are reviewed.'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
$payload = [...$this->documentResourcePayload($document->id, 'Guia público revisto'),
|
||||
'rights_status' => 'authorized', 'source_confirmation' => 'identified', 'data_classification' => 'public'];
|
||||
|
||||
$this->post('/management/portal-services/resources', [...$payload, 'rights_status' => 'unconfirmed'])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('portal_resources', 0);
|
||||
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$resource = DB::table('portal_resources')->firstOrFail();
|
||||
$this->assertDatabaseHas('documents', ['id' => $document->id, 'data_classification' => 'public', 'rights_status' => 'authorized']);
|
||||
$this->assertDatabaseHas('portal_resources', ['id' => $resource->id, 'published' => false, 'approved_by' => null]);
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
$this->get('/documentos/'.$resource->id.'/download')->assertNotFound();
|
||||
|
||||
$this->post('/management/portal-services/resources/'.$resource->id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 1)->where('resources.data.0.title', 'Guia público revisto'));
|
||||
$this->get('/documentos/'.$resource->id.'/download')->assertOk()->assertDownload('public-guide.txt');
|
||||
}
|
||||
|
||||
public function test_public_pdf_preview_is_available_only_after_publication_and_hash_verification(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->create('consultation.pdf', 10, 'application/pdf'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
$payload = [...$this->documentResourcePayload($document->id, 'Ficha PDF'),
|
||||
'rights_status' => 'authorized', 'source_confirmation' => 'identified', 'data_classification' => 'public'];
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$id = (int) DB::table('portal_resources')->value('id');
|
||||
$this->get('/documentos/'.$id.'/view')->assertNotFound();
|
||||
$this->post('/management/portal-services/resources/'.$id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/documentos/'.$id.'/view')->assertOk()->assertHeader('Content-Type', 'application/pdf')->assertHeader('Content-Disposition', 'inline; filename=consultation.pdf');
|
||||
$this->get('/documentos/'.$id)->assertInertia(fn (Assert $page) => $page->where('resource.view_url', route('services.document.view', ['id' => $id])));
|
||||
Storage::disk('local')->put($document->storage_key, 'replaced bytes');
|
||||
$this->get('/documentos/'.$id.'/view')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_threat_and_unavailable_results_stay_quarantined_with_hash_history(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->bindMalwareResult('infected', 'threat_detected');
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('infected-fixture.txt', 'synthetic infected scanner result fixture'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$infected = DB::table('documents')->where('file_name', 'infected-fixture.txt')->firstOrFail();
|
||||
$this->assertSame('quarantined', $infected->status);
|
||||
$this->assertSame('infected', $infected->malware_scan_status);
|
||||
$this->assertSame($infected->sha256, $infected->malware_scanned_sha256);
|
||||
$this->assertDatabaseHas('document_malware_scans', ['document_id' => $infected->id, 'file_sha256' => $infected->sha256,
|
||||
'result' => 'infected', 'reason_code' => 'threat_detected']);
|
||||
|
||||
$this->bindMalwareResult('inconclusive', 'scanner_unavailable');
|
||||
$this->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('unscanned-fixture.txt', 'synthetic scanner unavailable fixture'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$unavailable = DB::table('documents')->where('file_name', 'unscanned-fixture.txt')->firstOrFail();
|
||||
$this->assertSame('quarantined', $unavailable->status);
|
||||
$this->assertSame('inconclusive', $unavailable->malware_scan_status);
|
||||
$this->assertSame('scanner_unavailable', $unavailable->malware_failure_reason);
|
||||
$this->assertSame(0, DB::table('portal_resources')->count());
|
||||
}
|
||||
|
||||
public function test_manager_can_prepare_private_editorial_draft_before_malware_scan_finishes(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->bindMalwareResult('inconclusive', 'scanner_unavailable');
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('pending-private.txt', 'Private pending document.'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
$this->assertSame('quarantined', $document->status);
|
||||
$this->post('/management/portal-services/resources', $this->documentResourcePayload($document->id, 'Rascunho privado'))
|
||||
->assertSessionHasNoErrors();
|
||||
$resource = DB::table('portal_resources')->firstOrFail();
|
||||
$this->assertFalse((bool) $resource->published);
|
||||
$this->assertSame('internal', DB::table('documents')->where('id', $document->id)->value('data_classification'));
|
||||
$this->post('/management/portal-services/resources/'.$resource->id, ['published' => true])->assertUnprocessable();
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
$this->get('/documentos/'.$resource->id)->assertNotFound();
|
||||
$this->get('/documentos/'.$resource->id.'/download')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_identical_upload_is_rejected_and_required_applicability_needs_a_basis(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager);
|
||||
$contents = 'same document body';
|
||||
$this->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('original.txt', $contents)])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->first();
|
||||
$this->from('/management/portal-services')->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('duplicate.txt', $contents)])
|
||||
->assertSessionHasErrors('file');
|
||||
$payload = $this->documentResourcePayload($document->id, 'Manual QA');
|
||||
$payload['associations'] = [['target_type' => 'procedure', 'target_key' => 'licence-test', 'relationship' => 'applies_to',
|
||||
'applicability' => 'required', 'condition_text' => '', 'basis_reference' => '']];
|
||||
$this->from('/management/portal-services')->post('/management/portal-services/resources', $payload)->assertSessionHasErrors('associations.0.basis_reference');
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$payload['associations'] = [];
|
||||
$payload['issuer'] = 'Gazeta oficial QA';
|
||||
$payload['document_number'] = 'BR 44';
|
||||
$payload['source_reference'] = 'Referência documental sintética de QA.';
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$firstId = (int) DB::table('portal_resources')->value('id');
|
||||
$this->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('new-version.txt', 'different version body')])->assertSessionHasNoErrors();
|
||||
$secondDocument = DB::table('documents')->where('file_name', 'new-version.txt')->first();
|
||||
$this->post('/management/portal-services/resources', [...$payload, 'document_id' => $secondDocument->id, 'title' => 'Manual QA v2'])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('portal_resources', ['title' => 'Manual QA v2', 'duplicate_of_resource_id' => $firstId]);
|
||||
$this->assertDatabaseCount('portal_resources', 2);
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
}
|
||||
|
||||
public function test_requirement_links_use_known_technical_keys_and_expose_only_confirmed_citations_as_evidence(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('evidence.txt', 'Documentary source for QA.'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
$payload = $this->documentResourcePayload($document->id, 'Evidência fiscal QA');
|
||||
$payload['associations'][] = ['target_type' => 'requirement', 'target_key' => 'fiscal.iva.lei_22_2022',
|
||||
'relationship' => 'cites', 'applicability' => 'evidence', 'review_status' => 'confirmed',
|
||||
'condition_text' => 'Evidência documental, sem activar cálculo.', 'basis_reference' => 'Lei 22/2022, art. 17(1), página 3.'];
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$id = (int) DB::table('portal_resources')->where('title', 'Evidência fiscal QA')->value('id');
|
||||
$this->assertDatabaseHas('portal_resource_links', ['resource_id' => $id, 'target_type' => 'requirement',
|
||||
'target_key' => 'fiscal.iva.lei_22_2022', 'review_status' => 'confirmed']);
|
||||
|
||||
$payload['associations'][] = ['target_type' => 'requirement', 'target_key' => 'legal.tax.anything',
|
||||
'relationship' => 'cites', 'applicability' => 'evidence', 'review_status' => 'confirmed', 'basis_reference' => 'Sem chave aprovada.'];
|
||||
$this->from('/management/portal-services')->post('/management/portal-services/resources', $payload)
|
||||
->assertSessionHasErrors('associations.4.target_key');
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
}
|
||||
|
||||
private function registerDocumentResource(string $documentId, string $title, array $overrides = []): int
|
||||
{
|
||||
$payload = [...$this->documentResourcePayload($documentId, $title), ...$overrides];
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
|
||||
return (int) DB::table('portal_resources')->where('document_id', $documentId)->where('title', $title)->value('id');
|
||||
}
|
||||
|
||||
private function documentResourcePayload(string $documentId, string $title): array
|
||||
{
|
||||
return ['document_id' => $documentId, 'title' => $title, 'description' => 'Resumo sintético de controlo de qualidade.',
|
||||
'category' => 'Guia', 'topic' => 'Investimento', 'document_type' => 'guide', 'issuer' => 'Entidade sintética de QA',
|
||||
'document_number' => null, 'document_date' => null, 'source_url' => 'https://example.gov.mz/source', 'language' => 'pt',
|
||||
'version_label' => 'QA-1', 'document_group_id' => null, 'territorial_scope' => 'national', 'territory_id' => null,
|
||||
'source_confirmation' => 'identified', 'legal_status' => 'not_applicable', 'rights_status' => 'authorized',
|
||||
'source_reference' => 'Fonte sintética apenas para testes isolados.', 'legislation' => false, 'essential' => true, 'independent_review' => false,
|
||||
'applicable_from' => '', 'applicable_until' => '',
|
||||
'associations' => [
|
||||
['target_type' => 'module', 'target_key' => 'simulator', 'relationship' => 'supports', 'applicability' => 'evidence', 'condition_text' => '', 'basis_reference' => 'Teste sintético, secção 1.'],
|
||||
['target_type' => 'activity', 'target_key' => 'CAE-TEST', 'relationship' => 'applies_to', 'applicability' => 'evidence', 'condition_text' => '', 'basis_reference' => 'Teste sintético, secção 2.'],
|
||||
['target_type' => 'stage', 'target_key' => 'review', 'relationship' => 'supports', 'applicability' => 'evidence', 'condition_text' => '', 'basis_reference' => 'Teste sintético, secção 3.'],
|
||||
]];
|
||||
}
|
||||
|
||||
public function test_amount_filters_do_not_mix_currencies_or_expose_drafts(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Sector de teste', 'slug' => 'sector-teste', 'is_active' => true]);
|
||||
@@ -92,4 +382,24 @@ class PortalServicesTest extends TestCase
|
||||
$this->getJson('/api/v1/opportunities/search?currency=USD&min_amount=100&max_amount=600')->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson('/api/v1/opportunities/search?currency=USD&min_amount=600&max_amount=100')->assertUnprocessable();
|
||||
}
|
||||
|
||||
private function bindMalwareResult(string $result, ?string $reason): void
|
||||
{
|
||||
$this->app->instance(MalwareScanner::class, new class($result, $reason) implements MalwareScanner
|
||||
{
|
||||
public function __construct(private readonly string $result, private readonly ?string $reason) {}
|
||||
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
return ['result' => $this->result, 'reason_code' => $this->reason, 'engine' => 'ClamAV-Test-Double',
|
||||
'engine_version' => 'fixture', 'signatures_at' => new \DateTimeImmutable('2026-10-05T00:00:00Z'), 'duration_ms' => 1, 'detail' => null];
|
||||
}
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
return ['available' => true, 'engine' => 'ClamAV-Test-Double', 'engine_version' => 'fixture',
|
||||
'signatures_at' => new \DateTimeImmutable('2026-10-05T00:00:00Z'), 'signature_age_hours' => 0.0, 'reason_code' => null];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SimulationDraftContinuityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_recovery_cookie_is_http_only_scoped_and_has_a_thirty_day_deadline(): void
|
||||
{
|
||||
$response = $this->getJson('/api/v1/simulation-drafts/current')->assertOk()->assertJsonPath('data', null);
|
||||
$setCookieHeaders = $response->headers->all('set-cookie');
|
||||
$cookieHeader = implode('; ', $setCookieHeaders);
|
||||
|
||||
$this->assertStringContainsString('investmoz_simulation_recovery=', $cookieHeader);
|
||||
$this->assertStringContainsString('Max-Age=2592000', $cookieHeader);
|
||||
$this->assertStringContainsString('path=/api/v1', $cookieHeader);
|
||||
$this->assertStringContainsString('httponly', strtolower($cookieHeader));
|
||||
$this->assertStringContainsString('samesite=lax', strtolower($cookieHeader));
|
||||
}
|
||||
|
||||
public function test_automatic_reads_do_not_renew_expiry_but_an_explicit_save_does(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$created = $this->postJson('/api/v1/simulation-drafts', $this->payload('Prazo de teste'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$id = $created->json('data.id');
|
||||
$saved = $this->putJson('/api/v1/simulation-drafts/'.$id, $this->payload('Prazo após gravação'), [
|
||||
'If-Match' => $created->headers->get('ETag'), 'X-Simulation-Token' => $token,
|
||||
])->assertOk();
|
||||
$this->assertStringContainsString('Max-Age=2592000', implode('; ', $saved->headers->all('set-cookie')));
|
||||
$initial = SimulationFormDraft::findOrFail($id);
|
||||
$expiresAt = $initial->expires_at->toISOString();
|
||||
$updatedAt = $initial->updated_at->toISOString();
|
||||
|
||||
$read = $this->getJson('/api/v1/simulation-drafts/current', ['X-Simulation-Token' => $token])->assertOk();
|
||||
$read->assertJsonPath('data.expires_at', $expiresAt);
|
||||
$this->assertSame($updatedAt, SimulationFormDraft::findOrFail($id)->updated_at->toISOString());
|
||||
|
||||
$this->travel(10)->days();
|
||||
$updated = $this->putJson('/api/v1/simulation-drafts/'.$id, $this->payload('Prazo renovado'), [
|
||||
'If-Match' => $saved->headers->get('ETag'), 'X-Simulation-Token' => $token,
|
||||
])
|
||||
->assertOk();
|
||||
$this->assertEquals(now()->addDays(30)->timestamp, SimulationFormDraft::findOrFail($id)->expires_at->timestamp);
|
||||
}
|
||||
|
||||
public function test_forget_current_soft_deletes_only_the_anonymous_draft_and_clears_cookie(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$created = $this->postJson('/api/v1/simulation-drafts', $this->payload('Esquecer'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
|
||||
$response = $this->deleteJson('/api/v1/simulation-drafts/current', [], ['X-Simulation-Token' => $token])->assertNoContent();
|
||||
|
||||
$this->assertDatabaseHas('simulation_form_drafts', ['id' => $created->json('data.id')]);
|
||||
$this->assertNotNull(DB::table('simulation_form_drafts')->where('id', $created->json('data.id'))->value('deleted_at'));
|
||||
$this->assertStringContainsString('Max-Age=0', implode('; ', $response->headers->all('set-cookie')));
|
||||
}
|
||||
|
||||
public function test_a_routine_read_does_not_refresh_an_existing_recovery_cookie(): void
|
||||
{
|
||||
$request = Request::create('/api/v1/simulation-drafts/current', 'GET', cookies: [
|
||||
EnsureSimulationRecoveryCookie::NAME => Str::random(48),
|
||||
]);
|
||||
$response = app(EnsureSimulationRecoveryCookie::class)->handle($request, fn () => response()->json(['data' => null]));
|
||||
|
||||
$this->assertEmpty($response->headers->all('set-cookie'));
|
||||
}
|
||||
|
||||
public function test_explicit_continue_later_touch_renews_only_the_deadline_without_changing_snapshot_version(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$created = $this->postJson('/api/v1/simulation-drafts', $this->payload('Renovar sem alterações'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$this->travel(10)->days();
|
||||
|
||||
$response = $this->postJson('/api/v1/simulation-drafts/'.$created->json('data.id').'/touch', [], [
|
||||
'If-Match' => $created->headers->get('ETag'), 'X-Simulation-Token' => $token,
|
||||
])->assertOk();
|
||||
|
||||
$this->assertEquals(now()->addDays(30)->timestamp, SimulationFormDraft::findOrFail($created->json('data.id'))->expires_at->timestamp);
|
||||
$this->assertSame(1, SimulationFormDraft::findOrFail($created->json('data.id'))->version_no);
|
||||
$this->assertSame($created->headers->get('ETag'), $response->headers->get('ETag'));
|
||||
}
|
||||
|
||||
public function test_database_details_are_not_returned_by_simulation_draft_api_errors(): void
|
||||
{
|
||||
Route::get('/api/v1/simulation-drafts/synthetic-failure/force', function (): never {
|
||||
throw new \Illuminate\Database\QueryException('pgsql', 'select * from private_draft_table', ['private-token'], new \PDOException('private-db-name relation missing'));
|
||||
});
|
||||
|
||||
$this->getJson('/api/v1/simulation-drafts/synthetic-failure/force')->assertStatus(500)
|
||||
->assertJsonPath('message', 'Não foi possível guardar ou recuperar o rascunho. Os dados existentes não foram apagados. Tente novamente mais tarde.')
|
||||
->assertDontSee('private_draft_table')->assertDontSee('private-token')->assertDontSee('private-db-name');
|
||||
}
|
||||
|
||||
public function test_claiming_an_anonymous_draft_creates_another_private_project_without_merging_and_is_idempotent(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$anonymous = $this->postJson('/api/v1/simulation-drafts', $this->payload('Ideia temporária'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$actor = User::factory()->create();
|
||||
$this->actingAs($actor);
|
||||
$existing = $this->postJson('/api/v1/simulation-drafts', $this->payload('Projecto privado existente'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertCreated();
|
||||
|
||||
$this->getJson('/api/v1/simulation-drafts/claim-preview', ['X-Simulation-Token' => $token])
|
||||
->assertOk()->assertJsonPath('data.title', 'Ideia temporária');
|
||||
$claim = fn () => $this->postJson('/api/v1/simulation-drafts/claim', ['choice' => 'save_as_new'], [
|
||||
'X-Simulation-Token' => $token,
|
||||
]);
|
||||
$claim()->assertOk()->assertJsonPath('choice', 'save_as_new')->assertJsonPath('data.id', $anonymous->json('data.id'));
|
||||
$claim()->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('data.id', $anonymous->json('data.id'));
|
||||
|
||||
$this->assertDatabaseHas('simulation_form_drafts', [
|
||||
'id' => $anonymous->json('data.id'), 'owner_user_id' => $actor->id,
|
||||
'anonymous_token_hash' => null, 'expires_at' => null,
|
||||
'claimed_token_hash' => hash_hmac('sha256', $token, (string) config('app.key')),
|
||||
]);
|
||||
$this->getJson('/api/v1/simulation-drafts')->assertOk()->assertJsonCount(2, 'data');
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$existing->json('data.id'))
|
||||
->assertOk()->assertJsonPath('data.economic_snapshot.project_title', 'Projecto privado existente');
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$anonymous->json('data.id'))
|
||||
->assertOk()->assertJsonPath('data.economic_snapshot.project_title', 'Ideia temporária');
|
||||
}
|
||||
|
||||
public function test_continue_existing_choice_leaves_the_anonymous_draft_unclaimed(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$anonymous = $this->postJson('/api/v1/simulation-drafts', $this->payload('Não fundir'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$actor = User::factory()->create();
|
||||
$this->actingAs($actor);
|
||||
$existing = $this->postJson('/api/v1/simulation-drafts', $this->payload('Manter existente'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertCreated();
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts/claim', [
|
||||
'choice' => 'continue_existing', 'existing_draft_id' => $existing->json('data.id'),
|
||||
], ['X-Simulation-Token' => $token])->assertOk()->assertJsonPath('data.id', $existing->json('data.id'));
|
||||
|
||||
$this->assertDatabaseHas('simulation_form_drafts', [
|
||||
'id' => $anonymous->json('data.id'), 'owner_user_id' => null,
|
||||
'anonymous_token_hash' => hash_hmac('sha256', $token, (string) config('app.key')),
|
||||
]);
|
||||
$this->assertDatabaseCount('simulation_form_drafts', 2);
|
||||
}
|
||||
|
||||
public function test_expired_anonymous_draft_is_not_readable_and_same_recovery_cookie_can_start_a_new_draft(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$first = $this->postJson('/api/v1/simulation-drafts', $this->payload('Expira'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$this->travel(31)->days();
|
||||
$this->getJson('/api/v1/simulation-drafts/current', ['X-Simulation-Token' => $token])
|
||||
->assertOk()->assertJsonPath('data', null);
|
||||
$second = $this->postJson('/api/v1/simulation-drafts', $this->payload('Novo prazo'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
|
||||
$this->assertNotSame($first->json('data.id'), $second->json('data.id'));
|
||||
$this->assertDatabaseHas('simulation_form_drafts', ['id' => $first->json('data.id'), 'deleted_at' => now()]);
|
||||
$this->assertGreaterThan(now(), SimulationFormDraft::findOrFail($second->json('data.id'))->expires_at);
|
||||
}
|
||||
|
||||
public function test_business_association_is_explicit_reversible_and_does_not_copy_or_publish_data(): void
|
||||
{
|
||||
config(['existing-business.enabled' => true]);
|
||||
$actor = User::factory()->create();
|
||||
$this->actingAs($actor);
|
||||
$business = $this->postJson('/api/v1/existing-business/listings', [
|
||||
'modality' => 'company_sale', 'classification' => 'confidential', 'reason' => 'Create synthetic private test business',
|
||||
'payload' => ['title' => 'Negócio de teste', 'wizard_version' => '1', 'wizard_step' => '1'],
|
||||
])->assertCreated();
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', $this->payload('Plano separado'), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertCreated();
|
||||
$id = $draft->json('data.id');
|
||||
|
||||
$this->getJson('/api/v1/simulation-drafts/linkable-businesses')->assertOk()
|
||||
->assertJsonFragment(['id' => $business->json('id'), 'title' => 'Negócio de teste']);
|
||||
$this->postJson('/api/v1/simulation-drafts/'.$id.'/business-link', ['business_id' => $business->json('id')])
|
||||
->assertCreated();
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$id.'/business-link')->assertOk()
|
||||
->assertJsonPath('data.business_id', $business->json('id'))
|
||||
->assertJsonPath('data.title', 'Negócio de teste');
|
||||
$this->deleteJson('/api/v1/simulation-drafts/'.$id.'/business-link')->assertOk()->assertJsonPath('data.unlinked', true);
|
||||
|
||||
$this->assertDatabaseHas('simulation_draft_business_links', ['draft_id' => $id, 'business_id' => $business->json('id')]);
|
||||
$this->assertNotNull(DB::table('simulation_draft_business_links')->where('draft_id', $id)->value('unlinked_at'));
|
||||
$this->assertDatabaseHas('existing_businesses', ['id' => $business->json('id'), 'status' => 'draft']);
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()
|
||||
->assertJsonPath('data.economic_snapshot.project_title', 'Plano separado');
|
||||
}
|
||||
|
||||
/** @return array{personal_snapshot:array<string,string>,economic_snapshot:array<string,string>} */
|
||||
private function payload(string $title): array
|
||||
{
|
||||
return ['personal_snapshot' => [], 'economic_snapshot' => [
|
||||
'journey_type' => 'small_business', 'detail_level' => 'simple', 'purpose' => 'simulate_only',
|
||||
'project_title' => $title, 'tax_calculation' => 'no',
|
||||
]];
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,56 @@ class SimulationExecutionTest extends TestCase
|
||||
Queue::fake();
|
||||
}
|
||||
|
||||
public function test_account_history_contains_only_the_verified_users_personal_simulations(): 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' => '1200', 'rate' => '7.5', 'reduction' => '0',
|
||||
], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
|
||||
$this->actingAs($other)->postJson('/api/v1/simulations', [
|
||||
'base' => '9900', 'rate' => '9', 'reduction' => '1',
|
||||
], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
|
||||
$organizationId = (string) Str::uuid();
|
||||
DB::table('organizations')->insert([
|
||||
'id' => $organizationId, 'name' => 'History 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(),
|
||||
]);
|
||||
$this->actingAs($owner)->postJson('/api/v1/simulations', [
|
||||
'base' => '700', 'rate' => '4', 'reduction' => '0', 'organization_id' => $organizationId,
|
||||
], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
|
||||
auth()->logout();
|
||||
$this->postJson('/api/v1/simulations', [
|
||||
'base' => '500', 'rate' => '10', 'reduction' => '0',
|
||||
], ['Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48)])->assertAccepted();
|
||||
|
||||
$response = $this->actingAs($owner)->getJson('/api/v1/simulations/history')
|
||||
->assertOk()->assertJsonPath('meta.total', 2)->assertJsonPath('data.0.status', 'queued')
|
||||
->assertJsonStructure(['data' => [['id', 'scope', 'organization_name', 'status', 'version_no', 'created_at', 'updated_at', 'has_ready_report']],
|
||||
'meta' => ['current_page', 'last_page', 'per_page', 'total']]);
|
||||
$entries = $response->json('data');
|
||||
$this->assertEqualsCanonicalizing(['personal', 'organization'], array_column($entries, 'scope'));
|
||||
$this->assertSame('History organization', collect($entries)->firstWhere('scope', 'organization')['organization_name']);
|
||||
$entry = $entries[0];
|
||||
$this->assertArrayHasKey('id', $entry);
|
||||
$this->assertArrayNotHasKey('input_snapshot', $entry);
|
||||
$this->assertArrayNotHasKey('result_snapshot', $entry);
|
||||
$this->assertArrayNotHasKey('anonymous_token_hash', $entry);
|
||||
$this->actingAs($other)->getJson('/api/v1/simulations/history')
|
||||
->assertOk()->assertJsonPath('meta.total', 1);
|
||||
}
|
||||
|
||||
public function test_account_history_requires_authentication_and_verified_email(): void
|
||||
{
|
||||
$this->getJson('/api/v1/simulations/history')->assertUnauthorized();
|
||||
$user = User::factory()->create(['email_verified_at' => null]);
|
||||
$this->actingAs($user)->getJson('/api/v1/simulations/history')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_anonymous_execution_keeps_only_token_hash_and_reconciles_immutable_sources(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
@@ -43,8 +93,44 @@ class SimulationExecutionTest extends TestCase
|
||||
$this->assertNotSame($queuedEtag, $completedResponse->headers->get('ETag'));
|
||||
$simulationView = $completedResponse->json('data');
|
||||
$this->assertEqualsWithDelta(50.0, (float) $simulationView['result_snapshot']['indicative_total'], 0.0000001);
|
||||
$resultSnapshot = $simulationView['result_snapshot'];
|
||||
$scenario = DB::table('simulation_scenarios')->where('simulation_id', $simulationId)->first();
|
||||
$this->assertSame('custom_planning', $resultSnapshot['scenario_kind']);
|
||||
$this->assertSame('custom_planning', json_decode($scenario->parameters, true, flags: JSON_THROW_ON_ERROR)['scenario_kind']);
|
||||
$this->assertSame(1, $resultSnapshot['contract_version']);
|
||||
$this->assertSame('calculated', $resultSnapshot['result']['status']);
|
||||
$this->assertSame('Resultado aritmético determinístico; não constitui cálculo nem conclusão fiscal.', $resultSnapshot['result']['explanation']);
|
||||
$this->assertSame($resultSnapshot['indicative_total'], $resultSnapshot['result']['value']);
|
||||
$this->assertIsString($resultSnapshot['result']['value']);
|
||||
$this->assertSame([], $resultSnapshot['result']['missing_inputs']);
|
||||
$this->assertSame([], $resultSnapshot['result']['source_ids']);
|
||||
$this->assertSame((string) $scenario->id, $resultSnapshot['context']['scenario_id']);
|
||||
$this->assertSame((int) $scenario->version_no, $resultSnapshot['context']['scenario_version']);
|
||||
$this->assertSame(substr((string) $scenario->created_at, 0, 10), $resultSnapshot['context']['reference_date']);
|
||||
$this->assertNull($resultSnapshot['context']['currency']);
|
||||
$this->assertNull($resultSnapshot['context']['ruleset_version']);
|
||||
$this->assertSame('portal-arithmetic-v1+simulation-v1', $resultSnapshot['context']['engine_version']);
|
||||
$this->assertSame('portal-arithmetic-v1', $resultSnapshot['formula_version']);
|
||||
$this->assertDatabaseHas('simulation_result_sources', ['source_type' => 'user_input']);
|
||||
$this->assertSame(1, DB::table('simulation_reports')->where('simulation_id', $simulationId)->where('status', 'ready')->count());
|
||||
$savedReport = DB::table('simulation_reports')->where('simulation_id', $simulationId)->where('status', 'ready')->first();
|
||||
$this->assertSame($resultSnapshot, json_decode($savedReport->report_snapshot, true, flags: JSON_THROW_ON_ERROR));
|
||||
$reportResponse = $this->getJson('/api/v1/simulations/'.$simulationId.'/reports/'.$savedReport->id, [
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertOk()->assertJsonPath('data.id', $savedReport->id)
|
||||
->assertJsonPath('data.status', 'ready')
|
||||
->assertJsonStructure(['data' => ['id', 'simulation_id', 'version_no', 'status', 'report_snapshot', 'report_sha256']]);
|
||||
$this->assertSame($resultSnapshot, $reportResponse->json('data.report_snapshot'));
|
||||
$this->assertSame(trim((string) $savedReport->report_sha256), $reportResponse->json('data.report_sha256'));
|
||||
$jobsResponse = $this->getJson('/api/v1/simulations/'.$simulationId.'/jobs', ['X-Simulation-Token' => $token])
|
||||
->assertOk()->assertJsonPath('data.0.status', 'succeeded')
|
||||
->assertJsonStructure(['data' => [['id', 'simulation_id', 'job_type', 'status', 'attempts', 'available_at', 'started_at', 'finished_at', 'error_code']]]);
|
||||
$this->assertNotNull($jobsResponse->json('data.0.started_at'));
|
||||
$this->assertNotNull($jobsResponse->json('data.0.finished_at'));
|
||||
$this->assertNull($jobsResponse->json('data.0.error_code'));
|
||||
$this->getJson('/api/v1/simulations/'.$simulationId.'/reports/'.$savedReport->id, [
|
||||
'X-Simulation-Token' => Str::random(48),
|
||||
])->assertNotFound();
|
||||
|
||||
$simulation = DB::table('simulations')->where('id', $simulationId)->first();
|
||||
$result = DB::table('simulation_results')->where('simulation_id', $simulationId)->first();
|
||||
@@ -54,12 +140,35 @@ class SimulationExecutionTest extends TestCase
|
||||
$this->assertSame($result->result_sha256, hash('sha256', $resultCanonical));
|
||||
$this->assertSame($source->source_sha256, hash('sha256', $sourceCanonical));
|
||||
$this->assertNotNull($simulation->questionnaire_version_id);
|
||||
}
|
||||
|
||||
public function test_simulation_audit_events_are_append_only_for_an_authorized_owner(): void
|
||||
{
|
||||
$owner = User::factory()->create(['email_verified_at' => now()]);
|
||||
$response = $this->actingAs($owner)->postJson('/api/v1/simulations', [
|
||||
'base' => '1000', 'rate' => '10', 'reduction' => '0',
|
||||
], ['Idempotency-Key' => (string) Str::uuid()])->assertAccepted();
|
||||
$simulationId = $response->json('data.id');
|
||||
app(SimulationExecution::class)->setContext($owner->id, null);
|
||||
$event = DB::table('simulation_audit_events')->where('simulation_id', $simulationId)->first();
|
||||
$this->assertNotNull($event);
|
||||
|
||||
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.');
|
||||
DB::transaction(fn () => DB::table('simulation_audit_events')
|
||||
->where('id', $event->id)
|
||||
->update(['action' => 'audit.tampered']));
|
||||
} catch (QueryException) {
|
||||
$this->assertDatabaseMissing('simulation_audit_events', ['simulation_id' => $simulationId, 'action' => 'audit.tampered']);
|
||||
// Superuser-based test connections reach the immutable trigger;
|
||||
// restricted roles may be denied earlier by row-level security.
|
||||
}
|
||||
$this->assertDatabaseMissing('simulation_audit_events', [
|
||||
'id' => $event->id,
|
||||
'action' => 'audit.tampered',
|
||||
]);
|
||||
$this->assertSame(1, (int) DB::selectOne(
|
||||
'select count(*) as n from pg_trigger where tgname = ? and not tgisinternal',
|
||||
['simulation_audit_immutable'],
|
||||
)->n);
|
||||
}
|
||||
|
||||
public function test_execution_requires_an_explicit_user_supplied_reduction(): void
|
||||
@@ -100,7 +209,12 @@ class SimulationExecutionTest extends TestCase
|
||||
$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');
|
||||
$updated->assertHeader('ETag', '"sim-'.$id.'-v3"')
|
||||
->assertJsonPath('data.status', 'queued')
|
||||
->assertJsonPath('data.version_no', 3)
|
||||
->assertJsonPath('data.scenarios.0.parameters.base', '2000')
|
||||
->assertJsonPath('data.scenarios.0.parameters.rate', '8')
|
||||
->assertJsonPath('data.scenarios.0.parameters.reduction', '25');
|
||||
|
||||
$tokenHash = hash_hmac('sha256', $token, (string) config('app.key'));
|
||||
app(RunSimulation::class, ['simulationId' => $id, 'actorId' => null, 'tokenHash' => $tokenHash])->handle(app(SimulationExecution::class));
|
||||
@@ -118,6 +232,7 @@ class SimulationExecutionTest extends TestCase
|
||||
$execution = app(SimulationExecution::class);
|
||||
|
||||
DB::unprepared('DO $$ BEGIN CREATE ROLE simulation_rls_test NOLOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$');
|
||||
DB::statement('GRANT simulation_rls_test TO CURRENT_USER');
|
||||
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 {
|
||||
@@ -128,7 +243,9 @@ class SimulationExecutionTest extends TestCase
|
||||
$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('REVOKE simulation_rls_test FROM CURRENT_USER');
|
||||
DB::statement('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM simulation_rls_test');
|
||||
DB::statement('REVOKE USAGE ON SCHEMA public FROM simulation_rls_test');
|
||||
DB::statement('DROP ROLE IF EXISTS simulation_rls_test');
|
||||
}
|
||||
$this->actingAs($other)->getJson('/api/v1/simulations/'.$id)->assertNotFound();
|
||||
@@ -166,6 +283,7 @@ class SimulationExecutionTest extends TestCase
|
||||
$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 simulation_rls_test TO CURRENT_USER');
|
||||
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');
|
||||
@@ -174,10 +292,21 @@ class SimulationExecutionTest extends TestCase
|
||||
$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]));
|
||||
$affected = null;
|
||||
try {
|
||||
$affected = DB::transaction(fn () => DB::affectingStatement(
|
||||
'update public.simulations set version_no = version_no + 1 where id = ?',
|
||||
[$id],
|
||||
));
|
||||
} catch (QueryException) {
|
||||
// PostgreSQL may reject the UPDATE with WITH CHECK instead of returning zero rows.
|
||||
}
|
||||
$this->assertTrue($affected === null || $affected === 0);
|
||||
} finally {
|
||||
DB::statement('RESET ROLE');
|
||||
DB::statement('DROP OWNED BY simulation_rls_test');
|
||||
DB::statement('REVOKE simulation_rls_test FROM CURRENT_USER');
|
||||
DB::statement('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM simulation_rls_test');
|
||||
DB::statement('REVOKE USAGE ON SCHEMA public FROM 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();
|
||||
@@ -194,6 +323,7 @@ class SimulationExecutionTest extends TestCase
|
||||
$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 simulation_rls_test TO CURRENT_USER');
|
||||
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 {
|
||||
@@ -205,7 +335,9 @@ class SimulationExecutionTest extends TestCase
|
||||
$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('REVOKE simulation_rls_test FROM CURRENT_USER');
|
||||
DB::statement('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM simulation_rls_test');
|
||||
DB::statement('REVOKE USAGE ON SCHEMA public FROM simulation_rls_test');
|
||||
DB::statement('DROP ROLE IF EXISTS simulation_rls_test');
|
||||
}
|
||||
}
|
||||
@@ -248,6 +380,7 @@ class SimulationExecutionTest extends TestCase
|
||||
public function test_questionnaire_endpoint_exposes_only_published_version_with_etag(): void
|
||||
{
|
||||
$this->getJson('/api/v1/questionnaires/user-entered-arithmetic')->assertOk()
|
||||
->assertJsonStructure(['data' => ['id', 'code', 'version_no', 'locale', 'schema_snapshot', 'status', 'valid_from', 'valid_to', 'created_at', 'updated_at']])
|
||||
->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();
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Services\SimulationExecution;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -11,7 +14,7 @@ class SimulationFormDraftTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_anonymous_draft_is_encrypted_scoped_and_restorable(): void
|
||||
public function test_anonymous_draft_is_encrypted_scoped_and_restorable_without_persisting_personal_data(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$key = (string) Str::uuid();
|
||||
@@ -23,13 +26,110 @@ class SimulationFormDraftTest extends TestCase
|
||||
$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->assertSame([], SimulationFormDraft::decryptSnapshot($stored->personal_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');
|
||||
->assertOk()->assertJsonPath('data.personal_snapshot', [])
|
||||
->assertJsonPath('data.economic_snapshot.base', '1200')
|
||||
->assertJsonPath('data.economic_snapshot.journey_type', 'personal');
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$id, ['X-Simulation-Token' => Str::random(48)])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_anonymous_autosave_accepts_an_explicitly_empty_personal_snapshot(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$payload = $this->payload();
|
||||
$payload['personal_snapshot'] = [];
|
||||
|
||||
$created = $this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(),
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertCreated()->assertJsonPath('data.version_no', 1);
|
||||
|
||||
$stored = DB::table('simulation_form_drafts')->where('id', $created->json('data.id'))->first();
|
||||
$this->assertSame([], SimulationFormDraft::decryptSnapshot($stored->personal_snapshot));
|
||||
$this->getJson('/api/v1/simulation-drafts/current', ['X-Simulation-Token' => $token])
|
||||
->assertOk()->assertJsonPath('data.personal_snapshot', [])
|
||||
->assertJsonPath('data.economic_snapshot.purpose', 'simulate_only');
|
||||
}
|
||||
|
||||
public function test_exploratory_small_business_idea_and_market_assumptions_are_saved_in_the_economic_snapshot(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$payload = $this->payload();
|
||||
$payload['personal_snapshot'] = [];
|
||||
$payload['economic_snapshot'] = [
|
||||
'journey_type' => 'small_business',
|
||||
'purpose' => 'simulate_only',
|
||||
'project_title' => 'Piloto sintetico sem semeadura',
|
||||
'maturity_stage' => 'operation',
|
||||
'selection_labels' => ['maturity_stage' => 'Operação'],
|
||||
'project_problem' => 'Necessidade declarada para teste.',
|
||||
'target_customers' => 'Clientes hipoteticos para teste.',
|
||||
'value_proposition' => 'Proposta de valor declarada para teste.',
|
||||
'market_assumption' => 'Hipotese de procura, sem fonte oficial.',
|
||||
'market_source' => 'Declaracao de teste, 2026-10-04.',
|
||||
'competitor_assumption' => 'Alternativas locais por verificar.',
|
||||
'sales_channel_assumption' => 'Venda directa em avaliação.',
|
||||
'marketing_approach' => 'Testar divulgação local.',
|
||||
'location_rationale' => 'Proximidade de clientes a confirmar.',
|
||||
'customer_validation_status' => 'partial',
|
||||
'cost_estimate_status' => 'unknown',
|
||||
'location_assessment_status' => 'partial',
|
||||
'funding_status' => 'in_process',
|
||||
'project_questionnaire_version' => 'investmoz-project-dossier-2026-10-05.1',
|
||||
'project_risk_responses_snapshot' => json_encode([['risk_id' => 'customers', 'action' => 'Entrevistar potenciais clientes', 'owner' => 'Equipa', 'estimated_cost' => '0', 'due_date' => '2026-11-30']], JSON_THROW_ON_ERROR),
|
||||
'project_milestones' => 'Planeado: validar procura; prazo: 2026-11-30.',
|
||||
'project_team_snapshot' => json_encode([['competency' => 'Gestão', 'state' => 'gap', 'action' => 'Formação', 'estimated_cost' => '1200.00', 'due_date' => '2026-11-30']], JSON_THROW_ON_ERROR),
|
||||
'project_execution_snapshot' => json_encode([['title' => 'Abrir loja', 'due_date' => '2026-12-01', 'status' => 'planned', 'planned_amount' => '5000', 'actual_amount' => '']], JSON_THROW_ON_ERROR),
|
||||
];
|
||||
|
||||
$created = $this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(),
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
|
||||
$this->getJson('/api/v1/simulation-drafts/current', ['X-Simulation-Token' => $token])
|
||||
->assertOk()
|
||||
->assertJsonPath('data.personal_snapshot', [])
|
||||
->assertJsonPath('data.economic_snapshot.project_problem', 'Necessidade declarada para teste.')
|
||||
->assertJsonPath('data.economic_snapshot.market_source', 'Declaracao de teste, 2026-10-04.')
|
||||
->assertJsonPath('data.economic_snapshot.project_questionnaire_version', 'investmoz-project-dossier-2026-10-05.1')
|
||||
->assertJsonPath('data.economic_snapshot.customer_validation_status', 'partial')
|
||||
->assertJsonPath('data.economic_snapshot.project_risk_responses_snapshot', $payload['economic_snapshot']['project_risk_responses_snapshot'])
|
||||
->assertJsonPath('data.economic_snapshot.selection_labels.maturity_stage', 'Operação')
|
||||
->assertJsonPath('data.economic_snapshot.project_milestones', 'Planeado: validar procura; prazo: 2026-11-30.')
|
||||
->assertJsonPath('data.economic_snapshot.project_team_snapshot', $payload['economic_snapshot']['project_team_snapshot'])
|
||||
->assertJsonPath('data.economic_snapshot.project_execution_snapshot', $payload['economic_snapshot']['project_execution_snapshot']);
|
||||
}
|
||||
|
||||
public function test_structured_project_plans_reject_negative_amounts(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
$payload['economic_snapshot']['project_execution_snapshot'] = json_encode([
|
||||
['title' => 'Marco', 'due_date' => '', 'status' => 'planned', 'planned_amount' => '-1', 'actual_amount' => ''],
|
||||
], JSON_THROW_ON_ERROR);
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot.project_execution_snapshot');
|
||||
}
|
||||
|
||||
public function test_project_risk_responses_reject_negative_costs_and_invalid_statuses(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
$payload['economic_snapshot']['project_risk_responses_snapshot'] = json_encode([
|
||||
['risk_id' => 'customers', 'action' => 'Validar', 'owner' => '', 'estimated_cost' => '-1', 'due_date' => ''],
|
||||
], JSON_THROW_ON_ERROR);
|
||||
$payload['economic_snapshot']['funding_status'] = 'guaranteed';
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertUnprocessable()->assertJsonValidationErrors([
|
||||
'economic_snapshot.project_risk_responses_snapshot', 'economic_snapshot.funding_status',
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_creation_is_idempotent_and_rejects_key_reuse_with_changed_data(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
@@ -44,6 +144,16 @@ class SimulationFormDraftTest extends TestCase
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, $headers)->assertConflict();
|
||||
}
|
||||
|
||||
public function test_clients_cannot_forge_server_owned_simulation_sources(): void
|
||||
{
|
||||
$payload = $this->payload();
|
||||
$payload['economic_snapshot']['simulation_sources'] = [['simulation_id' => (string) Str::uuid()]];
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_updates_require_a_current_etag_and_delete_is_reversible_until_expiry(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
@@ -56,9 +166,132 @@ class SimulationFormDraftTest extends TestCase
|
||||
$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);
|
||||
$expectedTokenHash = hash_hmac('sha256', $token, (string) config('app.key'));
|
||||
$this->assertSame(
|
||||
$expectedTokenHash,
|
||||
DB::selectOne("select current_setting('app.simulation_token_hash', true) as token_hash")->token_hash,
|
||||
);
|
||||
$storedBeforeDelete = DB::table('simulation_form_drafts')->where('id', $id)->first();
|
||||
$this->assertSame($expectedTokenHash, rtrim($storedBeforeDelete->anonymous_token_hash));
|
||||
$this->assertNull($storedBeforeDelete->deleted_at);
|
||||
$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]);
|
||||
$this->getJson($url, ['X-Simulation-Token' => $token])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_completed_simulation_is_attached_with_explicit_consent_as_an_immutable_versioned_snapshot(): void
|
||||
{
|
||||
Queue::fake();
|
||||
$token = Str::random(48);
|
||||
$formalPayload = $this->payload();
|
||||
$formalPayload['economic_snapshot']['purpose'] = 'own_investment';
|
||||
$draftResponse = $this->postJson('/api/v1/simulation-drafts', $formalPayload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$draftId = $draftResponse->json('data.id');
|
||||
$simulationResponse = $this->postJson('/api/v1/simulations', [
|
||||
'base' => '1200', 'rate' => '8', 'reduction' => '0',
|
||||
], ['Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token])->assertAccepted();
|
||||
$simulationId = $simulationResponse->json('data.id');
|
||||
app(SimulationExecution::class)->setContext(null, hash_hmac('sha256', $token, (string) config('app.key')));
|
||||
$result = ['base' => '1200', 'rate_percent' => '8', 'reduction_percent' => '0', 'indicative_total' => '96.00000000', 'legal_interpretation' => false, 'formula_version' => 'portal-tax-arithmetic-v1'];
|
||||
DB::table('simulations')->where('id', $simulationId)->update([
|
||||
'status' => 'completed', 'version_no' => 2, 'result_snapshot' => json_encode($result),
|
||||
]);
|
||||
$canonicalResult = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [json_encode($result, JSON_THROW_ON_ERROR)])->canonical;
|
||||
$reportHash = hash('sha256', $canonicalResult);
|
||||
DB::table('simulation_reports')->insert([
|
||||
'id' => (string) Str::uuid(), 'simulation_id' => $simulationId, 'version_no' => 1, 'status' => 'ready',
|
||||
'report_snapshot' => json_encode($result), 'report_sha256' => $reportHash,
|
||||
'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
$url = '/api/v1/simulation-drafts/'.$draftId.'/conversions';
|
||||
$headers = ['X-Simulation-Token' => $token, 'If-Match' => $draftResponse->headers->get('ETag')];
|
||||
|
||||
$this->postJson($url, ['simulation_id' => $simulationId, 'consent_reuse' => false], $headers)->assertUnprocessable();
|
||||
$attached = $this->postJson($url, ['simulation_id' => $simulationId, 'consent_reuse' => true], $headers)
|
||||
->assertOk()->assertJsonPath('replayed', false)
|
||||
->assertJsonPath('data.version_no', 2)
|
||||
->assertJsonPath('data.simulation_sources.0.result_snapshot.legal_interpretation', false)
|
||||
->assertJsonPath('data.simulation_sources.0.report_sha256', $reportHash)
|
||||
->assertJsonMissingPath('data.economic_snapshot.simulation_sources');
|
||||
|
||||
$this->postJson($url, ['simulation_id' => $simulationId, 'consent_reuse' => true], $headers)
|
||||
->assertOk()->assertJsonPath('replayed', true)->assertJsonPath('data.version_no', 2);
|
||||
$this->assertSame(1, count($attached->json('data.simulation_sources')));
|
||||
$this->assertSame(2, $attached->json('data.simulation_sources.0.source_version_no'));
|
||||
$this->assertNotEmpty($attached->json('data.simulation_sources.0.consented_at'));
|
||||
$this->assertFalse($attached->json('replayed'));
|
||||
|
||||
$formalDraft = $this->payload();
|
||||
$formalDraft['economic_snapshot']['purpose'] = 'own_investment';
|
||||
$formalDraft['economic_snapshot']['reuse_simulation'] = 'no';
|
||||
$this->putJson('/api/v1/simulation-drafts/'.$draftId, $formalDraft, [
|
||||
'X-Simulation-Token' => $token, 'If-Match' => $attached->headers->get('ETag'),
|
||||
])->assertOk();
|
||||
$this->getJson('/api/v1/simulation-drafts/'.$draftId, ['X-Simulation-Token' => $token])
|
||||
->assertOk()->assertJsonPath('data.simulation_sources', []);
|
||||
}
|
||||
|
||||
public function test_simulation_conversion_rejects_a_report_that_does_not_match_the_result_snapshot(): void
|
||||
{
|
||||
Queue::fake();
|
||||
$token = Str::random(48);
|
||||
$formalPayload = $this->payload();
|
||||
$formalPayload['economic_snapshot']['purpose'] = 'own_investment';
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', $formalPayload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
$simulation = $this->postJson('/api/v1/simulations', [
|
||||
'base' => '1200', 'rate' => '8', 'reduction' => '0',
|
||||
], ['Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token])->assertAccepted();
|
||||
$simulationId = $simulation->json('data.id');
|
||||
app(SimulationExecution::class)->setContext(null, hash_hmac('sha256', $token, (string) config('app.key')));
|
||||
$result = ['indicative_total' => '96.00000000', 'legal_interpretation' => false, 'formula_version' => 'portal-tax-arithmetic-v1'];
|
||||
$forgedReport = $result;
|
||||
$forgedReport['indicative_total'] = '96000.00000000';
|
||||
DB::table('simulations')->where('id', $simulationId)->update([
|
||||
'status' => 'completed', 'version_no' => 2, 'result_snapshot' => json_encode($result),
|
||||
]);
|
||||
$canonicalReport = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [json_encode($forgedReport, JSON_THROW_ON_ERROR)])->canonical;
|
||||
DB::table('simulation_reports')->insert([
|
||||
'id' => (string) Str::uuid(), 'simulation_id' => $simulationId, 'version_no' => 1, 'status' => 'ready',
|
||||
'report_snapshot' => json_encode($forgedReport), 'report_sha256' => hash('sha256', $canonicalReport),
|
||||
'created_at' => now(), 'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts/'.$draft->json('data.id').'/conversions', [
|
||||
'simulation_id' => $simulationId, 'consent_reuse' => true,
|
||||
], ['X-Simulation-Token' => $token, 'If-Match' => $draft->headers->get('ETag')])
|
||||
->assertStatus(409);
|
||||
|
||||
DB::table('simulation_reports')->insert([
|
||||
'id' => (string) Str::uuid(), 'simulation_id' => $simulationId, 'version_no' => 2, 'status' => 'ready',
|
||||
'report_snapshot' => json_encode($result), 'report_sha256' => str_repeat('0', 64),
|
||||
'created_at' => now()->addSecond(), 'updated_at' => now()->addSecond(),
|
||||
]);
|
||||
$this->postJson('/api/v1/simulation-drafts/'.$draft->json('data.id').'/conversions', [
|
||||
'simulation_id' => $simulationId, 'consent_reuse' => true,
|
||||
], ['X-Simulation-Token' => $token, 'If-Match' => $draft->headers->get('ETag')])
|
||||
->assertStatus(409);
|
||||
}
|
||||
|
||||
public function test_simulation_conversion_rejects_an_unowned_execution_token(): void
|
||||
{
|
||||
Queue::fake();
|
||||
$draftToken = Str::random(48);
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', $this->payload(), [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $draftToken,
|
||||
])->assertCreated();
|
||||
$otherToken = Str::random(48);
|
||||
$simulation = $this->postJson('/api/v1/simulations', ['base' => '1200', 'rate' => '8', 'reduction' => '0'], [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $otherToken,
|
||||
])->assertAccepted();
|
||||
|
||||
$this->postJson('/api/v1/simulation-drafts/'.$draft->json('data.id').'/conversions', [
|
||||
'simulation_id' => $simulation->json('data.id'), 'consent_reuse' => true,
|
||||
], ['X-Simulation-Token' => $draftToken, 'If-Match' => $draft->headers->get('ETag')])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_server_rejects_invalid_rates_and_unlisted_snapshot_fields(): void
|
||||
@@ -77,12 +310,58 @@ class SimulationFormDraftTest extends TestCase
|
||||
])->assertUnprocessable()->assertJsonValidationErrors('economic_snapshot');
|
||||
}
|
||||
|
||||
public function test_fiscal_mode_rejects_manual_rates_and_incomplete_custom_assumptions(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$payload = $this->payload();
|
||||
unset($payload['economic_snapshot']['tax_calculation'], $payload['economic_snapshot']['base'], $payload['economic_snapshot']['rate'], $payload['economic_snapshot']['reduction']);
|
||||
$payload['economic_snapshot']['fiscal_scenario_mode'] = 'approved_parameters';
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => $token,
|
||||
])->assertCreated();
|
||||
|
||||
$payload['economic_snapshot']['base'] = '1000';
|
||||
$payload['economic_snapshot']['rate'] = '5';
|
||||
$payload['economic_snapshot']['reduction'] = '0';
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertUnprocessable()->assertJsonValidationErrors(['economic_snapshot.base', 'economic_snapshot.rate', 'economic_snapshot.reduction']);
|
||||
|
||||
$payload = $this->payload();
|
||||
unset($payload['economic_snapshot']['tax_calculation']);
|
||||
$payload['economic_snapshot']['fiscal_scenario_mode'] = 'custom_planning';
|
||||
unset($payload['economic_snapshot']['base'], $payload['economic_snapshot']['rate'], $payload['economic_snapshot']['reduction']);
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertCreated();
|
||||
|
||||
$payload = $this->payload();
|
||||
unset($payload['economic_snapshot']['tax_calculation'], $payload['economic_snapshot']['base'], $payload['economic_snapshot']['reduction']);
|
||||
$payload['economic_snapshot']['fiscal_scenario_mode'] = 'custom_planning';
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertUnprocessable()->assertJsonValidationErrors(['economic_snapshot.base', 'economic_snapshot.reduction']);
|
||||
|
||||
$payload = $this->payload();
|
||||
unset($payload['economic_snapshot']['tax_calculation']);
|
||||
$payload['economic_snapshot']['fiscal_scenario_mode'] = 'custom_planning';
|
||||
$payload['economic_snapshot']['base'] = '1000';
|
||||
$payload['economic_snapshot']['rate'] = '5';
|
||||
$payload['economic_snapshot']['reduction'] = '0';
|
||||
$this->postJson('/api/v1/simulation-drafts', $payload, [
|
||||
'Idempotency-Key' => (string) Str::uuid(), 'X-Simulation-Token' => Str::random(48),
|
||||
])->assertCreated();
|
||||
}
|
||||
|
||||
/** @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'],
|
||||
'economic_snapshot' => [
|
||||
'journey_type' => 'personal', 'detail_level' => 'simple', 'business_plan_snapshot' => '{"version":1}',
|
||||
'purpose' => 'simulate_only', 'tax_calculation' => 'yes', 'base' => '1200', 'rate' => '8', 'reduction' => '0',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SimulationRateLimitTest extends TestCase
|
||||
{
|
||||
public function test_public_calculation_endpoint_limits_repeated_requests_per_anonymous_token(): void
|
||||
{
|
||||
$token = Str::random(48);
|
||||
$limiterKey = 'simulation-calculation:anonymous:'.hash('sha256', $token);
|
||||
RateLimiter::clear($limiterKey);
|
||||
|
||||
try {
|
||||
for ($attempt = 0; $attempt < 10; $attempt++) {
|
||||
$this->postJson('/api/v1/simulations', [], [
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertUnprocessable();
|
||||
}
|
||||
|
||||
$response = $this->postJson('/api/v1/simulations', [], [
|
||||
'X-Simulation-Token' => $token,
|
||||
])->assertTooManyRequests()->assertHeader('Retry-After');
|
||||
$this->assertStringContainsString('demasiados', (string) $response->json('message'));
|
||||
} finally {
|
||||
RateLimiter::clear($limiterKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InvestmentLegalSource;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SimulationTaxRuleGovernanceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $editor;
|
||||
|
||||
private User $reviewer;
|
||||
|
||||
private User $approver;
|
||||
|
||||
private User $publisher;
|
||||
|
||||
private InvestmentLegalSource $source;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->editor = User::factory()->withTwoFactor()->create();
|
||||
$this->reviewer = User::factory()->withTwoFactor()->create();
|
||||
$this->approver = User::factory()->withTwoFactor()->create();
|
||||
$this->publisher = User::factory()->withTwoFactor()->create();
|
||||
config([
|
||||
'portal.managers' => [$this->editor->email, $this->reviewer->email, $this->approver->email, $this->publisher->email],
|
||||
'simulation-tax-governance.editors' => [$this->editor->email],
|
||||
'simulation-tax-governance.reviewers' => [$this->editor->email, $this->reviewer->email],
|
||||
'simulation-tax-governance.approvers' => [$this->approver->email],
|
||||
'simulation-tax-governance.publishers' => [$this->publisher->email],
|
||||
]);
|
||||
$this->source = InvestmentLegalSource::query()->create([
|
||||
'title' => 'Synthetic source for governance test',
|
||||
'url' => 'https://law.example.invalid/test',
|
||||
'diploma' => 'Synthetic test instrument',
|
||||
'article' => 'Article 1 (test only)',
|
||||
'competent_entity' => 'Synthetic test reviewer',
|
||||
'valid_from' => '2020-01-01',
|
||||
'valid_until' => null,
|
||||
'validation_status' => 'validated',
|
||||
'owner_id' => $this->editor->id,
|
||||
'validator_id' => $this->reviewer->id,
|
||||
'validated_at' => now(),
|
||||
'version_no' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_rule_requires_independent_review_approval_publication_and_records_hash_chained_versions(): void
|
||||
{
|
||||
$this->actingAs($this->editor);
|
||||
$created = $this->postJson('/api/v2/investment/admin/tax-rules', $this->rulePayload())
|
||||
->assertCreated()->assertJsonPath('status', 'draft')->assertJsonPath('version_no', 1);
|
||||
$id = $created->json('id');
|
||||
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/submit", $this->transitionPayload(1))
|
||||
->assertOk()->assertJsonPath('status', 'submitted')->assertJsonPath('version_no', 2);
|
||||
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/review", $this->transitionPayload(2))
|
||||
->assertForbidden();
|
||||
|
||||
$this->actingAs($this->reviewer)
|
||||
->postJson("/api/v2/investment/admin/tax-rules/{$id}/review", $this->transitionPayload(2))
|
||||
->assertOk()->assertJsonPath('status', 'reviewed')->assertJsonPath('reviewer_id', $this->reviewer->id);
|
||||
|
||||
$this->actingAs($this->approver)
|
||||
->postJson("/api/v2/investment/admin/tax-rules/{$id}/approve", $this->transitionPayload(3))
|
||||
->assertOk()->assertJsonPath('status', 'approved')->assertJsonPath('approver_id', $this->approver->id);
|
||||
|
||||
$this->actingAs($this->publisher)
|
||||
->postJson("/api/v2/investment/admin/tax-rules/{$id}/publish", $this->transitionPayload(4))
|
||||
->assertOk()->assertJsonPath('status', 'published')->assertJsonPath('publisher_id', $this->publisher->id);
|
||||
|
||||
$events = $this->visibleEvents($id);
|
||||
$this->assertSame(['created', 'submit', 'review', 'approve', 'publish'], $events->pluck('action')->all());
|
||||
foreach ($events as $event) {
|
||||
$canonical = DB::selectOne('select CAST(? AS jsonb)::text as canonical', [$event->snapshot])->canonical;
|
||||
$this->assertSame(hash('sha256', $canonical), $event->sha256);
|
||||
}
|
||||
$this->assertDatabaseHas('simulation_tax_rule_versions', [
|
||||
'id' => $id, 'status' => 'published', 'rule_version' => 1, 'source_version_no' => 2,
|
||||
]);
|
||||
|
||||
DB::select("select set_config('app.actor_user_id', '', true), set_config('app.simulation_tax_governance', '', true)");
|
||||
$affected = null;
|
||||
try {
|
||||
$affected = DB::transaction(fn () => DB::table('simulation_tax_rule_events')
|
||||
->where('rule_version_id', $id)->update(['action' => 'tampered']), 1);
|
||||
} catch (QueryException) {
|
||||
// The immutable trigger rejects this on superuser-based test connections.
|
||||
}
|
||||
$this->assertTrue($affected === null || $affected === 0, 'RLS or the immutable trigger must reject direct event mutation.');
|
||||
$this->assertSame($events->pluck('action')->all(), $this->visibleEvents($id)->pluck('action')->all());
|
||||
$publishedStatus = DB::transaction(function () use ($id): ?string {
|
||||
DB::select("select set_config('app.actor_user_id', ?, true), set_config('app.simulation_tax_governance', 'on', true)", [(string) $this->publisher->id]);
|
||||
|
||||
return DB::table('simulation_tax_rule_versions')->where('id', $id)->value('status');
|
||||
});
|
||||
$this->assertSame('published', $publishedStatus);
|
||||
$this->actingAs($this->publisher)->getJson('/api/v2/investment/admin/tax-rules?rule_code=SYNTHETIC.TEST.RULE')
|
||||
->assertOk()->assertJsonPath('total', 1);
|
||||
}
|
||||
|
||||
public function test_source_revocation_stops_publication_and_conflicting_effective_rules_are_rejected(): void
|
||||
{
|
||||
$first = $this->publishRule($this->rulePayload());
|
||||
$this->assertSame('published', $first['status']);
|
||||
|
||||
$conflict = $this->rulePayload();
|
||||
$conflict['rule_version'] = 2;
|
||||
$this->actingAs($this->editor);
|
||||
$draft = $this->postJson('/api/v2/investment/admin/tax-rules', $conflict)->assertCreated();
|
||||
$id = $draft->json('id');
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/submit", $this->transitionPayload(1))->assertOk();
|
||||
$this->actingAs($this->reviewer)->postJson("/api/v2/investment/admin/tax-rules/{$id}/review", $this->transitionPayload(2))->assertOk();
|
||||
$this->actingAs($this->approver)->postJson("/api/v2/investment/admin/tax-rules/{$id}/approve", $this->transitionPayload(3))->assertOk();
|
||||
$this->actingAs($this->publisher)->postJson("/api/v2/investment/admin/tax-rules/{$id}/publish", $this->transitionPayload(4))
|
||||
->assertConflict();
|
||||
|
||||
$this->source->update(['validation_status' => 'revoked', 'version_no' => 3]);
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/publish", $this->transitionPayload(4))
|
||||
->assertUnprocessable();
|
||||
$ruleId = $first['id'];
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$ruleId}/suspend", $this->transitionPayload(5))
|
||||
->assertOk()->assertJsonPath('status', 'suspended');
|
||||
}
|
||||
|
||||
public function test_draft_edit_uses_optimistic_locking_and_other_roles_cannot_create_rules(): void
|
||||
{
|
||||
$this->actingAs($this->reviewer)->postJson('/api/v2/investment/admin/tax-rules', $this->rulePayload())->assertForbidden();
|
||||
|
||||
$this->actingAs($this->editor);
|
||||
$created = $this->postJson('/api/v2/investment/admin/tax-rules', $this->rulePayload())->assertCreated();
|
||||
$id = $created->json('id');
|
||||
$payload = $this->rulePayload();
|
||||
$payload['rule_definition'] = ['kind' => 'unexecuted_declarative_example'];
|
||||
$this->putJson("/api/v2/investment/admin/tax-rules/{$id}", ['version_no' => 99, ...$payload])->assertConflict();
|
||||
$this->putJson("/api/v2/investment/admin/tax-rules/{$id}", ['version_no' => 1, ...$payload])
|
||||
->assertOk()->assertJsonPath('version_no', 2);
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/submit", $this->transitionPayload(1))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_rollback_refuses_to_drop_rule_versions_or_their_audit_history(): void
|
||||
{
|
||||
$this->actingAs($this->editor)->postJson('/api/v2/investment/admin/tax-rules', $this->rulePayload())->assertCreated();
|
||||
$migration = require database_path('migrations/2026_10_03_170000_create_simulation_tax_rule_governance.php');
|
||||
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Rollback must preserve recorded rule governance.');
|
||||
} catch (\RuntimeException $exception) {
|
||||
$this->assertStringContainsString('history exists', $exception->getMessage());
|
||||
}
|
||||
|
||||
$this->assertTrue(Schema::hasTable('simulation_tax_rule_versions'));
|
||||
$this->assertTrue(Schema::hasTable('simulation_tax_rule_events'));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function publishRule(array $payload): array
|
||||
{
|
||||
$this->actingAs($this->editor);
|
||||
$draft = $this->postJson('/api/v2/investment/admin/tax-rules', $payload)->assertCreated();
|
||||
$id = $draft->json('id');
|
||||
$this->postJson("/api/v2/investment/admin/tax-rules/{$id}/submit", $this->transitionPayload(1))->assertOk();
|
||||
$this->actingAs($this->reviewer)->postJson("/api/v2/investment/admin/tax-rules/{$id}/review", $this->transitionPayload(2))->assertOk();
|
||||
$this->actingAs($this->approver)->postJson("/api/v2/investment/admin/tax-rules/{$id}/approve", $this->transitionPayload(3))->assertOk();
|
||||
|
||||
return $this->actingAs($this->publisher)->postJson("/api/v2/investment/admin/tax-rules/{$id}/publish", $this->transitionPayload(4))
|
||||
->assertOk()->json();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function rulePayload(): array
|
||||
{
|
||||
return [
|
||||
'rule_code' => 'SYNTHETIC.TEST.RULE',
|
||||
'rule_version' => 1,
|
||||
'component' => 'IRPC',
|
||||
'scope_key' => 'MZ:test:synthetic',
|
||||
'valid_from' => '2026-01-01',
|
||||
'valid_until' => null,
|
||||
'legal_source_id' => $this->source->id,
|
||||
'source_sha256' => str_repeat('a', 64),
|
||||
'rule_definition' => ['kind' => 'unexecuted_synthetic_fixture'],
|
||||
'parameters' => ['fixture' => 'not-a-tax-rate'],
|
||||
'rounding_policy' => ['fixture' => 'not-approved'],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{version_no:int,evidence:string} */
|
||||
private function transitionPayload(int $version): array
|
||||
{
|
||||
return ['version_no' => $version, 'evidence' => 'Synthetic governance evidence for automated test only.'];
|
||||
}
|
||||
|
||||
/** @return Collection<int,object> */
|
||||
private function visibleEvents(string $ruleId): Collection
|
||||
{
|
||||
return DB::transaction(function () use ($ruleId): Collection {
|
||||
DB::select("select set_config('app.actor_user_id', ?, true), set_config('app.simulation_tax_governance', 'on', true)", [(string) $this->publisher->id]);
|
||||
|
||||
return DB::table('simulation_tax_rule_events')->where('rule_version_id', $ruleId)->orderBy('version_no')->get();
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user