@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
$server = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $errorMessage);
|
||||
if (! is_resource($server)) {
|
||||
fwrite(STDERR, 'Unable to bind local timeout fixture.');
|
||||
exit(1);
|
||||
}
|
||||
|
||||
echo stream_socket_get_name($server, false)."\n";
|
||||
fflush(STDOUT);
|
||||
for ($request = 0; $request < 3; $request++) {
|
||||
$connection = @stream_socket_accept($server, 5);
|
||||
if (! is_resource($connection)) {
|
||||
break;
|
||||
}
|
||||
|
||||
$command = stream_get_line($connection, 65536, "\0");
|
||||
if ($command === 'zPING') {
|
||||
fwrite($connection, "PONG\0");
|
||||
fclose($connection);
|
||||
continue;
|
||||
}
|
||||
if ($command === 'zVERSION') {
|
||||
fwrite($connection, 'ClamAV 1.5.4/999/'.gmdate('D M j H:i:s Y')."\0");
|
||||
fclose($connection);
|
||||
continue;
|
||||
}
|
||||
if ($command === 'zINSTREAM') {
|
||||
while (true) {
|
||||
$lengthBytes = '';
|
||||
while (strlen($lengthBytes) < 4) {
|
||||
$part = fread($connection, 4 - strlen($lengthBytes));
|
||||
if ($part === false || $part === '') {
|
||||
break 2;
|
||||
}
|
||||
$lengthBytes .= $part;
|
||||
}
|
||||
$length = unpack('Nlength', $lengthBytes)['length'];
|
||||
if ($length === 0) {
|
||||
sleep(4);
|
||||
break;
|
||||
}
|
||||
$remaining = $length;
|
||||
while ($remaining > 0) {
|
||||
$part = fread($connection, min(65536, $remaining));
|
||||
if ($part === false || $part === '') {
|
||||
break 3;
|
||||
}
|
||||
$remaining -= strlen($part);
|
||||
}
|
||||
}
|
||||
fclose($connection);
|
||||
break;
|
||||
}
|
||||
fclose($connection);
|
||||
}
|
||||
fclose($server);
|
||||
+19
-1
@@ -12,11 +12,29 @@ abstract class TestCase extends BaseTestCase
|
||||
public function createApplication(): Application
|
||||
{
|
||||
$app = parent::createApplication();
|
||||
$connectionName = $app->make('config')->get('database.default');
|
||||
$connection = $app->make('config')->get('database.connections.'.$connectionName, []);
|
||||
|
||||
// Never let a test runner silently fall back to the developer/application database.
|
||||
// Keep this check before RefreshDatabase or any schema cleanup can open a connection.
|
||||
if ($app->environment('testing') && ($connection['driver'] ?? null) === 'pgsql') {
|
||||
$database = strtolower((string) ($connection['database'] ?? ''));
|
||||
$host = strtolower((string) ($connection['host'] ?? ''));
|
||||
$url = $connection['url'] ?? null;
|
||||
|
||||
if ($database === 'investemoz'
|
||||
|| ! str_ends_with($database, '_test')
|
||||
|| ! in_array($host, ['127.0.0.1', 'localhost'], true)
|
||||
|| ! in_array($url, [null, ''], true)) {
|
||||
throw new \LogicException('PHPUnit PostgreSQL target rejected: configure an explicit loopback *_test database with no DB_URL.');
|
||||
}
|
||||
}
|
||||
|
||||
// migrate:fresh only clears the connection's public search path. This module owns a separate schema.
|
||||
if (! RefreshDatabaseState::$migrated && $app->environment('testing')) {
|
||||
$db = $app->make('db')->connection();
|
||||
if ($db->getDriverName() === 'pgsql'
|
||||
&& in_array($db->getDatabaseName(), ['portal_services_test', 'investmoz_test'], true)
|
||||
&& in_array($db->getDatabaseName(), ['portal_services_test', 'investmoz_test', 'investmoz_browser_e2e_test'], true)
|
||||
&& (string) $db->getConfig('port') === '55441'
|
||||
&& in_array($db->getConfig('host'), ['127.0.0.1', 'localhost'], true)) {
|
||||
$db->statement('DROP SCHEMA IF EXISTS skills_edu CASCADE');
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\SimulationFormDraftPrivacyPolicy;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class SimulationFormDraftPrivacyPolicyTest extends TestCase
|
||||
{
|
||||
public function test_anonymous_snapshots_discard_identity_but_keep_financial_assumptions(): void
|
||||
{
|
||||
$data = [
|
||||
'personal_snapshot' => ['legal_name' => 'Pessoa de teste', 'email' => 'person@example.com'],
|
||||
'economic_snapshot' => ['purpose' => 'simulate_only', 'currency' => 'MZN'],
|
||||
];
|
||||
|
||||
$this->assertSame([
|
||||
'personal_snapshot' => [],
|
||||
'economic_snapshot' => ['purpose' => 'simulate_only', 'currency' => 'MZN'],
|
||||
], SimulationFormDraftPrivacyPolicy::apply($data, false));
|
||||
}
|
||||
|
||||
public function test_authenticated_snapshots_can_retain_identity_in_the_owned_account_draft(): void
|
||||
{
|
||||
$data = [
|
||||
'personal_snapshot' => ['legal_name' => 'Pessoa de teste'],
|
||||
'economic_snapshot' => ['purpose' => 'own_investment'],
|
||||
];
|
||||
|
||||
$this->assertSame($data, SimulationFormDraftPrivacyPolicy::apply($data, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\SimulationTaxParameterResolver;
|
||||
use InvalidArgumentException;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class SimulationTaxParameterResolverTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_selects_the_published_version_effective_on_the_requested_date_and_returns_its_source(): void
|
||||
{
|
||||
$old = $this->version('2025-01-01', '2025-12-31', '15', 1);
|
||||
$current = $this->version('2026-01-01', null, '16', 2);
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
|
||||
self::assertSame('15', $resolver->resolve([$old, $current], 'IVA', 'scope:test', '2025-12-31', 'VAT_RATE')['value']);
|
||||
$resolved = $resolver->resolve([$old, $current], 'IVA', 'scope:test', '2026-01-01', 'VAT_RATE');
|
||||
self::assertSame('resolved', $resolved['status']);
|
||||
self::assertSame('16', $resolved['value']);
|
||||
self::assertSame('LAW-2026', $resolved['source']['diploma']);
|
||||
self::assertSame(2, $resolved['rule_version']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_indeterminate_for_missing_or_overlapping_candidates(): void
|
||||
{
|
||||
$version = $this->version('2026-01-01', null, '16', 1);
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
|
||||
self::assertSame('indeterminate_missing', $resolver->resolve([], 'IVA', 'scope:test', '2026-07-01', 'VAT_RATE')['status']);
|
||||
self::assertSame('indeterminate_missing', $resolver->resolve([$version], 'IVA', 'different-scope', '2026-07-01', 'VAT_RATE')['status']);
|
||||
self::assertSame('indeterminate_missing', $resolver->resolve([$version], 'IVA', 'scope:test', '2025-12-31', 'VAT_RATE')['status']);
|
||||
self::assertSame('indeterminate_overlap', $resolver->resolve([$version, $version], 'IVA', 'scope:test', '2026-07-01', 'VAT_RATE')['status']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_requires_exactly_matching_conditions_and_a_still_validated_source_version(): void
|
||||
{
|
||||
$version = $this->version('2026-01-01', null, '16', 1);
|
||||
$version['parameters']['VAT_RATE']['conditions'] = ['operation' => 'domestic'];
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
|
||||
self::assertSame('indeterminate_missing', $resolver->resolve([$version], 'IVA', 'scope:test', '2026-03-01', 'VAT_RATE', ['operation' => 'import'])['status']);
|
||||
$version['source_version_no'] = 2;
|
||||
self::assertSame('indeterminate_missing', $resolver->resolve([$version], 'IVA', 'scope:test', '2026-03-01', 'VAT_RATE', ['operation' => 'domestic'])['status']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_rejects_negative_values_and_percentages_over_one_hundred(): void
|
||||
{
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
foreach (['-0.01' => 'mzn', '100.0001' => 'percent'] as $value => $unit) {
|
||||
try {
|
||||
$resolver->validateParameters(['TEST_VALUE' => ['value' => $value, 'unit' => $unit, 'conditions' => []]]);
|
||||
self::fail('Invalid parameter value was accepted.');
|
||||
} catch (InvalidArgumentException) {
|
||||
self::assertTrue(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_does_not_select_a_parameter_when_its_validity_changes_inside_the_requested_period(): void
|
||||
{
|
||||
$before = $this->publicVersion('2026-01-01', '2026-06-30', '16', 1);
|
||||
$after = $this->publicVersion('2026-07-01', null, '17', 2);
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
|
||||
$result = $resolver->resolveAvailableParameters([$before, $after], 'IVA', '2026-01-01', '2026-12-31', ['operation' => 'domestic']);
|
||||
|
||||
self::assertSame('indeterminate_period_change', $result[0]['status']);
|
||||
self::assertNull($result[0]['value']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_resolves_a_single_parameter_only_for_an_exactly_matching_context(): void
|
||||
{
|
||||
$version = $this->publicVersion('2026-01-01', null, '16', 1);
|
||||
$resolver = new SimulationTaxParameterResolver;
|
||||
|
||||
$result = $resolver->resolveAvailableParameters([$version], 'IVA', '2026-01-01', '2026-12-31', ['operation' => 'domestic']);
|
||||
|
||||
self::assertSame('resolved', $result[0]['status']);
|
||||
self::assertSame('16', $result[0]['value']);
|
||||
self::assertSame('Synthetic source fixture', $result[0]['source']['title']);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function version(string $from, ?string $until, string $value, int $version): array
|
||||
{
|
||||
return [
|
||||
'id' => 'rule-'.$version,
|
||||
'rule_code' => 'IVA.VAT.RATE',
|
||||
'rule_version' => $version,
|
||||
'component' => 'IVA',
|
||||
'scope_key' => 'scope:test',
|
||||
'status' => 'published',
|
||||
'valid_from' => $from,
|
||||
'valid_until' => $until,
|
||||
'parameters' => ['VAT_RATE' => ['value' => $value, 'unit' => 'percent', 'conditions' => []]],
|
||||
'source_version_no' => 1,
|
||||
'source_sha256' => str_repeat('a', 64),
|
||||
'source' => [
|
||||
'validation_status' => 'validated',
|
||||
'version_no' => 1,
|
||||
'valid_from' => '2020-01-01',
|
||||
'valid_until' => null,
|
||||
'title' => 'Synthetic source fixture',
|
||||
'diploma' => 'LAW-2026',
|
||||
'article' => 'Article fixture',
|
||||
'url' => 'https://example.invalid/source',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function publicVersion(string $from, ?string $until, string $value, int $version): array
|
||||
{
|
||||
$record = $this->version($from, $until, $value, $version);
|
||||
$record['rule_definition'] = ['language' => 'investmoz.tax.v1'];
|
||||
$record['parameters']['VAT_RATE']['conditions'] = ['operation' => 'domestic'];
|
||||
|
||||
return $record;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\SimulationTaxRuleExpression;
|
||||
use InvalidArgumentException;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class SimulationTaxRuleExpressionTest extends TestCase
|
||||
{
|
||||
#[Test]
|
||||
public function it_evaluates_a_whitelisted_dag_with_exact_decimal_arithmetic_and_explicit_rounding(): void
|
||||
{
|
||||
$definition = $this->definition();
|
||||
$result = (new SimulationTaxRuleExpression)->evaluate($definition, ['base' => '1234.56'], ['rate' => '0.16']);
|
||||
|
||||
self::assertSame('determinate', $result['status']);
|
||||
self::assertSame('19753/100', $result['result']);
|
||||
self::assertCount(4, $result['steps']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_reports_missing_values_as_indeterminate_without_defaults(): void
|
||||
{
|
||||
$result = (new SimulationTaxRuleExpression)->evaluate($this->definition(), [], []);
|
||||
|
||||
self::assertSame('indeterminate', $result['status']);
|
||||
self::assertNull($result['result']);
|
||||
self::assertSame(['input:base', 'parameter:rate'], $result['missing']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_rejects_cycles_unknown_operations_and_undeclared_fields(): void
|
||||
{
|
||||
$engine = new SimulationTaxRuleExpression;
|
||||
$cycle = ['language' => 'investmoz.tax.v1', 'nodes' => ['a' => ['op' => 'add', 'args' => ['b', 'b']], 'b' => ['op' => 'add', 'args' => ['a', 'a']]], 'result' => 'a'];
|
||||
$unknown = ['language' => 'investmoz.tax.v1', 'nodes' => ['a' => ['op' => 'execute', 'code' => 'x']], 'result' => 'a'];
|
||||
$extra = ['language' => 'investmoz.tax.v1', 'nodes' => ['a' => ['op' => 'literal', 'value' => '1', 'formula' => 'x']], 'result' => 'a'];
|
||||
|
||||
foreach ([$cycle, $unknown, $extra] as $invalid) {
|
||||
try {
|
||||
$engine->validate($invalid);
|
||||
self::fail('Invalid DSL was accepted.');
|
||||
} catch (InvalidArgumentException) {
|
||||
self::assertTrue(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function definition(): array
|
||||
{
|
||||
return [
|
||||
'language' => 'investmoz.tax.v1',
|
||||
'nodes' => [
|
||||
'base' => ['op' => 'input', 'key' => 'base'],
|
||||
'rate' => ['op' => 'parameter', 'key' => 'rate'],
|
||||
'raw' => ['op' => 'multiply', 'args' => ['base', 'rate']],
|
||||
'tax' => ['op' => 'round', 'args' => ['raw'], 'scale' => 2, 'mode' => 'HALF_UP'],
|
||||
],
|
||||
'result' => 'tax',
|
||||
];
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
decodeBusinessLocations,
|
||||
emptyBusinessLocation,
|
||||
encodeBusinessLocations,
|
||||
hasDuplicateBusinessLocationPath,
|
||||
updateBusinessLocation,
|
||||
} from '../../resources/js/lib/business-locations.ts';
|
||||
|
||||
test('location paths survive draft encoding and malformed drafts are ignored safely', () => {
|
||||
const paths = [
|
||||
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
|
||||
{ province_id: 'province-b', district_id: '', admin_post_id: '', locality_id: '' },
|
||||
];
|
||||
assert.deepEqual(decodeBusinessLocations(encodeBusinessLocations(paths)), paths);
|
||||
assert.deepEqual(decodeBusinessLocations('{invalid'), []);
|
||||
assert.deepEqual(decodeBusinessLocations('null'), []);
|
||||
});
|
||||
|
||||
test('changing a parent clears every dependent selection in only that row', () => {
|
||||
const initial = {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-a',
|
||||
admin_post_id: 'post-a',
|
||||
locality_id: 'locality-a',
|
||||
};
|
||||
const rows = [initial, emptyBusinessLocation()];
|
||||
const updated = updateBusinessLocation(rows, 0, 'district_id', 'district-b');
|
||||
assert.deepEqual(updated[0], {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-b',
|
||||
admin_post_id: '',
|
||||
locality_id: '',
|
||||
});
|
||||
assert.deepEqual(updated[1], emptyBusinessLocation());
|
||||
});
|
||||
|
||||
test('overlapping paths are detected while separate administrative branches remain valid', () => {
|
||||
assert.equal(hasDuplicateBusinessLocationPath([
|
||||
{ province_id: 'province-a', district_id: '', admin_post_id: '', locality_id: '' },
|
||||
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
|
||||
]), true);
|
||||
assert.equal(hasDuplicateBusinessLocationPath([
|
||||
{ province_id: 'province-a', district_id: 'district-a', admin_post_id: '', locality_id: '' },
|
||||
{ province_id: 'province-a', district_id: 'district-b', admin_post_id: '', locality_id: '' },
|
||||
emptyBusinessLocation(),
|
||||
]), false);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { csvCell, csvCellWithDelimiter } from '../../resources/js/lib/csv.js';
|
||||
|
||||
test('CSV cells neutralize formula prefixes after spaces or controls', () => {
|
||||
assert.equal(csvCell('=SUM(A1:A2)'), "'=SUM(A1:A2)");
|
||||
assert.equal(csvCell('\t@SUM(A1:A2)'), "'\t@SUM(A1:A2)");
|
||||
assert.equal(csvCell('\uFEFF+cmd'), "'\uFEFF+cmd");
|
||||
assert.equal(csvCell('-2+cmd'), "'-2+cmd");
|
||||
});
|
||||
|
||||
test('CSV cells preserve numeric negatives and quote/escape delimiters', () => {
|
||||
assert.equal(csvCell('-5000.00'), '-5000.00');
|
||||
assert.equal(csvCellWithDelimiter('Planeado; realizado', ';'), '"Planeado; realizado"');
|
||||
assert.equal(csvCell('Operação, mensal'), '"Operação, mensal"');
|
||||
assert.equal(csvCell('=HYPERLINK("x")'), '"\'=HYPERLINK(""x"")"');
|
||||
});
|
||||
@@ -0,0 +1,338 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildLoanSchedule,
|
||||
calculateBreakEven,
|
||||
calculateBudget,
|
||||
calculateFinancialTools,
|
||||
calculateFundingGap,
|
||||
calculateLoanPayment,
|
||||
exportFinancialToolsCsv,
|
||||
restoreFinancialToolsSnapshot,
|
||||
serializeFinancialToolsSnapshot,
|
||||
} from '../../resources/js/lib/financial-calculators.ts';
|
||||
|
||||
function cents(value) {
|
||||
const [whole, fraction = ''] = value.split('.');
|
||||
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
||||
}
|
||||
|
||||
test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
|
||||
const data = {
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '100000',
|
||||
rate: '18',
|
||||
months: '24',
|
||||
rateType: 'nominal',
|
||||
periodMonths: '1',
|
||||
gracePeriods: '0',
|
||||
upfrontFee: '0',
|
||||
recurringFee: '0',
|
||||
},
|
||||
breakEven: { fixed: '50000', price: '1000', variable: '600' },
|
||||
funding: { total: '1000000', secured: '250000' },
|
||||
incomes: [{ label: 'Vendas', amount: '200000' }],
|
||||
expenses: [{ label: 'Renda', amount: '15000' }],
|
||||
};
|
||||
const snapshot = serializeFinancialToolsSnapshot(data);
|
||||
assert.deepEqual(restoreFinancialToolsSnapshot(snapshot), data);
|
||||
assert.equal(restoreFinancialToolsSnapshot('{"version":2}'), null);
|
||||
assert.equal(restoreFinancialToolsSnapshot('x'.repeat(30001)), null);
|
||||
assert.equal(
|
||||
restoreFinancialToolsSnapshot(
|
||||
serializeFinancialToolsSnapshot({ ...data, incomes: [] }),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
restoreFinancialToolsSnapshot(
|
||||
serializeFinancialToolsSnapshot({
|
||||
...data,
|
||||
incomes: Array.from({ length: 51 }, () => ({
|
||||
label: 'x',
|
||||
amount: '1',
|
||||
})),
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('loan payment handles zero interest exactly', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1200.00', '0', 12), {
|
||||
monthlyPayment: '100.00',
|
||||
totalPaid: '1200.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('loan payment computes a reproducible amortized estimate', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1000.00', '12', 12), {
|
||||
monthlyPayment: '88.85',
|
||||
totalPaid: '1066.19',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('break-even rounds required units upward and rejects nonpositive margin', () => {
|
||||
assert.deepEqual(calculateBreakEven('100.00', '30.00', '20.00'), {
|
||||
contributionPerUnit: '10.00',
|
||||
breakEvenUnits: '10',
|
||||
breakEvenRevenue: '300.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
assert.throws(() => calculateBreakEven('10', '20', '20'), /superior/);
|
||||
});
|
||||
|
||||
test('an invalid indicator does not hide independent financial calculations', () => {
|
||||
const result = calculateFinancialTools({
|
||||
loan: {
|
||||
principal: '1200',
|
||||
annualRatePercent: '0',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
},
|
||||
breakEven: {
|
||||
fixedCosts: '100',
|
||||
unitPrice: '20',
|
||||
variableCostPerUnit: '20',
|
||||
},
|
||||
funding: { totalInvestment: '5000', securedFunding: '1000' },
|
||||
incomes: ['500'],
|
||||
expenses: ['600'],
|
||||
});
|
||||
|
||||
assert.equal(result.loan.value?.schedule[0].totalPayment, '100.00');
|
||||
assert.match(result.breakEven.error ?? '', /superior/);
|
||||
assert.equal(result.funding.value?.gap, '4000.00');
|
||||
assert.equal(result.budget.value?.operatingBalance, '-100.00');
|
||||
});
|
||||
|
||||
test('funding gap distinguishes zero from a negative surplus', () => {
|
||||
assert.deepEqual(calculateFundingGap('100.00', '120.00'), {
|
||||
gap: '-20.00',
|
||||
reconciles: false,
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid precision and negative inputs are rejected', () => {
|
||||
assert.throws(() => calculateFundingGap('-1', '0'), /decimal/);
|
||||
assert.throws(() => calculateLoanPayment('1.001', '0', 1), /casas/);
|
||||
});
|
||||
|
||||
test('loan schedule supports nominal rates, interest-only grace and separate fees', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1200.00',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 4,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
gracePeriods: 2,
|
||||
upfrontFee: '10',
|
||||
recurringFee: '2',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '1.000000');
|
||||
assert.equal(result.netDisbursed, '1190.00');
|
||||
assert.equal(result.schedule[0].interest, '12.00');
|
||||
assert.equal(result.schedule[0].principal, '0.00');
|
||||
assert.equal(result.schedule[0].fee, '2.00');
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.principal), 0n),
|
||||
120000n,
|
||||
);
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.totalPayment),
|
||||
0n,
|
||||
) + cents(result.upfrontFee),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
for (const row of result.schedule) {
|
||||
assert.equal(
|
||||
cents(row.openingBalance) - cents(row.principal),
|
||||
cents(row.closingBalance),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('loan schedule reconciles exact cents and adjusts the final installment', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000.01',
|
||||
annualRatePercent: '7.123456',
|
||||
termMonths: 7,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '0.593621');
|
||||
assert.equal(result.totalInterest, '23.88');
|
||||
assert.equal(result.totalPaid, '1023.89');
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.principal), 0n),
|
||||
100001n,
|
||||
);
|
||||
assert.equal(
|
||||
result.schedule.reduce((sum, row) => sum + cents(row.totalPayment), 0n),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
});
|
||||
|
||||
test('effective annual rate is converted to the selected repayment period', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 12,
|
||||
rateType: 'effective',
|
||||
});
|
||||
assert.equal(result.periodicRatePercent, '12.000000');
|
||||
assert.equal(result.schedule[0].interest, '120.00');
|
||||
assert.equal(result.totalPaid, '1120.00');
|
||||
const quarterly = buildLoanSchedule({
|
||||
principal: '1000',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 3,
|
||||
rateType: 'effective',
|
||||
});
|
||||
assert.equal(quarterly.periodicRatePercent, '2.873734');
|
||||
assert.equal(quarterly.schedule.at(-1).closingBalance, '0.00');
|
||||
});
|
||||
|
||||
test('loan schedules reconcile across rates, periodicities and grace periods', () => {
|
||||
for (const periodMonths of [1, 2, 3, 4, 6, 12]) {
|
||||
for (const rateType of ['nominal', 'effective']) {
|
||||
for (const annualRatePercent of ['0', '8.500000', '24']) {
|
||||
for (const gracePeriods of [0, 2]) {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '12345.67',
|
||||
annualRatePercent,
|
||||
termMonths: periodMonths * 12,
|
||||
periodMonths,
|
||||
rateType,
|
||||
gracePeriods,
|
||||
upfrontFee: '15.25',
|
||||
recurringFee: '2.37',
|
||||
});
|
||||
|
||||
assert.equal(result.schedule.length, 12);
|
||||
assert.equal(result.schedule.at(-1).closingBalance, '0.00');
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.principal),
|
||||
0n,
|
||||
),
|
||||
1_234_567n,
|
||||
);
|
||||
for (const row of result.schedule) {
|
||||
assert.equal(
|
||||
cents(row.openingBalance) - cents(row.principal),
|
||||
cents(row.closingBalance),
|
||||
);
|
||||
assert.ok(cents(row.closingBalance) >= 0n);
|
||||
}
|
||||
assert.equal(
|
||||
result.schedule.reduce(
|
||||
(sum, row) => sum + cents(row.totalPayment),
|
||||
0n,
|
||||
) + cents(result.upfrontFee),
|
||||
cents(result.totalPaid),
|
||||
);
|
||||
assert.equal(
|
||||
cents(result.totalPaid),
|
||||
1_234_567n +
|
||||
cents(result.totalInterest) +
|
||||
cents(result.totalFees),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('budget preserves an operating deficit and rejects invalid values', () => {
|
||||
assert.deepEqual(calculateBudget(['100.00', '25.50'], ['140.00']), {
|
||||
incomeTotal: '125.50',
|
||||
expenseTotal: '140.00',
|
||||
operatingBalance: '-14.50',
|
||||
status: 'estimated',
|
||||
});
|
||||
assert.throws(() => calculateBudget(['0'], ['-1']), /não negativo/);
|
||||
});
|
||||
|
||||
test('budget distinguishes absent income or expense rows from explicit zero', () => {
|
||||
assert.throws(() => calculateBudget([], ['0']), /pelo menos uma linha/);
|
||||
assert.throws(() => calculateBudget(['0'], []), /pelo menos uma linha/);
|
||||
assert.deepEqual(calculateBudget(['0'], ['0']), {
|
||||
incomeTotal: '0.00',
|
||||
expenseTotal: '0.00',
|
||||
operatingBalance: '0.00',
|
||||
status: 'estimated',
|
||||
});
|
||||
});
|
||||
|
||||
test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
|
||||
const base = {
|
||||
principal: '1000',
|
||||
annualRatePercent: '0',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
};
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, periodMonths: 5 }),
|
||||
/Periodicidade/,
|
||||
);
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, gracePeriods: 12 }),
|
||||
/carência/,
|
||||
);
|
||||
assert.throws(
|
||||
() => buildLoanSchedule({ ...base, upfrontFee: '1001' }),
|
||||
/exceder o capital/,
|
||||
);
|
||||
});
|
||||
|
||||
test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
|
||||
const csv = exportFinancialToolsCsv({
|
||||
currency: 'MZN',
|
||||
generatedAt: '2026-10-02T10:00:00.000Z',
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '1200',
|
||||
annualRatePercent: '12',
|
||||
termMonths: 12,
|
||||
periodMonths: 1,
|
||||
rateType: 'nominal',
|
||||
gracePeriods: 0,
|
||||
upfrontFee: '10',
|
||||
recurringFee: '2',
|
||||
},
|
||||
breakEven: {
|
||||
fixedCosts: '1000',
|
||||
unitPrice: '30',
|
||||
variableCostPerUnit: '20',
|
||||
},
|
||||
funding: { totalInvestment: '5000', securedFunding: '3000' },
|
||||
incomes: [
|
||||
{ label: '=HYPERLINK("https://example.invalid")', amount: '2500' },
|
||||
],
|
||||
expenses: [{ label: 'Operação, mensal', amount: '1800' }],
|
||||
});
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /financial-tools-v1/);
|
||||
assert.match(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /2026-10-02T10:00:00\.000Z/);
|
||||
assert.match(csv, /Período do orçamento e dos custos fixos,Mensal/);
|
||||
assert.match(csv, /saldo decrescente/i);
|
||||
assert.match(csv, /Saldo operacional,,700\.00/);
|
||||
assert.match(csv, /Unidades de equilíbrio,100/);
|
||||
assert.match(csv, /Diferença por financiar,2000\.00/);
|
||||
assert.match(csv, /"'=HYPERLINK/);
|
||||
assert.match(csv, /"Operação, mensal"/);
|
||||
assert.match(csv, /não inclui impostos/);
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { buildFinancialFiscalBridge } from '../../resources/js/lib/financial-fiscal-bridge.ts';
|
||||
import { forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
const plan = {
|
||||
currency: 'MZN',
|
||||
openingCash: '0',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço',
|
||||
monthlyUnits: '10',
|
||||
unitPrice: '100',
|
||||
unitVariableCost: '30',
|
||||
},
|
||||
],
|
||||
monthlyCollections: '800',
|
||||
monthlyVariableCostPayments: '250',
|
||||
monthlyOperatingExpenses: '100',
|
||||
monthlyOperatingPayments: '80',
|
||||
monthlyPayrollExpense: '50',
|
||||
monthlyPayrollPayments: '40',
|
||||
assetInvestment: '0',
|
||||
inventory: '0',
|
||||
receivables: '0',
|
||||
payables: '0',
|
||||
equity: '0',
|
||||
shareholderLoans: '0',
|
||||
bankLoanProceeds: '0',
|
||||
grants: '0',
|
||||
assetDepreciation: '0',
|
||||
depreciationLifeMonths: 12,
|
||||
monthlyInterestExpense: '10',
|
||||
monthlyInterestPayment: '5',
|
||||
monthlyPrincipalRepayment: '60',
|
||||
periods: 2,
|
||||
};
|
||||
|
||||
test('financial to fiscal bridge reconciles accounting result while leaving tax base indeterminate', () => {
|
||||
const forecast = forecastBusinessPlan(plan);
|
||||
const bridge = buildFinancialFiscalBridge(forecast);
|
||||
const byCode = Object.fromEntries(
|
||||
bridge.accountingLines.map((line) => [line.code, line]),
|
||||
);
|
||||
const cents = (value) => {
|
||||
const [whole, fraction] = value.split('.');
|
||||
return BigInt(whole) * 100n + BigInt(fraction);
|
||||
};
|
||||
const accountingProfit = [
|
||||
byCode.revenue.total,
|
||||
...Object.values(byCode)
|
||||
.filter((line) => line.accountingEffect === 'expense')
|
||||
.map((line) => `-${line.total}`),
|
||||
].reduce((sum, value) => sum + cents(value), 0n);
|
||||
|
||||
assert.equal(bridge.status, 'incomplete');
|
||||
assert.equal(bridge.accountingProfitBeforeTax, '1080.00');
|
||||
assert.equal(accountingProfit, cents(bridge.accountingProfitBeforeTax));
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
assert.equal(bridge.taxableBase.amount, null);
|
||||
assert.ok(
|
||||
bridge.taxableBase.missingInputs.includes(
|
||||
'expense_deductibility_classification',
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
bridge.accountingLines.every(
|
||||
(line) => line.taxTreatment === 'unclassified',
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(byCode.revenue.monthlyAmounts[0].amount, '1000.00');
|
||||
assert.equal(byCode.cost_of_sales.monthlyAmounts[0].amount, '300.00');
|
||||
assert.equal(bridge.cashSchedule[0].collections, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].collectionMode, 'manual');
|
||||
assert.equal(bridge.cashSchedule[0].salesCollections, null);
|
||||
assert.equal(bridge.cashSchedule[0].openingReceivablesCollections, '0.00');
|
||||
assert.equal(bridge.cashSchedule[0].otherCollections, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].collectionsTotal, '800.00');
|
||||
assert.equal(bridge.cashSchedule[0].principalRepayments, '60.00');
|
||||
assert.equal(
|
||||
bridge.accountingLines.some(
|
||||
(line) => line.code === 'principal_repayment',
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.notEqual(
|
||||
bridge.cashSchedule[0].collections,
|
||||
byCode.revenue.monthlyAmounts[0].amount,
|
||||
);
|
||||
});
|
||||
|
||||
test('financial bridge separates opening receivables and scheduled sales collections', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
receivables: '200.00',
|
||||
monthlyCollections: '0',
|
||||
salesCollectionLagMonths: 0,
|
||||
salesCollectionPercent: '75',
|
||||
openingReceivablesCollectionMonth: 1,
|
||||
openingReceivablesCollectionPercent: '50',
|
||||
periods: 1,
|
||||
});
|
||||
const bridge = buildFinancialFiscalBridge(forecast);
|
||||
assert.deepEqual(bridge.cashSchedule[0], {
|
||||
period: 1,
|
||||
collectionMode: 'scheduled',
|
||||
salesCollections: '750.00',
|
||||
openingReceivablesBalance: '100.00',
|
||||
openingReceivablesCollections: '100.00',
|
||||
otherCollections: '0.00',
|
||||
collections: '850.00',
|
||||
collectionsTotal: '850.00',
|
||||
salesReceivablesBalance: '250.00',
|
||||
supplierPayments: '250.00',
|
||||
operatingPayments: '80.00',
|
||||
personnelPayments: '40.00',
|
||||
interestPayments: '5.00',
|
||||
principalRepayments: '60.00',
|
||||
netCashFlow: '415.00',
|
||||
closingCash: '215.00',
|
||||
});
|
||||
assert.equal(
|
||||
bridge.accountingLines.find((line) => line.code === 'revenue').total,
|
||||
'1000.00',
|
||||
);
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
periods: 2,
|
||||
monthlyOperatingExpensesByPeriod: ['100', '250'],
|
||||
monthlyOperatingPaymentsByPeriod: ['20', '300'],
|
||||
monthlyPayrollExpenseByPeriod: ['50', '75'],
|
||||
monthlyPayrollPaymentsByPeriod: ['0', '100'],
|
||||
});
|
||||
const bridge = buildFinancialFiscalBridge(forecast);
|
||||
const byCode = Object.fromEntries(
|
||||
bridge.accountingLines.map((line) => [line.code, line]),
|
||||
);
|
||||
|
||||
assert.deepEqual(byCode.operating_expenses.monthlyAmounts, [
|
||||
{ period: 1, amount: '100.00' },
|
||||
{ period: 2, amount: '250.00' },
|
||||
]);
|
||||
assert.deepEqual(byCode.personnel.monthlyAmounts, [
|
||||
{ period: 1, amount: '50.00' },
|
||||
{ period: 2, amount: '75.00' },
|
||||
]);
|
||||
assert.equal(bridge.cashSchedule[0].operatingPayments, '20.00');
|
||||
assert.equal(bridge.cashSchedule[0].personnelPayments, '0.00');
|
||||
assert.equal(bridge.cashSchedule[1].operatingPayments, '300.00');
|
||||
assert.equal(bridge.cashSchedule[1].personnelPayments, '100.00');
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('financial bridge rejects a corrupted monthly cash schedule', () => {
|
||||
const forecast = forecastBusinessPlan(plan);
|
||||
const corrupted = {
|
||||
...forecast,
|
||||
rows: forecast.rows.map((row, index) =>
|
||||
index === 0 ? { ...row, closingCash: '999999.00' } : row,
|
||||
),
|
||||
};
|
||||
assert.throws(
|
||||
() => buildFinancialFiscalBridge(corrupted),
|
||||
/saldo de caixa mensal não reconcilia/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
exportMonthlyCashflowCsv,
|
||||
projectMonthlyCashflow,
|
||||
} from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
|
||||
test('projects exact monthly balances and reconciles cumulative net flow', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100.00',
|
||||
monthlyRevenue: '200.00',
|
||||
monthlyOperatingCosts: '150.00',
|
||||
monthlyDebtService: '10.00',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.rows[0].closingCash, '140.00');
|
||||
assert.equal(result.endingCash, '180.00');
|
||||
assert.equal(result.firstDeficitMonth, null);
|
||||
});
|
||||
|
||||
test('flags the first projected deficit without changing input values', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '50',
|
||||
monthlyOperatingCosts: '75',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 4,
|
||||
});
|
||||
assert.equal(result.firstDeficitMonth, 1);
|
||||
assert.equal(result.endingCash, '-100.00');
|
||||
});
|
||||
|
||||
test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '10',
|
||||
vatCreditEstimated: '80',
|
||||
vatRefundRequested: '70',
|
||||
vatRefundRecognized: '60',
|
||||
periods: 3,
|
||||
};
|
||||
const withoutReceipt = projectMonthlyCashflow(base);
|
||||
assert.equal(withoutReceipt.endingCash, '270.00');
|
||||
assert.equal(withoutReceipt.rows[0].taxAssessed, '10.00');
|
||||
assert.equal(withoutReceipt.rows[0].vatRefundExpectedReceipt, '0.00');
|
||||
const withReceipt = projectMonthlyCashflow({
|
||||
...base,
|
||||
vatRefundExpectedReceipt: '60',
|
||||
vatRefundExpectedMonth: '2',
|
||||
});
|
||||
assert.equal(withReceipt.rows[1].vatRefundExpectedReceipt, '60.00');
|
||||
assert.equal(withReceipt.endingCash, '330.00');
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({ ...base, vatRefundExpectedReceipt: '60' }),
|
||||
/mês previsto/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
...base,
|
||||
vatRefundExpectedReceipt: '60.01',
|
||||
vatRefundExpectedMonth: '2',
|
||||
}),
|
||||
/não pode exceder o montante reconhecido/,
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '150',
|
||||
monthlyDebtService: '10',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.status, 'incomplete');
|
||||
assert.equal(result.endingCash, null);
|
||||
assert.equal(result.endingCashBeforeUnassessedTax, '180.00');
|
||||
assert.equal(result.firstDeficitMonth, null);
|
||||
assert.equal(result.rows[0].taxAssessed, null);
|
||||
assert.equal(result.rows[0].netFlow, null);
|
||||
assert.equal(result.rows[0].closingCash, null);
|
||||
assert.equal(result.rows[0].netFlowBeforeUnassessedTax, '40.00');
|
||||
assert.equal(result.rows[0].closingCashBeforeUnassessedTax, '140.00');
|
||||
|
||||
const declaredZero = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '150',
|
||||
monthlyDebtService: '10',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(declaredZero.status, 'estimated');
|
||||
assert.equal(declaredZero.endingCash, '180.00');
|
||||
});
|
||||
|
||||
test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '50',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['10', '30'],
|
||||
periods: 2,
|
||||
});
|
||||
assert.equal(result.status, 'estimated');
|
||||
assert.equal(result.rows[0].taxAssessed, '10.00');
|
||||
assert.equal(result.rows[0].closingCash, '240.00');
|
||||
assert.equal(result.rows[1].openingCash, '240.00');
|
||||
assert.equal(result.rows[1].taxAssessed, '30.00');
|
||||
assert.equal(result.endingCash, '360.00');
|
||||
});
|
||||
|
||||
test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
monthlyOperatingCosts: '50',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['10', '', '30'],
|
||||
periods: 3,
|
||||
});
|
||||
assert.equal(result.status, 'incomplete');
|
||||
assert.equal(result.rows[0].closingCash, '240.00');
|
||||
assert.equal(result.rows[1].taxAssessed, null);
|
||||
assert.equal(result.rows[1].netFlow, null);
|
||||
assert.equal(result.rows[1].closingCash, null);
|
||||
assert.equal(result.rows[1].netFlowBeforeUnassessedTax, '150.00');
|
||||
assert.equal(result.rows[1].closingCashBeforeUnassessedTax, '390.00');
|
||||
assert.equal(result.rows[2].openingCash, null);
|
||||
assert.equal(result.rows[2].taxAssessed, '30.00');
|
||||
assert.equal(result.rows[2].netFlow, '120.00');
|
||||
assert.equal(result.rows[2].closingCash, null);
|
||||
assert.equal(result.endingCash, null);
|
||||
assert.equal(result.endingCashBeforeUnassessedTax, '510.00');
|
||||
});
|
||||
|
||||
test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
periods: 2,
|
||||
};
|
||||
assert.throws(
|
||||
() => projectMonthlyCashflow({ ...base, monthlyTaxSchedule: ['10'] }),
|
||||
/cada mês projectado/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
...base,
|
||||
monthlyTaxAssessed: '5',
|
||||
monthlyTaxSchedule: ['10', '20'],
|
||||
}),
|
||||
/não ambos/,
|
||||
);
|
||||
});
|
||||
|
||||
test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
|
||||
assert.equal(
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '-1.00',
|
||||
monthlyRevenue: '0',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxAssessed: '0',
|
||||
periods: 1,
|
||||
}).endingCash,
|
||||
'-1.00',
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '1.001',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
}),
|
||||
/duas casas/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '0',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
periods: 61,
|
||||
}),
|
||||
/60 meses/,
|
||||
);
|
||||
});
|
||||
|
||||
test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '10.00',
|
||||
monthlyRevenue: '20.00',
|
||||
monthlyOperatingCosts: '5.00',
|
||||
monthlyDebtService: '0.00',
|
||||
currency: 'MZN',
|
||||
periods: 2,
|
||||
},
|
||||
'2026-10-03T10:00:00.000Z',
|
||||
);
|
||||
assert.match(csv, /Saldo inicial,10\.00/);
|
||||
assert.match(csv, /Moeda,MZN/);
|
||||
assert.match(csv, /monthly-cashflow-v1/);
|
||||
assert.match(csv, /2026-10-03T10:00:00\.000Z/);
|
||||
assert.match(csv, /Horizonte,2 meses/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Valores do formulário; os valores pré-preenchidos podem ser exemplos demonstrativos/,
|
||||
);
|
||||
assert.match(csv, /Estado,incomplete/);
|
||||
assert.match(csv, /indeterminado; não informado/);
|
||||
assert.match(csv, /Fluxo líquido,Saldo final/);
|
||||
assert.match(csv, /indeterminado/);
|
||||
assert.match(csv, /antes de imposto não informado/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Crédito estimado, pedido e montante reconhecido não entram no caixa/,
|
||||
);
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
});
|
||||
|
||||
test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
monthlyOperatingCosts: '0',
|
||||
monthlyDebtService: '0',
|
||||
monthlyTaxSchedule: ['12.50', '', '0'],
|
||||
currency: 'MZN',
|
||||
periods: 3,
|
||||
},
|
||||
'2026-10-03T10:00:00.000Z',
|
||||
);
|
||||
assert.match(csv, /Calendário variável; consultar valores mensais abaixo/);
|
||||
assert.match(
|
||||
csv,
|
||||
/pressuposto do utilizador, não cálculo ou confirmação de obrigação fiscal/,
|
||||
);
|
||||
assert.match(csv, /Pressuposto mensal de imposto,Mês 1,12\.50/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Pressuposto mensal de imposto,Mês 2,indeterminado; não informado/,
|
||||
);
|
||||
assert.match(csv, /Pressuposto mensal de imposto,Mês 3,0/);
|
||||
});
|
||||
|
||||
test('cash flow CSV neutralizes formula-like assumption text', () => {
|
||||
const csv = exportMonthlyCashflowCsv({
|
||||
openingCash: '10.00',
|
||||
monthlyRevenue: '20.00',
|
||||
monthlyOperatingCosts: '5.00',
|
||||
monthlyDebtService: '0.00',
|
||||
currency: 'MZN',
|
||||
vatRefundExpectedMonth: '=HYPERLINK("https://example.invalid")',
|
||||
periods: 1,
|
||||
});
|
||||
assert.match(
|
||||
csv,
|
||||
/Mês previsto do recebimento IVA,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import JSZip from 'jszip';
|
||||
import {
|
||||
createProjectDossierPrintHtml,
|
||||
createProjectDossierReport,
|
||||
dossierReportSections,
|
||||
generateProjectDossierDocx,
|
||||
generateProjectDossierPackage,
|
||||
classifyDossierAttachment,
|
||||
validateDossierAttachments,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import { serializeBusinessPlanSnapshot, forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
const allSections = new Set(dossierReportSections.map((section) => section.id));
|
||||
|
||||
function simplePlan() {
|
||||
return {
|
||||
currency: 'MZN', openingCash: '0', products: [{ label: 'Pão', monthlyUnits: '100', unitPrice: '50', unitVariableCost: '20' }],
|
||||
monthlyCollections: '100', monthlyVariableCostPayments: '100', monthlyOperatingExpenses: '500', monthlyOperatingPayments: '500',
|
||||
monthlyPayrollExpense: '0', monthlyPayrollPayments: '0', assetInvestment: '0', inventory: '0', receivables: '0', payables: '0',
|
||||
equity: '10000', shareholderLoans: '0', bankLoanProceeds: '0', grants: '0', assetDepreciation: '0', depreciationLifeMonths: 12,
|
||||
monthlyInterestExpense: '0', monthlyInterestPayment: '0', monthlyPrincipalRepayment: '0', periods: 12,
|
||||
};
|
||||
}
|
||||
|
||||
test('incomplete dossier identifies unknowns without inventing zeroes', () => {
|
||||
const report = createProjectDossierReport({}, { selectedSections: allSections, generatedAt: '2026-10-04T10:00:00.000Z' });
|
||||
assert.equal(report.title, 'Não informado');
|
||||
assert.equal(report.sections.find((section) => section.id === 'summary').rows[0].value, 'Não informado');
|
||||
assert.match(report.sections.find((section) => section.id === 'resources').rows[0].value, /Informação insuficiente/);
|
||||
assert.doesNotMatch(JSON.stringify(report), /"value":"0(\.00)?"/);
|
||||
});
|
||||
|
||||
test('report sections are selected explicitly and preserve declared versus estimated provenance', () => {
|
||||
const selected = new Set(['summary', 'market', 'sources']);
|
||||
const report = createProjectDossierReport({ project_title: 'Moagem', market_assumption: 'procura crescente', market_source: 'entrevista própria; 2026-09-01' }, { selectedSections: selected, version: 'Revisão 3' });
|
||||
assert.deepEqual(report.sections.map((section) => section.id), ['summary', 'market', 'sources']);
|
||||
const market = report.sections.find((section) => section.id === 'market');
|
||||
assert.ok(market.rows.some((row) => row.value === 'procura crescente' && row.classification === 'Informação declarada, não verificada'));
|
||||
assert.equal(report.version, 'Revisão 3');
|
||||
});
|
||||
|
||||
test('business plan values in the dossier equal the existing simulator forecast', () => {
|
||||
const plan = simplePlan();
|
||||
const expected = forecastBusinessPlan(plan);
|
||||
const snapshot = serializeBusinessPlanSnapshot(plan);
|
||||
const report = createProjectDossierReport({ project_title: 'Padaria', currency: 'MZN', business_plan_snapshot: snapshot }, { selectedSections: allSections });
|
||||
const finance = report.sections.find((section) => section.id === 'finance');
|
||||
const row = (field) => finance.rows.find((item) => item.field === field).value;
|
||||
assert.equal(row('Facturação no horizonte'), `${expected.totalRevenue} MZN`);
|
||||
assert.equal(row('Resultado antes de impostos'), `${expected.totalProfitBeforeTax} MZN`);
|
||||
assert.equal(row('Caixa final projectada'), `${expected.endingCash} MZN`);
|
||||
assert.equal(row('Reconciliação do financiamento'), expected.fundingStatus);
|
||||
});
|
||||
|
||||
test('an attached simulator execution keeps its exact snapshot result, explanation and version', () => {
|
||||
const report = createProjectDossierReport({ project_title: 'Pequena indústria' }, {
|
||||
selectedSections: allSections,
|
||||
currentCalculation: {
|
||||
status: 'completed', version: 4, updatedAt: '2026-10-03T12:00:00Z', reportChecksum: 'a'.repeat(64),
|
||||
snapshot: {
|
||||
contract_version: 1, indicative_total: '1250.75',
|
||||
formula_version: 'v2', base: '2000', rate_percent: '75', reduction_percent: '16.6', currency: 'MZN',
|
||||
context: { reference_date: '2026-10-03', engine_version: 'engine-4', scenario_version: 4 },
|
||||
result: { status: 'calculated', value: '1250.75', unit: null, explanation: 'Cálculo indicativo guardado.', missing_inputs: [], source_ids: [] },
|
||||
},
|
||||
},
|
||||
});
|
||||
const finance = report.sections.find((section) => section.id === 'finance');
|
||||
assert.equal(finance.rows.find((row) => row.field === 'Resultado indicativo').value, '1250.75');
|
||||
assert.equal(finance.rows.find((row) => row.field === 'Explicação e dados em falta').value, 'Cálculo indicativo guardado.');
|
||||
assert.equal(finance.rows.find((row) => row.field === 'Revisão do resultado').value, '4');
|
||||
assert.equal(finance.rows.find((row) => row.field === 'Hash SHA-256 do relatório associado').value, 'a'.repeat(64));
|
||||
});
|
||||
|
||||
test('DOCX is a readable OpenXML package with Portuguese accents, tables and page fields', async () => {
|
||||
const report = createProjectDossierReport({ project_title: 'Produção de café', project_summary: 'Ideia com acção e localização.' }, { selectedSections: allSections, version: 'Revisão 2' });
|
||||
const blob = await generateProjectDossierDocx(report, [], true);
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
assert.deepEqual([...bytes.slice(0, 2)], [0x50, 0x4b]);
|
||||
const zip = await JSZip.loadAsync(bytes);
|
||||
const documentXml = await zip.file('word/document.xml').async('string');
|
||||
const footerXml = await zip.file('word/footer1.xml').async('string');
|
||||
assert.match(documentXml, /Produção de café/);
|
||||
assert.match(documentXml, /Classificação/);
|
||||
assert.match(documentXml, /projecto/);
|
||||
assert.match(footerXml, /PAGE/);
|
||||
assert.ok(zip.file('[Content_Types].xml'));
|
||||
});
|
||||
|
||||
test('CSV and plain-text annexes are embedded, while other originals get a ZIP index', async () => {
|
||||
const csv = new File(['Produto;Quantidade\r\nCafé;12'], 'tabela.csv', { type: 'text/csv' });
|
||||
const pdf = new File(['%PDF-1.7 example'], '../apoio.pdf', { type: 'application/pdf' });
|
||||
assert.equal(classifyDossierAttachment(csv), 'csv');
|
||||
assert.equal(classifyDossierAttachment(pdf), 'original-only');
|
||||
const attachments = [{ file: csv, include: true, caption: '' }, { file: pdf, include: true, caption: '' }];
|
||||
const report = createProjectDossierReport({ project_title: 'Projecto de café' }, { selectedSections: allSections });
|
||||
const docx = await generateProjectDossierDocx(report, attachments, true);
|
||||
const docxZip = await JSZip.loadAsync(await docx.arrayBuffer());
|
||||
const xml = await docxZip.file('word/document.xml').async('string');
|
||||
assert.match(xml, /Café/);
|
||||
assert.match(xml, /Este formato não foi incorporado/);
|
||||
const bundle = await generateProjectDossierPackage(docx, attachments, true);
|
||||
const bundleZip = await JSZip.loadAsync(await bundle.arrayBuffer());
|
||||
assert.ok(bundleZip.file('Anexos/tabela.csv'));
|
||||
assert.ok(bundleZip.file('Anexos/apoio.pdf'));
|
||||
const index = await bundleZip.file('indice-anexos.txt').async('string');
|
||||
assert.match(index, /Conteúdo não incorporado/);
|
||||
assert.match(index, /Conteúdo não incorporado; original preservado/);
|
||||
});
|
||||
|
||||
test('PNG photographs are embedded in the Word package with an image relationship and caption', async () => {
|
||||
const pngBytes = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/aZkAAAAASUVORK5CYII=', 'base64');
|
||||
const photo = new File([pngBytes], 'local.jpg', { type: 'image/png' });
|
||||
const report = createProjectDossierReport({ project_title: 'Projecto com fotografia' }, { selectedSections: allSections });
|
||||
const docx = await generateProjectDossierDocx(report, [{ file: photo, include: true, caption: 'Localização declarada' }], true);
|
||||
const zip = await JSZip.loadAsync(await docx.arrayBuffer());
|
||||
const mediaPath = Object.keys(zip.files).find((path) => /^word\/media\/.+\.png$/.test(path));
|
||||
assert.ok(mediaPath);
|
||||
assert.match(await zip.file('word/document.xml').async('string'), /Localização declarada/);
|
||||
assert.match(await zip.file('word/_rels/document.xml.rels').async('string'), new RegExp(`Target="media/${mediaPath.split('/').at(-1)}"`));
|
||||
});
|
||||
|
||||
test('print/PDF HTML escapes user content and explains omitted annexes', async () => {
|
||||
const report = createProjectDossierReport({ project_title: '<script>alert(1)</script>', project_summary: 'Acentuação: localização.' }, { selectedSections: new Set(['summary', 'annexes']) });
|
||||
const pdf = await createProjectDossierPrintHtml(report, [], false);
|
||||
assert.doesNotMatch(pdf, /<script>alert\(1\)<\/script>/);
|
||||
assert.match(pdf, /<script>/);
|
||||
assert.match(pdf, /não foram seleccionados|secção de anexos foi omitida/);
|
||||
assert.match(pdf, /@page\{size:A4/);
|
||||
});
|
||||
|
||||
test('attachment limits block oversized or excessive selections', () => {
|
||||
assert.equal(validateDossierAttachments([{ size: 1 }]), null);
|
||||
assert.match(validateDossierAttachments(Array.from({ length: 11 }, () => ({ size: 1 }))), /máximo 10/);
|
||||
assert.match(validateDossierAttachments([{ size: 15 * 1024 * 1024 + 1 }]), /15 MB/);
|
||||
assert.match(validateDossierAttachments(Array.from({ length: 4 }, () => ({ size: 15 * 1024 * 1024 }))), /50 MB/);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readRows, exportProjectDossierCsv } from '../../resources/js/lib/project-dossier.ts';
|
||||
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
|
||||
|
||||
test('structured planner tolerates incomplete or malformed snapshots', () => {
|
||||
assert.deepEqual(readRows('not-json', ['name']), []);
|
||||
assert.deepEqual(readRows('{"x":1}', ['name']), []);
|
||||
});
|
||||
|
||||
test('project export labels user market claims and insufficient finance evidence', () => {
|
||||
const csv = exportProjectDossierCsv({ market_assumption: 'procura alta', market_source: '', project_title: '=1+1', project_team_snapshot: JSON.stringify([{ competency: 'Gestão', state: 'gap', action: 'Formação', estimated_cost: '20', due_date: '' }]), project_execution_snapshot: JSON.stringify([{ title: 'Abrir', due_date: '', status: 'planned', planned_amount: '10', actual_amount: '' }]) });
|
||||
assert.match(csv, /Informação declarada, não verificada/);
|
||||
assert.match(csv, /Informação insuficiente/);
|
||||
assert.match(csv, /'=1\+1/);
|
||||
assert.match(csv, /Secção;Campo;Valor;Origem \/ estado/);
|
||||
assert.match(csv, /Gestão; gap; resposta: Formação/);
|
||||
assert.match(csv, /Marco 1/);
|
||||
});
|
||||
|
||||
test('project dossier exports readable financial assumptions and verified calculator outputs', () => {
|
||||
const financial_tools_snapshot = serializeFinancialToolsSnapshot({
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: { principal: '100000', rate: '18', months: '24', rateType: 'nominal', periodMonths: '1', gracePeriods: '0', upfrontFee: '0', recurringFee: '0' },
|
||||
breakEven: { fixed: '50000', price: '1000', variable: '600' },
|
||||
funding: { total: '1000000', secured: '250000' },
|
||||
incomes: [{ label: 'Vendas', amount: '200000' }],
|
||||
expenses: [{ label: 'Operação', amount: '150000' }],
|
||||
});
|
||||
const csv = exportProjectDossierCsv({ financial_tools_snapshot, currency: 'MZN' });
|
||||
assert.match(csv, /Unidades estimadas;125;/);
|
||||
assert.match(csv, /Diferença por financiar;750000\.00 MZN;/);
|
||||
assert.match(csv, /Saldo operacional estimado;50000\.00 MZN;/);
|
||||
assert.doesNotMatch(csv, /"\{""version""/);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { getProjectReadiness, readPlannedRiskResponses, serializePlannedRiskResponses } from '../../resources/js/lib/project-readiness.ts';
|
||||
import { getSimulationSections } from '../../resources/js/lib/simulation-form.ts';
|
||||
import { createProjectDossierReport } from '../../resources/js/lib/project-dossier-report.ts';
|
||||
|
||||
test('idea journey reuses one dossier and exposes the six requested stages', () => {
|
||||
const sections = getSimulationSections({ purpose: 'simulate_only', journey_type: 'small_business' });
|
||||
assert.deepEqual(sections.map((section) => section.title), [
|
||||
'Ideia e objectivos', 'Clientes e mercado', 'Localização e recursos',
|
||||
'Equipa e execução', 'Investimento e financiamento', 'Resultados, riscos e plano',
|
||||
]);
|
||||
});
|
||||
|
||||
test('missing customer details remain visible even if the answer says yes', () => {
|
||||
const items = getProjectReadiness({ purpose: 'simulate_only', journey_type: 'small_business', customer_validation_status: 'yes' });
|
||||
assert.ok(items.some((item) => item.id === 'customers' && item.kind === 'missing'));
|
||||
assert.ok(items.every((item) => !('probability' in item) && !('severity' in item)));
|
||||
});
|
||||
|
||||
test('not applicable suppresses only the matching readiness prompts', () => {
|
||||
const items = getProjectReadiness({
|
||||
target_customers: '', customer_validation_status: 'not_applicable',
|
||||
cost_estimate_status: 'not_applicable', location_assessment_status: 'not_applicable',
|
||||
funding_status: 'not_applicable', project_team_snapshot: '[]',
|
||||
});
|
||||
assert.equal(items.some((item) => ['customers', 'costs', 'location', 'funding'].includes(item.id)), false);
|
||||
});
|
||||
|
||||
test('planned responses round-trip and invalid data is ignored', () => {
|
||||
const source = [{ risk_id: 'customers', action: 'Falar com clientes', owner: 'Equipa', estimated_cost: '20', due_date: '2026-11-10' }];
|
||||
assert.deepEqual(readPlannedRiskResponses({ project_risk_responses_snapshot: serializePlannedRiskResponses(source) }), source);
|
||||
assert.deepEqual(readPlannedRiskResponses({ project_risk_responses_snapshot: 'invalid' }), []);
|
||||
});
|
||||
|
||||
test('dossier report includes generated gaps and user response plans without inventing summary data', () => {
|
||||
const draft = { project_title: 'Projecto de teste', project_questionnaire_version: 'investmoz-project-dossier-2026-10-05.1', project_risk_responses_snapshot: JSON.stringify([{ risk_id: 'customers', action: 'Fazer entrevistas', owner: 'Equipa', estimated_cost: '', due_date: '' }]) };
|
||||
const report = createProjectDossierReport(draft, { selectedSections: new Set(['summary', 'risk']), version: '1' });
|
||||
const summary = report.sections.find((section) => section.id === 'summary');
|
||||
const risk = report.sections.find((section) => section.id === 'risk');
|
||||
assert.match(summary.paragraphs.join(' '), /Projecto de teste/);
|
||||
assert.match(risk.rows.map((row) => `${row.field}: ${row.value}`).join(' '), /Clientes ainda pouco definidos/);
|
||||
assert.match(risk.rows.map((row) => row.value).join(' '), /Fazer entrevistas/);
|
||||
assert.match(risk.rows.map((row) => row.value).join(' '), /Resposta planeada/);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
readSimulationApiJson,
|
||||
simulationApiErrorMessage,
|
||||
simulationPollingFailureMessage,
|
||||
simulationCatalogChoices,
|
||||
} from '../../resources/js/lib/simulation-api.ts';
|
||||
|
||||
test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
|
||||
assert.equal(
|
||||
await readSimulationApiJson(
|
||||
new Response('<html>gateway error</html>', {
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
status: 502,
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
await readSimulationApiJson(
|
||||
new Response('{"truncated":', {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
status: 500,
|
||||
}),
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('API error messages prefer validated field details and reject malformed shapes', () => {
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({
|
||||
message: 'Validation failed',
|
||||
errors: { base: ['Base is required'], rate: ['Rate is invalid'] },
|
||||
}),
|
||||
'Base is required Rate is invalid',
|
||||
);
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({ message: 'Try again' }),
|
||||
'Try again',
|
||||
);
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({ errors: { base: 'invalid' } }),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(simulationApiErrorMessage('<html>error</html>'), undefined);
|
||||
});
|
||||
|
||||
test('polling failures explain that an accepted calculation may still be pending', () => {
|
||||
assert.equal(
|
||||
simulationPollingFailureMessage(null),
|
||||
'O cenário foi recebido, mas não foi possível confirmar o estado do cálculo. Consulte o histórico antes de tentar novamente.',
|
||||
);
|
||||
assert.equal(
|
||||
simulationPollingFailureMessage({ message: 'Acesso expirado' }),
|
||||
'Acesso expirado',
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
|
||||
assert.deepEqual(simulationCatalogChoices({ data: [] }), []);
|
||||
assert.deepEqual(
|
||||
simulationCatalogChoices({
|
||||
data: [
|
||||
{ id: 'country-1', label: 'Moçambique' },
|
||||
{ value: 2, name: 'Província de Maputo' },
|
||||
{ id: 'incomplete', label: '' },
|
||||
null,
|
||||
],
|
||||
}),
|
||||
[
|
||||
{ id: 'country-1', label: 'Moçambique' },
|
||||
{ id: '2', label: 'Província de Maputo' },
|
||||
],
|
||||
);
|
||||
assert.throws(() => simulationCatalogChoices('<html>gateway error</html>'));
|
||||
});
|
||||
@@ -0,0 +1,620 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
isApiErrorV1,
|
||||
isApiQuestionnaireReadResponseV1,
|
||||
isApiSimulationJobsReadResponseV1,
|
||||
isApiSimulationReportReadResponseV1,
|
||||
isApiSimulationDraftAttachResponseV1,
|
||||
isApiSimulationDraftReadResponseV1,
|
||||
isApiSimulationDraftWriteResponseV1,
|
||||
isApiSimulationHistoryResponseV1,
|
||||
fiscalComponentCodes,
|
||||
indeterminateFiscalComponent,
|
||||
isApiSimulationCreateResponseV1,
|
||||
isApiSimulationReadResponseV1,
|
||||
isApiSimulationResultSnapshotV1,
|
||||
isSimulationCurrency,
|
||||
simulationCurrencyFractionDigits,
|
||||
simulationCurrencyOptions,
|
||||
validateSimulationResult,
|
||||
} from '../../resources/js/lib/simulation-contract.ts';
|
||||
|
||||
const apiSnapshot = {
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-03',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 1,
|
||||
engine_version: 'portal-arithmetic-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.000000',
|
||||
unit: null,
|
||||
explanation: 'Arithmetic indicative.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
indicative_total: '0.000000',
|
||||
legal_interpretation: false,
|
||||
formula_version: 'portal-arithmetic-v1',
|
||||
};
|
||||
const apiExecution = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
status: 'queued',
|
||||
version_no: 1,
|
||||
result_snapshot: null,
|
||||
};
|
||||
const apiDraft = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
version_no: 2,
|
||||
snapshot_sha256: 'a'.repeat(64),
|
||||
personal_snapshot: [],
|
||||
economic_snapshot: { purpose: 'simulate_only' },
|
||||
simulation_sources: [],
|
||||
updated_at: '2026-10-03T12:30:00.000000Z',
|
||||
};
|
||||
const apiHistory = {
|
||||
data: [
|
||||
{
|
||||
id: apiExecution.id,
|
||||
scope: 'personal',
|
||||
organization_name: null,
|
||||
status: 'completed',
|
||||
version_no: 1,
|
||||
created_at: '2026-10-03T12:00:00.000000Z',
|
||||
updated_at: '2026-10-03T12:00:01.000000Z',
|
||||
has_ready_report: true,
|
||||
},
|
||||
],
|
||||
meta: { current_page: 1, last_page: 1, per_page: 10, total: 1 },
|
||||
};
|
||||
const apiJob = {
|
||||
id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
simulation_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
job_type: 'execute',
|
||||
status: 'succeeded',
|
||||
attempts: 1,
|
||||
available_at: '2026-10-03T12:00:00.000000Z',
|
||||
started_at: '2026-10-03T12:00:01.000000Z',
|
||||
finished_at: '2026-10-03T12:00:02.000000Z',
|
||||
error_code: null,
|
||||
};
|
||||
|
||||
test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
|
||||
const openapi = JSON.parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
'../../docs/investmoz/simulations/openapi.json',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const schemas = openapi.components.schemas;
|
||||
|
||||
assert.ok(schemas.DecimalInputString.pattern.includes(String.raw`\.`));
|
||||
assert.equal(
|
||||
schemas.SimulationInput.properties.base.allOf[0].$ref,
|
||||
'#/components/schemas/DecimalInputString',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.SimulationInput.properties.rate.allOf[0].$ref,
|
||||
'#/components/schemas/PercentageInputString',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.UpdateScenarioInput.properties.base.allOf[0].$ref,
|
||||
'#/components/schemas/DecimalInputString',
|
||||
);
|
||||
assert.deepEqual(schemas.SimulationExecutionV1.properties.status.enum, [
|
||||
'queued',
|
||||
'running',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations'].post.responses['202'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationCreateResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/history'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationHistoryResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulation-drafts/current'].get.responses['200']
|
||||
.content['application/json'].schema.$ref,
|
||||
'#/components/schemas/SimulationDraftReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/questionnaires/{code}'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/QuestionnaireReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/jobs'].get.responses['200'].content[
|
||||
'application/json'
|
||||
].schema.$ref,
|
||||
'#/components/schemas/SimulationJobsReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/scenarios/{scenarioId}'].patch
|
||||
.responses['202'].content['application/json'].schema.$ref,
|
||||
'#/components/schemas/SimulationReadResponseV1',
|
||||
);
|
||||
assert.equal(
|
||||
openapi.paths['/simulations/{id}/scenarios/{scenarioId}'].patch
|
||||
.responses['422'].content['application/json'].schema.$ref,
|
||||
'#/components/schemas/ApiErrorV1',
|
||||
);
|
||||
assert.equal(
|
||||
schemas.SimulationHistoryResponseV1.properties.meta.properties.per_page
|
||||
.maximum,
|
||||
50,
|
||||
);
|
||||
for (const pathItem of Object.values(openapi.paths)) {
|
||||
for (const operation of Object.values(pathItem)) {
|
||||
for (const [status, response] of Object.entries(
|
||||
operation.responses ?? {},
|
||||
)) {
|
||||
if (!/^4\d\d$/.test(status)) continue;
|
||||
assert.equal(
|
||||
response.content?.['application/json']?.schema?.$ref,
|
||||
'#/components/schemas/ApiErrorV1',
|
||||
`HTTP ${status} must use the shared API error contract`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('currency codes are explicit and must be present in the supported currency catalog', () => {
|
||||
assert.equal(isSimulationCurrency('MZN'), true);
|
||||
assert.equal(isSimulationCurrency('USD'), true);
|
||||
assert.equal(isSimulationCurrency('mzn'), false);
|
||||
assert.equal(isSimulationCurrency('XYZ'), false);
|
||||
assert.equal(simulationCurrencyFractionDigits('JPY'), 0);
|
||||
assert.equal(simulationCurrencyFractionDigits('KWD'), 3);
|
||||
assert.equal(simulationCurrencyOptions.includes('JPY'), false);
|
||||
assert.equal(simulationCurrencyOptions.includes('KWD'), false);
|
||||
});
|
||||
|
||||
test('calculated values preserve exact decimal strings, including zero', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'calculated',
|
||||
value: '0.00',
|
||||
unit: 'MZN',
|
||||
explanation: 'Cenário aritmético.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
|
||||
assert.equal(isApiSimulationResultSnapshotV1(apiSnapshot), true);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
context: { ...apiSnapshot.context, reference_date: '2026-02-31' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
context: { ...apiSnapshot.context, reference_date: '2024-02-29' },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
indicative_total: null,
|
||||
result: {
|
||||
...apiSnapshot.result,
|
||||
status: 'indeterminate',
|
||||
value: null,
|
||||
missing_inputs: ['approved_rule'],
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
indicative_total: '0.000001',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
result: { ...apiSnapshot.result, value: '0' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
...apiSnapshot,
|
||||
result: {
|
||||
...apiSnapshot.result,
|
||||
status: 'indeterminate',
|
||||
missing_inputs: [],
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('simulation creation and polling responses require a valid execution view', () => {
|
||||
const queuedExecution = { ...apiExecution };
|
||||
delete queuedExecution.result_snapshot;
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: queuedExecution,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(isApiSimulationReadResponseV1({ data: apiExecution }), true);
|
||||
const completedExecution = {
|
||||
...apiExecution,
|
||||
status: 'completed',
|
||||
version_no: 2,
|
||||
result_snapshot: apiSnapshot,
|
||||
};
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({ data: completedExecution }),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...completedExecution, result_snapshot: { broken: true } },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...completedExecution, result_snapshot: null },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: {
|
||||
...apiExecution,
|
||||
result_snapshot: {
|
||||
contract_version: 1,
|
||||
indicative_total: '12',
|
||||
},
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: {
|
||||
...completedExecution,
|
||||
result_snapshot: { indicative_total: '12.50' },
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: true,
|
||||
access_token: 'x'.repeat(48),
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { ...apiExecution, status: 'unknown' },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReadResponseV1({
|
||||
data: { id: apiExecution.id, status: 'completed', version_no: 2 },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationCreateResponseV1({
|
||||
data: apiExecution,
|
||||
replayed: 'false',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('history and encrypted-draft endpoints reject malformed envelopes', () => {
|
||||
assert.equal(isApiSimulationHistoryResponseV1(apiHistory), true);
|
||||
assert.equal(
|
||||
isApiSimulationHistoryResponseV1({
|
||||
...apiHistory,
|
||||
data: [{ ...apiHistory.data[0], status: 'unrecognized' }],
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationHistoryResponseV1({ ...apiHistory, meta: {} }),
|
||||
false,
|
||||
);
|
||||
|
||||
assert.equal(isApiSimulationDraftReadResponseV1({ data: apiDraft }), true);
|
||||
assert.equal(isApiSimulationDraftReadResponseV1({ data: null }), true);
|
||||
assert.equal(
|
||||
isApiSimulationDraftReadResponseV1({
|
||||
data: { ...apiDraft, personal_snapshot: ['private'] },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftWriteResponseV1({
|
||||
data: { id: apiDraft.id, version_no: 3 },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftWriteResponseV1({
|
||||
data: { id: 'bad', version_no: 0 },
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftAttachResponseV1({
|
||||
data: apiDraft,
|
||||
replayed: false,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationDraftAttachResponseV1({
|
||||
data: apiDraft,
|
||||
replayed: 'false',
|
||||
}),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('questionnaire, report, job and error envelopes match their server contracts', () => {
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
code: 'user-entered-arithmetic',
|
||||
version_no: 1,
|
||||
locale: 'pt-MZ',
|
||||
schema_snapshot: { inputs: {} },
|
||||
status: 'published',
|
||||
valid_from: '2026-10-01',
|
||||
valid_to: null,
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
code: 'user-entered-arithmetic',
|
||||
version_no: 1,
|
||||
locale: 'pt-MZ',
|
||||
schema_snapshot: { inputs: {} },
|
||||
status: 'published',
|
||||
valid_from: '2026-02-31',
|
||||
valid_to: null,
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({ data: { locale: 'en' } }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: apiSnapshot,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: [],
|
||||
report_sha256: 'invalid',
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'queued',
|
||||
report_snapshot: apiSnapshot,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiSimulationReportReadResponseV1({
|
||||
data: {
|
||||
id: apiExecution.id,
|
||||
simulation_id: apiExecution.id,
|
||||
version_no: 1,
|
||||
status: 'ready',
|
||||
report_snapshot: null,
|
||||
report_sha256: null,
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(isApiSimulationJobsReadResponseV1({ data: [apiJob] }), true);
|
||||
assert.equal(
|
||||
isApiSimulationJobsReadResponseV1({
|
||||
data: [{ ...apiJob, attempts: 4 }],
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isApiErrorV1({
|
||||
message: 'Validation failed',
|
||||
errors: { base: ['Invalid'] },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(isApiErrorV1({ message: 42 }), false);
|
||||
assert.equal(isApiErrorV1({ errors: { base: 'Invalid' } }), false);
|
||||
});
|
||||
|
||||
test('wire contract guards survive a real JSON encode/decode round trip', () => {
|
||||
const wirePayloads = [
|
||||
[isApiSimulationReadResponseV1, { data: apiExecution }],
|
||||
[
|
||||
isApiSimulationCreateResponseV1,
|
||||
{
|
||||
data: apiExecution,
|
||||
replayed: false,
|
||||
access_token: 'x'.repeat(48),
|
||||
},
|
||||
],
|
||||
[isApiSimulationHistoryResponseV1, apiHistory],
|
||||
[isApiSimulationDraftReadResponseV1, { data: apiDraft }],
|
||||
[
|
||||
isApiSimulationDraftAttachResponseV1,
|
||||
{ data: apiDraft, replayed: false },
|
||||
],
|
||||
[isApiSimulationJobsReadResponseV1, { data: [apiJob] }],
|
||||
[
|
||||
isApiSimulationResultSnapshotV1,
|
||||
{ ...apiSnapshot, result: { ...apiSnapshot.result } },
|
||||
],
|
||||
];
|
||||
|
||||
for (const [guard, payload] of wirePayloads) {
|
||||
const decoded = JSON.parse(JSON.stringify(payload));
|
||||
assert.equal(guard(decoded), true);
|
||||
}
|
||||
});
|
||||
|
||||
test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'indeterminate',
|
||||
value: null,
|
||||
unit: null,
|
||||
explanation: 'Falta a classificação.',
|
||||
missingInputs: ['tariff_code'],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'indeterminate',
|
||||
value: '0',
|
||||
unit: 'MZN',
|
||||
explanation: 'Sem dados.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
['indeterminate_inputs'],
|
||||
);
|
||||
});
|
||||
|
||||
test('estimated and not-applicable states must be explicit', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'estimated',
|
||||
value: '12.30',
|
||||
unit: 'MZN',
|
||||
explanation: 'Estimativa incompleta.',
|
||||
missingInputs: ['tariff_code'],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'not_applicable',
|
||||
value: null,
|
||||
unit: null,
|
||||
explanation: 'Fora do cenário.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
[],
|
||||
);
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'not_applicable',
|
||||
value: '0',
|
||||
unit: 'MZN',
|
||||
explanation: 'Fora do cenário.',
|
||||
missingInputs: [],
|
||||
sourceIds: [],
|
||||
}),
|
||||
['not_applicable_value'],
|
||||
);
|
||||
});
|
||||
|
||||
test('every tax component remains indeterminate until an approved effective rule exists', () => {
|
||||
assert.deepEqual(fiscalComponentCodes, [
|
||||
'IRPS',
|
||||
'INSS',
|
||||
'IVA',
|
||||
'IRPC',
|
||||
'ISPC',
|
||||
'RETENCOES',
|
||||
]);
|
||||
for (const code of fiscalComponentCodes) {
|
||||
const result = indeterminateFiscalComponent(code, '2026-10-02');
|
||||
assert.deepEqual(validateSimulationResult(result), []);
|
||||
assert.equal(result.value, null);
|
||||
assert.ok(result.missingInputs.includes('approved_rule'));
|
||||
assert.deepEqual(result.sourceIds, []);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const openapi = JSON.parse(
|
||||
readFileSync(
|
||||
new URL(
|
||||
'../../docs/investmoz/simulations/openapi.json',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
|
||||
test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
|
||||
const operation =
|
||||
openapi.paths['/simulation-drafts/{id}/conversions']?.post;
|
||||
assert.ok(operation);
|
||||
assert.deepEqual(
|
||||
operation.parameters.map((parameter) => parameter.$ref),
|
||||
[
|
||||
'#/components/parameters/Id',
|
||||
'#/components/parameters/IfMatch',
|
||||
'#/components/parameters/SimulationToken',
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
operation.requestBody.content['application/json'].schema.$ref,
|
||||
'#/components/schemas/AttachSimulationToDraftInput',
|
||||
);
|
||||
for (const response of ['200', '404', '409', '412', '422', '428', '429'])
|
||||
assert.ok(
|
||||
operation.responses[response],
|
||||
`missing response ${response}`,
|
||||
);
|
||||
assert.match(
|
||||
operation.description,
|
||||
/does not submit a project or create a CRM record/i,
|
||||
);
|
||||
|
||||
const schema = openapi.components.schemas.AttachSimulationToDraftInput;
|
||||
assert.deepEqual(schema.required, ['simulation_id', 'consent_reuse']);
|
||||
assert.equal(schema.additionalProperties, false);
|
||||
assert.equal(schema.properties.simulation_id.format, 'uuid');
|
||||
assert.equal(schema.properties.consent_reuse.const, true);
|
||||
});
|
||||
@@ -1,67 +1,832 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
getSimulationSections,
|
||||
simulationFieldGroups,
|
||||
getAutosaveSnapshot,
|
||||
advancedSimulationFields,
|
||||
partitionSimulationDraft,
|
||||
replaceSimulationValue,
|
||||
restoreSimulationDraft,
|
||||
simulationOptions,
|
||||
validateCustomFiscalPlanning,
|
||||
simulationDraftFingerprint,
|
||||
validateSimulationDraft,
|
||||
} from "../../resources/js/lib/simulation-form.ts";
|
||||
exportCompletedArithmeticCsv,
|
||||
readArithmeticSnapshot,
|
||||
readVersionedArithmeticReportReference,
|
||||
moveSearchChoiceIndex,
|
||||
getFiscalPeriodRange,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
test("changing territorial or sector parents clears every dependent value", () => {
|
||||
test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue({
|
||||
province_id: "p1", district_id: "d1", admin_post_id: "a1", locality_id: "l1",
|
||||
}, "province_id", "p2"),
|
||||
{ province_id: "p2" },
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2024',
|
||||
fiscal_periodicity: 'annual',
|
||||
}),
|
||||
{ start: '2024-01-01', end: '2024-12-31' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue({ sector_id: "s1", activity_id: "a1", activity_id_label: "A" }, "sector_id", "s2"),
|
||||
{ sector_id: "s2" },
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2024',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_month: '02',
|
||||
}),
|
||||
{ start: '2024-02-01', end: '2024-02-29' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'quarterly',
|
||||
fiscal_quarter: 'Q4',
|
||||
}),
|
||||
{ start: '2026-10-01', end: '2026-12-31' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_reference_date: '2026-06-15',
|
||||
}),
|
||||
{ start: '2026-06-15', end: '2026-06-15' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_reference_date: '2025-06-15',
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("switching to anonymous simulation clears formal identity and project data", () => {
|
||||
const next = replaceSimulationValue({
|
||||
purpose: "own_investment", legal_name: "Empresa", email: "a@b.co", project_title: "Projecto",
|
||||
total_investment: "10", total_investment_label: "10",
|
||||
}, "purpose", "simulate_only");
|
||||
assert.deepEqual(next, { purpose: "simulate_only" });
|
||||
test('searchable choice keyboard navigation starts at the first result and stays in bounds', () => {
|
||||
assert.equal(moveSearchChoiceIndex(-1, 1, 3), 0);
|
||||
assert.equal(moveSearchChoiceIndex(-1, -1, 3), 2);
|
||||
assert.equal(moveSearchChoiceIndex(0, -1, 3), 0);
|
||||
assert.equal(moveSearchChoiceIndex(2, 1, 3), 2);
|
||||
assert.equal(moveSearchChoiceIndex(0, 1, 0), -1);
|
||||
assert.equal(moveSearchChoiceIndex(0, -1, -1), -1);
|
||||
});
|
||||
|
||||
test("client validation rejects absent arithmetic inputs and out-of-range rates", () => {
|
||||
assert.deepEqual(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes" }, "tax"), {
|
||||
base: "Este campo é obrigatório.",
|
||||
rate: "Este campo é obrigatório.",
|
||||
reduction: "Este campo é obrigatório.",
|
||||
test('anonymous arithmetic journey skips formal investor and project sections', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({ purpose: 'simulate_only' }).map(
|
||||
(section) => section.id,
|
||||
),
|
||||
['purpose', 'tax', 'review'],
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections({ purpose: 'own_investment' }).length,
|
||||
11,
|
||||
);
|
||||
});
|
||||
|
||||
test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
|
||||
const draft = {
|
||||
journey_type: 'small_business',
|
||||
purpose: 'simulate_only',
|
||||
detail_level: 'simple',
|
||||
};
|
||||
assert.deepEqual(
|
||||
getSimulationSections(draft).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'market',
|
||||
'location',
|
||||
'team',
|
||||
'financial',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'market'), {});
|
||||
const ideaFields = [...simulationFieldGroups.project, ...simulationFieldGroups.market].filter((field) =>
|
||||
field.showWhen?.(draft),
|
||||
).filter((field, index, all) => all.findIndex((candidate) => candidate.key === field.key) === index);
|
||||
for (const key of [
|
||||
'project_title',
|
||||
'project_summary',
|
||||
'project_problem',
|
||||
'target_customers',
|
||||
'value_proposition',
|
||||
'market_assumption',
|
||||
'market_source',
|
||||
'project_type',
|
||||
'sector_id',
|
||||
'activity_id',
|
||||
'products_services',
|
||||
'maturity_stage',
|
||||
'expected_start_date',
|
||||
'project_duration_years',
|
||||
]) assert.ok(ideaFields.some((field) => field.key === key), `missing ${key}`);
|
||||
assert.equal(
|
||||
ideaFields.some((field) =>
|
||||
typeof field.required === 'function'
|
||||
? field.required(draft)
|
||||
: Boolean(field.required),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections(draft).some((section) =>
|
||||
['identity', 'documents', 'tax'].includes(section.id),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'location'), {});
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
|
||||
});
|
||||
|
||||
test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
|
||||
const selected = replaceSimulationValue({}, 'journey_type', 'investor');
|
||||
assert.equal(selected.purpose, 'simulate_only');
|
||||
const sections = getSimulationSections(selected).map((section) => section.id);
|
||||
assert.deepEqual(sections, [
|
||||
'purpose', 'project', 'location', 'financial', 'tax', 'scenarios', 'procedures', 'review',
|
||||
]);
|
||||
for (const sectionId of ['project', 'location', 'financial', 'tax', 'procedures']) {
|
||||
assert.deepEqual(validateSimulationDraft(selected, sectionId), {});
|
||||
}
|
||||
const fieldsVisible = (group) => simulationFieldGroups[group].filter((field) => field.showWhen?.(selected) ?? true);
|
||||
assert.ok(fieldsVisible('project').some((field) => field.key === 'activity_id'));
|
||||
assert.ok(fieldsVisible('location').some((field) => field.key === 'infrastructure_needs'));
|
||||
assert.ok(fieldsVisible('financial').some((field) => field.key === 'total_investment'));
|
||||
assert.equal(simulationFieldGroups.procedures[0].showWhen(selected), true);
|
||||
assert.ok(simulationOptions.infrastructure.includes('raw_materials'));
|
||||
assert.ok(simulationOptions.infrastructure.includes('legal_requirements'));
|
||||
});
|
||||
|
||||
test('public journeys offer distinct section paths for personal, small business, company, and investor', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'personal',
|
||||
purpose: 'own_investment',
|
||||
}).map((section) => section.id),
|
||||
['purpose', 'financial', 'tax', 'review'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'small_business',
|
||||
purpose: 'own_investment',
|
||||
}).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'promoter',
|
||||
'project',
|
||||
'financial',
|
||||
'impact',
|
||||
'tax',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
assert.equal(
|
||||
getSimulationSections({
|
||||
journey_type: 'company',
|
||||
purpose: 'own_investment',
|
||||
}).length,
|
||||
11,
|
||||
);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'investor',
|
||||
purpose: 'seek_investor',
|
||||
}).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'promoter',
|
||||
'identity',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'opportunity',
|
||||
'documents',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
assert.equal(advancedSimulationFields.has('deductible_costs'), true);
|
||||
});
|
||||
|
||||
test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
journey_type: 'personal',
|
||||
detail_level: 'advanced',
|
||||
legal_name: 'Nome',
|
||||
email: 'a@b.co',
|
||||
},
|
||||
'purpose',
|
||||
'simulate_only',
|
||||
),
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
journey_type: 'personal',
|
||||
detail_level: 'advanced',
|
||||
legal_name: 'Nome',
|
||||
email: 'a@b.co',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('changing territorial or sector parents clears every dependent value', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
province_id: 'p1',
|
||||
district_id: 'd1',
|
||||
admin_post_id: 'a1',
|
||||
locality_id: 'l1',
|
||||
},
|
||||
'province_id',
|
||||
'p2',
|
||||
),
|
||||
{ province_id: 'p2' },
|
||||
);
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{ sector_id: 's1', activity_id: 'a1', activity_id_label: 'A' },
|
||||
'sector_id',
|
||||
's2',
|
||||
),
|
||||
{ sector_id: 's2' },
|
||||
);
|
||||
});
|
||||
|
||||
test('changing the purpose preserves private and project answers for later correction', () => {
|
||||
const next = replaceSimulationValue(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
legal_name: 'Empresa',
|
||||
email: 'a@b.co',
|
||||
project_title: 'Projecto',
|
||||
total_investment: '10',
|
||||
total_investment_label: '10',
|
||||
},
|
||||
'purpose',
|
||||
'simulate_only',
|
||||
);
|
||||
assert.deepEqual(next, {
|
||||
purpose: 'simulate_only',
|
||||
legal_name: 'Empresa',
|
||||
email: 'a@b.co',
|
||||
project_title: 'Projecto',
|
||||
total_investment: '10',
|
||||
total_investment_label: '10',
|
||||
});
|
||||
assert.equal(validateSimulationDraft({ purpose: "simulate_only", tax_calculation: "yes", base: "0", rate: "101", reduction: "0" }, "tax").rate,
|
||||
"O valor não pode exceder 100.");
|
||||
});
|
||||
|
||||
test("financial reconciliation reports a mismatch without inventing a fiscal value", () => {
|
||||
const errors = validateSimulationDraft({
|
||||
currency: "USD", total_investment: "100", own_capital: "20", domestic_debt: "20", foreign_debt: "20", grants: "20",
|
||||
}, "financial");
|
||||
test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_month: '04',
|
||||
fiscal_component: 'iva',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_operation: 'domestic',
|
||||
fiscal_establishments: '1',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
|
||||
});
|
||||
|
||||
test('custom planning mode requires user assumptions and validates percentage limits', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_component: 'iva',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_operation: 'domestic',
|
||||
fiscal_establishments: '1',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'custom_planning',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
|
||||
assert.deepEqual(validateCustomFiscalPlanning(base), {
|
||||
base: 'Este pressuposto é necessário para executar este cenário.',
|
||||
rate: 'Este pressuposto é necessário para executar este cenário.',
|
||||
reduction: 'Este pressuposto é necessário para executar este cenário.',
|
||||
});
|
||||
assert.deepEqual(
|
||||
validateSimulationDraft(
|
||||
{ ...base, fiscal_documentation: 'unknown' },
|
||||
'tax',
|
||||
),
|
||||
{},
|
||||
);
|
||||
const overLimit = {
|
||||
...base,
|
||||
fiscal_documentation: 'unknown',
|
||||
base: '0',
|
||||
rate: '101',
|
||||
reduction: '0',
|
||||
};
|
||||
assert.deepEqual(validateSimulationDraft(overLimit, 'tax'), {});
|
||||
assert.equal(
|
||||
validateCustomFiscalPlanning(overLimit).rate,
|
||||
'O valor não pode exceder 100.',
|
||||
);
|
||||
});
|
||||
|
||||
test('fiscal intake asks only component-specific questions and leaves residence unresolved when unknown', () => {
|
||||
assert.equal(
|
||||
simulationOptions.fiscal_period.includes(
|
||||
String(new Date().getFullYear() + 1),
|
||||
),
|
||||
true,
|
||||
);
|
||||
const ispcErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'quarterly',
|
||||
fiscal_component: 'ispc',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(ispcErrors.fiscal_activity, 'Este campo é obrigatório.');
|
||||
assert.equal(ispcErrors.fiscal_establishments, 'Este campo é obrigatório.');
|
||||
assert.equal(ispcErrors.fiscal_residency_assessment, undefined);
|
||||
const irpsErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'annual',
|
||||
fiscal_component: 'irps',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
irpsErrors.fiscal_residency_assessment,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
assert.equal(
|
||||
irpsErrors.fiscal_income_category,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
assert.deepEqual(simulationOptions.irps_salary_view, [
|
||||
'monthly_net_estimate',
|
||||
'monthly_withholding',
|
||||
'annual_assessment',
|
||||
]);
|
||||
const salaryViewErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'monthly',
|
||||
fiscal_component: 'irps',
|
||||
fiscal_income_category: 'employment',
|
||||
fiscal_residency_assessment: 'unknown',
|
||||
fiscal_documentation: 'unknown',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
salaryViewErrors.irps_salary_view,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
const customsErrors = validateSimulationDraft(
|
||||
{
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
fiscal_periodicity: 'one_off',
|
||||
fiscal_component: 'customs_ice',
|
||||
fiscal_operation: 'import',
|
||||
fiscal_scenario_mode: 'approved_parameters',
|
||||
},
|
||||
'tax',
|
||||
);
|
||||
assert.equal(
|
||||
customsErrors.fiscal_customs_code,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
});
|
||||
|
||||
test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
|
||||
const errors = validateSimulationDraft(
|
||||
{
|
||||
currency: 'USD',
|
||||
total_investment: '100',
|
||||
own_capital: '20',
|
||||
domestic_debt: '20',
|
||||
foreign_debt: '20',
|
||||
grants: '20',
|
||||
},
|
||||
'financial',
|
||||
);
|
||||
assert.match(errors.total_investment, /corresponder ao investimento total/);
|
||||
assert.equal(validateSimulationDraft({}, "financial").currency, "Este campo é obrigatório.");
|
||||
assert.equal(
|
||||
validateSimulationDraft({}, 'financial').currency,
|
||||
'Este campo é obrigatório.',
|
||||
);
|
||||
});
|
||||
|
||||
test("autosave omits identity and contact fields from browser storage", () => {
|
||||
assert.deepEqual(getAutosaveSnapshot({
|
||||
total_investment: "50", legal_name: "Nome", email: "person@example.com", nuit: "123",
|
||||
project_title: "Projecto", legal_name_label: "Nome",
|
||||
}), { total_investment: "50", project_title: "Projecto" });
|
||||
test('autosave omits identity and contact fields from browser storage', () => {
|
||||
assert.deepEqual(
|
||||
getAutosaveSnapshot({
|
||||
total_investment: '50',
|
||||
legal_name: 'Nome',
|
||||
email: 'person@example.com',
|
||||
nuit: '123',
|
||||
project_title: 'Projecto',
|
||||
legal_name_label: 'Nome',
|
||||
}),
|
||||
{ total_investment: '50', project_title: 'Projecto' },
|
||||
);
|
||||
});
|
||||
|
||||
test("server draft snapshots split private identity from economic values", () => {
|
||||
assert.deepEqual(partitionSimulationDraft({ purpose: "simulate_only", legal_name: "Nome", base: "10", rate: "2", province_id_label: "Tete", person_type: "collective", person_type_label: "Pessoa colectiva" }), {
|
||||
personal_snapshot: { legal_name: "Nome", person_type: "collective", selection_labels: { person_type: "Pessoa colectiva" } },
|
||||
economic_snapshot: { purpose: "simulate_only", base: "10", rate: "2", selection_labels: { province_id: "Tete" } },
|
||||
});
|
||||
assert.deepEqual(restoreSimulationDraft({ activity_id: "uuid", infrastructure_needs: ["energia", "água"], selection_labels: { activity_id: "Energia", infrastructure_needs: ["Energia", "Água"] } }, {}), {
|
||||
activity_id: "uuid", activity_id_label: "Energia", infrastructure_needs: ["energia", "água"], infrastructure_needs_label: ["Energia", "Água"],
|
||||
});
|
||||
assert.equal(simulationDraftFingerprint({ base: "10", purpose: "simulate_only" }), simulationDraftFingerprint({ purpose: "simulate_only", base: "10" }));
|
||||
test('server draft snapshots split private identity from economic values', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft({
|
||||
journey_type: 'personal',
|
||||
detail_level: 'simple',
|
||||
purpose: 'simulate_only',
|
||||
legal_name: 'Nome',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
rate: '2',
|
||||
province_id_label: 'Tete',
|
||||
person_type: 'collective',
|
||||
person_type_label: 'Pessoa colectiva',
|
||||
}),
|
||||
{
|
||||
personal_snapshot: {
|
||||
legal_name: 'Nome',
|
||||
person_type: 'collective',
|
||||
selection_labels: { person_type: 'Pessoa colectiva' },
|
||||
},
|
||||
economic_snapshot: {
|
||||
journey_type: 'personal',
|
||||
detail_level: 'simple',
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
rate: '2',
|
||||
selection_labels: { province_id: 'Tete' },
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft({
|
||||
purpose: 'own_investment',
|
||||
business_plan_snapshot: '{"version":1}',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
}).economic_snapshot,
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
business_plan_snapshot: '{"version":1}',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
restoreSimulationDraft(
|
||||
{
|
||||
activity_id: 'uuid',
|
||||
infrastructure_needs: ['energia', 'água'],
|
||||
selection_labels: {
|
||||
activity_id: 'Energia',
|
||||
infrastructure_needs: ['Energia', 'Água'],
|
||||
},
|
||||
},
|
||||
{},
|
||||
),
|
||||
{
|
||||
activity_id: 'uuid',
|
||||
project_questionnaire_version: 'legacy-unversioned',
|
||||
activity_id_label: 'Energia',
|
||||
infrastructure_needs: ['energia', 'água'],
|
||||
infrastructure_needs_label: ['Energia', 'Água'],
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
simulationDraftFingerprint({ base: '10', purpose: 'simulate_only' }),
|
||||
simulationDraftFingerprint({ purpose: 'simulate_only', base: '10' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('anonymous server snapshots omit personal values and labels before transmission', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft(
|
||||
{
|
||||
legal_name: 'Nome',
|
||||
legal_name_label: 'Nome',
|
||||
email: 'person@example.com',
|
||||
fiscal_residency_country: 'mzn-country',
|
||||
fiscal_residency_country_label: 'Moçambique',
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
false,
|
||||
),
|
||||
{
|
||||
personal_snapshot: {},
|
||||
economic_snapshot: {
|
||||
purpose: 'simulate_only',
|
||||
base: '10',
|
||||
financial_tools_snapshot: '{"version":1}',
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
|
||||
const restored = restoreSimulationDraft(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
simulation_sources: [{ simulation_id: 'abc' }],
|
||||
base: '100',
|
||||
},
|
||||
{},
|
||||
);
|
||||
assert.equal(restored.base, '100');
|
||||
assert.equal('simulation_sources' in restored, false);
|
||||
assert.equal(
|
||||
'simulation_sources' in
|
||||
partitionSimulationDraft(restored).economic_snapshot,
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
|
||||
const simulation = {
|
||||
id: '12345678-aaaa-bbbb-cccc-123456789abc',
|
||||
status: 'completed',
|
||||
version_no: 4,
|
||||
updated_at: '2026-10-02T10:00:00Z',
|
||||
legal_name: 'Pessoa Privada',
|
||||
email: 'private@example.com',
|
||||
reports: [
|
||||
{
|
||||
id: 'report-1',
|
||||
version_no: 3,
|
||||
status: 'ready',
|
||||
created_at: '2026-10-02T10:00:00Z',
|
||||
report_sha256: 'a'.repeat(64),
|
||||
},
|
||||
],
|
||||
result_snapshot: {
|
||||
base: '100000.00',
|
||||
rate_percent: '10',
|
||||
reduction_percent: '5',
|
||||
indicative_total: '9500.000000',
|
||||
currency: null,
|
||||
legal_interpretation: false,
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 3,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '9500.000000',
|
||||
unit: null,
|
||||
explanation: 'Resultado aritmético; sem conclusão fiscal.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
simulation.reports[0].report_snapshot = structuredClone(
|
||||
simulation.result_snapshot,
|
||||
);
|
||||
const csv = exportCompletedArithmeticCsv(
|
||||
simulation,
|
||||
'2026-10-02T11:00:00Z',
|
||||
);
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /Versão da execução,4/);
|
||||
assert.match(csv, /Versão do contrato,1/);
|
||||
assert.match(csv, /Data de referência,2026-10-02/);
|
||||
assert.match(csv, /ID do cenário,87654321-aaaa-bbbb-cccc-123456789abc/);
|
||||
assert.match(
|
||||
csv,
|
||||
/Versão do motor,portal-tax-arithmetic-v1\+simulation-v1/,
|
||||
);
|
||||
assert.match(csv, /Estado do resultado,calculated/);
|
||||
assert.match(csv, /ID do relatório,report-1/);
|
||||
assert.match(csv, /Versão do relatório\/cenário,3/);
|
||||
assert.match(csv, /Hash SHA-256 do relatório,aaaaaaaa/);
|
||||
assert.match(csv, /Período,cenário aritmético pontual/);
|
||||
assert.match(csv, /IDs de fontes,nenhum/);
|
||||
assert.match(csv, /portal-tax-arithmetic-v1/);
|
||||
assert.match(csv, /Base introduzida,100000\.00/);
|
||||
assert.match(csv, /Resultado aritmético indicativo,9500\.000000/);
|
||||
assert.match(csv, /Moeda,não fornecida/);
|
||||
assert.match(csv, /Fontes legais,nenhuma associada/);
|
||||
assert.doesNotMatch(csv, /Pessoa Privada|private@example\.com/);
|
||||
assert.throws(
|
||||
() => exportCompletedArithmeticCsv({ status: 'running' }),
|
||||
/concluída/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: { base: 1 },
|
||||
}),
|
||||
/base/,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
|
||||
const snapshot = {
|
||||
contract_version: 1,
|
||||
context: { scenario_version: 4 },
|
||||
indicative_total: '12.50',
|
||||
};
|
||||
const simulation = {
|
||||
status: 'completed',
|
||||
result_snapshot: snapshot,
|
||||
reports: [
|
||||
{
|
||||
id: 'matching-report',
|
||||
status: 'ready',
|
||||
version_no: 4,
|
||||
report_snapshot: structuredClone(snapshot),
|
||||
report_sha256: 'b'.repeat(64),
|
||||
created_at: '2026-10-03T10:00:00Z',
|
||||
},
|
||||
],
|
||||
};
|
||||
assert.deepEqual(readVersionedArithmeticReportReference(simulation), {
|
||||
id: 'matching-report',
|
||||
version_no: 4,
|
||||
report_sha256: 'b'.repeat(64),
|
||||
created_at: '2026-10-03T10:00:00Z',
|
||||
});
|
||||
assert.equal(
|
||||
readVersionedArithmeticReportReference({
|
||||
...simulation,
|
||||
reports: [
|
||||
{
|
||||
...simulation.reports[0],
|
||||
report_snapshot: { ...snapshot, indicative_total: '99' },
|
||||
},
|
||||
],
|
||||
}),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
readVersionedArithmeticReportReference({
|
||||
...simulation,
|
||||
reports: [{ ...simulation.reports[0], report_sha256: 'invalid' }],
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: {
|
||||
base: '10',
|
||||
rate_percent: '2',
|
||||
reduction_percent: '0',
|
||||
indicative_total: '0.2',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
engine_version:
|
||||
'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.3',
|
||||
explanation: 'Aritmética apenas.',
|
||||
},
|
||||
},
|
||||
}),
|
||||
/não reconcilia/,
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '10.00',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 2,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v2',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '10.00',
|
||||
unit: null,
|
||||
explanation: 'Aritmética apenas.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
};
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
status: 'completed',
|
||||
result_snapshot: snapshot,
|
||||
reports: [
|
||||
{
|
||||
id: 'stale-report',
|
||||
status: 'ready',
|
||||
version_no: 1,
|
||||
report_sha256: 'a'.repeat(64),
|
||||
report_snapshot: structuredClone(snapshot),
|
||||
},
|
||||
],
|
||||
}),
|
||||
/nao corresponde a versao atual do resultado/,
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '0.20',
|
||||
legal_interpretation: false,
|
||||
contract_version: 1,
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
context: {
|
||||
reference_date: '2026-10-02',
|
||||
currency: null,
|
||||
currency_fraction_digits: null,
|
||||
scenario_id: '87654321-aaaa-bbbb-cccc-123456789abc',
|
||||
scenario_version: 3,
|
||||
engine_version: 'portal-tax-arithmetic-v1+simulation-v1',
|
||||
ruleset_version: null,
|
||||
},
|
||||
result: {
|
||||
status: 'calculated',
|
||||
value: '0.20',
|
||||
unit: null,
|
||||
explanation: 'Aritmética apenas.',
|
||||
missing_inputs: [],
|
||||
source_ids: [],
|
||||
},
|
||||
};
|
||||
assert.equal(readArithmeticSnapshot(snapshot).integrity, 'versioned');
|
||||
assert.equal(readArithmeticSnapshot(snapshot).value, '0.20');
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({ indicative_total: '0.20' }).integrity,
|
||||
'legacy',
|
||||
);
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({
|
||||
...snapshot,
|
||||
result: { ...snapshot.result, value: '0.2' },
|
||||
}).integrity,
|
||||
'invalid',
|
||||
);
|
||||
assert.equal(
|
||||
readArithmeticSnapshot({ ...snapshot, contract_version: 99 }).integrity,
|
||||
'invalid',
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result CSV neutralizes formula-like report metadata', () => {
|
||||
const csv = exportCompletedArithmeticCsv({
|
||||
id: '=HYPERLINK("https://example.invalid")',
|
||||
status: 'completed',
|
||||
version_no: 1,
|
||||
result_snapshot: {
|
||||
base: '10',
|
||||
rate_percent: '2',
|
||||
reduction_percent: '0',
|
||||
indicative_total: '0.2',
|
||||
formula_version: 'portal-tax-arithmetic-v1',
|
||||
},
|
||||
});
|
||||
assert.match(
|
||||
csv,
|
||||
/ID da execução,"'=HYPERLINK\(""https:\/\/example\.invalid""\)"/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const homePage = readFileSync(
|
||||
new URL('../../resources/js/pages/PortalInvestidor.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const simulator = readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/components/simulation-form.tsx',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
test('portal home hero exposes a direct public simulator link', () => {
|
||||
const hero = homePage.slice(
|
||||
homePage.indexOf('function Hero('),
|
||||
homePage.indexOf('function SectorGrid('),
|
||||
);
|
||||
assert.match(hero, /href="\/simulador-fiscal"/);
|
||||
assert.match(hero, /Planear finanças/);
|
||||
});
|
||||
|
||||
test('completed simulator result keeps public interest submission independent', () => {
|
||||
assert.match(simulator, /href="\/manifestar-interesse"/);
|
||||
assert.match(
|
||||
simulator,
|
||||
/Manifestar interesse sem partilhar\s+esta simulação/,
|
||||
);
|
||||
assert.match(simulator, /sem\s+partilhar os dados desta simulação/);
|
||||
});
|
||||
Reference in New Issue
Block a user