@@ -67,7 +67,7 @@ class ClamDScannerIntegrationTest extends TestCase
|
||||
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);
|
||||
$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]));
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DatabaseErrorRedactionTest extends TestCase
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Console\Commands\ImportDocumentBatch;
|
||||
use App\Jobs\ScanDocumentForMalware;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ImportDocumentBatchTest extends TestCase
|
||||
@@ -22,7 +24,7 @@ class ImportDocumentBatchTest extends TestCase
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->batchName = 'test-'.\Illuminate\Support\Str::uuid();
|
||||
$this->batchName = 'test-'.Str::uuid();
|
||||
$this->staging = storage_path('app/private/document-import-staging/'.$this->batchName);
|
||||
File::ensureDirectoryExists($this->staging);
|
||||
Storage::fake('local');
|
||||
@@ -47,14 +49,14 @@ class ImportDocumentBatchTest extends TestCase
|
||||
'version_label' => 'edição de teste', 'category' => 'general', 'topic' => 'test', 'document_type' => 'guide',
|
||||
];
|
||||
file_put_contents($this->staging.'/manifest.json', json_encode(['documents' => [$record, $record]], JSON_THROW_ON_ERROR));
|
||||
$actor = \App\Models\User::factory()->create();
|
||||
$actor = User::factory()->create();
|
||||
|
||||
$this->artisan(new ImportDocumentBatch(), ['manifest' => $this->batchName.'/manifest.json'])->assertSuccessful();
|
||||
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json'])->assertSuccessful();
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
$this->assertDatabaseCount('portal_resources', 0);
|
||||
$this->assertSame([], Storage::disk('local')->allFiles('portal-documents'));
|
||||
|
||||
$this->artisan(new ImportDocumentBatch(), ['manifest' => $this->batchName.'/manifest.json', '--apply' => true, '--actor' => (string) $actor->id])->assertSuccessful();
|
||||
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json', '--apply' => true, '--actor' => (string) $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('portal_resources', 1);
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
@@ -66,7 +68,7 @@ class ImportDocumentBatchTest extends TestCase
|
||||
$this->assertDatabaseHas('audit_events', ['actor_user_id' => $actor->id, 'action' => 'private_document_batch_imported']);
|
||||
Bus::assertDispatchedTimes(ScanDocumentForMalware::class, 1);
|
||||
|
||||
$this->artisan(new ImportDocumentBatch(), ['manifest' => $this->batchName.'/manifest.json', '--apply' => true, '--actor' => (string) $actor->id])->assertSuccessful();
|
||||
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json', '--apply' => true, '--actor' => (string) $actor->id])->assertSuccessful();
|
||||
$this->assertDatabaseCount('documents', 1);
|
||||
$this->assertDatabaseCount('portal_resources', 1);
|
||||
$this->assertDatabaseCount('audit_events', 1);
|
||||
@@ -79,10 +81,10 @@ class ImportDocumentBatchTest extends TestCase
|
||||
$record = ['external_id' => 'test-document', 'relative_path' => '..\\..\\..\\..\\.env', 'title' => 'Test', 'issuer' => 'Test'];
|
||||
file_put_contents($this->staging.'/manifest.json', json_encode(['documents' => [$record]], JSON_THROW_ON_ERROR));
|
||||
|
||||
$this->artisan(new ImportDocumentBatch(), ['manifest' => $this->batchName.'/manifest.json', '--apply' => true])->assertFailed();
|
||||
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json', '--apply' => true])->assertFailed();
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
|
||||
$this->artisan(new ImportDocumentBatch(), ['manifest' => $this->batchName.'/manifest.json'])->assertFailed();
|
||||
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json'])->assertFailed();
|
||||
$this->assertDatabaseCount('documents', 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ class InterestSubmissionTest extends TestCase
|
||||
DB::statement('CREATE TRIGGER test_reject_outbox BEFORE INSERT ON outbox_events FOR EACH ROW EXECUTE FUNCTION investmoz_reject_audit_change()');
|
||||
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => ['team@example.invalid']]);
|
||||
$headers = ['Idempotency-Key' => (string) Str::uuid()];
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertStatus(500);
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertStatus(503)->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
$this->assertDatabaseCount('interest_submission_receipts', 0);
|
||||
$this->assertDatabaseCount('jobs', 0);
|
||||
|
||||
@@ -157,8 +157,8 @@ class InvestmentPortfolioTest extends TestCase
|
||||
public function test_private_manifestation_link_requires_authentication_and_preserves_the_public_dossier(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
$this->app['auth']->forgetGuards();
|
||||
$dossierId = $dossier->id;
|
||||
$this->app['auth']->forgetGuards();
|
||||
$dossierId = $dossier->id;
|
||||
$owner = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
use Database\Seeders\InvestmentReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@@ -15,12 +16,20 @@ use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentUnificationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->app->bind(MalwareScanner::class, fn () => new CleanScannerFixture);
|
||||
$this->withoutVite();
|
||||
}
|
||||
|
||||
private function option(string $group, string $code): int
|
||||
{
|
||||
return DB::table('investment_reference_options')->where('group', $group)->where('code', $code)->value('id');
|
||||
@@ -66,7 +75,8 @@ class InvestmentUnificationTest extends TestCase
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertHeader('Cache-Control', 'no-store, private');
|
||||
InterestRequest::firstOrFail()->update(['status' => 'in_review']);
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload(2))->assertJsonPath('status', 'in_review');
|
||||
$this->get('/balcao-virtual')->assertInertia(fn (Assert $page) => $page->has('requests', 1));
|
||||
$this->get('/balcao-virtual')->assertRedirect('/balcao-virtual/painel');
|
||||
$this->get('/balcao-virtual/painel')->assertInertia(fn (Assert $page) => $page->has('legacyRequests', 1));
|
||||
$this->assertSame(3, DB::table('investment_submission_events')->where('submission_id', $id)->count());
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $this->payload(3))->assertConflict();
|
||||
}
|
||||
|
||||
@@ -3,18 +3,26 @@
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
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\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentZoneAttachmentTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->app->bind(MalwareScanner::class, fn () => new CleanScannerFixture);
|
||||
}
|
||||
|
||||
public function test_upload_is_private_until_administrative_review_and_explicit_public_selection(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Investor;
|
||||
use App\Models\InvestorJourney;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestorGuidanceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $investor;
|
||||
|
||||
private User $manager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
|
||||
$this->assertStringEndsWith('_test', $identity->name);
|
||||
$this->assertSame(55441, (int) $identity->port);
|
||||
$this->investor = User::factory()->create();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email], 'investmoz_ai.enabled' => false, 'suitecrm.enabled' => false]);
|
||||
Http::fake();
|
||||
}
|
||||
|
||||
private function dossier(array $extra = []): string
|
||||
{
|
||||
return $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', ['title' => 'Ideia fictícia QA', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, ...$extra])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function guidance(string $id): array
|
||||
{
|
||||
return $this->actingAs($this->investor)->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertOk()->json();
|
||||
}
|
||||
|
||||
private function service(): string
|
||||
{
|
||||
return $this->actingAs($this->manager)->postJson('/management/balcao/servicos', ['code' => 'project-preparation', 'confirm' => true])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_panel_creation_redirect_confirms_persistence_and_never_submits_a_request(): void
|
||||
{
|
||||
$payload = ['title' => 'Dossier de teste QA do painel', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true];
|
||||
$response = $this->actingAs($this->investor)->post('/balcao-virtual/dossiers', $payload);
|
||||
$case = DB::table('desk_cases')->where('client_key', $payload['client_key'])->first();
|
||||
$this->assertNotNull($case);
|
||||
$response->assertRedirect('/balcao-virtual/dossiers/'.$case->id)->assertSessionHas('success');
|
||||
$this->post('/balcao-virtual/dossiers', $payload)->assertRedirect('/balcao-virtual/dossiers/'.$case->id);
|
||||
$this->assertDatabaseCount('desk_cases', 1);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$this->getJson('/balcao-virtual/painel')->assertJsonPath('cases.0.id', $case->id);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$case->id)->assertJsonPath('case.title', $payload['title']);
|
||||
$this->post('/balcao-virtual/dossiers', [...$payload, 'reuse_consent' => false, 'client_key' => (string) Str::uuid()])->assertSessionHasErrors('reuse_consent');
|
||||
$this->assertDatabaseCount('desk_cases', 1);
|
||||
}
|
||||
|
||||
public function test_message_kind_is_recorded_at_send_time_and_legacy_is_not_reinterpreted(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$service = $this->service();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->json('id');
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$requestId.'/mensagens', ['body' => 'Resposta original do responsável.', 'client_key' => (string) Str::uuid()])->assertOk();
|
||||
config(['portal.managers' => []]);
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$requestId)->assertOk()->assertJsonPath('messages.0.kind', 'responsible_response')->assertJsonPath('messages.0.name', $this->manager->name);
|
||||
DB::table('desk_messages')->insert(['id' => (string) Str::uuid(), 'request_id' => $requestId, 'actor_id' => $this->investor->id,
|
||||
'client_key' => (string) Str::uuid(), 'body' => Crypt::encryptString('Mensagem histórica sem tipo original.'), 'created_at' => now()->addSecond()]);
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$requestId)->assertJsonPath('messages.1.kind', 'historical_unclassified');
|
||||
$this->assertDatabaseCount('desk_messages', 2);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_link_monitor_expires_checks_and_records_human_evidence_without_external_calls(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$link = (string) Str::uuid();
|
||||
DB::table('desk_institutional_links')->insert(['id' => $link, 'stage' => 'E10', 'entity' => 'Instituição sintética QA', 'purpose' => 'Preparação',
|
||||
'url' => 'https://example.invalid/', 'contact' => null, 'source_reference' => 'Fixture QA', 'status' => 'active', 'verified_at' => now()->subDays(8)]);
|
||||
$this->get('/balcao-virtual/encaminhar/'.$link.'?case_id='.$id)->assertRedirect('/balcao-virtual/dossiers/'.$id)->assertSessionHas('warning');
|
||||
$path = '/management/balcao/ligacoes/'.$link.'/conferencia';
|
||||
$data = ['version' => 1, 'available' => false, 'evidence' => 'Consulta manual QA identificou indisponibilidade.', 'contact' => 'Contacto sintético QA; fonte fixture'];
|
||||
$this->postJson($path, $data)->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson($path, $data)->assertOk();
|
||||
$this->postJson($path, $data)->assertConflict();
|
||||
$this->assertDatabaseHas('desk_institutional_links', ['id' => $link, 'status' => 'unavailable', 'verified_by' => $this->manager->id]);
|
||||
$this->assertDatabaseHas('audit_events', ['action' => 'institutional_link_checked', 'actor_user_id' => $this->manager->id]);
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/dossiers/'.$id)->assertOk()->assertJsonPath('links.0.monitor.available', false);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertOk();
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_complete_idea_request_response_and_internal_crm_task_reuses_existing_identity(): void
|
||||
{
|
||||
$existing = Investor::create(['legal_name' => 'Investidor QA', 'investor_type' => 'individual', 'status' => 'prospect']);
|
||||
DB::table('investor_accounts')->insert(['user_id' => $this->investor->id, 'investor_id' => $existing->id]);
|
||||
$project = (string) Str::uuid();
|
||||
DB::table('projects')->insert(['id' => $project, 'code' => 'GUIDANCE-QA', 'name' => 'Projecto fictício', 'status' => 'draft']);
|
||||
$dossier = (string) Str::uuid();
|
||||
DB::table('investment_dossiers')->insert(['id' => $dossier, 'project_id' => $project, 'title' => 'Projecto QA', 'content' => '{}', 'source' => 'fixture']);
|
||||
$journey = InvestorJourney::create(['user_id' => $this->investor->id, 'investor_id' => $existing->id, 'dossier_id' => $dossier, 'status' => 'started']);
|
||||
$id = $this->dossier(['journey_id' => $journey->id]);
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $id, 'investor_id' => $existing->id, 'project_id' => $project, 'journey_id' => $journey->id]);
|
||||
$view = $this->guidance($id);
|
||||
$this->assertCount(7, $view['phases']);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$service = $this->service();
|
||||
$requestKey = (string) Str::uuid();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => $requestKey])->assertCreated()->json('id');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => $requestKey])->assertJsonPath('id', $requestId);
|
||||
$code = 'support_preparation';
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/recomendacoes', ['code' => $code, 'context_hash' => $view['fingerprint'], 'decision' => 'accepted', 'reason' => 'Pretendo preparar apoio.'])->assertOk();
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$taskInput = ['code' => $code, 'context_hash' => $view['fingerprint'], 'consent' => true, 'due_at' => now()->addDays(2)->toIso8601String(), 'request_id' => $requestId];
|
||||
$taskId = $this->postJson('/balcao-virtual/dossiers/'.$id.'/tarefas', $taskInput)->assertCreated()->json('id');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/tarefas', $taskInput)->assertJsonPath('id', $taskId);
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$this->assertDatabaseHas('tasks', ['id' => $taskId, 'desk_case_id' => $id, 'desk_request_id' => $requestId, 'assignee_user_id' => $this->investor->id, 'status' => 'open', 'external_sync_status' => 'pending_authorization']);
|
||||
$payload = ['title' => 'Projecto QA', 'description' => 'Preciso de orientação sobre preparação.', 'regime' => 'unknown', 'investment_amount' => '1000.00', 'currency' => 'MZN', 'own_finance' => '600.00', 'other_finance' => '400.00'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, ['version' => 1, 'payload' => $payload, 'submit' => false])->assertOk()->assertJsonPath('status', 'draft');
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$requestId)->assertJsonPath('request.payload.description', $payload['description']);
|
||||
$submit = ['version' => 2, 'payload' => $payload, 'submit' => true, 'consent' => true];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, $submit)->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, $submit)->assertOk();
|
||||
$this->get('/balcao-virtual/pedidos/'.$requestId.'/recibo')->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 3, 'status' => 'reviewing', 'reason' => 'Autodecisão indevida.'])->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$requestId.'/responsavel', ['version' => 3, 'analyst_id' => $this->manager->id, 'reason' => 'Atribuição real QA.'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 4, 'status' => 'reviewing', 'reason' => 'Análise interna iniciada.'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/mensagens', ['body' => 'Resposta humana QA: indique as evidências de mercado.', 'client_key' => (string) Str::uuid()])->assertOk();
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$requestId)->assertJsonPath('messages.0.kind', 'responsible_response');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/tarefas/'.$taskId, ['version' => 1, 'status' => 'done', 'reason' => 'Pedido submetido e primeira resposta consultada.'])->assertOk();
|
||||
$this->assertDatabaseHas('tasks', ['id' => $taskId, 'status' => 'done']);
|
||||
$this->assertDatabaseHas('desk_events', ['case_id' => $id, 'action' => 'guidance_task_updated']);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_incomplete_context_corrections_stale_choices_and_no_external_services(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$view = $this->guidance($id);
|
||||
$this->assertNotEmpty($view['phases'][1]['questions']);
|
||||
$this->assertSame('not_configured', $view['external_ai']['status']);
|
||||
$this->assertSame([], $view['consulted']);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/recomendacoes', ['code' => 'market_preparation', 'context_hash' => $view['fingerprint'], 'decision' => 'rejected', 'reason' => 'Hipótese ainda sem evidência.'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/pressupostos', ['version' => 1, 'assumptions' => ['activity' => 'Transformação', 'expected_start_date' => '2027-01-01', 'ready_date' => '2027-02-01']])->assertOk();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/pressupostos', ['version' => 1, 'assumptions' => ['activity' => 'Alteração obsoleta']])->assertConflict();
|
||||
$new = $this->guidance($id);
|
||||
$this->assertTrue($new['phases'][1]['recommendations'][0]['review']['stale']);
|
||||
$this->assertSame('declared_contradiction', $new['phases'][5]['risks'][0]['classification']);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/tarefas', ['code' => 'market_preparation', 'context_hash' => $view['fingerprint'], 'consent' => true, 'due_at' => now()->addDay()->toIso8601String()])->assertConflict();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/fontes', ['query' => 'Licenciamento'])->assertOk()->assertJsonPath('status', 'unavailable')->assertJsonPath('consulted', []);
|
||||
$this->assertDatabaseCount('tasks', 0);
|
||||
$this->get('/balcao-virtual/dossiers/'.$id)->assertOk();
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_private_linked_draft_is_not_shared_with_manager_and_is_recovered_for_owner(): void
|
||||
{
|
||||
$draft = SimulationFormDraft::create(['id' => (string) Str::uuid(), 'owner_user_id' => $this->investor->id, 'version_no' => 1,
|
||||
'create_key_hash' => hash('sha256', 'qa-key'), 'create_payload_hash' => hash('sha256', 'qa-data'), 'snapshot_sha256' => hash('sha256', 'qa-data'),
|
||||
'personal_snapshot' => SimulationFormDraft::encryptSnapshot(['name' => 'PRIVATE PERSONAL']),
|
||||
'economic_snapshot' => SimulationFormDraft::encryptSnapshot(['project_summary' => 'Ideia guardada', 'market_assumption' => 'Hipótese, sem procura provada', 'business_plan_snapshot' => '{"version":999}'])]);
|
||||
$id = $this->dossier(['simulation_id' => $draft->id]);
|
||||
$owner = $this->guidance($id);
|
||||
$this->assertSame('Ideia guardada', $owner['facts']['project_summary']);
|
||||
$this->assertArrayNotHasKey('market_evidence', $owner['facts']);
|
||||
$this->assertStringNotContainsString('PRIVATE PERSONAL', json_encode($owner));
|
||||
$this->assertSame(1, $owner['consulted'][0]['version']);
|
||||
$manager = $this->actingAs($this->manager)->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertOk()->json();
|
||||
$this->assertNull($manager['financial_draft']);
|
||||
$this->assertSame([], $manager['consulted']);
|
||||
$this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', ['title' => 'Reutilização', 'simulation_id' => $draft->id, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertJsonPath('id', $id);
|
||||
$this->assertDatabaseCount('desk_cases', 1);
|
||||
$this->actingAs(User::factory()->create())->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/dossiers', ['title' => 'Tentativa', 'simulation_id' => $draft->id, 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_request_constraints_and_draft_permissions_preserve_existing_flow(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$service = $this->service();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$data = ['version' => 1, 'payload' => ['title' => 'QA', 'description' => 'Contradição declarada', 'investment_amount' => '1000.00', 'currency' => 'MZN', 'own_finance' => '1.00', 'other_finance' => '1.00'], 'submit' => true, 'consent' => true];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, $data)->assertUnprocessable();
|
||||
$this->assertDatabaseHas('desk_requests', ['id' => $requestId, 'status' => 'draft', 'version' => 1]);
|
||||
$this->actingAs($this->manager)->putJson('/balcao-virtual/pedidos/'.$requestId, $data)->assertForbidden();
|
||||
$this->actingAs(User::factory()->create())->getJson('/balcao-virtual/pedidos/'.$requestId)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_clarification_resubmission_and_signed_internal_outcome_preserve_snapshots(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$service = $this->service();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->json('id');
|
||||
$payload = ['title' => 'QA', 'description' => 'Descrição inicial', 'regime' => 'unknown', 'investment_amount' => '1000.00', 'currency' => 'MZN'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, ['version' => 1, 'payload' => $payload, 'submit' => true, 'consent' => true])->assertOk();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 2, 'status' => 'returned', 'reason' => 'Esclareça o mercado previsto.', 'editable_fields' => ['description']])->assertOk();
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$requestId)->assertJsonPath('request.submitted_snapshot.payload.description', 'Descrição inicial');
|
||||
$changed = [...$payload, 'title' => 'Alteração indevida', 'description' => 'Mercado declarado, evidência pendente.'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, ['version' => 3, 'payload' => $changed, 'submit' => true, 'consent' => true, 'reason' => 'Resposta ao esclarecimento.'])->assertUnprocessable();
|
||||
$payload['description'] = 'Mercado declarado, evidência pendente.';
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$requestId, ['version' => 3, 'payload' => $payload, 'submit' => true, 'consent' => true, 'reason' => 'Resposta ao esclarecimento.'])->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 4, 'status' => 'reviewing', 'reason' => 'Resposta analisada internamente.'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 5, 'status' => 'opinion', 'reason' => 'Parecer interno, sem licença oficial.'])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/estado', ['version' => 6, 'status' => 'accepted', 'reason' => 'Dossier aceite para acompanhamento interno.'])->assertOk();
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/pedidos/'.$requestId)->assertJsonPath('request.status', 'accepted')->assertJsonCount(2, 'revisions');
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_manual_document_payment_and_communication_evidence_without_external_confirmation(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$id = $this->dossier();
|
||||
$service = $this->service();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->json('id');
|
||||
$doc = (string) Str::uuid();
|
||||
$link = (string) Str::uuid();
|
||||
$bytes = 'Comprovativo fictício QA, sem valor oficial.';
|
||||
Storage::disk('local')->put('qa-proof.txt', $bytes);
|
||||
$hash = hash('sha256', $bytes);
|
||||
DB::table('documents')->insert(['id' => $doc, 'source_system' => 'qa', 'file_name' => 'qa-proof.txt', 'media_type' => 'text/plain', 'storage_key' => 'qa-proof.txt', 'sha256' => $hash, 'size_bytes' => strlen($bytes), 'uploaded_by' => $this->investor->id, 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => $hash, 'data_classification' => 'confidential']);
|
||||
DB::table('desk_documents')->insert(['id' => $link, 'case_id' => $id, 'document_id' => $doc, 'category' => 'proof', 'source_reference' => 'Fixture QA', 'linked_by' => $this->investor->id]);
|
||||
$review = ['version' => 1, 'outcome' => 'internal_verified', 'what_checked' => 'Legibilidade e referência declarada.', 'evidence' => 'Documento QA e declaração do investidor.'];
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/documentos/'.$link.'/conferencia', $review)->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/dossiers/'.$id.'/documentos/'.$link.'/conferencia', $review)->assertOk();
|
||||
$event = DB::table('desk_events')->where('action', 'document_reviewed')->first();
|
||||
$this->assertSame($this->manager->id, (int) $event->actor_id);
|
||||
$this->assertSame($hash, app(VirtualDesk::class)->decode($event->payload)['sha256']);
|
||||
$this->assertDatabaseHas('documents', ['id' => $doc, 'status' => 'active']);
|
||||
$payment = ['reference' => 'QA-MANUAL-1', 'amount' => '25.50', 'currency' => 'MZN', 'source_reference' => 'Valor declarado em comprovativo fictício, não taxa automática.', 'document_id' => $doc, 'consent' => true];
|
||||
$this->actingAs($this->investor)->postJson('/balcao-virtual/pedidos/'.$requestId.'/pagamentos', $payment)->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/pagamentos', $payment)->assertOk();
|
||||
$this->assertDatabaseCount('desk_payments', 1);
|
||||
$record = DB::table('desk_payments')->first();
|
||||
$this->assertSame('pending', $record->status);
|
||||
$check = ['version' => 1, 'status' => 'internal_verified', 'reason' => 'Conferida referência e valor no comprovativo.', 'evidence' => 'Comprovativo QA, não consulta bancária.'];
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/pagamentos/'.$record->id.'/conferencia', $check)->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/pedidos/'.$requestId.'/pagamentos/'.$record->id.'/conferencia', $check)->assertOk();
|
||||
$this->assertDatabaseHas('desk_payments', ['id' => $record->id, 'status' => 'internal_verified', 'verified_by' => $this->manager->id]);
|
||||
$communication = ['channel' => 'whatsapp', 'direction' => 'received', 'occurred_at' => now()->subMinute()->toIso8601String(), 'summary' => 'Comunicação fictícia registada manualmente.', 'evidence' => 'Referência declarada pelo responsável QA.', 'client_key' => (string) Str::uuid()];
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/comunicacoes', $communication)->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/comunicacoes', $communication)->assertOk();
|
||||
$this->assertSame(1, DB::table('desk_events')->where('action', 'manual_communication_recorded')->count());
|
||||
Storage::disk('local')->put('qa-proof.txt', 'Ficheiro alterado');
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/documentos/'.$link.'/conferencia', [...$review, 'version' => 2])->assertUnprocessable();
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_parallel_preparation_unavailable_link_and_ordered_contestable_recommendations(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/etapas', ['version' => 1, 'stage' => 'E10', 'status' => 'preparing', 'reason' => 'Preparar em paralelo com o registo.'])->assertOk();
|
||||
$this->actingAs($this->manager)->postJson('/balcao-virtual/dossiers/'.$id.'/etapas', ['version' => 2, 'stage' => 'E10', 'status' => 'completed', 'reason' => 'Conclusão sem suporte.', 'evidence' => 'Afirmação sem documento.'])->assertUnprocessable();
|
||||
$view = $this->guidance($id);
|
||||
foreach (['accepted', 'rejected', 'corrected'] as $decision) {
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/recomendacoes', ['code' => 'support_preparation', 'context_hash' => $view['fingerprint'], 'decision' => $decision, 'reason' => 'Revisão explícita QA.'])->assertOk();
|
||||
}
|
||||
$updated = $this->guidance($id);
|
||||
$this->assertSame('corrected', $updated['phases'][6]['recommendations'][0]['review']['decision']);
|
||||
$link = (string) Str::uuid();
|
||||
DB::table('desk_institutional_links')->insert(['id' => $link, 'stage' => 'E10', 'entity' => 'Entidade QA', 'purpose' => 'Preparação', 'url' => 'https://example.invalid/', 'contact' => 'Contacto fictício QA', 'status' => 'pending', 'source_reference' => 'Fixture não confirmada']);
|
||||
$this->get('/balcao-virtual/encaminhar/'.$link.'?case_id='.$id)->assertRedirect('/balcao-virtual/dossiers/'.$id)->assertSessionHas('warning');
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$id)->assertOk();
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertOk();
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_organization_viewers_and_removed_members_keep_module_permissions(): void
|
||||
{
|
||||
$viewer = User::factory()->create();
|
||||
$officer = User::factory()->create();
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'Organização fictícia QA', 'organization_type' => 'private']);
|
||||
foreach ([[$this->investor, 'manager'], [$viewer, 'viewer'], [$officer, 'officer']] as [$user, $role]) {
|
||||
DB::table('memberships')->insert(['user_id' => $user->id, 'organization_id' => $organization, 'role' => $role]);
|
||||
}
|
||||
$id = $this->dossier(['organization_id' => $organization]);
|
||||
$service = $this->service();
|
||||
$requestId = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->json('id');
|
||||
$this->actingAs($viewer)->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertOk()->assertJsonPath('can_write', false);
|
||||
$this->postJson('/balcao-virtual/dossiers/'.$id.'/pressupostos', ['version' => 1, 'assumptions' => ['activity' => 'Alteração indevida']])->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/mensagens', ['body' => 'Tentativa de escrita viewer.', 'client_key' => (string) Str::uuid()])->assertForbidden();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/comunicacoes', ['channel' => 'phone', 'direction' => 'received', 'occurred_at' => now()->subMinute()->toIso8601String(), 'summary' => 'Tentativa de escrita viewer.', 'evidence' => 'Sem permissão.', 'client_key' => (string) Str::uuid()])->assertForbidden();
|
||||
$this->actingAs($officer)->postJson('/balcao-virtual/dossiers/'.$id.'/pressupostos', ['version' => 1, 'assumptions' => ['activity' => 'Declaração autorizada da organização']])->assertOk();
|
||||
$this->postJson('/balcao-virtual/pedidos/'.$requestId.'/mensagens', ['body' => 'Mensagem original do membro investidor.', 'client_key' => (string) Str::uuid()])->assertOk();
|
||||
DB::table('memberships')->where('organization_id', $organization)->where('user_id', $officer->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($this->manager)->getJson('/balcao-virtual/pedidos/'.$requestId)->assertOk()->assertJsonPath('messages.0.kind', 'investor_message')->assertJsonPath('messages.0.name', $officer->name);
|
||||
DB::table('memberships')->where('organization_id', $organization)->where('user_id', $this->investor->id)->update(['deleted_at' => now()]);
|
||||
$this->actingAs($this->investor)->getJson('/balcao-virtual/dossiers/'.$id)->assertForbidden();
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$requestId)->assertForbidden();
|
||||
$this->getJson('/balcao-virtual/contextos')->assertJsonCount(0, 'cases');
|
||||
}
|
||||
|
||||
public function test_pending_installation_preserves_legacy_desk_and_requires_authentication(): void
|
||||
{
|
||||
$this->mock(VirtualDesk::class)->shouldReceive('installed')->andReturn(false);
|
||||
$this->actingAs($this->investor)->get('/balcao-virtual')->assertOk();
|
||||
$this->getJson('/balcao-virtual/painel')->assertStatus(503);
|
||||
$this->getJson('/management/balcao/fontes')->assertForbidden();
|
||||
$this->actingAs($this->manager)->getJson('/management/balcao/fontes')->assertOk()->assertJsonStructure(['total', 'attachmentCount', 'forms']);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_installation_preview_shows_target_and_refuses_proofs_for_a_different_database(): void
|
||||
{
|
||||
$this->mock(VirtualDesk::class)->shouldReceive('installed')->andReturn(false);
|
||||
$this->actingAs($this->investor)->getJson('/management/balcao-install')->assertForbidden();
|
||||
$view = $this->actingAs($this->manager)->getJson('/management/balcao-install')->assertOk()
|
||||
->assertJsonPath('target.database', 'investmoz_v2_20261008_test')->assertJsonPath('backupVerified', false)
|
||||
->assertJsonStructure(['pendingMigrations', 'databaseReady', 'scanner', 'rollback', 'compatibilityVerified'])->json();
|
||||
$before = DB::table('migrations')->count();
|
||||
$this->postJson('/management/balcao-install', ['hash' => $view['hash'], 'confirm' => true])->assertStatus(422);
|
||||
$this->assertSame($before, DB::table('migrations')->count());
|
||||
}
|
||||
|
||||
public function test_existing_support_request_and_crm_investor_are_associated_without_copying(): void
|
||||
{
|
||||
$canonical = Investor::create(['legal_name' => 'Investidor já acompanhado QA', 'investor_type' => 'individual', 'status' => 'active']);
|
||||
$original = InterestRequest::create(['reference' => 'QA-EXISTING-SUPPORT', 'full_name' => 'Investidor QA', 'email' => 'private@example.invalid', 'investor_type' => 'individual', 'country' => 'Moçambique', 'sector_interest' => 'Energia QA', 'message' => 'Pedido original preservado.', 'privacy_consent' => true,
|
||||
'investor_id' => $canonical->id, 'assigned_to' => $this->manager->id, 'next_action' => 'Conferir documentação no registo existente.', 'metadata' => ['portal_user_id' => $this->investor->id]]);
|
||||
$id = $this->dossier(['interest_request_id' => $original->id]);
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('desk_requests', 0);
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
$this->assertDatabaseHas('desk_cases', ['id' => $id, 'interest_request_id' => $original->id, 'investor_id' => $canonical->id]);
|
||||
$this->getJson('/balcao-virtual/dossiers/'.$id)->assertJsonPath('legacyRequest.reference', 'QA-EXISTING-SUPPORT')->assertJsonPath('legacyRequest.responsible_name', $this->manager->name)->assertJsonMissingPath('legacyRequest.email');
|
||||
$this->postJson('/balcao-virtual/dossiers', ['title' => 'Reutilizar', 'interest_request_id' => $original->id, 'reuse_consent' => true, 'client_key' => (string) Str::uuid()])->assertJsonPath('id', $id);
|
||||
$this->assertDatabaseCount('desk_cases', 1);
|
||||
$this->actingAs(User::factory()->create())->postJson('/balcao-virtual/dossiers', ['title' => 'Sem autorização', 'interest_request_id' => $original->id, 'reuse_consent' => true, 'client_key' => (string) Str::uuid()])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_guidance_evidence_tracks_scope_latest_review_hash_expiration_and_permissions(): void
|
||||
{
|
||||
$id = $this->dossier();
|
||||
$initial = $this->guidance($id);
|
||||
$this->assertSame('absent', $initial['phases'][2]['evidence'][0]['state']);
|
||||
$doc = (string) Str::uuid();
|
||||
$link = (string) Str::uuid();
|
||||
$bytes = 'Evidencia ficticia V2 QA';
|
||||
Storage::disk('local')->put('v2-location-proof.txt', $bytes);
|
||||
$hash = hash('sha256', $bytes);
|
||||
DB::table('documents')->insert(['id' => $doc, 'source_system' => 'qa', 'file_name' => 'v2-location-proof.txt', 'media_type' => 'text/plain', 'storage_key' => 'v2-location-proof.txt', 'sha256' => $hash, 'version_no' => 1, 'size_bytes' => strlen($bytes), 'uploaded_by' => $this->investor->id, 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_scanned_sha256' => $hash, 'data_classification' => 'confidential']);
|
||||
DB::table('desk_documents')->insert(['id' => $link, 'case_id' => $id, 'document_id' => $doc, 'category' => 'location_evidence', 'source_reference' => 'Fixture QA', 'linked_by' => $this->investor->id]);
|
||||
$attached = $this->guidance($id);
|
||||
$this->assertSame('attached_unchecked', $attached['phases'][2]['evidence'][0]['state']);
|
||||
$this->assertNotSame($initial['fingerprint'], $attached['fingerprint']);
|
||||
$review = ['version' => 1, 'outcome' => 'internal_verified', 'what_checked' => 'Acesso descrito no documento ficticio.', 'evidence' => 'Texto e hash da fixture QA.', 'supports' => ['location_evidence']];
|
||||
$url = '/balcao-virtual/dossiers/'.$id.'/documentos/'.$link.'/conferencia';
|
||||
$this->postJson($url, $review)->assertForbidden();
|
||||
$this->actingAs($this->manager)->postJson($url, $review)->assertOk();
|
||||
$verified = $this->guidance($id);
|
||||
$e = $verified['phases'][2]['evidence'][0];
|
||||
$this->assertSame('internally_verified', $e['state']);
|
||||
$this->assertSame($this->manager->name, $e['documents'][0]['review']['author']);
|
||||
$this->assertNotEmpty($e['documents'][0]['review']['date']);
|
||||
$this->assertSame($review['what_checked'], $e['documents'][0]['review']['what_checked']);
|
||||
$this->assertSame([], $verified['phases'][2]['risks']);
|
||||
$this->assertSame('absent', $verified['phases'][3]['evidence'][0]['state']);
|
||||
$this->actingAs(User::factory()->create())->getJson('/balcao-virtual/dossiers/'.$id.'/orientacao')->assertForbidden();
|
||||
DB::table('desk_documents')->where('id', $link)->update(['valid_until' => now()->subDay()->toDateString()]);
|
||||
$this->assertSame('expired', $this->guidance($id)['phases'][2]['evidence'][0]['state']);
|
||||
DB::table('desk_documents')->where('id', $link)->update(['valid_until' => null]);
|
||||
DB::table('documents')->where('id', $doc)->update(['version_no' => 2]);
|
||||
$this->assertSame('superseded', $this->guidance($id)['phases'][2]['evidence'][0]['state']);
|
||||
DB::table('documents')->where('id', $doc)->update(['version_no' => 1]);
|
||||
Storage::disk('local')->put('v2-location-proof.txt', 'Bytes substituidos QA');
|
||||
$this->assertSame('superseded', $this->guidance($id)['phases'][2]['evidence'][0]['state']);
|
||||
Storage::disk('local')->put('v2-location-proof.txt', $bytes);
|
||||
$this->actingAs($this->manager)->postJson($url, [...$review, 'version' => 2, 'outcome' => 'contradiction_identified'])->assertOk();
|
||||
$this->assertSame('contradiction', $this->guidance($id)['phases'][2]['evidence'][0]['state']);
|
||||
// A new conference with no scope must not resurrect an older verification.
|
||||
$this->actingAs($this->manager)->postJson($url, [...$review, 'version' => 3, 'supports' => []])->assertOk();
|
||||
$this->assertSame('attached_unchecked', $this->guidance($id)['phases'][2]['evidence'][0]['state']);
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ 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\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
@@ -42,7 +42,7 @@ class PortalServicesTest extends TestCase
|
||||
public function test_public_sections_render_and_desk_requires_login(): void
|
||||
{
|
||||
foreach (['sectores', 'como-investir', 'legislacao', 'documentos', 'apoio', 'parcerias', 'simulador-fiscal', 'Simulador', 'formularios/investidor', 'formularios/empresa'] as $path) {
|
||||
$this->get('/'.$path)->assertOk()->assertInertia(fn (Assert $page) => $page->component('portal/services'));
|
||||
$this->get('/'.$path)->assertOk()->assertInertia(fn (Assert $page) => $page->component($path === 'parcerias' ? 'partnerships/catalogue' : 'portal/services'));
|
||||
}
|
||||
$this->get('/balcao-virtual')->assertRedirect('/login');
|
||||
$this->get('/management/portal-services')->assertRedirect('/login');
|
||||
@@ -81,8 +81,9 @@ class PortalServicesTest extends TestCase
|
||||
$this->post('/apoio', $payload)->assertSessionHasNoErrors();
|
||||
$this->assertSame(1, InterestRequest::count());
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
$this->get('/balcao-virtual')->assertInertia(fn (Assert $page) => $page->has('requests', 1));
|
||||
$this->actingAs(User::factory()->create())->get('/balcao-virtual')->assertInertia(fn (Assert $page) => $page->has('requests', 0));
|
||||
$this->get('/balcao-virtual')->assertRedirect('/balcao-virtual/painel');
|
||||
$this->get('/balcao-virtual/painel')->assertInertia(fn (Assert $page) => $page->has('legacyRequests', 1));
|
||||
$this->actingAs(User::factory()->create())->get('/balcao-virtual/painel')->assertInertia(fn (Assert $page) => $page->has('legacyRequests', 0));
|
||||
$this->post('/apoio', $payload)->assertStatus(409);
|
||||
}
|
||||
|
||||
@@ -102,13 +103,18 @@ class PortalServicesTest extends TestCase
|
||||
$this->actingAs($owner)->post('/parcerias', ['title' => 'Parceria de teste', 'sector' => 'Agricultura', 'province' => 'Gaza',
|
||||
'offer' => 'Capacidade de processamento de teste.', 'seeking' => 'Parceiro de logística para teste.', 'publication_consent' => true])->assertSessionHasNoErrors();
|
||||
$id = DB::table('portal_partnerships')->value('id');
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('partnerships.data', 0));
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('results.data', 0));
|
||||
$this->post('/management/portal-services/partnerships/'.$id, ['published' => true])->assertForbidden();
|
||||
config(['portal.managers' => [$owner->email]]);
|
||||
$this->post('/management/portal-services/partnerships/'.$id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('partnerships.data', 1)->missing('partnerships.data.0.user_id'));
|
||||
$this->post('/management/portal-services/partnerships/'.$id, ['published' => false])->assertSessionHasNoErrors();
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('partnerships.data', 0));
|
||||
$moderator = User::factory()->create();
|
||||
config(['portal.managers' => [$moderator->email]]);
|
||||
$this->actingAs($moderator)->post('/management/portal-services/partnerships/'.$id, ['published' => true])->assertRedirect('/parcerias/'.$id);
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('results.data', 0));
|
||||
$version = DB::table('portal_partnerships')->where('id', $id)->value('version');
|
||||
$this->post('/parcerias/'.$id.'/estado', ['version' => $version, 'action' => 'publish', 'reason' => 'Divulgação autorizada e revista pelo moderador QA.'])->assertSessionHasNoErrors();
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('results.data', 1)->missing('results.data.0.user_id'));
|
||||
$version = DB::table('portal_partnerships')->where('id', $id)->value('version');
|
||||
$this->post('/parcerias/'.$id.'/estado', ['version' => $version, 'action' => 'suspend', 'reason' => 'Retirada de divulgação na revisão QA.'])->assertSessionHasNoErrors();
|
||||
$this->get('/parcerias')->assertInertia(fn (Assert $page) => $page->has('results.data', 0));
|
||||
}
|
||||
|
||||
public function test_document_download_rechecks_classification_checksum_and_publication(): void
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
||||
use App\Models\SimulationFormDraft;
|
||||
use App\Models\User;
|
||||
use App\Http\Middleware\EnsureSimulationRecoveryCookie;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -100,7 +101,7 @@ class SimulationDraftContinuityTest extends TestCase
|
||||
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'));
|
||||
throw new 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)
|
||||
|
||||
@@ -18,11 +18,13 @@ for ($request = 0; $request < 3; $request++) {
|
||||
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') {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Support;
|
||||
|
||||
use App\Services\Malware\MalwareScanner;
|
||||
|
||||
/** A deterministic QA fixture, never registered in application providers. */
|
||||
class CleanScannerFixture implements MalwareScanner
|
||||
{
|
||||
public function scan(string $path, int $fileSizeBytes, string $storageRoot): array
|
||||
{
|
||||
return ['result' => 'clean', 'reason_code' => null, 'engine' => 'QA-Test-Double', 'engine_version' => 'fixture', 'signatures_at' => new \DateTimeImmutable('2026-10-08T00:00:00Z'), 'duration_ms' => 1, 'detail' => null];
|
||||
}
|
||||
|
||||
public function health(): array
|
||||
{
|
||||
return ['available' => true, 'engine' => 'QA-Test-Double', 'engine_version' => 'fixture', 'signatures_at' => new \DateTimeImmutable('2026-10-08T00:00:00Z'), 'signature_age_hours' => 0.0, 'reason_code' => null];
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -34,7 +34,7 @@ abstract class TestCase extends BaseTestCase
|
||||
if (! RefreshDatabaseState::$migrated && $app->environment('testing')) {
|
||||
$db = $app->make('db')->connection();
|
||||
if ($db->getDriverName() === 'pgsql'
|
||||
&& in_array($db->getDatabaseName(), ['portal_services_test', 'investmoz_test', 'investmoz_browser_e2e_test'], true)
|
||||
&& in_array($db->getDatabaseName(), ['portal_services_test', 'investmoz_test', 'investmoz_browser_e2e_test', 'investmoz_guidance_20261008_test', 'investmoz_v2_20261008_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,61 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\Ai\InvestorGuidanceRules;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class InvestorGuidanceRulesTest extends TestCase
|
||||
{
|
||||
public function test_declared_quantities_require_common_scope_and_never_invent_missing_values(): void
|
||||
{
|
||||
$rules = new InvestorGuidanceRules;
|
||||
$missing = $rules->evaluate(['demand_quantity' => '100', 'capacity_quantity' => '50']);
|
||||
$this->assertContains('demand_quantity_comparison_incomplete', array_column($missing[1]['risks'], 'code'));
|
||||
$facts = ['demand_quantity' => '100', 'capacity_quantity' => '50', 'quantity_unit' => 'toneladas', 'quantity_period' => 'ano',
|
||||
'resources_required' => '12', 'resources_available' => '0', 'resource_unit' => 'pessoas',
|
||||
'funding_required' => '100.50', 'funding_committed' => '100.49', 'funding_currency' => 'MZN',
|
||||
'expected_start_date' => '2026-12-01', 'funding_ready_date' => '2027-01-01', 'completion_date' => '2026-11-01'];
|
||||
$phases = $rules->evaluate($facts);
|
||||
foreach ([1 => 'demand_quantity_declared_gap', 3 => 'resources_required_declared_gap', 4 => 'funding_required_declared_gap'] as $i => $code) {
|
||||
$this->assertContains($code, array_column($phases[$i]['risks'], 'code'));
|
||||
foreach ($phases[$i]['risks'] as $risk) {
|
||||
$this->assertFalse($risk['restriction']);
|
||||
}
|
||||
}
|
||||
$this->assertCount(2, $phases[5]['risks']);
|
||||
$facts['funding_committed'] = '100.50';
|
||||
$this->assertNotContains('funding_required_declared_gap', array_column($rules->evaluate($facts)[4]['risks'], 'code'));
|
||||
}
|
||||
|
||||
public function test_missing_declared_and_attached_information_are_not_verified(): void
|
||||
{
|
||||
$rules = new InvestorGuidanceRules;
|
||||
$this->assertSame('absent', $rules->evaluate([])[2]['evidence'][0]['state']);
|
||||
$declared = $rules->evaluate(['location_evidence' => 'Declaração QA']);
|
||||
$this->assertSame('investor_declared_not_verified', $declared[2]['evidence'][0]['state']);
|
||||
$attached = $rules->evaluate([], ['location_evidence' => ['state' => 'attached_unchecked', 'documents' => []]]);
|
||||
$this->assertSame('attached_unchecked', $attached[2]['evidence'][0]['state']);
|
||||
$this->assertNotEmpty($attached[2]['risks']);
|
||||
}
|
||||
|
||||
public function test_scoped_internal_verification_removes_only_the_corresponding_pending_alert(): void
|
||||
{
|
||||
$evidence = ['location_evidence' => ['state' => 'internally_verified', 'documents' => [['review' => ['author' => 'Verificador QA', 'date' => '2026-10-08', 'scope' => 'Acesso descrito no documento QA']]]]];
|
||||
$phases = (new InvestorGuidanceRules)->evaluate([], $evidence);
|
||||
$this->assertSame([], $phases[2]['risks']);
|
||||
$this->assertNotEmpty($phases[3]['risks']);
|
||||
$this->assertSame($evidence['location_evidence']['documents'], $phases[2]['evidence'][0]['documents']);
|
||||
$this->assertStringContainsString('não aprova', $phases[2]['recommendations'][0]['limitations'][0]);
|
||||
}
|
||||
|
||||
public function test_contradictions_expiration_and_replacement_are_specific_non_blocking_alerts(): void
|
||||
{
|
||||
foreach (['contradiction', 'expired', 'superseded'] as $state) {
|
||||
$phase = (new InvestorGuidanceRules)->evaluate([], ['market_evidence' => ['state' => $state, 'documents' => []]])[1];
|
||||
$this->assertSame('market_evidence_'.$state, $phase['risks'][0]['code']);
|
||||
$this->assertFalse($phase['risks'][0]['restriction']);
|
||||
$this->assertSame($state === 'contradiction' ? 'documented_contradiction' : 'insufficient_information', $phase['risks'][0]['classification']);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ const assumptions = {
|
||||
periods: 12,
|
||||
};
|
||||
|
||||
test('financial forecast reconciles revenue, finance sources, working capital and monthly cash', () => {
|
||||
void test('financial forecast reconciles revenue, finance sources, working capital and monthly cash', () => {
|
||||
const result = forecastBusinessPlan(assumptions);
|
||||
assert.equal(result.workingCapital, '25000.00');
|
||||
assert.equal(result.initialUses, '125000.00');
|
||||
@@ -90,7 +90,7 @@ test('financial forecast reconciles revenue, finance sources, working capital an
|
||||
assert.equal(result.endingCash, '113000.00');
|
||||
});
|
||||
|
||||
test('opening payable installments reduce cash without changing profit and retain unpaid balances', () => {
|
||||
void test('opening payable installments reduce cash without changing profit and retain unpaid balances', () => {
|
||||
const opening = {
|
||||
...assumptions,
|
||||
periods: 3,
|
||||
@@ -171,7 +171,7 @@ test('opening payable installments reduce cash without changing profit and retai
|
||||
);
|
||||
});
|
||||
|
||||
test('opening payable schedule caps cent rounding at the remaining balance', () => {
|
||||
void test('opening payable schedule caps cent rounding at the remaining balance', () => {
|
||||
const rounded = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
periods: 2,
|
||||
@@ -213,7 +213,7 @@ test('opening payable schedule caps cent rounding at the remaining balance', ()
|
||||
assert.equal(rounded.openingPayablesAtEnd, '0.00');
|
||||
});
|
||||
|
||||
test('monthly unit schedules drive revenue, costs, inventory and scenario volume', () => {
|
||||
void test('monthly unit schedules drive revenue, costs, inventory and scenario volume', () => {
|
||||
const seasonal = {
|
||||
...assumptions,
|
||||
periods: 3,
|
||||
@@ -286,7 +286,7 @@ test('monthly unit schedules drive revenue, costs, inventory and scenario volume
|
||||
);
|
||||
});
|
||||
|
||||
test('monthly unit schedules must match the horizon and contain valid quantities', () => {
|
||||
void test('monthly unit schedules must match the horizon and contain valid quantities', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
forecastBusinessPlan({
|
||||
@@ -331,7 +331,7 @@ test('monthly unit schedules must match the horizon and contain valid quantities
|
||||
);
|
||||
});
|
||||
|
||||
test('monthly prices and unit costs affect revenue, consumption and scenarios', () => {
|
||||
void test('monthly prices and unit costs affect revenue, consumption and scenarios', () => {
|
||||
const plan = {
|
||||
...assumptions,
|
||||
periods: 3,
|
||||
@@ -385,7 +385,7 @@ test('monthly prices and unit costs affect revenue, consumption and scenarios',
|
||||
);
|
||||
});
|
||||
|
||||
test('monthly money schedules cover the horizon and reject invalid amounts', () => {
|
||||
void test('monthly money schedules cover the horizon and reject invalid amounts', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
forecastBusinessPlan({
|
||||
@@ -430,7 +430,7 @@ test('monthly money schedules cover the horizon and reject invalid amounts', ()
|
||||
);
|
||||
});
|
||||
|
||||
test('monthly operating and payroll expense schedules remain separate from payments', () => {
|
||||
void test('monthly operating and payroll expense schedules remain separate from payments', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
periods: 3,
|
||||
@@ -486,7 +486,7 @@ test('monthly operating and payroll expense schedules remain separate from payme
|
||||
assert.equal(scenarios.favorable.result.rows[0].payrollExpense, '450.00');
|
||||
});
|
||||
|
||||
test('monthly operating schedules require full horizon, exact cents and current snapshot version', () => {
|
||||
void test('monthly operating schedules require full horizon, exact cents and current snapshot version', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
forecastBusinessPlan({
|
||||
@@ -546,7 +546,7 @@ test('monthly operating schedules require full horizon, exact cents and current
|
||||
assert.match(csv, /Pagamentos de pessoal/);
|
||||
});
|
||||
|
||||
test('losses and negative closing cash remain visible instead of being clamped to zero', () => {
|
||||
void test('losses and negative closing cash remain visible instead of being clamped to zero', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
openingCash: '-100',
|
||||
@@ -569,7 +569,7 @@ test('losses and negative closing cash remain visible instead of being clamped t
|
||||
assert.ok(Number(result.endingCash) < 0);
|
||||
});
|
||||
|
||||
test('principal repayments affect cash but are excluded from profit expenses', () => {
|
||||
void test('principal repayments affect cash but are excluded from profit expenses', () => {
|
||||
const withPrincipal = forecastBusinessPlan(assumptions);
|
||||
const withoutPrincipal = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
@@ -586,7 +586,7 @@ test('principal repayments affect cash but are excluded from profit expenses', (
|
||||
);
|
||||
});
|
||||
|
||||
test('depreciation allocation reconciles exactly over useful life', () => {
|
||||
void test('depreciation allocation reconciles exactly over useful life', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
assetDepreciation: '100.00',
|
||||
@@ -599,7 +599,7 @@ test('depreciation allocation reconciles exactly over useful life', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('missing currency, products, invalid numbers and invalid horizons are explicit errors', () => {
|
||||
void test('missing currency, products, invalid numbers and invalid horizons are explicit errors', () => {
|
||||
assert.throws(
|
||||
() => forecastBusinessPlan({ ...assumptions, currency: '' }),
|
||||
/moeda ISO/,
|
||||
@@ -643,7 +643,7 @@ test('missing currency, products, invalid numbers and invalid horizons are expli
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned plan snapshots restore assumptions and reject unsupported or oversized data', () => {
|
||||
void test('versioned plan snapshots restore assumptions and reject unsupported or oversized data', () => {
|
||||
const saved = serializeBusinessPlanSnapshot(assumptions);
|
||||
assert.deepEqual(restoreBusinessPlanSnapshot(saved), assumptions);
|
||||
assert.equal(
|
||||
@@ -976,7 +976,7 @@ test('versioned plan snapshots restore assumptions and reject unsupported or ove
|
||||
);
|
||||
});
|
||||
|
||||
test('business plan serializer refuses snapshots above the server storage limit', () => {
|
||||
void test('business plan serializer refuses snapshots above the server storage limit', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
serializeBusinessPlanSnapshot({
|
||||
@@ -992,7 +992,7 @@ test('business plan serializer refuses snapshots above the server storage limit'
|
||||
);
|
||||
});
|
||||
|
||||
test('sales invoicing and receipts follow an optional declared collection lag', () => {
|
||||
void test('sales invoicing and receipts follow an optional declared collection lag', () => {
|
||||
const delayed = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
monthlyCollections: '0',
|
||||
@@ -1024,7 +1024,7 @@ test('sales invoicing and receipts follow an optional declared collection lag',
|
||||
assert.equal(sameMonth.totalProfitBeforeTax, delayed.totalProfitBeforeTax);
|
||||
});
|
||||
|
||||
test('scheduled collection percentage keeps unpaid invoices in receivables with exact rounding', () => {
|
||||
void test('scheduled collection percentage keeps unpaid invoices in receivables with exact rounding', () => {
|
||||
const partial = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
monthlyCollections: '0',
|
||||
@@ -1071,7 +1071,7 @@ test('scheduled collection percentage keeps unpaid invoices in receivables with
|
||||
);
|
||||
});
|
||||
|
||||
test('sales recovery applies only to overdue invoices and never exceeds open balances', () => {
|
||||
void test('sales recovery applies only to overdue invoices and never exceeds open balances', () => {
|
||||
const recovered = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
monthlyCollections: '0',
|
||||
@@ -1142,7 +1142,7 @@ test('sales recovery applies only to overdue invoices and never exceeds open bal
|
||||
);
|
||||
});
|
||||
|
||||
test('opening receivables affect cash only when a month and collection percentage are declared', () => {
|
||||
void test('opening receivables affect cash only when a month and collection percentage are declared', () => {
|
||||
const unscheduled = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
monthlyCollections: '0',
|
||||
@@ -1190,7 +1190,7 @@ test('opening receivables affect cash only when a month and collection percentag
|
||||
);
|
||||
});
|
||||
|
||||
test('opening receivable installments reconcile to the initial balance across months', () => {
|
||||
void test('opening receivable installments reconcile to the initial balance across months', () => {
|
||||
const scheduled = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
monthlyCollections: '0',
|
||||
@@ -1263,7 +1263,7 @@ test('opening receivable installments reconcile to the initial balance across mo
|
||||
);
|
||||
});
|
||||
|
||||
test('opening receivable installments cap independently rounded cents at the available balance', () => {
|
||||
void test('opening receivable installments cap independently rounded cents at the available balance', () => {
|
||||
const rounded = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
receivables: '0.01',
|
||||
@@ -1280,7 +1280,7 @@ test('opening receivable installments cap independently rounded cents at the ava
|
||||
assert.equal(rounded.openingReceivablesAtEnd, '0.00');
|
||||
});
|
||||
|
||||
test('inventory purchases, consumption, closing stock and stock shortfall reconcile independently of payments', () => {
|
||||
void test('inventory purchases, consumption, closing stock and stock shortfall reconcile independently of payments', () => {
|
||||
const supplied = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
inventory: '0',
|
||||
@@ -1302,7 +1302,7 @@ test('inventory purchases, consumption, closing stock and stock shortfall reconc
|
||||
assert.equal(supplied.rows[0].variableCostPayments, '0.00');
|
||||
});
|
||||
|
||||
test('inventory lead time separates monthly orders, receipts, shortages and goods still in transit', () => {
|
||||
void test('inventory lead time separates monthly orders, receipts, shortages and goods still in transit', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
inventory: '0',
|
||||
@@ -1333,7 +1333,7 @@ test('inventory lead time separates monthly orders, receipts, shortages and good
|
||||
assert.equal(result.endingCash, noDelay.endingCash);
|
||||
});
|
||||
|
||||
test('monthly inventory purchase schedule reconciles variable orders, lead times, receipts and transit', () => {
|
||||
void test('monthly inventory purchase schedule reconciles variable orders, lead times, receipts and transit', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
periods: 4,
|
||||
@@ -1436,7 +1436,7 @@ test('monthly inventory purchase schedule reconciles variable orders, lead times
|
||||
assert.match(csv, /Prazo da encomenda \(meses\)/);
|
||||
});
|
||||
|
||||
test('monthly variable purchase payments affect cash independently from inventory orders and profit', () => {
|
||||
void test('monthly variable purchase payments affect cash independently from inventory orders and profit', () => {
|
||||
const base = {
|
||||
...assumptions,
|
||||
periods: 3,
|
||||
@@ -1464,7 +1464,7 @@ test('monthly variable purchase payments affect cash independently from inventor
|
||||
);
|
||||
});
|
||||
|
||||
test('product inventory schedules reconcile independently and do not transfer stock between products', () => {
|
||||
void test('product inventory schedules reconcile independently and do not transfer stock between products', () => {
|
||||
const plan = {
|
||||
...assumptions,
|
||||
periods: 2,
|
||||
@@ -1542,7 +1542,7 @@ test('product inventory schedules reconcile independently and do not transfer st
|
||||
);
|
||||
});
|
||||
|
||||
test('supplier payment terms drive purchase cash flow and expose amounts due beyond the horizon', () => {
|
||||
void test('supplier payment terms drive purchase cash flow and expose amounts due beyond the horizon', () => {
|
||||
const plan = {
|
||||
...assumptions,
|
||||
periods: 2,
|
||||
@@ -1624,7 +1624,7 @@ test('supplier payment terms drive purchase cash flow and expose amounts due bey
|
||||
);
|
||||
});
|
||||
|
||||
test('supplier order installments reconcile exact cents, cash dates and unallocated balances', () => {
|
||||
void test('supplier order installments reconcile exact cents, cash dates and unallocated balances', () => {
|
||||
const plan = {
|
||||
...assumptions,
|
||||
periods: 2,
|
||||
@@ -1691,7 +1691,7 @@ test('supplier order installments reconcile exact cents, cash dates and unalloca
|
||||
assert.equal(restoreBusinessPlanSnapshot(JSON.stringify(snapshot)), null);
|
||||
});
|
||||
|
||||
test('business assumptions survive the existing encrypted-draft snapshot split and restore', () => {
|
||||
void test('business assumptions survive the existing encrypted-draft snapshot split and restore', () => {
|
||||
const encoded = serializeBusinessPlanSnapshot(assumptions);
|
||||
const snapshots = partitionSimulationDraft({
|
||||
purpose: 'own_investment',
|
||||
@@ -1709,7 +1709,7 @@ test('business assumptions survive the existing encrypted-draft snapshot split a
|
||||
);
|
||||
});
|
||||
|
||||
test('presentation currency conversion requires and reports its rate, date, and declared source', () => {
|
||||
void test('presentation currency conversion requires and reports its rate, date, and declared source', () => {
|
||||
const result = forecastBusinessPlan({
|
||||
...assumptions,
|
||||
presentationCurrency: 'USD',
|
||||
@@ -1760,7 +1760,7 @@ test('presentation currency conversion requires and reports its rate, date, and
|
||||
);
|
||||
});
|
||||
|
||||
test('CSV marks presentation currency conversion as an unverified user planning assumption', () => {
|
||||
void test('CSV marks presentation currency conversion as an unverified user planning assumption', () => {
|
||||
const csv = exportBusinessPlanCsv(
|
||||
{
|
||||
...assumptions,
|
||||
@@ -1779,7 +1779,7 @@ test('CSV marks presentation currency conversion as an unverified user planning
|
||||
);
|
||||
});
|
||||
|
||||
test('business plan export carries its assumptions, formulas, period, currency, and matching result', () => {
|
||||
void test('business plan export carries its assumptions, formulas, period, currency, and matching result', () => {
|
||||
const csv = exportBusinessPlanCsv(
|
||||
{ ...assumptions, periods: 1 },
|
||||
'2026-10-02T10:00:00.000Z',
|
||||
@@ -1805,7 +1805,7 @@ test('business plan export carries its assumptions, formulas, period, currency,
|
||||
assert.match(csv, /Existências em trânsito no fim do horizonte,0\.00/);
|
||||
});
|
||||
|
||||
test('business plan CSV preserves declared monthly product schedules', () => {
|
||||
void test('business plan CSV preserves declared monthly product schedules', () => {
|
||||
const csv = exportBusinessPlanCsv(
|
||||
{
|
||||
...assumptions,
|
||||
@@ -1826,7 +1826,7 @@ test('business plan CSV preserves declared monthly product schedules', () => {
|
||||
assert.ok(csv.includes('"[""40"",""55"",""30"",""20""]"'));
|
||||
});
|
||||
|
||||
test('CSV export exposes the sales collection assumption and outstanding receivable', () => {
|
||||
void test('CSV export exposes the sales collection assumption and outstanding receivable', () => {
|
||||
const csv = exportBusinessPlanCsv(
|
||||
{
|
||||
...assumptions,
|
||||
@@ -1849,7 +1849,7 @@ test('CSV export exposes the sales collection assumption and outstanding receiva
|
||||
);
|
||||
});
|
||||
|
||||
test('business plan CSV neutralizes formula-like labels and preserves negative financial values', () => {
|
||||
void test('business plan CSV neutralizes formula-like labels and preserves negative financial values', () => {
|
||||
const csv = exportBusinessPlanCsv({
|
||||
...assumptions,
|
||||
products: [
|
||||
@@ -1865,7 +1865,7 @@ test('business plan CSV neutralizes formula-like labels and preserves negative f
|
||||
assert.match(csv, /Diferença entre usos e fontes,-5000\.00/);
|
||||
});
|
||||
|
||||
test('financial scenarios expose user-declared changes without creating tax values', () => {
|
||||
void test('financial scenarios expose user-declared changes without creating tax values', () => {
|
||||
const scenarioPlan = {
|
||||
...assumptions,
|
||||
periods: 1,
|
||||
|
||||
@@ -8,17 +8,30 @@ import {
|
||||
updateBusinessLocation,
|
||||
} from '../../resources/js/lib/business-locations.ts';
|
||||
|
||||
test('location paths survive draft encoding and malformed drafts are ignored safely', () => {
|
||||
void 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: '' },
|
||||
{
|
||||
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(encodeBusinessLocations(paths)),
|
||||
paths,
|
||||
);
|
||||
assert.deepEqual(decodeBusinessLocations('{invalid'), []);
|
||||
assert.deepEqual(decodeBusinessLocations('null'), []);
|
||||
});
|
||||
|
||||
test('changing a parent clears every dependent selection in only that row', () => {
|
||||
void test('changing a parent clears every dependent selection in only that row', () => {
|
||||
const initial = {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-a',
|
||||
@@ -26,7 +39,12 @@ test('changing a parent clears every dependent selection in only that row', () =
|
||||
locality_id: 'locality-a',
|
||||
};
|
||||
const rows = [initial, emptyBusinessLocation()];
|
||||
const updated = updateBusinessLocation(rows, 0, 'district_id', 'district-b');
|
||||
const updated = updateBusinessLocation(
|
||||
rows,
|
||||
0,
|
||||
'district_id',
|
||||
'district-b',
|
||||
);
|
||||
assert.deepEqual(updated[0], {
|
||||
province_id: 'province-a',
|
||||
district_id: 'district-b',
|
||||
@@ -36,14 +54,40 @@ test('changing a parent clears every dependent selection in only that row', () =
|
||||
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);
|
||||
void 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,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2,16 +2,19 @@ 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', () => {
|
||||
void 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', () => {
|
||||
void 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(
|
||||
csvCellWithDelimiter('Planeado; realizado', ';'),
|
||||
'"Planeado; realizado"',
|
||||
);
|
||||
assert.equal(csvCell('Operação, mensal'), '"Operação, mensal"');
|
||||
assert.equal(csvCell('=HYPERLINK("x")'), '"\'=HYPERLINK(""x"")"');
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ function cents(value) {
|
||||
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
||||
}
|
||||
|
||||
test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
|
||||
void test('financial tools snapshot persists editable calculations and rejects malformed data', () => {
|
||||
const data = {
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
@@ -59,7 +59,7 @@ test('financial tools snapshot persists editable calculations and rejects malfor
|
||||
);
|
||||
});
|
||||
|
||||
test('loan payment handles zero interest exactly', () => {
|
||||
void test('loan payment handles zero interest exactly', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1200.00', '0', 12), {
|
||||
monthlyPayment: '100.00',
|
||||
totalPaid: '1200.00',
|
||||
@@ -67,7 +67,7 @@ test('loan payment handles zero interest exactly', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('loan payment computes a reproducible amortized estimate', () => {
|
||||
void test('loan payment computes a reproducible amortized estimate', () => {
|
||||
assert.deepEqual(calculateLoanPayment('1000.00', '12', 12), {
|
||||
monthlyPayment: '88.85',
|
||||
totalPaid: '1066.19',
|
||||
@@ -75,7 +75,7 @@ test('loan payment computes a reproducible amortized estimate', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('break-even rounds required units upward and rejects nonpositive margin', () => {
|
||||
void 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',
|
||||
@@ -85,7 +85,7 @@ test('break-even rounds required units upward and rejects nonpositive margin', (
|
||||
assert.throws(() => calculateBreakEven('10', '20', '20'), /superior/);
|
||||
});
|
||||
|
||||
test('an invalid indicator does not hide independent financial calculations', () => {
|
||||
void test('an invalid indicator does not hide independent financial calculations', () => {
|
||||
const result = calculateFinancialTools({
|
||||
loan: {
|
||||
principal: '1200',
|
||||
@@ -110,7 +110,7 @@ test('an invalid indicator does not hide independent financial calculations', ()
|
||||
assert.equal(result.budget.value?.operatingBalance, '-100.00');
|
||||
});
|
||||
|
||||
test('funding gap distinguishes zero from a negative surplus', () => {
|
||||
void test('funding gap distinguishes zero from a negative surplus', () => {
|
||||
assert.deepEqual(calculateFundingGap('100.00', '120.00'), {
|
||||
gap: '-20.00',
|
||||
reconciles: false,
|
||||
@@ -118,12 +118,12 @@ test('funding gap distinguishes zero from a negative surplus', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('invalid precision and negative inputs are rejected', () => {
|
||||
void 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', () => {
|
||||
void test('loan schedule supports nominal rates, interest-only grace and separate fees', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1200.00',
|
||||
annualRatePercent: '12',
|
||||
@@ -159,7 +159,7 @@ test('loan schedule supports nominal rates, interest-only grace and separate fee
|
||||
}
|
||||
});
|
||||
|
||||
test('loan schedule reconciles exact cents and adjusts the final installment', () => {
|
||||
void test('loan schedule reconciles exact cents and adjusts the final installment', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000.01',
|
||||
annualRatePercent: '7.123456',
|
||||
@@ -181,7 +181,7 @@ test('loan schedule reconciles exact cents and adjusts the final installment', (
|
||||
);
|
||||
});
|
||||
|
||||
test('effective annual rate is converted to the selected repayment period', () => {
|
||||
void test('effective annual rate is converted to the selected repayment period', () => {
|
||||
const result = buildLoanSchedule({
|
||||
principal: '1000',
|
||||
annualRatePercent: '12',
|
||||
@@ -203,7 +203,7 @@ test('effective annual rate is converted to the selected repayment period', () =
|
||||
assert.equal(quarterly.schedule.at(-1).closingBalance, '0.00');
|
||||
});
|
||||
|
||||
test('loan schedules reconcile across rates, periodicities and grace periods', () => {
|
||||
void 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']) {
|
||||
@@ -254,7 +254,7 @@ test('loan schedules reconcile across rates, periodicities and grace periods', (
|
||||
}
|
||||
});
|
||||
|
||||
test('budget preserves an operating deficit and rejects invalid values', () => {
|
||||
void 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',
|
||||
@@ -264,7 +264,7 @@ test('budget preserves an operating deficit and rejects invalid values', () => {
|
||||
assert.throws(() => calculateBudget(['0'], ['-1']), /não negativo/);
|
||||
});
|
||||
|
||||
test('budget distinguishes absent income or expense rows from explicit zero', () => {
|
||||
void 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']), {
|
||||
@@ -275,7 +275,7 @@ test('budget distinguishes absent income or expense rows from explicit zero', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
|
||||
void test('loan terms reject invalid periodicity, excessive grace and commission larger than principal', () => {
|
||||
const base = {
|
||||
principal: '1000',
|
||||
annualRatePercent: '0',
|
||||
@@ -297,7 +297,7 @@ test('loan terms reject invalid periodicity, excessive grace and commission larg
|
||||
);
|
||||
});
|
||||
|
||||
test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
|
||||
void test('financial tools CSV records reproducible assumptions, periods, formulas and matching results', () => {
|
||||
const csv = exportFinancialToolsCsv({
|
||||
currency: 'MZN',
|
||||
generatedAt: '2026-10-02T10:00:00.000Z',
|
||||
|
||||
@@ -36,7 +36,7 @@ const plan = {
|
||||
periods: 2,
|
||||
};
|
||||
|
||||
test('financial to fiscal bridge reconciles accounting result while leaving tax base indeterminate', () => {
|
||||
void 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(
|
||||
@@ -90,7 +90,7 @@ test('financial to fiscal bridge reconciles accounting result while leaving tax
|
||||
);
|
||||
});
|
||||
|
||||
test('financial bridge separates opening receivables and scheduled sales collections', () => {
|
||||
void test('financial bridge separates opening receivables and scheduled sales collections', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
receivables: '200.00',
|
||||
@@ -127,7 +127,7 @@ test('financial bridge separates opening receivables and scheduled sales collect
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
|
||||
void test('bridge maps monthly recognised expenses but keeps scheduled payments in cash only', () => {
|
||||
const forecast = forecastBusinessPlan({
|
||||
...plan,
|
||||
periods: 2,
|
||||
@@ -156,7 +156,7 @@ test('bridge maps monthly recognised expenses but keeps scheduled payments in ca
|
||||
assert.equal(bridge.taxableBase.status, 'indeterminate');
|
||||
});
|
||||
|
||||
test('financial bridge rejects a corrupted monthly cash schedule', () => {
|
||||
void test('financial bridge rejects a corrupted monthly cash schedule', () => {
|
||||
const forecast = forecastBusinessPlan(plan);
|
||||
const corrupted = {
|
||||
...forecast,
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
guidanceFinance,
|
||||
guidanceFinancialTools,
|
||||
} from '../../resources/js/lib/investor-guidance-finance.ts';
|
||||
import { buildProjectDossierRows } from '../../resources/js/lib/project-dossier.ts';
|
||||
import { serializeFinancialToolsSnapshot } from '../../resources/js/lib/financial-calculators.ts';
|
||||
import {
|
||||
forecastBusinessPlan,
|
||||
serializeBusinessPlanSnapshot,
|
||||
compareBusinessScenarios,
|
||||
} from '../../resources/js/lib/business-financial-plan.ts';
|
||||
|
||||
const assumptions = {
|
||||
currency: 'MZN',
|
||||
openingCash: '0',
|
||||
products: [
|
||||
{
|
||||
label: 'Serviço',
|
||||
monthlyUnits: '100',
|
||||
unitPrice: '1000',
|
||||
unitVariableCost: '400',
|
||||
},
|
||||
],
|
||||
monthlyCollections: '90000',
|
||||
salesCollectionLagMonths: null,
|
||||
salesCollectionPercent: '100',
|
||||
salesRecoverySchedule: [],
|
||||
monthlyVariableCostPayments: '42000',
|
||||
monthlyVariableCostPaymentsByPeriod: null,
|
||||
monthlyInventoryPurchases: '40000',
|
||||
inventoryPurchaseLeadMonths: 0,
|
||||
inventoryPurchaseSchedule: null,
|
||||
useInventoryPurchaseSchedule: false,
|
||||
useProductInventorySchedule: false,
|
||||
useSupplierPaymentTerms: false,
|
||||
monthlyOperatingExpenses: '20000',
|
||||
monthlyOperatingPayments: '18000',
|
||||
monthlyPayrollExpense: '15000',
|
||||
monthlyPayrollPayments: '15000',
|
||||
assetInvestment: '100000',
|
||||
inventory: '20000',
|
||||
receivables: '10000',
|
||||
openingReceivablesCollectionMonth: null,
|
||||
openingReceivablesCollectionPercent: '100',
|
||||
openingReceivablesInstallments: [],
|
||||
openingPayablesInstallments: [],
|
||||
payables: '5000',
|
||||
equity: '80000',
|
||||
shareholderLoans: '0',
|
||||
bankLoanProceeds: '50000',
|
||||
grants: '0',
|
||||
assetDepreciation: '100000',
|
||||
depreciationLifeMonths: 60,
|
||||
monthlyInterestExpense: '1200',
|
||||
monthlyInterestPayment: '1000',
|
||||
monthlyPrincipalRepayment: '5000',
|
||||
periods: 12,
|
||||
};
|
||||
|
||||
void test('guidance reuses the dossier calculator report and preserves partial indeterminacy', () => {
|
||||
const source = {
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '',
|
||||
rate: '',
|
||||
months: '',
|
||||
rateType: 'nominal',
|
||||
periodMonths: '',
|
||||
gracePeriods: '',
|
||||
upfrontFee: '',
|
||||
recurringFee: '',
|
||||
},
|
||||
breakEven: { fixed: '', price: '', variable: '' },
|
||||
funding: { total: '1000', secured: '400' },
|
||||
incomes: [{ label: 'Receita QA', amount: '300' }],
|
||||
expenses: [{ label: 'Custo QA', amount: '200' }],
|
||||
};
|
||||
const draft = {
|
||||
financial_tools_snapshot: serializeFinancialToolsSnapshot(source),
|
||||
currency: 'MZN',
|
||||
};
|
||||
const result = guidanceFinancialTools(draft);
|
||||
assert.deepEqual(
|
||||
result.rows,
|
||||
buildProjectDossierRows(draft).filter(
|
||||
(row) => row[0] === 'Plano financeiro',
|
||||
),
|
||||
);
|
||||
assert.deepEqual(result.assumptions, source);
|
||||
assert.equal(
|
||||
guidanceFinancialTools({ financial_tools_snapshot: '{"version":999}' }),
|
||||
null,
|
||||
);
|
||||
assert.equal(guidanceFinancialTools(null), null);
|
||||
});
|
||||
|
||||
void test('guidance keeps missing, malformed and unsupported financial snapshots indeterminate', () => {
|
||||
for (const snapshot of [
|
||||
undefined,
|
||||
'',
|
||||
'{}',
|
||||
'{invalid',
|
||||
'{"version":999,"plan":{}}',
|
||||
]) {
|
||||
const view = guidanceFinance(
|
||||
snapshot ? { business_plan_snapshot: snapshot } : null,
|
||||
);
|
||||
assert.equal(view.status, 'indeterminate');
|
||||
assert.equal(view.result, null);
|
||||
}
|
||||
});
|
||||
|
||||
void test('guidance uses exact deterministic outputs and preserves negative cash and original assumptions', () => {
|
||||
const plan = { ...assumptions, monthlyCollections: '0' };
|
||||
const snapshot = serializeBusinessPlanSnapshot(plan);
|
||||
const view = guidanceFinance({ business_plan_snapshot: snapshot });
|
||||
assert.equal(view.status, 'calculated');
|
||||
assert.deepEqual(view.result, forecastBusinessPlan(view.assumptions));
|
||||
assert.equal(view.result.endingCash.startsWith('-'), true);
|
||||
assert.equal(view.tax, 'indeterminate');
|
||||
assert.equal(view.scenarios, null);
|
||||
assert.equal(snapshot, serializeBusinessPlanSnapshot(plan));
|
||||
});
|
||||
|
||||
void test('guidance scenarios are the existing deterministic scenario tool without success probabilities', () => {
|
||||
const scenario = {
|
||||
...assumptions,
|
||||
scenarioAdjustments: {
|
||||
favorable: {
|
||||
unitVolumePercent: '10',
|
||||
unitPricePercent: '5',
|
||||
unitCostPercent: '0',
|
||||
operatingCostsPercent: '0',
|
||||
cashCollectionsPercent: '10',
|
||||
},
|
||||
unfavorable: {
|
||||
unitVolumePercent: '-10',
|
||||
unitPricePercent: '-5',
|
||||
unitCostPercent: '10',
|
||||
operatingCostsPercent: '10',
|
||||
cashCollectionsPercent: '-10',
|
||||
},
|
||||
},
|
||||
};
|
||||
const view = guidanceFinance({
|
||||
business_plan_snapshot: serializeBusinessPlanSnapshot(scenario),
|
||||
});
|
||||
assert.deepEqual(
|
||||
view.scenarios,
|
||||
compareBusinessScenarios(view.assumptions),
|
||||
);
|
||||
assert.equal('success_probability' in view, false);
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
projectMonthlyCashflow,
|
||||
} from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
|
||||
test('projects exact monthly balances and reconciles cumulative net flow', () => {
|
||||
void test('projects exact monthly balances and reconciles cumulative net flow', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100.00',
|
||||
monthlyRevenue: '200.00',
|
||||
@@ -19,7 +19,7 @@ test('projects exact monthly balances and reconciles cumulative net flow', () =>
|
||||
assert.equal(result.firstDeficitMonth, null);
|
||||
});
|
||||
|
||||
test('flags the first projected deficit without changing input values', () => {
|
||||
void test('flags the first projected deficit without changing input values', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '50',
|
||||
@@ -32,7 +32,7 @@ test('flags the first projected deficit without changing input values', () => {
|
||||
assert.equal(result.endingCash, '-100.00');
|
||||
});
|
||||
|
||||
test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
|
||||
void test('keeps VAT credit stages out of cash and includes only an explicitly forecast receipt', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
@@ -71,7 +71,7 @@ test('keeps VAT credit stages out of cash and includes only an explicitly foreca
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
|
||||
void test('unknown assessed tax keeps the cash projection incomplete instead of assuming zero', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
@@ -101,7 +101,7 @@ test('unknown assessed tax keeps the cash projection incomplete instead of assum
|
||||
assert.equal(declaredZero.endingCash, '180.00');
|
||||
});
|
||||
|
||||
test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
|
||||
void test('monthly tax calendar applies varying user assumptions and reconciles each closing balance', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
@@ -118,7 +118,7 @@ test('monthly tax calendar applies varying user assumptions and reconciles each
|
||||
assert.equal(result.endingCash, '360.00');
|
||||
});
|
||||
|
||||
test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
|
||||
void test('a missing month remains indeterminate while known months and tax amounts reconcile', () => {
|
||||
const result = projectMonthlyCashflow({
|
||||
openingCash: '100',
|
||||
monthlyRevenue: '200',
|
||||
@@ -142,7 +142,7 @@ test('a missing month remains indeterminate while known months and tax amounts r
|
||||
assert.equal(result.endingCashBeforeUnassessedTax, '510.00');
|
||||
});
|
||||
|
||||
test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
|
||||
void test('monthly tax schedule requires one entry per month and cannot conflict with the fixed amount', () => {
|
||||
const base = {
|
||||
openingCash: '0',
|
||||
monthlyRevenue: '100',
|
||||
@@ -165,7 +165,7 @@ test('monthly tax schedule requires one entry per month and cannot conflict with
|
||||
);
|
||||
});
|
||||
|
||||
test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
|
||||
void test('allows an opening cash deficit and rejects excess-precision or invalid horizon inputs', () => {
|
||||
assert.equal(
|
||||
projectMonthlyCashflow({
|
||||
openingCash: '-1.00',
|
||||
@@ -200,7 +200,7 @@ test('allows an opening cash deficit and rejects excess-precision or invalid hor
|
||||
);
|
||||
});
|
||||
|
||||
test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
|
||||
void test('CSV export includes assumptions, monthly totals and an explicit scope note', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '10.00',
|
||||
@@ -233,7 +233,7 @@ test('CSV export includes assumptions, monthly totals and an explicit scope note
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
});
|
||||
|
||||
test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
|
||||
void test('CSV export records each monthly tax assumption and unknown month explicitly', () => {
|
||||
const csv = exportMonthlyCashflowCsv(
|
||||
{
|
||||
openingCash: '0',
|
||||
@@ -259,7 +259,7 @@ test('CSV export records each monthly tax assumption and unknown month explicitl
|
||||
assert.match(csv, /Pressuposto mensal de imposto,Mês 3,0/);
|
||||
});
|
||||
|
||||
test('cash flow CSV neutralizes formula-like assumption text', () => {
|
||||
void test('cash flow CSV neutralizes formula-like assumption text', () => {
|
||||
const csv = exportMonthlyCashflowCsv({
|
||||
openingCash: '10.00',
|
||||
monthlyRevenue: '20.00',
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
portalNavigation,
|
||||
currentNavigationGroup,
|
||||
currentNavigationItem,
|
||||
} from '../../resources/js/lib/portal-navigation.ts';
|
||||
|
||||
void test('public and authenticated navigation share groups without revealing management', () => {
|
||||
const publicGroups = portalNavigation({
|
||||
authenticated: false,
|
||||
manager: false,
|
||||
});
|
||||
const investor = portalNavigation({ authenticated: true, manager: false });
|
||||
assert.deepEqual(publicGroups.slice(0, 3), investor.slice(0, 3));
|
||||
assert.deepEqual(
|
||||
publicGroups.map((g) => g.id),
|
||||
['explore', 'prepare', 'support', 'partnerships', 'account'],
|
||||
);
|
||||
const hrefs = JSON.stringify(investor);
|
||||
assert.equal(hrefs.includes('/management/'), false);
|
||||
assert.equal(JSON.stringify(publicGroups).includes('/login'), true);
|
||||
assert.equal(hrefs.includes('/investidor/profile'), true);
|
||||
assert.equal(hrefs.includes('/balcao-virtual'), true);
|
||||
});
|
||||
|
||||
void test('management and optional modules follow permissions and feature flags', () => {
|
||||
const groups = portalNavigation({
|
||||
authenticated: true,
|
||||
manager: true,
|
||||
businesses: true,
|
||||
education: true,
|
||||
ai: true,
|
||||
});
|
||||
assert.equal(groups.at(-1).id, 'management');
|
||||
assert.equal(JSON.stringify(groups).includes('/investidor/negocios'), true);
|
||||
assert.equal(JSON.stringify(groups).includes('/management/ai'), true);
|
||||
assert.equal(
|
||||
JSON.stringify(
|
||||
portalNavigation({
|
||||
authenticated: false,
|
||||
manager: false,
|
||||
education: false,
|
||||
}),
|
||||
).includes('/educacao'),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
void test('detail URLs and filtered catalogue pages retain the current group', () => {
|
||||
const groups = portalNavigation({ authenticated: true, manager: true });
|
||||
for (const url of [
|
||||
'/carteira/project/fixture',
|
||||
'/zonas?category=zee',
|
||||
'/zonas/fixture',
|
||||
'/oportunidades/fixture',
|
||||
])
|
||||
assert.equal(currentNavigationGroup(groups, url), 'explore');
|
||||
assert.equal(
|
||||
currentNavigationGroup(
|
||||
groups,
|
||||
'/balcao-virtual/dossiers/fixture?phase=market',
|
||||
),
|
||||
'support',
|
||||
);
|
||||
assert.equal(
|
||||
currentNavigationGroup(groups, '/investidor/profile'),
|
||||
'account',
|
||||
);
|
||||
assert.equal(
|
||||
currentNavigationGroup(groups, '/management/crm/leads/fixture'),
|
||||
'management',
|
||||
);
|
||||
assert.equal(currentNavigationGroup(groups, '/unknown'), null);
|
||||
assert.equal(
|
||||
currentNavigationItem(groups, '/carteira?q=QA&kind=project'),
|
||||
'projects',
|
||||
);
|
||||
assert.equal(
|
||||
currentNavigationItem(groups, '/zonas?category=zee&q=QA'),
|
||||
'zee',
|
||||
);
|
||||
});
|
||||
@@ -10,75 +10,190 @@ import {
|
||||
classifyDossierAttachment,
|
||||
validateDossierAttachments,
|
||||
} from '../../resources/js/lib/project-dossier-report.ts';
|
||||
import { serializeBusinessPlanSnapshot, forecastBusinessPlan } from '../../resources/js/lib/business-financial-plan.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,
|
||||
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' });
|
||||
void 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.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', () => {
|
||||
void 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 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.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', () => {
|
||||
void 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 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`);
|
||||
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: [] },
|
||||
void 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));
|
||||
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' });
|
||||
void 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]);
|
||||
assert.deepEqual(Array.from(bytes.subarray(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');
|
||||
@@ -89,13 +204,23 @@ test('DOCX is a readable OpenXML package with Portuguese accents, tables and pag
|
||||
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' });
|
||||
void 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 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');
|
||||
@@ -110,20 +235,44 @@ test('CSV and plain-text annexes are embedded, while other originals get a ZIP i
|
||||
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');
|
||||
void 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 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));
|
||||
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)}"`));
|
||||
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']) });
|
||||
void 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>/);
|
||||
@@ -131,9 +280,22 @@ test('print/PDF HTML escapes user content and explains omitted annexes', async (
|
||||
assert.match(pdf, /@page\{size:A4/);
|
||||
});
|
||||
|
||||
test('attachment limits block oversized or excessive selections', () => {
|
||||
void 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/);
|
||||
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/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,15 +1,40 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readRows, exportProjectDossierCsv } from '../../resources/js/lib/project-dossier.ts';
|
||||
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', () => {
|
||||
void 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: '' }]) });
|
||||
void 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/);
|
||||
@@ -18,16 +43,28 @@ test('project export labels user market claims and insufficient finance evidence
|
||||
assert.match(csv, /Marco 1/);
|
||||
});
|
||||
|
||||
test('project dossier exports readable financial assumptions and verified calculator outputs', () => {
|
||||
void 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' },
|
||||
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' });
|
||||
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;/);
|
||||
|
||||
@@ -1,45 +1,122 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { getProjectReadiness, readPlannedRiskResponses, serializePlannedRiskResponses } from '../../resources/js/lib/project-readiness.ts';
|
||||
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: '[]',
|
||||
void test('idea journey reuses one dossier and exposes the six requested stages', () => {
|
||||
const sections = getSimulationSections({
|
||||
purpose: 'simulate_only',
|
||||
journey_type: 'small_business',
|
||||
});
|
||||
assert.equal(items.some((item) => ['customers', 'costs', 'location', 'funding'].includes(item.id)), false);
|
||||
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('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' }), []);
|
||||
void 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('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' });
|
||||
void 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,
|
||||
);
|
||||
});
|
||||
|
||||
void 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',
|
||||
}),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
void 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/);
|
||||
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/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
simulationCatalogChoices,
|
||||
} from '../../resources/js/lib/simulation-api.ts';
|
||||
|
||||
test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
|
||||
void test('malformed and non-JSON API bodies do not leak parser exceptions', async () => {
|
||||
assert.equal(
|
||||
await readSimulationApiJson(
|
||||
new Response('<html>gateway error</html>', {
|
||||
@@ -28,7 +28,7 @@ test('malformed and non-JSON API bodies do not leak parser exceptions', async ()
|
||||
);
|
||||
});
|
||||
|
||||
test('API error messages prefer validated field details and reject malformed shapes', () => {
|
||||
void test('API error messages prefer validated field details and reject malformed shapes', () => {
|
||||
assert.equal(
|
||||
simulationApiErrorMessage({
|
||||
message: 'Validation failed',
|
||||
@@ -47,7 +47,7 @@ test('API error messages prefer validated field details and reject malformed sha
|
||||
assert.equal(simulationApiErrorMessage('<html>error</html>'), undefined);
|
||||
});
|
||||
|
||||
test('polling failures explain that an accepted calculation may still be pending', () => {
|
||||
void 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.',
|
||||
@@ -58,7 +58,7 @@ test('polling failures explain that an accepted calculation may still be pending
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
|
||||
void test('catalog parser distinguishes a valid empty list and filters malformed options', () => {
|
||||
assert.deepEqual(simulationCatalogChoices({ data: [] }), []);
|
||||
assert.deepEqual(
|
||||
simulationCatalogChoices({
|
||||
|
||||
@@ -86,7 +86,7 @@ const apiJob = {
|
||||
error_code: null,
|
||||
};
|
||||
|
||||
test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
|
||||
void test('OpenAPI matches decimal-string inputs and execution response guards', async () => {
|
||||
const openapi = JSON.parse(
|
||||
await readFile(
|
||||
new URL(
|
||||
@@ -184,7 +184,7 @@ test('OpenAPI matches decimal-string inputs and execution response guards', asyn
|
||||
}
|
||||
});
|
||||
|
||||
test('currency codes are explicit and must be present in the supported currency catalog', () => {
|
||||
void 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);
|
||||
@@ -195,7 +195,7 @@ test('currency codes are explicit and must be present in the supported currency
|
||||
assert.equal(simulationCurrencyOptions.includes('KWD'), false);
|
||||
});
|
||||
|
||||
test('calculated values preserve exact decimal strings, including zero', () => {
|
||||
void test('calculated values preserve exact decimal strings, including zero', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'calculated',
|
||||
@@ -209,7 +209,7 @@ test('calculated values preserve exact decimal strings, including zero', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
|
||||
void test('API v1 wire envelope preserves exact zero and validates indeterminate states', () => {
|
||||
assert.equal(isApiSimulationResultSnapshotV1(apiSnapshot), true);
|
||||
assert.equal(
|
||||
isApiSimulationResultSnapshotV1({
|
||||
@@ -265,7 +265,7 @@ test('API v1 wire envelope preserves exact zero and validates indeterminate stat
|
||||
);
|
||||
});
|
||||
|
||||
test('simulation creation and polling responses require a valid execution view', () => {
|
||||
void test('simulation creation and polling responses require a valid execution view', () => {
|
||||
const queuedExecution = { ...apiExecution };
|
||||
delete queuedExecution.result_snapshot;
|
||||
assert.equal(
|
||||
@@ -355,7 +355,7 @@ test('simulation creation and polling responses require a valid execution view',
|
||||
);
|
||||
});
|
||||
|
||||
test('history and encrypted-draft endpoints reject malformed envelopes', () => {
|
||||
void test('history and encrypted-draft endpoints reject malformed envelopes', () => {
|
||||
assert.equal(isApiSimulationHistoryResponseV1(apiHistory), true);
|
||||
assert.equal(
|
||||
isApiSimulationHistoryResponseV1({
|
||||
@@ -405,7 +405,7 @@ test('history and encrypted-draft endpoints reject malformed envelopes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('questionnaire, report, job and error envelopes match their server contracts', () => {
|
||||
void test('questionnaire, report, job and error envelopes match their server contracts', () => {
|
||||
assert.equal(
|
||||
isApiQuestionnaireReadResponseV1({
|
||||
data: {
|
||||
@@ -510,7 +510,7 @@ test('questionnaire, report, job and error envelopes match their server contract
|
||||
assert.equal(isApiErrorV1({ errors: { base: 'Invalid' } }), false);
|
||||
});
|
||||
|
||||
test('wire contract guards survive a real JSON encode/decode round trip', () => {
|
||||
void test('wire contract guards survive a real JSON encode/decode round trip', () => {
|
||||
const wirePayloads = [
|
||||
[isApiSimulationReadResponseV1, { data: apiExecution }],
|
||||
[
|
||||
@@ -540,7 +540,7 @@ test('wire contract guards survive a real JSON encode/decode round trip', () =>
|
||||
}
|
||||
});
|
||||
|
||||
test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
|
||||
void test('indeterminate results require missing inputs and cannot carry a numeric value', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'indeterminate',
|
||||
@@ -565,7 +565,7 @@ test('indeterminate results require missing inputs and cannot carry a numeric va
|
||||
);
|
||||
});
|
||||
|
||||
test('estimated and not-applicable states must be explicit', () => {
|
||||
void test('estimated and not-applicable states must be explicit', () => {
|
||||
assert.deepEqual(
|
||||
validateSimulationResult({
|
||||
status: 'estimated',
|
||||
@@ -601,7 +601,7 @@ test('estimated and not-applicable states must be explicit', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('every tax component remains indeterminate until an approved effective rule exists', () => {
|
||||
void test('every tax component remains indeterminate until an approved effective rule exists', () => {
|
||||
assert.deepEqual(fiscalComponentCodes, [
|
||||
'IRPS',
|
||||
'INSS',
|
||||
|
||||
@@ -12,7 +12,7 @@ const openapi = JSON.parse(
|
||||
),
|
||||
);
|
||||
|
||||
test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
|
||||
void test('simulation-to-investment-draft conversion contract documents consent and access controls', () => {
|
||||
const operation =
|
||||
openapi.paths['/simulation-drafts/{id}/conversions']?.post;
|
||||
assert.ok(operation);
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
getFiscalPeriodRange,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
|
||||
test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
|
||||
void test('fiscal period range requires and respects exact annual, monthly, quarterly, and one-off dates', () => {
|
||||
assert.deepEqual(
|
||||
getFiscalPeriodRange({
|
||||
fiscal_period: '2024',
|
||||
@@ -68,7 +68,7 @@ test('fiscal period range requires and respects exact annual, monthly, quarterly
|
||||
);
|
||||
});
|
||||
|
||||
test('searchable choice keyboard navigation starts at the first result and stays in bounds', () => {
|
||||
void 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);
|
||||
@@ -77,7 +77,7 @@ test('searchable choice keyboard navigation starts at the first result and stays
|
||||
assert.equal(moveSearchChoiceIndex(0, -1, -1), -1);
|
||||
});
|
||||
|
||||
test('anonymous arithmetic journey skips formal investor and project sections', () => {
|
||||
void test('anonymous arithmetic journey skips formal investor and project sections', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({ purpose: 'simulate_only' }).map(
|
||||
(section) => section.id,
|
||||
@@ -90,7 +90,7 @@ test('anonymous arithmetic journey skips formal investor and project sections',
|
||||
);
|
||||
});
|
||||
|
||||
test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
|
||||
void test('small business exploratory draft includes idea and finance without mandatory formal project data', () => {
|
||||
const draft = {
|
||||
journey_type: 'small_business',
|
||||
purpose: 'simulate_only',
|
||||
@@ -98,35 +98,39 @@ test('small business exploratory draft includes idea and finance without mandato
|
||||
};
|
||||
assert.deepEqual(
|
||||
getSimulationSections(draft).map((section) => section.id),
|
||||
[
|
||||
'purpose',
|
||||
'market',
|
||||
'location',
|
||||
'team',
|
||||
'financial',
|
||||
'review',
|
||||
],
|
||||
['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);
|
||||
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}`);
|
||||
'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'
|
||||
@@ -145,26 +149,54 @@ test('small business exploratory draft includes idea and finance without mandato
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
|
||||
});
|
||||
|
||||
test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
|
||||
void 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);
|
||||
const sections = getSimulationSections(selected).map(
|
||||
(section) => section.id,
|
||||
);
|
||||
assert.deepEqual(sections, [
|
||||
'purpose', 'project', 'location', 'financial', 'tax', 'scenarios', 'procedures', 'review',
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'tax',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
'review',
|
||||
]);
|
||||
for (const sectionId of ['project', 'location', 'financial', 'tax', 'procedures']) {
|
||||
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'));
|
||||
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', () => {
|
||||
void test('public journeys offer distinct section paths for personal, small business, company, and investor', () => {
|
||||
assert.deepEqual(
|
||||
getSimulationSections({
|
||||
journey_type: 'personal',
|
||||
@@ -214,7 +246,7 @@ test('public journeys offer distinct section paths for personal, small business,
|
||||
assert.equal(advancedSimulationFields.has('deductible_costs'), true);
|
||||
});
|
||||
|
||||
test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
|
||||
void test('switching to anonymous mode keeps non-sensitive journey and detail choices', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
@@ -237,7 +269,7 @@ test('switching to anonymous mode keeps non-sensitive journey and detail choices
|
||||
);
|
||||
});
|
||||
|
||||
test('changing territorial or sector parents clears every dependent value', () => {
|
||||
void test('changing territorial or sector parents clears every dependent value', () => {
|
||||
assert.deepEqual(
|
||||
replaceSimulationValue(
|
||||
{
|
||||
@@ -261,7 +293,7 @@ test('changing territorial or sector parents clears every dependent value', () =
|
||||
);
|
||||
});
|
||||
|
||||
test('changing the purpose preserves private and project answers for later correction', () => {
|
||||
void test('changing the purpose preserves private and project answers for later correction', () => {
|
||||
const next = replaceSimulationValue(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
@@ -284,7 +316,7 @@ test('changing the purpose preserves private and project answers for later corre
|
||||
});
|
||||
});
|
||||
|
||||
test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
|
||||
void test('approved-parameter fiscal mode does not ask users to enter a rate', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
@@ -300,7 +332,7 @@ test('approved-parameter fiscal mode does not ask users to enter a rate', () =>
|
||||
assert.deepEqual(validateSimulationDraft(base, 'tax'), {});
|
||||
});
|
||||
|
||||
test('custom planning mode requires user assumptions and validates percentage limits', () => {
|
||||
void test('custom planning mode requires user assumptions and validates percentage limits', () => {
|
||||
const base = {
|
||||
purpose: 'simulate_only',
|
||||
fiscal_period: '2026',
|
||||
@@ -339,7 +371,7 @@ test('custom planning mode requires user assumptions and validates percentage li
|
||||
);
|
||||
});
|
||||
|
||||
test('fiscal intake asks only component-specific questions and leaves residence unresolved when unknown', () => {
|
||||
void 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),
|
||||
@@ -416,7 +448,7 @@ test('fiscal intake asks only component-specific questions and leaves residence
|
||||
);
|
||||
});
|
||||
|
||||
test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
|
||||
void test('financial reconciliation reports a mismatch without inventing a fiscal value', () => {
|
||||
const errors = validateSimulationDraft(
|
||||
{
|
||||
currency: 'USD',
|
||||
@@ -435,7 +467,7 @@ test('financial reconciliation reports a mismatch without inventing a fiscal val
|
||||
);
|
||||
});
|
||||
|
||||
test('autosave omits identity and contact fields from browser storage', () => {
|
||||
void test('autosave omits identity and contact fields from browser storage', () => {
|
||||
assert.deepEqual(
|
||||
getAutosaveSnapshot({
|
||||
total_investment: '50',
|
||||
@@ -449,7 +481,7 @@ test('autosave omits identity and contact fields from browser storage', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('server draft snapshots split private identity from economic values', () => {
|
||||
void test('server draft snapshots split private identity from economic values', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft({
|
||||
journey_type: 'personal',
|
||||
@@ -518,7 +550,7 @@ test('server draft snapshots split private identity from economic values', () =>
|
||||
);
|
||||
});
|
||||
|
||||
test('anonymous server snapshots omit personal values and labels before transmission', () => {
|
||||
void test('anonymous server snapshots omit personal values and labels before transmission', () => {
|
||||
assert.deepEqual(
|
||||
partitionSimulationDraft(
|
||||
{
|
||||
@@ -544,7 +576,7 @@ test('anonymous server snapshots omit personal values and labels before transmis
|
||||
);
|
||||
});
|
||||
|
||||
test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
|
||||
void test('server-owned converted simulation snapshots are restored separately from editable form fields', () => {
|
||||
const restored = restoreSimulationDraft(
|
||||
{
|
||||
purpose: 'own_investment',
|
||||
@@ -562,7 +594,7 @@ test('server-owned converted simulation snapshots are restored separately from e
|
||||
);
|
||||
});
|
||||
|
||||
test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
|
||||
void test('completed arithmetic CSV preserves calculation details without exporting personal data', () => {
|
||||
const simulation = {
|
||||
id: '12345678-aaaa-bbbb-cccc-123456789abc',
|
||||
status: 'completed',
|
||||
@@ -649,7 +681,7 @@ test('completed arithmetic CSV preserves calculation details without exporting p
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
|
||||
void test('versioned arithmetic report reference requires the exact current snapshot and a valid hash', () => {
|
||||
const snapshot = {
|
||||
contract_version: 1,
|
||||
context: { scenario_version: 4 },
|
||||
@@ -696,7 +728,7 @@ test('versioned arithmetic report reference requires the exact current snapshot
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
|
||||
void test('versioned arithmetic CSV refuses a result envelope that differs from the legacy total', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
exportCompletedArithmeticCsv({
|
||||
@@ -727,7 +759,7 @@ test('versioned arithmetic CSV refuses a result envelope that differs from the l
|
||||
);
|
||||
});
|
||||
|
||||
test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
|
||||
void test('versioned arithmetic CSV refuses a report from another scenario revision', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '10.00',
|
||||
legal_interpretation: false,
|
||||
@@ -769,7 +801,7 @@ test('versioned arithmetic CSV refuses a report from another scenario revision',
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
|
||||
void test('arithmetic result reader exposes only reconciled versioned or legacy values', () => {
|
||||
const snapshot = {
|
||||
indicative_total: '0.20',
|
||||
legal_interpretation: false,
|
||||
@@ -812,7 +844,7 @@ test('arithmetic result reader exposes only reconciled versioned or legacy value
|
||||
);
|
||||
});
|
||||
|
||||
test('arithmetic result CSV neutralizes formula-like report metadata', () => {
|
||||
void test('arithmetic result CSV neutralizes formula-like report metadata', () => {
|
||||
const csv = exportCompletedArithmeticCsv({
|
||||
id: '=HYPERLINK("https://example.invalid")',
|
||||
status: 'completed',
|
||||
|
||||
@@ -14,7 +14,7 @@ const simulator = readFileSync(
|
||||
'utf8',
|
||||
);
|
||||
|
||||
test('portal home hero exposes a direct public simulator link', () => {
|
||||
void test('portal home hero exposes a direct public simulator link', () => {
|
||||
const hero = homePage.slice(
|
||||
homePage.indexOf('function Hero('),
|
||||
homePage.indexOf('function SectorGrid('),
|
||||
@@ -23,7 +23,7 @@ test('portal home hero exposes a direct public simulator link', () => {
|
||||
assert.match(hero, /Planear finanças/);
|
||||
});
|
||||
|
||||
test('completed simulator result keeps public interest submission independent', () => {
|
||||
void test('completed simulator result keeps public interest submission independent', () => {
|
||||
assert.match(simulator, /href="\/manifestar-interesse"/);
|
||||
assert.match(
|
||||
simulator,
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { replaceTerritoryPath } from "../../resources/js/lib/territory-path.js";
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { replaceTerritoryPath } from '../../resources/js/lib/territory-path.js';
|
||||
|
||||
test("changing a parent replaces its value and clears every descendant", () => {
|
||||
const path = ["province-a", "district-a", "post-a", "locality-a"];
|
||||
void test('changing a parent replaces its value and clears every descendant', () => {
|
||||
const path = ['province-a', 'district-a', 'post-a', 'locality-a'];
|
||||
|
||||
assert.deepEqual(replaceTerritoryPath(path, 0, "province-b"), ["province-b"]);
|
||||
assert.deepEqual(replaceTerritoryPath(path, 1, "district-b"), ["province-a", "district-b"]);
|
||||
assert.deepEqual(replaceTerritoryPath(path, 0, 'province-b'), [
|
||||
'province-b',
|
||||
]);
|
||||
assert.deepEqual(replaceTerritoryPath(path, 1, 'district-b'), [
|
||||
'province-a',
|
||||
'district-b',
|
||||
]);
|
||||
});
|
||||
|
||||
test("clearing a level also clears that level and all descendants", () => {
|
||||
const path = ["province-a", "district-a", "post-a", "locality-a"];
|
||||
void test('clearing a level also clears that level and all descendants', () => {
|
||||
const path = ['province-a', 'district-a', 'post-a', 'locality-a'];
|
||||
|
||||
assert.deepEqual(replaceTerritoryPath(path, 0), []);
|
||||
assert.deepEqual(replaceTerritoryPath(path, 2, null), ["province-a", "district-a"]);
|
||||
assert.deepEqual(replaceTerritoryPath(path, 2, null), [
|
||||
'province-a',
|
||||
'district-a',
|
||||
]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user