@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\AiRun;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AiGatewayTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->assertSame('testing', app()->environment());
|
||||
$this->assertSame('pgsql', DB::connection()->getDriverName());
|
||||
$this->assertStringEndsWith('_test', DB::connection()->getDatabaseName());
|
||||
$this->assertSame(DB::connection()->getDatabaseName(), DB::selectOne('select current_database() as name')->name);
|
||||
DB::beginTransaction();
|
||||
$this->beforeApplicationDestroyed(fn () => DB::rollBack());
|
||||
$this->withoutVite();
|
||||
Http::preventStrayRequests();
|
||||
config(['investmoz_ai.enabled' => true]);
|
||||
DB::table('ai_controls')->update(['suspended' => false]);
|
||||
}
|
||||
|
||||
private function manager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [...config('portal.managers', []), $user->email]]);
|
||||
$this->actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function source(string $classification = 'internal', string $language = 'pt', ?string $text = null): string
|
||||
{
|
||||
$id = (string) Str::uuid();
|
||||
$text ??= 'Documento exclusivamente sintético: formação técnica e investimento em equipamentos para oficinas.';
|
||||
$key = 'ai-test-'.$id.'.txt';
|
||||
Storage::disk('local')->put($key, $text);
|
||||
$this->beforeApplicationDestroyed(fn () => Storage::disk('local')->delete($key));
|
||||
DB::table('documents')->insert(['id' => $id, 'file_name' => $key, 'media_type' => 'text/plain', 'storage_key' => $key,
|
||||
'sha256' => hash('sha256', $text), 'status' => 'active', 'data_classification' => $classification]);
|
||||
$response = $this->postJson('/api/v1/ai/sources', ['document_id' => $id, 'title' => 'Fonte sintética', 'language' => $language,
|
||||
'nature' => 'illustrative', 'source_url' => 'https://example.org/synthetic', 'source_owner' => 'Entidade de teste',
|
||||
'evidence_reference' => 'Autorização exclusivamente sintética.', 'source_date' => now()->toDateString(),
|
||||
'valid_until' => now()->addMonth()->toDateString(), 'authorised' => true]);
|
||||
if (in_array($classification, ['confidential', 'restricted'], true)) {
|
||||
$response->assertUnprocessable();
|
||||
|
||||
return $id;
|
||||
}
|
||||
$response->assertOk();
|
||||
|
||||
return DB::table('ai_sources')->where('document_id', $id)->value('id');
|
||||
}
|
||||
|
||||
private function ask(string $query = 'formação', string $language = 'pt'): string
|
||||
{
|
||||
return $this->postJson('/api/v1/ai/runs', ['capability' => 'assistant', 'purpose' => 'investment_information',
|
||||
'query' => $query, 'language' => $language])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
public function test_authentication_authorisation_flag_and_purpose_are_enforced(): void
|
||||
{
|
||||
$this->get('/management/ai')->assertRedirect('/login');
|
||||
$this->actingAs(User::factory()->create())->get('/management/ai')->assertForbidden();
|
||||
$this->manager();
|
||||
$this->get('/management/ai')->assertInertia(fn (AssertableInertia $page) => $page->component('ai/index'));
|
||||
$this->postJson('/api/v1/ai/runs', ['capability' => 'assistant', 'purpose' => 'interest_triage', 'query' => 'formação', 'language' => 'pt'])->assertUnprocessable();
|
||||
config(['investmoz_ai.enabled' => false]);
|
||||
$this->get('/management/ai')->assertNotFound();
|
||||
$this->postJson('/api/v1/ai/runs', [])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_unreviewed_confidential_and_revoked_sources_never_leak(): void
|
||||
{
|
||||
$this->manager();
|
||||
$source = $this->source();
|
||||
$this->source('confidential');
|
||||
$pending = $this->ask();
|
||||
$this->getJson('/api/v1/ai/runs/'.$pending)->assertJsonCount(0, 'result.items');
|
||||
$this->postJson('/api/v1/ai/sources/'.$source.'/review', ['status' => 'approved', 'expected_status' => 'pending'])->assertForbidden();
|
||||
$this->manager();
|
||||
$this->postJson('/api/v1/ai/sources/'.$source.'/review', ['status' => 'approved', 'expected_status' => 'pending'])->assertOk();
|
||||
$run = $this->ask();
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonCount(1, 'result.items')->assertJsonPath('result.items.0.source_id', $source)
|
||||
->assertJsonPath('result.mode', 'lexical_evidence')->assertJsonPath('result.model', null)->assertJsonPath('result.confidence', 'not_calibrated');
|
||||
$stored = DB::table('ai_runs')->where('id', $run)->first();
|
||||
$this->assertStringNotContainsString('equipamentos', $stored->result);
|
||||
$event = DB::table('audit_events')->where('entity_id', $run)->first();
|
||||
$this->assertStringNotContainsString('formação', $event->after_data);
|
||||
$this->postJson('/api/v1/ai/sources/'.$source.'/review', ['status' => 'revoked', 'expected_status' => 'approved'])->assertOk();
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonPath('unavailable', true)->assertJsonPath('result', null);
|
||||
$this->getJson('/api/v1/ai/runs/'.$this->ask())->assertJsonCount(0, 'result.items');
|
||||
}
|
||||
|
||||
public function test_language_expiry_and_document_version_are_checked_before_retrieval(): void
|
||||
{
|
||||
$this->manager();
|
||||
$source = $this->source('internal', 'en', 'Synthetic document: vocational training for renewable energy maintenance.');
|
||||
$this->manager();
|
||||
$this->postJson('/api/v1/ai/sources/'.$source.'/review', ['status' => 'approved', 'expected_status' => 'pending'])->assertOk();
|
||||
$this->getJson('/api/v1/ai/runs/'.$this->ask('renewable energy', 'en'))->assertJsonCount(1, 'result.items');
|
||||
$this->getJson('/api/v1/ai/runs/'.$this->ask('renewable energy', 'pt'))->assertJsonCount(0, 'result.items');
|
||||
$doc = DB::table('ai_sources')->where('id', $source)->value('document_id');
|
||||
DB::table('documents')->where('id', $doc)->increment('version_no');
|
||||
$this->getJson('/api/v1/ai/runs/'.$this->ask('renewable energy', 'en'))->assertJsonCount(0, 'result.items');
|
||||
DB::table('documents')->where('id', $doc)->decrement('version_no');
|
||||
$this->travel(2)->months();
|
||||
$this->getJson('/api/v1/ai/runs/'.$this->ask('renewable energy', 'en'))->assertJsonCount(0, 'result.items');
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_unsafe_feedback_suspends_capability_and_review_cannot_change_official_state(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$run = $this->ask('sem evidência');
|
||||
$this->postJson('/api/v1/ai/runs/'.$run.'/review', ['status' => 'accepted', 'version_no' => 1])->assertForbidden();
|
||||
$this->manager();
|
||||
$this->postJson('/api/v1/ai/runs/'.$run.'/review', ['status' => 'rejected', 'version_no' => 1])->assertOk();
|
||||
$this->postJson('/api/v1/ai/runs/'.$run.'/review', ['status' => 'accepted', 'version_no' => 1])->assertConflict();
|
||||
$this->postJson('/api/v1/ai/runs/'.$run.'/feedback', ['rating' => 'unsafe', 'review_requested' => true])->assertOk();
|
||||
$this->assertDatabaseHas('ai_controls', ['capability' => 'assistant', 'suspended' => true]);
|
||||
$this->postJson('/api/v1/ai/runs', ['capability' => 'assistant', 'purpose' => 'investment_information', 'query' => 'teste', 'language' => 'pt'])->assertStatus(503);
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonPath('result', null);
|
||||
$this->assertSame($actor->id, AiRun::findOrFail($run)->actor_id);
|
||||
$this->assertDatabaseCount('ai_feedback', 1);
|
||||
}
|
||||
|
||||
public function test_rules_and_extractive_summary_do_not_call_external_models(): void
|
||||
{
|
||||
$this->manager();
|
||||
foreach (['recommend' => 'investment_information', 'quality' => 'data_quality', 'sla' => 'execution_monitoring'] as $capability => $purpose) {
|
||||
$id = $this->postJson('/api/v1/ai/runs', compact('capability', 'purpose') + ['language' => 'pt'])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/ai/runs/'.$id)->assertJsonPath('result.mode', 'structured_rules')->assertJsonPath('result.model', null);
|
||||
}
|
||||
$source = $this->source();
|
||||
$this->manager();
|
||||
$this->postJson('/api/v1/ai/sources/'.$source.'/review', ['status' => 'approved', 'expected_status' => 'pending'])->assertOk();
|
||||
$id = $this->postJson('/api/v1/ai/runs', ['capability' => 'summary', 'purpose' => 'investment_information', 'language' => 'pt', 'source_id' => $source])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/ai/runs/'.$id)->assertJsonPath('result.mode', 'extractive_preview')->assertJsonCount(1, 'result.items');
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_text_upload_uses_canonical_documents_and_does_not_auto_authorise_retrieval(): void
|
||||
{
|
||||
$this->manager();
|
||||
$response = $this->postJson('/api/v1/ai/documents', ['file' => UploadedFile::fake()->createWithContent('source.txt', 'Synthetic authorised plain text.'), 'authorised' => true])->assertCreated();
|
||||
$document = DB::table('documents')->where('id', $response->json('document_id'))->first();
|
||||
$this->beforeApplicationDestroyed(fn () => Storage::disk('local')->delete($document->storage_key));
|
||||
$this->assertSame('internal', $document->data_classification);
|
||||
$this->assertSame(hash('sha256', 'Synthetic authorised plain text.'), $document->sha256);
|
||||
$this->assertDatabaseCount('ai_sources', 0);
|
||||
$this->postJson('/api/v1/ai/documents', ['file' => UploadedFile::fake()->create('unsafe.pdf', 10, 'application/pdf'), 'authorised' => true])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_triage_requires_specific_consent_and_withdrawal_hides_old_result(): void
|
||||
{
|
||||
$actor = $this->manager();
|
||||
$interest = InterestRequest::create(['reference' => (string) Str::uuid(), 'full_name' => 'Private synthetic name',
|
||||
'email' => 'private@example.invalid', 'investor_type' => 'empresa', 'country' => 'MZ', 'sector_interest' => 'Energia',
|
||||
'message' => 'Private synthetic message.', 'privacy_consent' => true]);
|
||||
$input = ['capability' => 'classify', 'purpose' => 'interest_triage', 'interest_id' => $interest->id, 'language' => 'pt'];
|
||||
$this->postJson('/api/v1/ai/runs', $input)->assertUnprocessable();
|
||||
$consent = (string) Str::uuid();
|
||||
DB::table('consents')->insert(['id' => $consent, 'user_id' => $actor->id, 'subject_ref' => $interest->reference,
|
||||
'purpose' => 'ai_assistance', 'status' => 'granted', 'granted_at' => now()]);
|
||||
$run = $this->postJson('/api/v1/ai/runs', $input)->assertCreated()->json('id');
|
||||
$response = $this->getJson('/api/v1/ai/runs/'.$run)->assertJsonPath('result.items.0.intention', 'general_information');
|
||||
$this->assertStringNotContainsString('private@example.invalid', $response->getContent());
|
||||
$this->assertStringNotContainsString('Private synthetic', $response->getContent());
|
||||
DB::table('consents')->where('id', $consent)->update(['status' => 'withdrawn', 'withdrawn_at' => now()]);
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonPath('result', null);
|
||||
$this->manager();
|
||||
$this->postJson('/api/v1/ai/runs/'.$run.'/review', ['status' => 'accepted', 'version_no' => 1])->assertUnprocessable();
|
||||
$this->assertSame('received', $interest->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_recommendations_use_explicit_filters_and_unpublished_results_are_hidden(): void
|
||||
{
|
||||
$this->manager();
|
||||
$sector = Sector::create(['name' => 'Sector sintético', 'slug' => (string) Str::uuid()]);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => (string) Str::uuid(),
|
||||
'title' => 'Oportunidade sintética', 'slug' => (string) Str::uuid(), 'status' => 'published', 'published_at' => now(), 'province' => 'Território de teste']);
|
||||
$run = $this->postJson('/api/v1/ai/runs', ['capability' => 'recommend', 'purpose' => 'investment_information',
|
||||
'language' => 'pt', 'province' => 'Território de teste'])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonCount(1, 'result.items')->assertJsonPath('result.items.0.score', 1);
|
||||
$opportunity->update(['status' => 'draft']);
|
||||
$this->getJson('/api/v1/ai/runs/'.$run)->assertJsonPath('result', null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AuthenticationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_login_screen_can_be_rendered()
|
||||
{
|
||||
$response = $this->get(route('login'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
|
||||
public function test_users_can_authenticate_using_the_login_screen()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this->post(route('login.store'), [
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$this->assertAuthenticated();
|
||||
$response->assertRedirect(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
public function test_users_with_two_factor_enabled_are_redirected_to_two_factor_challenge()
|
||||
{
|
||||
$this->skipUnlessFortifyHas(Features::twoFactorAuthentication());
|
||||
|
||||
Features::twoFactorAuthentication([
|
||||
'confirm' => true,
|
||||
'confirmPassword' => true,
|
||||
]);
|
||||
|
||||
$user = User::factory()->withTwoFactor()->create();
|
||||
|
||||
$response = $this->post(route('login'), [
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$response->assertRedirect(route('two-factor.login'));
|
||||
$response->assertSessionHas('login.id', $user->id);
|
||||
$this->assertGuest();
|
||||
}
|
||||
|
||||
public function test_users_can_not_authenticate_with_invalid_password()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('login.store'), [
|
||||
'email' => $user->email,
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$this->assertGuest();
|
||||
}
|
||||
|
||||
public function test_users_can_logout()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this->actingAs($user)->post(route('logout'));
|
||||
|
||||
$response->assertRedirect(route('home'));
|
||||
|
||||
$this->assertGuest();
|
||||
}
|
||||
|
||||
public function test_users_are_rate_limited()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
RateLimiter::increment(md5('login'.implode('|', [$user->email, '127.0.0.1'])), amount: 5);
|
||||
|
||||
$response = $this->post(route('login.store'), [
|
||||
'email' => $user->email,
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$response->assertTooManyRequests();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Events\Verified;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class EmailVerificationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->skipUnlessFortifyHas(Features::emailVerification());
|
||||
}
|
||||
|
||||
public function test_email_verification_screen_can_be_rendered()
|
||||
{
|
||||
$user = User::factory()->unverified()->create();
|
||||
|
||||
$response = $this->actingAs($user)->get(route('verification.notice'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
|
||||
public function test_email_can_be_verified()
|
||||
{
|
||||
$user = User::factory()->unverified()->create();
|
||||
|
||||
Event::fake();
|
||||
|
||||
$verificationUrl = URL::temporarySignedRoute(
|
||||
'verification.verify',
|
||||
now()->addMinutes(60),
|
||||
['id' => $user->id, 'hash' => sha1($user->email)],
|
||||
);
|
||||
|
||||
$response = $this->actingAs($user)->get($verificationUrl);
|
||||
|
||||
Event::assertDispatched(Verified::class);
|
||||
|
||||
$this->assertTrue($user->fresh()->hasVerifiedEmail());
|
||||
$response->assertRedirect(route('dashboard', absolute: false).'?verified=1');
|
||||
}
|
||||
|
||||
public function test_email_is_not_verified_with_invalid_hash()
|
||||
{
|
||||
$user = User::factory()->unverified()->create();
|
||||
|
||||
Event::fake();
|
||||
|
||||
$verificationUrl = URL::temporarySignedRoute(
|
||||
'verification.verify',
|
||||
now()->addMinutes(60),
|
||||
['id' => $user->id, 'hash' => sha1('wrong-email')],
|
||||
);
|
||||
|
||||
$this->actingAs($user)->get($verificationUrl);
|
||||
|
||||
Event::assertNotDispatched(Verified::class);
|
||||
$this->assertFalse($user->fresh()->hasVerifiedEmail());
|
||||
}
|
||||
|
||||
public function test_email_is_not_verified_with_invalid_user_id(): void
|
||||
{
|
||||
$user = User::factory()->unverified()->create();
|
||||
|
||||
Event::fake();
|
||||
|
||||
$verificationUrl = URL::temporarySignedRoute(
|
||||
'verification.verify',
|
||||
now()->addMinutes(60),
|
||||
['id' => 123, 'hash' => sha1($user->email)],
|
||||
);
|
||||
|
||||
$this->actingAs($user)->get($verificationUrl);
|
||||
|
||||
Event::assertNotDispatched(Verified::class);
|
||||
$this->assertFalse($user->fresh()->hasVerifiedEmail());
|
||||
}
|
||||
|
||||
public function test_verified_user_is_redirected_to_dashboard_from_verification_prompt(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
Event::fake();
|
||||
|
||||
$response = $this->actingAs($user)->get(route('verification.notice'));
|
||||
|
||||
Event::assertNotDispatched(Verified::class);
|
||||
$response->assertRedirect(route('dashboard', absolute: false));
|
||||
}
|
||||
|
||||
public function test_already_verified_user_visiting_verification_link_is_redirected_without_firing_event_again(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
Event::fake();
|
||||
|
||||
$verificationUrl = URL::temporarySignedRoute(
|
||||
'verification.verify',
|
||||
now()->addMinutes(60),
|
||||
['id' => $user->id, 'hash' => sha1($user->email)],
|
||||
);
|
||||
|
||||
$this->actingAs($user)->get($verificationUrl)
|
||||
->assertRedirect(route('dashboard', absolute: false).'?verified=1');
|
||||
|
||||
Event::assertNotDispatched(Verified::class);
|
||||
$this->assertTrue($user->fresh()->hasVerifiedEmail());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PasswordConfirmationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_confirm_password_screen_can_be_rendered()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this->actingAs($user)->get(route('password.confirm'));
|
||||
|
||||
$response->assertOk();
|
||||
|
||||
$response->assertInertia(fn (Assert $page) => $page
|
||||
->component('auth/confirm-password'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_password_confirmation_requires_authentication()
|
||||
{
|
||||
$response = $this->get(route('password.confirm'));
|
||||
|
||||
$response->assertRedirect(route('login'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PasswordResetTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->skipUnlessFortifyHas(Features::resetPasswords());
|
||||
}
|
||||
|
||||
public function test_reset_password_link_screen_can_be_rendered()
|
||||
{
|
||||
$response = $this->get(route('password.request'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
|
||||
public function test_reset_password_link_can_be_requested()
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class);
|
||||
}
|
||||
|
||||
public function test_reset_password_screen_can_be_rendered()
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) {
|
||||
$response = $this->get(route('password.reset', $notification->token));
|
||||
|
||||
$response->assertOk();
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function test_password_can_be_reset_with_valid_token()
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->post(route('password.email'), ['email' => $user->email]);
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function ($notification) use ($user) {
|
||||
$response = $this->post(route('password.update'), [
|
||||
'token' => $notification->token,
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('login'));
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public function test_password_cannot_be_reset_with_invalid_token(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this->post(route('password.update'), [
|
||||
'token' => 'invalid-token',
|
||||
'email' => $user->email,
|
||||
'password' => 'newpassword123',
|
||||
'password_confirmation' => 'newpassword123',
|
||||
]);
|
||||
|
||||
$response->assertSessionHasErrors('email');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class RegistrationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->skipUnlessFortifyHas(Features::registration());
|
||||
}
|
||||
|
||||
public function test_registration_screen_can_be_rendered()
|
||||
{
|
||||
$response = $this->get(route('register'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
|
||||
public function test_new_users_can_register()
|
||||
{
|
||||
$response = $this->post(route('register.store'), [
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
]);
|
||||
|
||||
$this->assertAuthenticated();
|
||||
$response->assertRedirect(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class TwoFactorChallengeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->skipUnlessFortifyHas(Features::twoFactorAuthentication());
|
||||
}
|
||||
|
||||
public function test_two_factor_challenge_redirects_to_login_when_not_authenticated(): void
|
||||
{
|
||||
$response = $this->get(route('two-factor.login'));
|
||||
|
||||
$response->assertRedirect(route('login'));
|
||||
}
|
||||
|
||||
public function test_two_factor_challenge_can_be_rendered(): void
|
||||
{
|
||||
Features::twoFactorAuthentication([
|
||||
'confirm' => true,
|
||||
'confirmPassword' => true,
|
||||
]);
|
||||
|
||||
$user = User::factory()->withTwoFactor()->create();
|
||||
|
||||
$this->post(route('login'), [
|
||||
'email' => $user->email,
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$this->get(route('two-factor.login'))
|
||||
->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page
|
||||
->component('auth/two-factor-challenge'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Auth;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\VerifyEmail;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class VerificationNotificationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->skipUnlessFortifyHas(Features::emailVerification());
|
||||
}
|
||||
|
||||
public function test_sends_verification_notification(): void
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->unverified()->create();
|
||||
|
||||
$this->actingAs($user)
|
||||
->post(route('verification.send'))
|
||||
->assertRedirect(route('home'));
|
||||
|
||||
Notification::assertSentTo($user, VerifyEmail::class);
|
||||
}
|
||||
|
||||
public function test_does_not_send_verification_notification_if_email_is_verified(): void
|
||||
{
|
||||
Notification::fake();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->actingAs($user)
|
||||
->post(route('verification.send'))
|
||||
->assertRedirect(route('dashboard', absolute: false));
|
||||
|
||||
Notification::assertNothingSent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\InvestmentGap;
|
||||
use App\Models\User;
|
||||
use App\Models\ValueChain;
|
||||
use App\Models\ValueChainLink;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ClusterValueChainTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function manager(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->actingAs($user);
|
||||
}
|
||||
|
||||
private function cluster(string $code): EconomicCluster
|
||||
{
|
||||
return EconomicCluster::create(['code' => $code, 'name' => $code, 'sector' => 'Energia', 'status' => 'planned']);
|
||||
}
|
||||
|
||||
private function chain(EconomicCluster $cluster, string $code): ValueChain
|
||||
{
|
||||
return ValueChain::create(['cluster_id' => $cluster->id, 'code' => $code, 'name' => $code, 'stage' => 'input']);
|
||||
}
|
||||
|
||||
public function test_links_are_idempotent_and_reject_self_foreign_and_deleted_stages(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster('C1');
|
||||
$origin = $this->chain($cluster, 'Input');
|
||||
$destination = $this->chain($cluster, 'Production');
|
||||
$foreign = $this->chain($this->cluster('C2'), 'Foreign');
|
||||
$url = '/management/clusters/'.$cluster->id.'/chain-links';
|
||||
$data = ['from_value_chain_id' => $origin->id, 'to_value_chain_id' => $destination->id, 'link_type' => 'supplies'];
|
||||
$this->post($url, $data)->assertSessionHasNoErrors();
|
||||
$this->post($url, $data)->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseCount('value_chain_links', 1);
|
||||
$this->assertSame(1, DB::table('audit_events')->where('entity_type', 'value_chain_links')->count());
|
||||
$this->post($url, [...$data, 'to_value_chain_id' => $origin->id])->assertSessionHasErrors('to_value_chain_id');
|
||||
$this->post($url, [...$data, 'to_value_chain_id' => $foreign->id])->assertSessionHasErrors('to_value_chain_id');
|
||||
$destination->delete();
|
||||
$this->post($url, $data)->assertSessionHasErrors('to_value_chain_id');
|
||||
}
|
||||
|
||||
public function test_removal_preserves_history_and_cannot_target_another_cluster(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster('C1');
|
||||
$other = $this->cluster('C2');
|
||||
$data = ['from_value_chain_id' => $this->chain($cluster, 'A')->id, 'to_value_chain_id' => $this->chain($cluster, 'B')->id, 'link_type' => 'supports'];
|
||||
$url = '/management/clusters/'.$cluster->id.'/chain-links';
|
||||
$this->post($url, $data)->assertSessionHasNoErrors();
|
||||
$link = ValueChainLink::firstOrFail();
|
||||
$this->delete('/management/clusters/'.$other->id.'/chain-links/'.$link->id)->assertNotFound();
|
||||
$this->assertNotSoftDeleted($link);
|
||||
$this->delete($url.'/'.$link->id)->assertSessionHasNoErrors();
|
||||
$this->assertSoftDeleted($link);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('entity_id', $link->id)->count());
|
||||
$this->post($url, $data)->assertSessionHasNoErrors();
|
||||
$this->assertSame(1, ValueChainLink::count());
|
||||
$this->assertDatabaseCount('value_chain_links', 2);
|
||||
}
|
||||
|
||||
public function test_gap_requires_details_and_stays_within_cluster(): void
|
||||
{
|
||||
$this->manager();
|
||||
$cluster = $this->cluster('C1');
|
||||
$other = $this->cluster('C2');
|
||||
$stage = $this->chain($cluster, 'Logistics');
|
||||
$foreign = $this->chain($other, 'Foreign');
|
||||
$data = ['value_chain_id' => $stage->id, 'title' => 'Armazenagem', 'location' => 'Distrito de teste',
|
||||
'required_capacity' => '500 toneladas', 'rationale' => 'Falta capacidade de armazenamento.', 'status' => 'identified', 'call_to_action' => 'Apresentar proposta de investimento.'];
|
||||
$url = '/management/clusters/'.$cluster->id.'/gaps';
|
||||
$this->post($url, [...$data, 'required_capacity' => ''])->assertSessionHasErrors('required_capacity');
|
||||
$this->post($url, [...$data, 'value_chain_id' => $foreign->id])->assertSessionHasErrors('value_chain_id');
|
||||
$this->post($url, $data)->assertSessionHasNoErrors();
|
||||
$gap = InvestmentGap::firstOrFail();
|
||||
$this->put('/management/clusters/'.$other->id.'/gaps/'.$gap->id, [...$data, 'value_chain_id' => $foreign->id])->assertNotFound();
|
||||
$this->put($url.'/'.$gap->id, [...$data, 'status' => 'resolved'])->assertSessionHasNoErrors();
|
||||
$this->assertSame('resolved', $gap->fresh()->status);
|
||||
$event = DB::table('audit_events')->where('entity_id', $gap->id)->where('action', 'created')->first();
|
||||
$this->assertStringNotContainsString($data['rationale'], $event->after_data);
|
||||
$this->get('/management/clusters/'.$cluster->id.'/edit')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->component('structures/editor')->has('gaps', 1)->where('gaps.0.status', 'resolved')->has('chainLinks', 0));
|
||||
}
|
||||
|
||||
public function test_anonymous_and_unauthorised_users_cannot_write_network_or_gaps(): void
|
||||
{
|
||||
$cluster = $this->cluster('C1');
|
||||
$this->post('/management/clusters/'.$cluster->id.'/gaps', [])->assertRedirect('/login');
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->post('/management/clusters/'.$cluster->id.'/gaps', [])->assertForbidden();
|
||||
$this->post('/management/clusters/'.$cluster->id.'/chain-links', [])->assertForbidden();
|
||||
$this->assertDatabaseCount('investment_gaps', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Contact;
|
||||
use App\Models\CrmTask;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Investor;
|
||||
use App\Models\Lead;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
class CrmIntakeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function setupManager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function interest(string $reference = 'IR-CRM-1'): InterestRequest
|
||||
{
|
||||
return InterestRequest::create(['reference' => $reference, 'full_name' => 'Contacto fictício', 'email' => 'CONTACT@example.invalid',
|
||||
'investor_type' => 'empresa', 'country' => 'Moçambique', 'sector_interest' => 'Energia', 'message' => 'Mensagem do pedido de teste.', 'privacy_consent' => true]);
|
||||
}
|
||||
|
||||
private function data(User $user): array
|
||||
{
|
||||
return ['legal_name' => 'Empresa de teste', 'investor_type' => 'domestic', 'owner_user_id' => $user->id,
|
||||
'title' => 'Lead de energia', 'next_action' => 'Rever informação', 'due_at' => now()->addDay()->toIso8601String()];
|
||||
}
|
||||
|
||||
public function test_conversion_is_idempotent_and_preserves_source_with_owner_and_future_task(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$interest = $this->interest();
|
||||
$data = $this->data($user);
|
||||
$this->post('/management/crm/convert/'.$interest->id, $data)->assertRedirect();
|
||||
$this->post('/management/crm/convert/'.$interest->id, $data)->assertRedirect();
|
||||
$this->assertDatabaseCount('leads', 1);
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
$this->assertDatabaseCount('contacts', 1);
|
||||
$this->assertDatabaseCount('tasks', 1);
|
||||
$lead = Lead::firstOrFail();
|
||||
$this->assertSame('portal:IR-CRM-1', $lead->first_source);
|
||||
$this->assertSame($user->id, $lead->owner_user_id);
|
||||
$this->assertSame('contact@example.invalid', Contact::firstOrFail()->email);
|
||||
$this->assertSame($lead->id, CrmTask::firstOrFail()->lead_id);
|
||||
$this->get('/management/crm/leads')->assertOk();
|
||||
$this->get('/management/crm/leads/'.$lead->id)->assertOk();
|
||||
$this->assertSame(4, DB::table('audit_events')->where('source_system', 'portal-management')->count());
|
||||
}
|
||||
|
||||
public function test_existing_contact_requires_explicit_investor_selection_and_is_not_duplicated(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$first = $this->interest();
|
||||
$this->post('/management/crm/convert/'.$first->id, $this->data($user))->assertRedirect();
|
||||
$next = $this->interest('IR-CRM-2');
|
||||
$this->post('/management/crm/convert/'.$next->id, $this->data($user))->assertSessionHasErrors('investor_id');
|
||||
$this->assertDatabaseCount('leads', 1);
|
||||
$this->post('/management/crm/convert/'.$next->id, [...$this->data($user), 'investor_id' => Investor::firstOrFail()->id])->assertRedirect();
|
||||
$this->assertDatabaseCount('contacts', 1);
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
$this->assertDatabaseCount('leads', 2);
|
||||
}
|
||||
|
||||
public function test_unauthorised_users_cannot_convert_and_input_requires_owner_and_future_action(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$interest = $this->interest();
|
||||
$this->post('/management/crm/convert/'.$interest->id, [...$this->data($user), 'due_at' => now()->subDay()->toIso8601String()])->assertSessionHasErrors('due_at');
|
||||
$this->actingAs(User::factory()->create())->post('/management/crm/convert/'.$interest->id, $this->data($user))->assertForbidden();
|
||||
$this->assertDatabaseCount('leads', 0);
|
||||
}
|
||||
|
||||
public function test_active_lead_keeps_a_next_action_and_qualification_is_audited(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$interest = $this->interest();
|
||||
$this->post('/management/crm/convert/'.$interest->id, $this->data($user))->assertRedirect();
|
||||
$lead = Lead::firstOrFail();
|
||||
$task = CrmTask::firstOrFail();
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['status' => 'done'])->assertSessionHasErrors('status');
|
||||
$this->post('/management/crm/leads/'.$lead->id.'/tasks', ['title' => 'Reunião', 'due_at' => now()->addDays(2)->toIso8601String(), 'assignee_user_id' => $user->id])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id.'/tasks/'.$task->id, ['status' => 'done'])->assertRedirect();
|
||||
$this->patch('/management/crm/leads/'.$lead->id, ['status' => 'qualified', 'owner_user_id' => $user->id, 'qualification_reason' => 'Informação confirmada pelo gestor.'])->assertRedirect();
|
||||
$this->assertSame('qualified', $lead->fresh()->status);
|
||||
$this->assertDatabaseHas('audit_events', ['entity_id' => $lead->id, 'action' => 'updated']);
|
||||
}
|
||||
|
||||
public function test_investor_edit_and_contact_duplicate_protection_are_scoped(): void
|
||||
{
|
||||
$user = $this->setupManager();
|
||||
$interest = $this->interest();
|
||||
$this->post('/management/crm/convert/'.$interest->id, $this->data($user))->assertRedirect();
|
||||
$investor = Investor::firstOrFail();
|
||||
$contact = Contact::firstOrFail();
|
||||
$this->get('/management/crm/investors')->assertOk();
|
||||
$this->get('/management/crm/investors/'.$investor->id)->assertOk();
|
||||
$this->patch('/management/crm/investors/'.$investor->id, ['legal_name' => 'Nome revisto', 'investor_type' => 'domestic', 'status' => 'active'])->assertRedirect();
|
||||
$this->assertSame('Nome revisto', $investor->fresh()->legal_name);
|
||||
$other = Contact::create(['full_name' => 'Outro', 'email' => 'other@example.invalid']);
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$contact->id, ['full_name' => 'Nome revisto', 'email' => 'OTHER@example.invalid'])->assertSessionHasErrors('email');
|
||||
$this->patch('/management/crm/investors/'.$investor->id.'/contacts/'.$other->id, ['full_name' => 'Outro', 'email' => 'new@example.invalid'])->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DashboardTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_guests_are_redirected_to_the_login_page()
|
||||
{
|
||||
$response = $this->get(route('dashboard'));
|
||||
$response->assertRedirect(route('login'));
|
||||
}
|
||||
|
||||
public function test_authenticated_users_can_visit_the_dashboard()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user);
|
||||
|
||||
$response = $this->get(route('dashboard'));
|
||||
$response->assertOk();
|
||||
$response->assertInertia(fn (Assert $page) => $page->component('dashboard')->where('summary', null));
|
||||
}
|
||||
|
||||
public function test_manager_sees_real_counts_and_only_five_recent_requests(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$sector = Sector::create(['name' => 'Energia', 'slug' => 'energia', 'is_active' => true]);
|
||||
foreach (['published', 'draft', 'archived'] as $status) {
|
||||
Opportunity::create(['sector_id' => $sector->id, 'reference' => $status, 'slug' => $status,
|
||||
'title' => $status, 'status' => $status, 'published_at' => now()->subMinute()]);
|
||||
}
|
||||
for ($i = 0; $i < 7; $i++) {
|
||||
InterestRequest::create(['reference' => 'IR-TEST-'.$i, 'full_name' => 'Pessoa de teste',
|
||||
'email' => 'test@example.invalid', 'investor_type' => 'empresa', 'country' => 'Moçambique',
|
||||
'sector_interest' => 'Energia', 'message' => 'Mensagem privada de teste', 'privacy_consent' => true,
|
||||
'status' => $i === 0 ? 'closed' : 'received']);
|
||||
}
|
||||
$this->actingAs($user)->get(route('dashboard'))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component('dashboard')->where('summary.requestsByStatus.received', 6)
|
||||
->where('summary.requestsByStatus.closed', 1)->where('summary.requestsByStatus.in_review', 0)
|
||||
->where('summary.publishedOpportunities', 1)->where('summary.draftOpportunities', 1)
|
||||
->where('summary.activeSectors', 1)->has('summary.recentRequests', 5)
|
||||
->where('summary.recentRequests.0.reference', 'IR-TEST-6')
|
||||
->missing('summary.recentRequests.0.email')->missing('summary.recentRequests.0.message'));
|
||||
$this->actingAs(User::factory()->create())->get(route('dashboard'))->assertInertia(fn (Assert $page) => $page->where('summary', null));
|
||||
}
|
||||
|
||||
public function test_empty_manager_dashboard_has_zero_counts(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->actingAs($user)->get(route('dashboard'))->assertInertia(fn (Assert $page) => $page
|
||||
->where('summary.requestsByStatus.received', 0)->where('summary.publishedOpportunities', 0)
|
||||
->where('summary.activeSectors', 0)->has('summary.recentRequests', 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Course;
|
||||
use App\Models\EducationInvestmentProposal;
|
||||
use App\Models\LabourDemand;
|
||||
use App\Models\Occupation;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\Skill;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\TrainingProvider;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class EducationTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// No fresh migrations or destructive operations: require a prepared isolated DB.
|
||||
$this->assertSame('testing', app()->environment());
|
||||
$this->assertSame('pgsql', DB::connection()->getDriverName());
|
||||
$this->assertStringEndsWith('_test', DB::connection()->getDatabaseName());
|
||||
$this->assertSame(DB::connection()->getDatabaseName(), DB::selectOne('select current_database() as name')->name);
|
||||
DB::beginTransaction();
|
||||
$this->beforeApplicationDestroyed(fn () => DB::rollBack());
|
||||
$this->withoutVite();
|
||||
config(['education.enabled' => true]);
|
||||
}
|
||||
|
||||
private function manager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [...config('portal.managers', []), $user->email]]);
|
||||
$this->actingAs($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function declaration(): array
|
||||
{
|
||||
$territory = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $territory, 'name' => 'Território sintético', 'code' => $territory, 'location_type' => 'district']);
|
||||
|
||||
return [
|
||||
'project_id' => Project::create(['code' => (string) Str::uuid(), 'name' => 'Projecto sintético', 'status' => 'draft'])->id,
|
||||
'occupation_id' => Occupation::create(['code' => (string) Str::uuid(), 'name' => 'Ocupação sintética'])->id,
|
||||
'skill_id' => Skill::create(['code' => (string) Str::uuid(), 'name' => 'Competência sintética'])->id,
|
||||
'geo_location_id' => $territory, 'employer' => 'Empregador sintético', 'qualification' => 'Nível de teste',
|
||||
'quantity' => 100, 'period_start' => now()->addMonths(3)->toDateString(),
|
||||
'period_end' => now()->addMonths(6)->toDateString(), 'reference_date' => now()->toDateString(),
|
||||
'valid_until' => now()->addYear()->toDateString(), 'source' => 'Fonte exclusivamente sintética para teste.',
|
||||
];
|
||||
}
|
||||
|
||||
private function course(): Course
|
||||
{
|
||||
$provider = TrainingProvider::create(['name' => 'Instituição sintética', 'status' => 'candidate']);
|
||||
|
||||
return Course::create(['provider_id' => $provider->id, 'code' => (string) Str::uuid(), 'title' => 'Curso sintético', 'status' => 'draft']);
|
||||
}
|
||||
|
||||
public function test_educational_proposal_requires_review_and_is_a_single_unpublished_canonical_opportunity(): void
|
||||
{
|
||||
$this->manager();
|
||||
$demandData = $this->declaration();
|
||||
$this->post('/management/education/demands', $demandData)->assertSessionHasNoErrors();
|
||||
$demand = LabourDemand::where('project_id', $demandData['project_id'])->firstOrFail();
|
||||
$sector = Sector::create(['name' => 'Sector sintético', 'slug' => (string) Str::uuid(), 'is_active' => true]);
|
||||
$data = ['demand_version' => 1, 'sector_id' => $sector->id, 'title' => 'Oficina sintética',
|
||||
'intervention' => 'Resposta formativa sintética para verificação do fluxo.', 'risks' => 'Custos e viabilidade por confirmar.',
|
||||
'source' => 'Fonte sintética identificada no teste.', 'currency' => 'MZN'];
|
||||
$url = '/management/education/demands/'.$demand->id.'/investment';
|
||||
$this->post($url, $data)->assertUnprocessable();
|
||||
$this->manager();
|
||||
$this->post('/management/education/demands/'.$demand->id.'/review', ['status' => 'reviewed', 'version_no' => 1,
|
||||
'review_reason' => 'Revisão independente sintética.'])->assertSessionHasNoErrors();
|
||||
$this->post($url, $data)->assertConflict();
|
||||
$data['demand_version'] = 2;
|
||||
$this->post($url, [...$data, 'status' => 'published'])->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->post($url, $data)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->assertSame(1, EducationInvestmentProposal::where('labour_demand_id', $demand->id)->count());
|
||||
$proposal = EducationInvestmentProposal::where('labour_demand_id', $demand->id)->firstOrFail();
|
||||
$opportunity = Opportunity::findOrFail($proposal->opportunity_id);
|
||||
$this->assertSame('draft', $opportunity->status);
|
||||
$this->assertNull($opportunity->published_at);
|
||||
$this->assertNull($opportunity->estimated_investment_amount);
|
||||
$this->assertFalse(Opportunity::published()->whereKey($opportunity->id)->exists());
|
||||
$this->assertSame(1, DB::table('audit_events')->where('entity_id', $proposal->id)->count());
|
||||
$this->get('/management/education/demands/'.$demand->id.'/analysis')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('proposal.opportunity_id', $opportunity->id)->where('proposal.demand_version', 2));
|
||||
$this->put('/management/opportunities/'.$opportunity->id, [
|
||||
'sector_id' => $sector->id, 'reference' => $opportunity->reference, 'title' => $opportunity->title,
|
||||
'slug' => $opportunity->slug, 'status' => 'published', 'is_featured' => false, 'estimated_investment_currency' => 'MZN',
|
||||
])->assertSessionHasErrors('status');
|
||||
$this->assertSame('draft', $opportunity->fresh()->status);
|
||||
$this->travel(2)->years();
|
||||
$this->post($url, $data)->assertUnprocessable();
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_education_filters_and_record_indicators_do_not_treat_expired_records_as_current(): void
|
||||
{
|
||||
$this->manager();
|
||||
$data = $this->declaration();
|
||||
$this->post('/management/education/demands', $data)->assertSessionHasNoErrors();
|
||||
$this->get('/management/education?q=Nível&status=submitted&geo_location_id='.$data['geo_location_id'])
|
||||
->assertInertia(fn (AssertableInertia $page) => $page->has('demands.data', 1)
|
||||
->where('indicators.pending_demands', 1)->where('indicators.expired_demands', 0));
|
||||
$this->get('/management/education?q=inexistente')->assertInertia(fn (AssertableInertia $page) => $page->has('demands.data', 0));
|
||||
$this->travel(2)->years();
|
||||
$this->get('/management/education?status=submitted')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->has('demands.data', 0)->where('indicators.pending_demands', 0)->where('indicators.expired_demands', 1));
|
||||
$this->get('/management/education?status=expired')->assertInertia(fn (AssertableInertia $page) => $page->has('demands.data', 1));
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_access_requires_verified_manager_and_enabled_feature(): void
|
||||
{
|
||||
$this->get('/management/education')->assertRedirect('/login');
|
||||
$this->actingAs(User::factory()->create())->get('/management/education')->assertForbidden();
|
||||
$this->manager();
|
||||
config(['education.enabled' => false]);
|
||||
$this->get('/management/education')->assertNotFound();
|
||||
$this->post('/management/education/catalog/skills', ['name' => 'Teste', 'code' => 'TEST'])->assertNotFound();
|
||||
config(['education.enabled' => true]);
|
||||
$this->get('/management/education')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->component('education/index')->where('educationEnabled', true));
|
||||
$this->actingAs(User::factory()->unverified()->create())->get('/management/education')->assertRedirect('/email/verify');
|
||||
}
|
||||
|
||||
public function test_intake_does_not_accept_official_status_or_caller_supplied_reviewer(): void
|
||||
{
|
||||
$user = $this->manager();
|
||||
$data = $this->declaration();
|
||||
$this->post('/management/education/demands', [...$data, 'status' => 'certified', 'reviewed_by' => $user->id])
|
||||
->assertSessionHasNoErrors()->assertRedirect();
|
||||
$demand = LabourDemand::where('project_id', $data['project_id'])->firstOrFail();
|
||||
$this->assertSame('submitted', $demand->status);
|
||||
$this->assertNull($demand->reviewed_by);
|
||||
$this->assertSame($user->id, $demand->submitted_by);
|
||||
$audit = DB::table('audit_events')->where('entity_id', $demand->id)->first();
|
||||
$this->assertNotNull($audit);
|
||||
$this->assertStringNotContainsString($data['source'], $audit->after_data);
|
||||
$this->post('/management/education/demands', [...$data, 'quantity' => -1])->assertSessionHasErrors('quantity');
|
||||
$this->post('/management/education/demands', [...$data, 'period_end' => now()->toDateString()])->assertSessionHasErrors('period_end');
|
||||
Skill::findOrFail($data['skill_id'])->delete();
|
||||
$this->post('/management/education/demands', $data)->assertSessionHasErrors('skill_id');
|
||||
}
|
||||
|
||||
public function test_review_requires_another_person_current_evidence_and_matching_version(): void
|
||||
{
|
||||
$this->manager();
|
||||
$data = $this->declaration();
|
||||
$this->post('/management/education/demands', $data)->assertSessionHasNoErrors();
|
||||
$demand = LabourDemand::where('project_id', $data['project_id'])->firstOrFail();
|
||||
$url = '/management/education/demands/'.$demand->id.'/review';
|
||||
$decision = ['status' => 'reviewed', 'version_no' => 1, 'review_reason' => 'Revisão independente com evidência sintética.'];
|
||||
$this->post($url, $decision)->assertForbidden();
|
||||
$reviewer = $this->manager();
|
||||
$this->post($url, [...$decision, 'status' => 'accredited'])->assertSessionHasErrors('status');
|
||||
$this->post($url, $decision)->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->assertSame($reviewer->id, $demand->fresh()->reviewed_by);
|
||||
$this->assertSame(2, $demand->fresh()->version_no);
|
||||
$this->post($url, $decision)->assertConflict();
|
||||
$this->travel(2)->years();
|
||||
$this->post($url, [...$decision, 'version_no' => 2])->assertUnprocessable();
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_retired_courses_and_inactive_providers_cannot_receive_capacity(): void
|
||||
{
|
||||
$this->manager();
|
||||
$data = $this->declaration();
|
||||
$course = $this->course();
|
||||
$data['course_id'] = $course->id;
|
||||
$this->post('/management/education/capacities', $data)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('training_capacities', ['course_id' => $course->id, 'status' => 'submitted']);
|
||||
$course->update(['status' => 'retired']);
|
||||
$this->post('/management/education/capacities', $data)->assertSessionHasErrors('course_id');
|
||||
$course->update(['status' => 'draft']);
|
||||
TrainingProvider::findOrFail($course->provider_id)->update(['status' => 'inactive']);
|
||||
$this->post('/management/education/capacities', $data)->assertSessionHasErrors('course_id');
|
||||
}
|
||||
|
||||
public function test_catalogue_keeps_institutions_and_courses_nonofficial(): void
|
||||
{
|
||||
$this->manager();
|
||||
$name = 'Instituição sintética '.Str::uuid();
|
||||
$this->post('/management/education/catalog/providers', ['name' => $name, 'status' => 'approved'])
|
||||
->assertRedirect()->assertSessionHasNoErrors();
|
||||
$provider = TrainingProvider::where('name', $name)->firstOrFail();
|
||||
$this->assertSame('candidate', $provider->status);
|
||||
$data = ['provider_id' => $provider->id, 'title' => 'Curso sintético', 'code' => (string) Str::uuid(), 'status' => 'published'];
|
||||
$this->post('/management/education/catalog/courses', $data)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('courses', ['code' => $data['code'], 'status' => 'draft']);
|
||||
$this->post('/management/education/catalog/courses', $data)->assertSessionHasErrors('code');
|
||||
$provider->update(['status' => 'inactive']);
|
||||
$this->post('/management/education/catalog/courses', [...$data, 'code' => (string) Str::uuid()])
|
||||
->assertSessionHasErrors('provider_id');
|
||||
}
|
||||
|
||||
public function test_matching_never_subtracts_training_places_from_workers_and_excludes_unavailable_courses(): void
|
||||
{
|
||||
$submitter = $this->manager();
|
||||
$data = $this->declaration();
|
||||
$this->post('/management/education/demands', $data)->assertSessionHasNoErrors();
|
||||
$demand = LabourDemand::where('project_id', $data['project_id'])->firstOrFail();
|
||||
$course = $this->course();
|
||||
$capacity = $data;
|
||||
unset($capacity['project_id'], $capacity['employer']);
|
||||
$reviewer = $this->manager();
|
||||
TrainingCapacity::create([...$capacity, 'course_id' => $course->id, 'submitted_by' => $submitter->id,
|
||||
'reviewed_by' => $reviewer->id, 'status' => 'reviewed', 'review_reason' => 'Evidência sintética revista.',
|
||||
'period_start' => now()->toDateString(), 'period_end' => $data['period_start']]);
|
||||
$url = '/management/education/demands/'.$demand->id.'/analysis';
|
||||
$this->get($url)->assertInertia(fn (AssertableInertia $page) => $page->where('eligible', false)->has('candidates', 0));
|
||||
$this->post('/management/education/demands/'.$demand->id.'/review', ['status' => 'reviewed', 'version_no' => 1,
|
||||
'review_reason' => 'Revisão independente sintética.'])->assertSessionHasNoErrors();
|
||||
$this->get($url)->assertInertia(fn (AssertableInertia $page) => $page->component('education/analysis')
|
||||
->where('eligible', true)->has('candidates', 1)->where('gap.people', null)->where('gap.state', 'insufficient_data'));
|
||||
$course->delete();
|
||||
$this->get($url)->assertInertia(fn (AssertableInertia $page) => $page->has('candidates', 0)->where('gap.people', null));
|
||||
$this->travel(2)->years();
|
||||
$this->get($url)->assertInertia(fn (AssertableInertia $page) => $page->where('eligible', false)->where('gap.state', 'expired'));
|
||||
$this->travelBack();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ExampleTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_returns_a_successful_response()
|
||||
{
|
||||
$response = $this->get(route('home'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InterestSubmissionTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function payload(): array
|
||||
{
|
||||
return ['fullName' => 'Pessoa de teste', 'email' => 'portal-integration-test@gmail.com',
|
||||
'investorType' => 'empresa', 'country' => 'Moçambique', 'sectorInterest' => 'Energia',
|
||||
'message' => 'Pedido de teste na base isolada.', 'privacyConsent' => true];
|
||||
}
|
||||
|
||||
public function test_replay_reuses_original_confirmation_event_and_notification(): void
|
||||
{
|
||||
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => ['team@example.invalid']]);
|
||||
$headers = ['Idempotency-Key' => (string) Str::uuid()];
|
||||
$first = $this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertCreated();
|
||||
InterestRequest::firstOrFail()->update(['status' => 'closed']);
|
||||
$second = $this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertCreated();
|
||||
$this->assertSame($first->json(), $second->json());
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('interest_submission_receipts', 1);
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
$this->assertDatabaseCount('jobs', 1);
|
||||
$event = DB::table('outbox_events')->first();
|
||||
$this->assertSame('pending', $event->status);
|
||||
$this->assertSame(InterestRequest::firstOrFail()->integration_id, $event->aggregate_id);
|
||||
$this->assertEquals(['schema_version' => 1, 'interest_id' => $event->aggregate_id], json_decode($event->payload, true));
|
||||
$this->assertStringNotContainsString('gmail', $event->payload);
|
||||
}
|
||||
|
||||
public function test_key_reuse_with_changed_payload_is_conflict_and_invalid_keys_are_rejected(): void
|
||||
{
|
||||
$headers = ['Idempotency-Key' => (string) Str::uuid()];
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertCreated();
|
||||
$this->postJson('/api/v1/interest-requests', [...$this->payload(), 'message' => 'Uma mensagem diferente com outros dados.'], $headers)->assertStatus(409);
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), ['Idempotency-Key' => 'unsafe-key'])->assertUnprocessable();
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), ['Idempotency-Key' => ''])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
}
|
||||
|
||||
public function test_old_clients_still_work_and_distinct_keys_create_distinct_submissions(): void
|
||||
{
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload())->assertCreated();
|
||||
foreach ([Str::uuid(), Str::uuid()] as $key) {
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), ['Idempotency-Key' => (string) $key])->assertCreated();
|
||||
}
|
||||
$this->assertDatabaseCount('interest_requests', 3);
|
||||
$this->assertDatabaseCount('outbox_events', 3);
|
||||
$this->assertDatabaseCount('interest_submission_receipts', 2);
|
||||
}
|
||||
|
||||
public function test_event_insert_failure_rolls_back_request_receipt_and_notification(): void
|
||||
{
|
||||
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->assertDatabaseCount('interest_requests', 0);
|
||||
$this->assertDatabaseCount('interest_submission_receipts', 0);
|
||||
$this->assertDatabaseCount('jobs', 0);
|
||||
DB::statement('DROP TRIGGER test_reject_outbox ON outbox_events');
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), $headers)->assertCreated();
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
}
|
||||
|
||||
public function test_schema_rollback_refuses_to_destroy_captured_identities(): void
|
||||
{
|
||||
$this->postJson('/api/v1/interest-requests', $this->payload(), ['Idempotency-Key' => (string) Str::uuid()])->assertCreated();
|
||||
$migration = require database_path('migrations/2026_09_25_120000_add_interest_submission_receipts.php');
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('Preserve submission identities');
|
||||
$migration->down();
|
||||
}
|
||||
|
||||
public function test_accepted_request_can_be_replayed_after_opportunity_is_archived(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Energia', 'slug' => 'energia']);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'INV-REPLAY', 'title' => 'Teste', 'slug' => 'teste-replay',
|
||||
'status' => 'published', 'published_at' => now()->subDay()]);
|
||||
$payload = [...$this->payload(), 'opportunityReference' => $opportunity->reference];
|
||||
$headers = ['Idempotency-Key' => (string) Str::uuid()];
|
||||
$first = $this->postJson('/api/v1/interest-requests', $payload, $headers)->assertCreated();
|
||||
$opportunity->update(['status' => 'archived']);
|
||||
$this->postJson('/api/v1/interest-requests', $payload, $headers)->assertCreated()->assertJsonPath('data.reference', $first->json('data.reference'));
|
||||
$this->postJson('/api/v1/interest-requests', $payload, ['Idempotency-Key' => (string) Str::uuid()])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\InvestorJourney;
|
||||
use App\Models\User;
|
||||
use App\Services\ConvertInterestToLead;
|
||||
use Database\Seeders\InvestmentPortfolioSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentPortfolioTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_document_import_is_idempotent_preserves_edits_and_links_all_anchors(): void
|
||||
{
|
||||
$this->seed(InvestmentPortfolioSeeder::class);
|
||||
$dossier = InvestmentDossier::firstOrFail();
|
||||
$dossier->update(['version_no' => $dossier->version_no, 'title' => 'Revisão humana preservada']);
|
||||
$this->seed(InvestmentPortfolioSeeder::class);
|
||||
$this->assertDatabaseCount('projects', 15);
|
||||
$this->assertDatabaseCount('economic_clusters', 8);
|
||||
$this->assertDatabaseCount('development_corridors', 6);
|
||||
$this->assertDatabaseCount('investment_dossiers', 29);
|
||||
$this->assertSame('Revisão humana preservada', $dossier->fresh()->title);
|
||||
$this->assertSame(15, DB::table('corridor_projects')->distinct()->count('project_id'));
|
||||
$this->assertDatabaseHas('cluster_projects', ['role' => 'anchor']);
|
||||
$this->get('/carteira')->assertInertia(fn (Assert $page) => $page->component('portfolio/index')->has('records.data', 0));
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_stale_editor_cannot_overwrite_or_publish_a_newer_version(): void
|
||||
{
|
||||
$this->seed(InvestmentPortfolioSeeder::class);
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$dossier = InvestmentDossier::firstOrFail();
|
||||
$url = '/management/portfolio/'.$dossier->id;
|
||||
$payload = ['version_no' => $dossier->version_no, 'title' => 'Revisao mais recente', 'source' => $dossier->source, 'content' => $dossier->content];
|
||||
$this->actingAs($manager)->put($url, $payload)->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->putJson($url, [...$payload, 'title' => 'Alteracao obsoleta'])->assertStatus(409);
|
||||
$approval = ['version_no' => $dossier->version_no, 'approval_evidence' => 'Aprovacao sintetica da versao revista'];
|
||||
$this->postJson($url.'/publish', $approval)->assertStatus(409);
|
||||
$this->assertSame('Revisao mais recente', $dossier->fresh()->title);
|
||||
$this->assertSame('draft', $dossier->fresh()->publication_status);
|
||||
$this->assertSame(2, $dossier->fresh()->version_no);
|
||||
$this->post($url.'/publish', [...$approval, 'version_no' => 2])->assertRedirect()->assertSessionHasNoErrors();
|
||||
$this->assertSame(3, $dossier->fresh()->version_no);
|
||||
$this->assertSame('published', $dossier->fresh()->publication_status);
|
||||
$this->postJson($url.'/publish', [...$approval, 'version_no' => 2])->assertStatus(409);
|
||||
$this->putJson($url, array_diff_key($payload, ['version_no' => true]))->assertUnprocessable()->assertJsonValidationErrors('version_no');
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (Assert $page) => $page->missing('record.version_no')->missing('record.approval_evidence'));
|
||||
$audit = DB::table('audit_events')->where('entity_id', $dossier->id)->orderByDesc('created_at')->get();
|
||||
$this->assertCount(2, $audit);
|
||||
$this->assertStringNotContainsString('Aprovacao sintetica', json_encode($audit));
|
||||
}
|
||||
|
||||
private function publish(): InvestmentDossier
|
||||
{
|
||||
$this->seed(InvestmentPortfolioSeeder::class);
|
||||
$editor = User::factory()->create();
|
||||
$reviewer = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email, $reviewer->email]]);
|
||||
$dossier = InvestmentDossier::whereNotNull('project_id')->firstOrFail();
|
||||
$this->actingAs($editor)->put('/management/portfolio/'.$dossier->id,
|
||||
['version_no' => $dossier->version_no, 'title' => $dossier->title, 'source' => $dossier->source, 'content' => $dossier->content])->assertSessionHasNoErrors();
|
||||
$evidence = ['approval_evidence' => 'Autorização fictícia apenas para teste'];
|
||||
$this->post('/management/portfolio/'.$dossier->id.'/publish', [...$evidence, 'version_no' => $dossier->fresh()->version_no])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->assertSame($editor->id, $dossier->fresh()->reviewer_id);
|
||||
$this->actingAs($reviewer)->post('/management/portfolio/'.$dossier->id.'/publish', [...$evidence, 'version_no' => $dossier->fresh()->version_no])->assertSessionHasNoErrors()->assertRedirect();
|
||||
|
||||
return $dossier->fresh();
|
||||
}
|
||||
|
||||
public function test_authorized_manager_can_publish_and_internal_evidence_is_hidden(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (Assert $page) => $page->component('portfolio/show')
|
||||
->where('record.title', $dossier->title)->missing('record.approval_evidence')->missing('record.editor_id')->has('related', 0));
|
||||
$this->put('/management/portfolio/'.$dossier->id, ['version_no' => $dossier->version_no, 'title' => 'Conteúdo alterado', 'source' => $dossier->source, 'content' => $dossier->content])->assertSessionHasNoErrors();
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
$this->actingAs(User::factory()->create())->get('/management/portfolio')->assertForbidden();
|
||||
$this->post('/management/portfolio/'.$dossier->id.'/publish', ['approval_evidence' => 'Tentativa sem privilégios de gestão'])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_owner_approval_publishes_document_once_and_preserves_later_edits(): void
|
||||
{
|
||||
$approval = 'Aprovação expressa do proprietário para executar a carteira v4.';
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->assertSame(29, InvestmentDossier::where('publication_status', 'published')->count());
|
||||
$this->assertSame(29, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$dossier = InvestmentDossier::firstOrFail();
|
||||
$this->get('/carteira/'.$dossier->id)->assertInertia(fn (Assert $page) => $page
|
||||
->missing('record.approval_evidence')->missing('record.approval_basis'));
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->assertSame(29, DB::table('audit_events')->where('action', 'owner_approved')->count());
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$this->actingAs($editor)->put('/management/portfolio/'.$dossier->id, [
|
||||
'version_no' => $dossier->version_no, 'title' => 'Alteração posterior', 'source' => $dossier->source, 'content' => $dossier->content,
|
||||
])->assertSessionHasNoErrors();
|
||||
$this->artisan('portfolio:import', ['--approval' => $approval])->assertSuccessful();
|
||||
$this->assertSame('draft', $dossier->fresh()->publication_status);
|
||||
$this->assertSame('Alteração posterior', $dossier->fresh()->title);
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_personal_journey_is_isolated_and_retries_do_not_duplicate_interest_or_event(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
$owner = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
$this->actingAs($owner)->post('/investidor/guardar/'.$dossier->id)->assertRedirect('/investidor');
|
||||
$this->post('/investidor/guardar/'.$dossier->id)->assertRedirect();
|
||||
$this->assertDatabaseCount('investor_journeys', 1);
|
||||
$journey = InvestorJourney::firstOrFail();
|
||||
$payload = ['message' => 'Pretendo investir neste projecto de teste.', 'country' => 'Moçambique', 'privacy_consent' => true, 'role' => 'investir', 'horizon' => '12 meses'];
|
||||
$url = '/investidor/'.$journey->id.'/interesse';
|
||||
$this->post($url, [...$payload, 'privacy_consent' => false])->assertSessionHasErrors('privacy_consent');
|
||||
$this->actingAs($other)->post($url, $payload)->assertNotFound();
|
||||
$this->get('/investidor')->assertInertia(fn (Assert $page) => $page->has('journeys', 0));
|
||||
$this->actingAs($owner)->post($url, $payload)->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->post($url, $payload)->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
$this->assertDatabaseHas('investor_journeys', ['id' => $journey->id, 'status' => 'active']);
|
||||
$metadata = json_decode(DB::table('interest_requests')->value('metadata'), true);
|
||||
$this->assertSame($journey->id, $metadata['journey_id']);
|
||||
$this->assertSame($dossier->project_id, $metadata['project_id']);
|
||||
$this->get('/investidor')->assertInertia(fn (Assert $page) => $page->has('journeys', 1)->where('journeys.0.request_status', 'received'));
|
||||
$conversion = ['owner_user_id' => $owner->id, 'title' => 'Interesse da jornada', 'next_action' => 'Contactar investidor', 'due_at' => now()->addDay()->toIso8601String()];
|
||||
$interest = InterestRequest::firstOrFail();
|
||||
try {
|
||||
app(ConvertInterestToLead::class)->convert($interest, $conversion, $owner->id);
|
||||
$this->fail('A conversão deve preservar o investidor da jornada.');
|
||||
} catch (ValidationException $exception) {
|
||||
$this->assertArrayHasKey('investor_id', $exception->errors());
|
||||
}
|
||||
$lead = app(ConvertInterestToLead::class)->convert($interest, [...$conversion, 'investor_id' => $journey->investor_id], $owner->id);
|
||||
$this->assertSame($journey->investor_id, $lead->investor_id);
|
||||
$this->assertDatabaseCount('investors', 1);
|
||||
}
|
||||
|
||||
public function test_unpublished_and_deleted_entities_cannot_start_journeys(): void
|
||||
{
|
||||
$dossier = $this->publish();
|
||||
DB::table('projects')->where('id', $dossier->project_id)->update(['deleted_at' => now()]);
|
||||
$this->get('/carteira/'.$dossier->id)->assertNotFound();
|
||||
$this->post('/investidor/guardar/'.$dossier->id)->assertNotFound();
|
||||
$this->assertDatabaseCount('investor_journeys', 0);
|
||||
}
|
||||
|
||||
public function test_origin_context_is_validated_and_preserved_in_the_interest(): void
|
||||
{
|
||||
$project = $this->publish();
|
||||
$corridorId = DB::table('corridor_projects')->where('project_id', $project->project_id)->value('corridor_id');
|
||||
$origin = InvestmentDossier::where('corridor_id', $corridorId)->firstOrFail();
|
||||
$origin->update(['editor_id' => $project->editor_id, 'reviewer_id' => $project->reviewer_id,
|
||||
'publication_status' => 'published', 'published_at' => now(), 'approval_evidence' => 'Teste de contexto autorizado']);
|
||||
$other = InvestmentDossier::whereNotNull('project_id')->where('id', '!=', $project->id)->firstOrFail();
|
||||
$other->update(['editor_id' => $project->editor_id, 'reviewer_id' => $project->reviewer_id,
|
||||
'publication_status' => 'published', 'published_at' => now(), 'approval_evidence' => 'Teste de contexto autorizado']);
|
||||
$this->actingAs(User::factory()->create())->post('/investidor/guardar/'.$project->id, ['origin_id' => $other->id])->assertStatus(422);
|
||||
$this->post('/investidor/guardar/'.$project->id, ['origin_id' => $origin->id])->assertRedirect();
|
||||
$journey = InvestorJourney::firstOrFail();
|
||||
$this->post('/investidor/'.$journey->id.'/interesse', ['message' => 'Participar no corredor através deste projecto.',
|
||||
'country' => 'Moçambique', 'privacy_consent' => true, 'role' => 'financiar', 'horizon' => '24 meses'])->assertSessionHasNoErrors();
|
||||
$metadata = json_decode(DB::table('interest_requests')->value('metadata'), true);
|
||||
$this->assertSame($origin->corridor_id, $metadata['corridor_id']);
|
||||
$this->assertSame($project->project_id, $metadata['project_id']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\EconomicCluster;
|
||||
use App\Models\Project;
|
||||
use App\Models\User;
|
||||
use App\Models\ValueChain;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentStructureTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function manager(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->actingAs($user);
|
||||
}
|
||||
|
||||
public function test_project_validates_money_dates_and_duplicate_codes_without_precision_loss(): void
|
||||
{
|
||||
$this->manager();
|
||||
$data = ['code' => 'P-001', 'name' => 'Projecto de teste', 'status' => 'planned',
|
||||
'budget_amount' => '999999999999999999.99', 'budget_currency' => 'MZN',
|
||||
'start_date' => '2026-10-01', 'end_date' => '2026-11-01'];
|
||||
$this->post('/management/projects', [...$data, 'end_date' => '2026-09-01'])->assertSessionHasErrors('end_date');
|
||||
$this->post('/management/projects', [...$data, 'budget_currency' => ''])->assertSessionHasErrors('budget_currency');
|
||||
$this->post('/management/projects', $data)->assertSessionHasNoErrors()->assertRedirect();
|
||||
$project = Project::firstOrFail();
|
||||
$this->assertSame($data['budget_amount'], $project->budget_amount);
|
||||
$this->post('/management/projects', $data)->assertSessionHasErrors('code');
|
||||
$this->put('/management/projects/'.$project->id, [...$data, 'status' => 'active'])->assertSessionHasNoErrors();
|
||||
$this->get('/management/projects/'.$project->id.'/edit')->assertOk();
|
||||
$this->get('/management/projects?q=P-001')->assertOk();
|
||||
$this->assertDatabaseCount('projects', 1);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('entity_type', 'projects')->count());
|
||||
}
|
||||
|
||||
public function test_cluster_membership_is_idempotent_and_role_changes_are_audited(): void
|
||||
{
|
||||
$this->manager();
|
||||
$this->post('/management/clusters', ['code' => 'C-001', 'name' => 'Cluster de teste', 'sector' => 'Energia', 'status' => 'planned'])->assertSessionHasNoErrors();
|
||||
$cluster = EconomicCluster::firstOrFail();
|
||||
$project = Project::factory()->create();
|
||||
$url = '/management/clusters/'.$cluster->id.'/projects';
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasNoErrors();
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseCount('cluster_projects', 1);
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'supporting'])->assertSessionHasNoErrors();
|
||||
$this->assertDatabaseHas('cluster_projects', ['project_id' => $project->id, 'role' => 'supporting']);
|
||||
$this->assertSame(2, DB::table('audit_events')->where('entity_type', 'cluster_projects')->count());
|
||||
$project->delete();
|
||||
$this->post($url, ['project_id' => $project->id, 'role' => 'anchor'])->assertSessionHasErrors('project_id');
|
||||
$this->get('/management/clusters/'.$cluster->id.'/edit')->assertOk();
|
||||
}
|
||||
|
||||
public function test_chain_edit_cannot_cross_cluster_and_codes_are_unique_per_cluster(): void
|
||||
{
|
||||
$this->manager();
|
||||
$first = EconomicCluster::create(['code' => 'C1', 'name' => 'Primeiro', 'sector' => 'Energia', 'status' => 'planned']);
|
||||
$second = EconomicCluster::create(['code' => 'C2', 'name' => 'Segundo', 'sector' => 'Agro', 'status' => 'planned']);
|
||||
$data = ['code' => 'INPUT', 'name' => 'Insumos', 'stage' => 'input'];
|
||||
$this->post('/management/clusters/'.$first->id.'/chains', $data)->assertSessionHasNoErrors();
|
||||
$chain = ValueChain::firstOrFail();
|
||||
$this->post('/management/clusters/'.$first->id.'/chains', $data)->assertSessionHasErrors('code');
|
||||
$this->post('/management/clusters/'.$second->id.'/chains', $data)->assertSessionHasNoErrors();
|
||||
$this->put('/management/clusters/'.$second->id.'/chains/'.$chain->id, [...$data, 'name' => 'Alterado'])->assertNotFound();
|
||||
$this->assertSame('Insumos', $chain->fresh()->name);
|
||||
$this->put('/management/clusters/'.$first->id.'/chains/'.$chain->id, [...$data, 'stage' => 'processing'])->assertSessionHasNoErrors();
|
||||
$this->assertSame('processing', $chain->fresh()->stage);
|
||||
}
|
||||
|
||||
public function test_structure_management_requires_authorised_verified_manager(): void
|
||||
{
|
||||
$this->get('/management/clusters')->assertRedirect('/login');
|
||||
$this->actingAs(User::factory()->create());
|
||||
$this->get('/management/projects')->assertForbidden();
|
||||
$this->post('/management/clusters', [])->assertForbidden();
|
||||
$this->assertDatabaseCount('economic_clusters', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\InvestmentReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentUnificationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function option(string $group, string $code): int
|
||||
{
|
||||
return DB::table('investment_reference_options')->where('group', $group)->where('code', $code)->value('id');
|
||||
}
|
||||
|
||||
private function opportunity(): Opportunity
|
||||
{
|
||||
$sector = Sector::firstOrCreate(['slug' => 'test-sector'], ['name' => 'Sector sintético', 'is_active' => true]);
|
||||
|
||||
return Opportunity::create(['sector_id' => $sector->id, 'reference' => (string) Str::uuid(), 'slug' => (string) Str::uuid(),
|
||||
'title' => 'Oportunidade sintética', 'status' => 'published', 'published_at' => now()->subMinute(), 'province' => 'Gaza',
|
||||
'estimated_investment_amount' => 1000, 'estimated_investment_currency' => 'USD']);
|
||||
}
|
||||
|
||||
private function payload(int $version = 1): array
|
||||
{
|
||||
return ['version' => $version, 'payload' => ['full_name' => 'Pessoa de teste', 'email' => 'test@example.com', 'country' => 'Moçambique',
|
||||
'profile_id' => $this->option('investor_profile', 'individual'), 'sector' => 'Educação',
|
||||
'objective' => 'Criar uma oficina de formação exclusivamente sintética.', 'participation_id' => $this->option('participation', 'invest'),
|
||||
'horizon' => '12 meses', 'contact_consent' => true], 'needs' => [['category_id' => $this->option('need_category', 'education'),
|
||||
'option_id' => $this->option('education', 'laboratory'), 'quantity' => 2, 'unit_id' => $this->option('unit', 'units'),
|
||||
'priority_id' => $this->option('priority', 'normal'), 'details' => ['description' => 'Laboratórios sintéticos para formação']]]];
|
||||
}
|
||||
|
||||
public function test_submission_is_versioned_encrypted_private_and_idempotently_integrated(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$user = User::factory()->create();
|
||||
$opportunity = $this->opportunity();
|
||||
$id = $this->actingAs($user)->postJson('/api/v1/investment/submissions', ['opportunity_id' => $opportunity->id])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertJsonPath('submission.payload.sector', 'Sector sintético')->assertJsonPath('submission.payload.location', 'Gaza');
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $this->payload())->assertOk()->assertJsonPath('version', 2);
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $this->payload())->assertConflict();
|
||||
$this->assertStringNotContainsString('test@example.com', DB::table('investment_submissions')->where('id', $id)->value('payload'));
|
||||
$this->assertStringNotContainsString('Laboratórios', DB::table('investment_specific_needs')->value('details'));
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/investment/submissions/'.$id)->assertNotFound();
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload(2))->assertNotFound();
|
||||
$this->actingAs($user)->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload(2))->assertOk();
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload(2))->assertOk();
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$this->assertDatabaseCount('outbox_events', 1);
|
||||
$this->assertSame($id, InterestRequest::firstOrFail()->metadata['submission_id']);
|
||||
$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->assertSame(3, DB::table('investment_submission_events')->where('submission_id', $id)->count());
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $this->payload(3))->assertConflict();
|
||||
}
|
||||
|
||||
public function test_invalid_reference_group_consent_and_unpublished_target_are_rejected(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$user = User::factory()->create();
|
||||
$opportunity = $this->opportunity();
|
||||
$id = $this->actingAs($user)->postJson('/api/v1/investment/submissions', ['opportunity_id' => $opportunity->id])->json('id');
|
||||
$data = $this->payload();
|
||||
$data['needs'][0]['option_id'] = $this->option('infrastructure', 'energy');
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $data)->assertUnprocessable();
|
||||
$data = $this->payload();
|
||||
$data['payload']['contact_consent'] = false;
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $data)->assertUnprocessable();
|
||||
$data = $this->payload();
|
||||
$data['payload']['participation_id'] = $this->option('participation', 'other');
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $data)->assertUnprocessable();
|
||||
$opportunity->update(['status' => 'draft']);
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload())->assertNotFound();
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
}
|
||||
|
||||
public function test_attachments_are_private_and_content_changes_are_blocked(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$user = User::factory()->create();
|
||||
$id = $this->actingAs($user)->postJson('/api/v1/investment/submissions')->assertCreated()->json('id');
|
||||
$this->post('/investidor/manifestacoes/'.$id.'/attachments', ['version' => '1',
|
||||
'file' => UploadedFile::fake()->createWithContent('nota.txt', 'Anexo privado de teste')])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$attachment = DB::table('investment_submission_attachments')->first();
|
||||
$document = DB::table('documents')->where('id', $attachment->document_id)->first();
|
||||
$url = '/investidor/manifestacoes/'.$id.'/attachments/'.$attachment->id;
|
||||
$this->get($url)->assertDownload('nota.txt');
|
||||
$this->assertSame('confidential', $document->data_classification);
|
||||
$this->actingAs(User::factory()->create())->get($url)->assertNotFound();
|
||||
Storage::disk('local')->put($document->storage_key, 'Alteração');
|
||||
$this->actingAs($user)->get($url)->assertNotFound();
|
||||
$this->assertSame(2, InvestmentSubmission::findOrFail($id)->version);
|
||||
}
|
||||
|
||||
public function test_context_editing_combined_facets_and_education_discovery(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$opportunity = $this->opportunity();
|
||||
$facet = $this->option('education', 'laboratory');
|
||||
$data = ['version' => 0, 'is_education' => true, 'facets' => [$facet], 'source_reference' => 'Fonte exclusivamente sintética'];
|
||||
$url = '/api/v1/investment/admin/opportunities/'.$opportunity->id.'/context';
|
||||
$this->actingAs($manager)->putJson($url, $data)->assertOk()->assertJsonPath('version', 1);
|
||||
$this->assertSame('draft', $opportunity->fresh()->status);
|
||||
$this->putJson($url, $data)->assertConflict();
|
||||
$this->getJson('/api/v1/investment/search?education=1')->assertJsonPath('total', 0);
|
||||
$opportunity->refresh()->update(['status' => 'published', 'published_at' => now()]);
|
||||
$this->getJson('/api/v1/investment/search?education=1&province=Gaza&facets[]='.$facet)->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson('/api/v1/investment/search?education=1&province=Maputo')->assertJsonPath('total', 0);
|
||||
$this->get('/educacao')->assertInertia(fn (Assert $page) => $page->where('filters.education', true)->has('results.data', 1));
|
||||
$this->actingAs(User::factory()->create())->putJson($url, [...$data, 'version' => 1])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_map_discloses_only_public_coordinates_of_published_opportunities(): void
|
||||
{
|
||||
$opportunity = $this->opportunity();
|
||||
$id = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert(['id' => $id, 'code' => $id, 'name' => 'Local de teste', 'location_type' => 'site', 'data_classification' => 'public']);
|
||||
DB::table('opportunity_locations')->insert(['opportunity_id' => $opportunity->id, 'geo_location_id' => $id]);
|
||||
DB::statement("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom,data_classification) VALUES(?, 'point', ST_SetSRID(ST_MakePoint(32,-25),4326), 'public')", [$id]);
|
||||
$this->getJson('/api/v1/investment/map')->assertOk()->assertJsonCount(1, 'features');
|
||||
DB::table('geo_geometries')->where('geo_location_id', $id)->update(['data_classification' => 'restricted']);
|
||||
$this->getJson('/api/v1/investment/map')->assertJsonCount(0, 'features');
|
||||
DB::table('geo_geometries')->where('geo_location_id', $id)->update(['data_classification' => 'public']);
|
||||
$opportunity->update(['status' => 'draft']);
|
||||
$this->getJson('/api/v1/investment/map')->assertJsonCount(0, 'features');
|
||||
}
|
||||
|
||||
public function test_territorial_filters_intersect_and_hide_withdrawn_relations(): void
|
||||
{
|
||||
$this->artisan('portfolio:import', ['--approval' => 'Autorização sintética exclusivamente para teste.'])->assertSuccessful();
|
||||
$clusters = InvestmentDossier::whereNotNull('cluster_id')->limit(2)->get();
|
||||
$corridor = InvestmentDossier::whereNotNull('corridor_id')->firstOrFail();
|
||||
$opportunity = $this->opportunity();
|
||||
foreach ($clusters as $cluster) {
|
||||
DB::table('opportunity_clusters')->insert(['opportunity_id' => $opportunity->id, 'cluster_id' => $cluster->cluster_id]);
|
||||
}
|
||||
DB::table('opportunity_corridors')->insert(['opportunity_id' => $opportunity->id, 'corridor_id' => $corridor->corridor_id]);
|
||||
$url = '/api/v1/investment/search?cluster_id='.$clusters[0]->cluster_id.'&corridor_id='.$corridor->corridor_id;
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson($url.'&province=Maputo')->assertJsonPath('total', 0);
|
||||
$this->getJson('/api/v1/investment/search?cluster_id='.$clusters[1]->cluster_id)->assertJsonPath('total', 1);
|
||||
$clusters[0]->update(['publication_status' => 'draft']);
|
||||
$this->getJson($url)->assertJsonPath('total', 0);
|
||||
$this->getJson('/api/v1/investment/opportunities/'.$opportunity->slug)->assertJsonCount(1, 'context.clusters');
|
||||
$this->getJson('/api/v1/investment/references')->assertJsonMissing(['id' => $clusters[0]->cluster_id]);
|
||||
}
|
||||
|
||||
public function test_favourites_comparison_and_csv_respect_publication_and_ownership(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$opportunity = $this->opportunity();
|
||||
$opportunity->update(['title' => '=FORMULA()']);
|
||||
$this->actingAs($user)->postJson('/api/v1/investment/favourites/'.$opportunity->id, ['saved' => true])->assertOk();
|
||||
$this->postJson('/api/v1/investment/favourites/'.$opportunity->id, ['saved' => true])->assertOk();
|
||||
$this->assertDatabaseCount('opportunity_favourites', 1);
|
||||
$this->getJson('/api/v1/investment/compare?ids[]='.$opportunity->id)->assertOk()->assertJsonCount(1, 'records');
|
||||
$this->assertStringContainsString("'=FORMULA()", $this->get('/api/v1/investment/export')->assertOk()->streamedContent());
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/investment/submissions')->assertJsonCount(0, 'favourites');
|
||||
$opportunity->update(['status' => 'draft']);
|
||||
$this->getJson('/api/v1/investment/compare?ids[]='.$opportunity->id)->assertNotFound();
|
||||
$this->postJson('/api/v1/investment/favourites/'.$opportunity->id, ['saved' => true])->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_reference_updates_preserve_codes_and_other_option(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$id = $this->option('education', 'other');
|
||||
$data = ['group' => 'education', 'code' => 'other', 'label' => 'Outro — detalhar', 'active' => true, 'requires_description' => true, 'sort_order' => 1];
|
||||
$this->actingAs($user)->postJson('/api/v1/investment/admin/references/'.$id, $data)->assertOk();
|
||||
$this->postJson('/api/v1/investment/admin/references/'.$id, [...$data, 'active' => false])->assertUnprocessable();
|
||||
$this->postJson('/api/v1/investment/admin/references/'.$id, [...$data, 'code' => 'changed'])->assertUnprocessable();
|
||||
$count = DB::table('investment_reference_options')->count();
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$this->assertSame($count, DB::table('investment_reference_options')->count());
|
||||
$this->assertSame('Outro — detalhar', DB::table('investment_reference_options')->where('id', $id)->value('label'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\InvestmentReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentWorkspaceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function draft(User $user): string
|
||||
{
|
||||
return $this->actingAs($user)->postJson('/api/v1/investment/submissions')->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function payload(int $version = 1): array
|
||||
{
|
||||
return ['version' => $version, 'payload' => ['full_name' => 'Investidor sintético', 'email' => 'qa@example.test', 'country' => 'Moçambique',
|
||||
'profile_id' => DB::table('investment_reference_options')->where('group', 'investor_profile')->where('code', 'individual')->value('id'),
|
||||
'participation_id' => DB::table('investment_reference_options')->where('group', 'participation')->where('code', 'invest')->value('id'),
|
||||
'sector' => 'Educação', 'objective' => 'Objectivo exclusivamente sintético para teste.', 'horizon' => '12 meses', 'contact_consent' => true], 'needs' => []];
|
||||
}
|
||||
|
||||
public function test_profile_and_company_are_private_versioned_and_do_not_grant_organization_access(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user)->putJson('/api/v1/investment/profile', ['version' => 0, 'payload' => ['country' => 'Moçambique', 'phone' => '123456', 'sector' => 'Educação']])->assertOk()->assertJsonPath('version', 1);
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 0, 'payload' => ['country' => 'Outro']])->assertConflict();
|
||||
$data = ['version' => 0, 'payload' => ['name' => 'Empresa sintética', 'country' => 'Moçambique', 'role' => 'Representante declarado']];
|
||||
$company = $this->postJson('/api/v1/investment/companies', $data)->assertOk()->json('id');
|
||||
$id = $this->postJson('/api/v1/investment/submissions', ['company_id' => $company])->assertCreated()->json('id');
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertJsonPath('submission.payload.organisation', 'Empresa sintética')->assertJsonPath('submission.payload.phone', '123456');
|
||||
$this->assertStringNotContainsString('Empresa sintética', DB::table('investment_company_declarations')->value('payload'));
|
||||
$this->assertStringNotContainsString('123456', DB::table('investment_accounts')->value('payload'));
|
||||
$this->assertDatabaseCount('memberships', 0);
|
||||
$this->assertDatabaseCount('organizations', 0);
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->get('/management/history')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->has('events.data', 3)->where('events.data.0.after_data.values.version', 1));
|
||||
$this->actingAs(User::factory()->create())->getJson('/api/v1/investment/profile')->assertJsonCount(0, 'companies');
|
||||
$this->postJson('/api/v1/investment/companies/'.$company, [...$data, 'version' => 1])->assertNotFound();
|
||||
$this->postJson('/api/v1/investment/submissions', ['company_id' => $company])->assertNotFound();
|
||||
$this->putJson('/api/v1/investment/profile', ['version' => 0, 'payload' => ['is_admin' => true]])->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_conversation_is_encrypted_authorized_and_idempotent_with_private_notifications(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$owner = User::factory()->create();
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$id = $this->draft($owner);
|
||||
$message = ['client_key' => (string) Str::uuid(), 'body' => 'Mensagem privada sintética do investidor.'];
|
||||
$url = '/api/v1/investment/submissions/'.$id.'/messages';
|
||||
$this->postJson($url, $message)->assertConflict();
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload())->assertOk();
|
||||
$first = $this->postJson($url, $message)->assertOk()->json('id');
|
||||
$this->postJson($url, $message)->assertJsonPath('id', $first);
|
||||
$this->postJson($url, [...$message, 'body' => 'Outro conteúdo com a mesma chave.'])->assertConflict();
|
||||
$this->assertDatabaseCount('investment_messages', 1);
|
||||
$this->assertStringNotContainsString('Mensagem privada', DB::table('investment_messages')->value('body'));
|
||||
$this->actingAs($manager)->getJson('/api/v1/investment/notifications')->assertJsonPath('unread', 1);
|
||||
$this->postJson($url, ['client_key' => (string) Str::uuid(), 'body' => 'Resposta sintética da equipa.'])->assertOk();
|
||||
$this->actingAs($owner)->getJson('/api/v1/investment/notifications')->assertJsonPath('unread', 2);
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertJsonCount(2, 'messages')->assertJsonPath('messages.1.sender_role', 'support');
|
||||
$notification = DB::table('investment_notifications')->where('user_id', $owner->id)->first();
|
||||
$this->postJson('/api/v1/investment/notifications/'.$notification->id.'/read')->assertOk();
|
||||
$this->getJson('/api/v1/investment/notifications')->assertJsonPath('unread', 1);
|
||||
$this->actingAs(User::factory()->create())->postJson($url, $message)->assertNotFound();
|
||||
$this->postJson('/api/v1/investment/notifications/'.$notification->id.'/read')->assertNotFound();
|
||||
config(['portal.managers' => []]);
|
||||
$this->actingAs($manager)->getJson('/api/v1/investment/notifications')->assertJsonCount(0, 'notifications.data');
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_revisions_preserve_encrypted_prior_values_without_exposing_them_to_other_users(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$owner = User::factory()->create();
|
||||
$id = $this->draft($owner);
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $this->payload())->assertOk();
|
||||
$next = $this->payload(2);
|
||||
$next['payload']['objective'] = 'Objectivo posterior exclusivamente sintético.';
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $next)->assertOk();
|
||||
$this->assertDatabaseCount('investment_submission_revisions', 3);
|
||||
$url = '/api/v1/investment/submissions/'.$id.'/revisions/2';
|
||||
$this->getJson($url)->assertOk()->assertJsonPath('snapshot.payload.objective', $this->payload()['payload']['objective'])->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->assertStringNotContainsString('Objectivo', DB::table('investment_submission_revisions')->where('version', 2)->value('snapshot'));
|
||||
$this->actingAs(User::factory()->create())->getJson($url)->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_status_review_notifies_owner_once_per_effective_change(): void
|
||||
{
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$owner = User::factory()->create();
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$id = $this->draft($owner);
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', $this->payload())->assertOk();
|
||||
$interest = InterestRequest::firstOrFail();
|
||||
$this->actingAs($manager)->patch('/management/interests/'.$interest->id, ['status' => 'in_review'])->assertRedirect();
|
||||
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review'])->assertRedirect();
|
||||
$this->patchJson('/api/v1/investment/admin/interests/'.$interest->id.'/status', ['status' => 'in_review'])->assertOk()->assertJsonPath('status', 'in_review');
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
$this->actingAs($owner)->getJson('/api/v1/investment/notifications')->assertJsonPath('unread', 2);
|
||||
}
|
||||
|
||||
public function test_incomplete_text_can_be_saved_as_draft_but_cannot_be_submitted(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$id = $this->draft($owner);
|
||||
$partial = ['version' => 1, 'payload' => ['full_name' => 'A', 'email' => 'parcial@', 'objective' => 'Ideia']];
|
||||
$this->putJson('/api/v1/investment/submissions/'.$id, $partial)->assertOk()->assertJsonPath('version', 2);
|
||||
$this->getJson('/api/v1/investment/submissions/'.$id)->assertJsonPath('submission.payload.email', 'parcial@');
|
||||
$this->postJson('/api/v1/investment/submissions/'.$id.'/submit', [...$partial, 'version' => 2])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Project;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Database\Seeders\InvestmentReferenceSeeder;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
class InvestmentZoneTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function manager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$user->forceFill(['two_factor_secret' => Crypt::encryptString('SYNTHETIC'), 'two_factor_confirmed_at' => now()])->save();
|
||||
config(['portal.managers' => [...config('portal.managers', []), $user->email]]);
|
||||
foreach (['legal_reviewers', 'gis_reviewers', 'publishers'] as $role) {
|
||||
config(['investment-zones.'.$role => [...config('investment-zones.'.$role, []), $user->email]]);
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
public function test_private_drafts_require_mfa_and_preserve_encrypted_immutable_revisions(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$url = '/api/v2/investment/admin/zones';
|
||||
$payload = ['code' => 'SYNTHETIC-ZEE', 'name' => 'Synthetic private zone', 'category' => 'zee'];
|
||||
$this->actingAs($user)->postJson($url, $payload)->assertForbidden();
|
||||
$this->actingAs($this->manager());
|
||||
$id = $this->postJson($url, $payload)->assertCreated()->json('id');
|
||||
$this->getJson('/api/v2/investment/zones')->assertJsonPath('records.total', 0);
|
||||
$this->postJson($url.'/'.$id, [...$payload, '_method' => 'PUT', 'version_no' => 1, 'name' => 'Changed synthetic zone'])->assertOk()->assertJsonPath('version_no', 2);
|
||||
$this->putJson($url.'/'.$id, [...$payload, 'version_no' => 1])->assertConflict();
|
||||
$this->postJson($url.'/'.$id.'/publish', ['version_no' => 2])->assertForbidden();
|
||||
$this->actingAs($this->manager())->postJson($url.'/'.$id.'/publish', ['version_no' => 2])->assertUnprocessable();
|
||||
$this->assertDatabaseCount('investment_zone_revisions', 2);
|
||||
$snapshot = DB::table('investment_zone_revisions')->where('zone_id', $id)->where('version_no', 1)->value('snapshot');
|
||||
$this->assertStringNotContainsString('Synthetic private zone', $snapshot);
|
||||
$this->assertStringContainsString('Synthetic private zone', Crypt::decryptString($snapshot));
|
||||
DB::statement('SAVEPOINT immutable_check');
|
||||
try {
|
||||
DB::table('investment_zone_revisions')->where('zone_id', $id)->delete();
|
||||
$this->fail('Revisions must reject deletion.');
|
||||
} catch (QueryException $e) {
|
||||
DB::statement('ROLLBACK TO SAVEPOINT immutable_check');
|
||||
$this->assertStringContainsString('Zone revisions are immutable', $e->getMessage());
|
||||
}
|
||||
$this->actingAs(User::factory()->create())->getJson($url.'/'.$id.'/revisions')->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_rollback_refuses_populated_foundation_and_empty_rollback_is_reversible(): void
|
||||
{
|
||||
$migration = require database_path('migrations/2026_09_28_100000_investment_zone_foundation.php');
|
||||
$originMigration = require database_path('migrations/2026_09_28_120000_investment_submission_zones.php');
|
||||
$geometryMigration = require database_path('migrations/2026_09_28_110000_zone_geometry_review.php');
|
||||
$originMigration->down();
|
||||
$geometryMigration->down();
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
$geometryMigration->up();
|
||||
$originMigration->up();
|
||||
$this->assertTrue(Schema::hasTable('investment_zone_links'));
|
||||
$this->actingAs($this->manager())->postJson('/api/v2/investment/admin/zones', ['code' => 'QA', 'name' => 'Synthetic', 'category' => 'pending'])->assertCreated();
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Populated rollback must refuse.');
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->assertStringContainsString('Zone data exists', $e->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('investment_zones', 1);
|
||||
}
|
||||
|
||||
public function test_validated_relations_filter_the_same_opportunity_and_revoked_sources_disappear(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
$reviewer = $this->manager();
|
||||
$this->actingAs($editor);
|
||||
$source = $this->postJson('/api/v2/investment/admin/legal-sources', [
|
||||
'title' => 'Synthetic legal evidence', 'url' => 'https://example.test/legal', 'diploma' => 'TEST ONLY',
|
||||
'article' => 'Synthetic article', 'competent_entity' => 'Synthetic authority', 'valid_from' => today()->subDay()->toDateString(),
|
||||
])->assertCreated()->json('id');
|
||||
$this->postJson('/api/v2/investment/admin/legal-sources/'.$source.'/validate', ['version_no' => 1])->assertForbidden();
|
||||
$this->actingAs($reviewer)->postJson('/api/v2/investment/admin/legal-sources/'.$source.'/validate', ['version_no' => 1])->assertOk();
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'Synthetic operator', 'organization_type' => 'private']);
|
||||
$sector = Sector::create(['slug' => 'qa-zone-sector', 'name' => 'Synthetic sector', 'is_active' => true]);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'QA-ZONE', 'slug' => 'qa-zone', 'title' => 'Synthetic investment', 'status' => 'published', 'published_at' => now()->subMinute()]);
|
||||
$zoneIds = [];
|
||||
foreach (['zee', 'zfi'] as $category) {
|
||||
$this->actingAs($editor);
|
||||
$zoneId = $this->postJson('/api/v2/investment/admin/zones', ['code' => 'QA-'.$category, 'name' => 'Synthetic '.$category,
|
||||
'category' => $category, 'name_en' => 'Synthetic zone', 'description' => 'Synthetic description', 'description_en' => 'Synthetic description',
|
||||
'operator_id' => $organization, 'legal_source_id' => $source])->assertCreated()->json('id');
|
||||
$linkPayload = ['opportunity_id' => $opportunity->id, 'association_type' => 'potential', 'role' => 'potential',
|
||||
'source_reference' => 'Synthetic relationship evidence', 'justification' => 'Synthetic potential investment', 'valid_from' => today()->toDateString()];
|
||||
$link = $this->postJson('/api/v2/investment/admin/zones/'.$zoneId.'/links', $linkPayload)->assertCreated()->json('id');
|
||||
$this->postJson('/api/v2/investment/admin/zones/'.$zoneId.'/links', $linkPayload)->assertConflict();
|
||||
$this->postJson('/api/v2/investment/admin/zone-links/'.$link.'/validate', ['version_no' => 1])->assertForbidden();
|
||||
$this->actingAs($reviewer)->postJson('/api/v2/investment/admin/zone-links/'.$link.'/validate', ['version_no' => 1])->assertOk();
|
||||
$this->postJson('/api/v2/investment/admin/zones/'.$zoneId.'/publish', ['version_no' => 1])->assertOk();
|
||||
$zoneIds[$category.'_id'] = $zoneId;
|
||||
$this->actingAs($editor);
|
||||
$geometry = $this->postJson('/api/v2/investment/admin/zones/'.$zoneId.'/geometries', [
|
||||
'geometry' => ['type' => 'Point', 'coordinates' => [32.5, -25.9]], 'purpose' => 'site',
|
||||
'source_reference' => 'Synthetic coordinate evidence', 'validating_entity' => 'Synthetic reviewer', 'observed_at' => today()->toDateString(),
|
||||
])->assertCreated()->json('id');
|
||||
$this->actingAs($reviewer)->postJson('/api/v2/investment/admin/zone-geometries/'.$geometry.'/validate', ['version_no' => 1])->assertOk();
|
||||
}
|
||||
$this->assertDatabaseCount('investment_items', 1);
|
||||
$this->assertDatabaseCount('investment_item_opportunities', 1);
|
||||
$query = http_build_query($zoneIds);
|
||||
$this->getJson('/api/v1/investment/search?'.$query)->assertOk()->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $opportunity->id);
|
||||
$this->getJson('/api/v1/investment/search?dimension=zee&view=combined')->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson('/api/v1/investment/search?dimension=zfi&view=list')->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson('/api/v1/investment/search?dimension=zee&q=not-present')->assertJsonPath('total', 0);
|
||||
$this->getJson('/api/v1/investment/search?dimension=invalid')->assertUnprocessable();
|
||||
$this->getJson('/api/v2/investment/zones')->assertJsonPath('records.total', 2)->assertJsonMissingPath('records.data.0.editor_id');
|
||||
$this->getJson('/api/v2/investment/zone-map')->assertJsonCount(2, 'features');
|
||||
$this->seed(InvestmentReferenceSeeder::class);
|
||||
$investor = User::factory()->create();
|
||||
$this->actingAs($investor);
|
||||
$origin = ['zone_id' => $zoneIds['zee_id'], 'intent' => 'interest', 'opportunity_id' => $opportunity->id];
|
||||
$submission = $this->postJson('/api/v1/investment/submissions', $origin)->assertCreated()->json('id');
|
||||
$this->postJson('/api/v1/investment/submissions', $origin)->assertCreated()->assertJsonPath('id', $submission);
|
||||
$this->assertDatabaseCount('investment_submissions', 1);
|
||||
$this->getJson('/api/v1/investment/submissions/'.$submission)->assertJsonPath('zone_origin.zone_id', $zoneIds['zee_id']);
|
||||
$submit = ['version' => 1, 'payload' => ['full_name' => 'Synthetic investor', 'email' => 'investor@example.test', 'country' => 'Test',
|
||||
'profile_id' => DB::table('investment_reference_options')->where('group', 'investor_profile')->where('code', 'individual')->value('id'),
|
||||
'sector' => 'Synthetic sector', 'objective' => 'Synthetic investment request with zone context.',
|
||||
'participation_id' => DB::table('investment_reference_options')->where('group', 'participation')->where('code', 'invest')->value('id'),
|
||||
'horizon' => 'Synthetic horizon', 'contact_consent' => true]];
|
||||
$reference = $this->postJson('/api/v1/investment/submissions/'.$submission.'/submit', $submit)->assertOk()->json('reference');
|
||||
$this->postJson('/api/v1/investment/submissions/'.$submission.'/submit', $submit)->assertOk()->assertJsonPath('reference', $reference);
|
||||
$this->assertDatabaseCount('interest_requests', 1);
|
||||
$metadata = json_decode(DB::table('interest_requests')->value('metadata'), true);
|
||||
$this->assertSame($zoneIds['zee_id'], $metadata['zone_origin']['zone_id']);
|
||||
$this->assertSame('interest', $metadata['zone_origin']['intent']);
|
||||
$this->actingAs($reviewer);
|
||||
$this->postJson('/api/v2/investment/admin/legal-sources/'.$source.'/revoke', ['version_no' => 2])->assertOk();
|
||||
$this->getJson('/api/v2/investment/zones')->assertJsonPath('records.total', 0);
|
||||
$this->getJson('/api/v2/investment/zone-map')->assertJsonCount(0, 'features');
|
||||
$this->getJson('/api/v1/investment/search?'.$query)->assertJsonPath('total', 0);
|
||||
$this->actingAs($investor)->postJson('/api/v1/investment/submissions', $origin)->assertNotFound();
|
||||
$this->assertDatabaseCount('investment_zones', 2);
|
||||
}
|
||||
|
||||
public function test_gis_rejects_invalid_shapes_and_requires_independent_review_without_granting_zone_status(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
$reviewer = $this->manager();
|
||||
$this->actingAs($editor);
|
||||
$id = $this->postJson('/api/v2/investment/admin/zones', ['code' => 'GIS-QA', 'name' => 'Synthetic GIS zone', 'category' => 'pending'])->assertCreated()->json('id');
|
||||
$url = '/api/v2/investment/admin/zones/'.$id.'/geometries';
|
||||
$payload = ['geometry' => ['type' => 'Point', 'coordinates' => [32.5, -25.9]], 'purpose' => 'site',
|
||||
'source_reference' => 'Synthetic coordinates, not real data', 'validating_entity' => 'Synthetic GIS reviewer', 'observed_at' => today()->toDateString()];
|
||||
$this->postJson($url, [...$payload, 'geometry' => ['type' => 'Point', 'coordinates' => [190, 0]]])->assertUnprocessable();
|
||||
$this->postJson($url, [...$payload, 'geometry' => ['type' => 'Polygon', 'coordinates' => [[[0, 0], [1, 1], [1, 0], [0, 1], [0, 0]]]]])->assertUnprocessable();
|
||||
$link = $this->postJson($url, $payload)->assertCreated()->json('id');
|
||||
$this->postJson('/api/v2/investment/admin/zone-geometries/'.$link.'/validate', ['version_no' => 1])->assertForbidden();
|
||||
$this->actingAs($reviewer)->postJson('/api/v2/investment/admin/zone-geometries/'.$link.'/validate', ['version_no' => 1])->assertOk();
|
||||
$this->getJson('/api/v2/investment/zone-map')->assertJsonCount(0, 'features');
|
||||
$this->assertDatabaseHas('investment_zones', ['id' => $id, 'category' => 'pending', 'publication_status' => 'draft']);
|
||||
$this->getJson('/api/v2/investment/zone-map?bbox[]=180&bbox[]=0&bbox[]=-180&bbox[]=10')->assertUnprocessable();
|
||||
}
|
||||
|
||||
public function test_anchor_can_link_multiple_zones_without_duplicates_or_self_approval(): void
|
||||
{
|
||||
$editor = $this->manager();
|
||||
$reviewer = $this->manager();
|
||||
$project = Project::factory()->create();
|
||||
foreach (['zee', 'zfi', 'industrial_park'] as $category) {
|
||||
$this->actingAs($editor);
|
||||
$id = $this->postJson('/api/v2/investment/admin/zones', ['code' => 'ANCHOR-'.$category, 'name' => 'Synthetic '.$category, 'category' => $category])->assertCreated()->json('id');
|
||||
$payload = ['project_id' => $project->id, 'association_type' => 'potential', 'role' => 'beneficiary',
|
||||
'source_reference' => 'Synthetic documentary relation', 'justification' => 'Synthetic anchor relation', 'valid_from' => today()->toDateString()];
|
||||
$url = '/api/v2/investment/admin/zones/'.$id.'/relations';
|
||||
$relation = $this->postJson($url, $payload)->assertCreated()->json('id');
|
||||
$this->postJson($url, $payload)->assertConflict();
|
||||
$this->postJson('/api/v2/investment/admin/zone-relations/'.$relation.'/validate', ['version_no' => 1])->assertForbidden();
|
||||
$this->actingAs($reviewer)->postJson('/api/v2/investment/admin/zone-relations/'.$relation.'/validate', ['version_no' => 1])->assertOk();
|
||||
}
|
||||
$this->assertDatabaseCount('projects', 1);
|
||||
$this->assertDatabaseCount('investment_zone_relations', 3);
|
||||
$this->assertDatabaseCount('investment_items', 0);
|
||||
config(['investment-zones.publishers' => [], 'investment-zones.legal_reviewers' => [], 'investment-zones.gis_reviewers' => []]);
|
||||
$this->postJson('/api/v2/investment/admin/zones/'.$id.'/publish', ['version_no' => 1])->assertForbidden();
|
||||
$this->getJson('/api/v2/investment/zones')->assertJsonPath('records.total', 0);
|
||||
}
|
||||
|
||||
public function test_identity_reconciliation_is_dry_by_default_idempotent_and_preserves_legacy_data(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$sector = Sector::create(['slug' => 'identity-qa', 'name' => 'Synthetic', 'is_active' => true]);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'IDENTITY-QA', 'slug' => 'identity-qa', 'title' => 'Synthetic identity', 'status' => 'draft']);
|
||||
$before = $opportunity->fresh()->getAttributes();
|
||||
$this->artisan('investment:reconcile-identities')->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_items', 0);
|
||||
$this->artisan('investment:reconcile-identities', ['--apply' => true])->assertSuccessful();
|
||||
$id = DB::table('investment_item_opportunities')->where('opportunity_id', $opportunity->id)->value('item_id');
|
||||
$this->artisan('investment:reconcile-identities', ['--apply' => true])->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_items', 1);
|
||||
$this->assertSame($id, DB::table('investment_item_opportunities')->value('item_id'));
|
||||
$this->assertSame($before, $opportunity->fresh()->getAttributes());
|
||||
$this->assertDatabaseCount('investment_item_projects', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\VerifyEmail;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ManagementAccessTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_setup_can_be_deferred_without_creating_an_account(): void
|
||||
{
|
||||
$this->get('/acesso-gestao')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component('management-access')->where('auth.user', null)->where('auth.canManagePortal', false));
|
||||
$this->assertDatabaseCount('users', 0);
|
||||
}
|
||||
|
||||
public function test_unverified_manager_can_view_setup_and_request_verification_but_cannot_manage(): void
|
||||
{
|
||||
Notification::fake();
|
||||
$user = User::factory()->unverified()->create();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->actingAs($user)->get('/acesso-gestao')->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page->where('auth.canManagePortal', false));
|
||||
$this->get('/management/interests')->assertRedirect(route('verification.notice'));
|
||||
$this->post(route('verification.send'))->assertRedirect();
|
||||
Notification::assertSentTo($user, VerifyEmail::class);
|
||||
$this->assertFalse($user->fresh()->hasVerifiedEmail());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PortalManagementTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_catalog_filters_combine_and_survive_pagination(): void
|
||||
{
|
||||
$this->actingAs($this->manager());
|
||||
$sector = $this->sector();
|
||||
for ($i = 0; $i < 22; $i++) {
|
||||
Opportunity::create(['sector_id' => $sector->id, 'reference' => 'SOL-'.$i,
|
||||
'title' => 'Solar '.$i, 'slug' => 'solar-'.$i, 'status' => $i === 21 ? 'draft' : 'published',
|
||||
'published_at' => now()->subMinute()]);
|
||||
}
|
||||
$url = '/management/opportunities?q=SOLAR&status=published§or_id='.$sector->id;
|
||||
$this->get($url)->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('records.total', 21)->has('records.data', 20)
|
||||
->where('records.next_page_url', fn ($url) => str_contains($url, 'status=published') && str_contains($url, 'q=SOLAR')));
|
||||
$this->get($url.'&page=2')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->has('records.data', 1)->where('records.data.0.reference', 'SOL-0'));
|
||||
$this->get('/management/opportunities?q=missing')->assertInertia(fn (AssertableInertia $page) => $page->where('records.total', 0));
|
||||
$sector->update(['is_active' => false]);
|
||||
$this->get('/management/sectors?status=active')->assertInertia(fn (AssertableInertia $page) => $page->where('records.total', 0));
|
||||
$this->get('/management/sectors?status=inactive&q=ENERGIA')->assertInertia(fn (AssertableInertia $page) => $page->where('records.total', 1));
|
||||
$this->getJson('/management/opportunities?status=invalid')->assertUnprocessable();
|
||||
$this->getJson('/management/opportunities?page=-1')->assertUnprocessable();
|
||||
}
|
||||
|
||||
protected function beforeRefreshingDatabase(): void
|
||||
{
|
||||
$this->assertSame('testing', app()->environment());
|
||||
$this->assertStringEndsWith('_test', config('database.connections.pgsql.database'));
|
||||
}
|
||||
|
||||
private function manager(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
config(['portal.managers' => [strtolower($user->email)]]);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function sector(): Sector
|
||||
{
|
||||
return Sector::create(['name' => 'Energia', 'slug' => 'energia', 'is_active' => true]);
|
||||
}
|
||||
|
||||
private function opportunity(array $attributes = []): Opportunity
|
||||
{
|
||||
return Opportunity::create(array_merge([
|
||||
'sector_id' => $this->sector()->id, 'reference' => 'INV-TEST-001',
|
||||
'title' => 'Energia solar', 'slug' => 'energia-solar',
|
||||
'status' => 'published', 'published_at' => now()->subMinute(),
|
||||
], $attributes));
|
||||
}
|
||||
|
||||
public function test_management_requires_an_explicit_verified_manager(): void
|
||||
{
|
||||
$this->get('/management/interests')->assertRedirect('/login');
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user)->get('/management/interests')->assertForbidden();
|
||||
$this->post('/management/sectors', ['name' => 'Intruso'])->assertForbidden();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$user->forceFill(['email_verified_at' => null])->save();
|
||||
$this->get('/management/interests')->assertRedirect(route('verification.notice'));
|
||||
$this->actingAs($this->manager())->get('/management/interests')->assertOk();
|
||||
}
|
||||
|
||||
public function test_manager_creates_and_edits_sectors_and_invalidates_home_cache(): void
|
||||
{
|
||||
$this->actingAs($this->manager());
|
||||
Cache::put('portal_home_pt', ['old' => true]);
|
||||
$data = ['name' => 'Energia', 'slug' => 'energia', 'sort_order' => 1, 'is_active' => true];
|
||||
$this->post('/management/sectors', $data)->assertRedirect('/management/sectors');
|
||||
$this->assertNull(Cache::get('portal_home_pt'));
|
||||
$sector = Sector::firstOrFail();
|
||||
$this->put('/management/sectors/'.$sector->id, [...$data, 'is_active' => false])->assertRedirect();
|
||||
$this->assertFalse($sector->fresh()->is_active);
|
||||
$this->post('/management/sectors', $data)->assertSessionHasErrors('slug');
|
||||
$this->get('/management/sectors/create')->assertOk();
|
||||
$this->get('/management/sectors/'.$sector->id.'/edit')->assertOk();
|
||||
}
|
||||
|
||||
public function test_opportunities_can_be_published_and_withdrawn_without_losing_money_precision(): void
|
||||
{
|
||||
$this->actingAs($this->manager());
|
||||
$data = ['sector_id' => $this->sector()->id, 'reference' => 'INV-TEST', 'title' => 'Solar',
|
||||
'slug' => 'solar', 'status' => 'draft', 'is_featured' => true, 'maturity_level' => 4,
|
||||
'estimated_investment_amount' => '1234567890123456.78', 'estimated_investment_currency' => 'MZN'];
|
||||
$this->post('/management/opportunities', $data)->assertRedirect('/management/opportunities');
|
||||
$opportunity = Opportunity::firstOrFail();
|
||||
$this->getJson('/api/v1/opportunities/solar')->assertNotFound();
|
||||
$this->put('/management/opportunities/'.$opportunity->id, [...$data, 'status' => 'published'])->assertRedirect();
|
||||
$this->getJson('/api/v1/opportunities/solar')->assertOk()
|
||||
->assertJsonPath('data.estimated_investment_amount', '1234567890123456.78')
|
||||
->assertJsonPath('data.maturity_label', 'Projecto estruturado');
|
||||
$this->getJson('/api/v1/home')->assertJsonPath('data.stats.opportunities', 1);
|
||||
$this->put('/management/opportunities/'.$opportunity->id, [...$data, 'status' => 'archived'])->assertRedirect();
|
||||
$this->getJson('/api/v1/opportunities/solar')->assertNotFound();
|
||||
$this->getJson('/api/v1/home')->assertJsonPath('data.stats.opportunities', 0);
|
||||
$this->put('/management/opportunities/'.$opportunity->id, [...$data, 'estimated_investment_amount' => '-1'])->assertSessionHasErrors('estimated_investment_amount');
|
||||
}
|
||||
|
||||
public function test_review_tracks_the_authenticated_reviewer_and_rejects_invalid_states(): void
|
||||
{
|
||||
$manager = $this->manager();
|
||||
$interest = InterestRequest::create(['reference' => 'IR-TEST', 'full_name' => 'Pessoa de teste',
|
||||
'email' => 'test@example.invalid', 'investor_type' => 'empresa', 'country' => 'Moçambique',
|
||||
'sector_interest' => 'Energia', 'message' => 'Pedido de informação para teste.', 'privacy_consent' => true]);
|
||||
$this->actingAs($manager)->get('/management/interests/'.$interest->id)->assertOk();
|
||||
$this->patch('/management/interests/'.$interest->id, ['status' => 'in_review', 'reviewed_by' => 999])->assertRedirect();
|
||||
$this->assertSame($manager->id, $interest->fresh()->reviewed_by);
|
||||
$this->assertNotNull($interest->fresh()->reviewed_at);
|
||||
$this->patch('/management/interests/'.$interest->id, ['status' => 'invalid'])->assertSessionHasErrors('status');
|
||||
}
|
||||
|
||||
public function test_public_requests_reject_missing_draft_deleted_and_future_opportunities(): void
|
||||
{
|
||||
$opportunity = $this->opportunity(['status' => 'draft']);
|
||||
$payload = ['fullName' => 'Teste do portal', 'email' => 'invalid', 'investorType' => 'empresa',
|
||||
'country' => 'Moçambique', 'sectorInterest' => 'Energia', 'message' => 'Pedido para verificar o contrato.',
|
||||
'privacyConsent' => true, 'opportunityReference' => 'MISSING'];
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertUnprocessable()->assertJsonValidationErrors('opportunityReference');
|
||||
$payload['opportunityReference'] = $opportunity->reference;
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertUnprocessable()->assertJsonValidationErrors('opportunityReference');
|
||||
$opportunity->update(['status' => 'published', 'published_at' => now()->addDay()]);
|
||||
$this->getJson('/api/v1/opportunities/'.$opportunity->slug)->assertNotFound();
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertUnprocessable()->assertJsonValidationErrors('opportunityReference');
|
||||
$opportunity->update(['published_at' => now()->subMinute()]);
|
||||
$opportunity->delete();
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertUnprocessable()->assertJsonValidationErrors('opportunityReference');
|
||||
$this->assertDatabaseCount('interest_requests', 0);
|
||||
}
|
||||
|
||||
public function test_valid_public_submissions_persist_and_return_distinct_references(): void
|
||||
{
|
||||
// DNS validation remains enabled; no mail is sent by this endpoint.
|
||||
$opportunity = $this->opportunity();
|
||||
$payload = ['fullName' => 'Pessoa de teste', 'email' => 'portal-integration-test@gmail.com',
|
||||
'investorType' => 'empresa', 'country' => 'Moçambique', 'sectorInterest' => 'Energia',
|
||||
'message' => 'Pedido fictício na base isolada de testes.', 'privacyConsent' => true,
|
||||
'opportunityReference' => $opportunity->reference];
|
||||
$first = $this->postJson('/api/v1/interest-requests', $payload)->assertCreated()->json('data.reference');
|
||||
$second = $this->postJson('/api/v1/interest-requests', $payload)->assertCreated()->json('data.reference');
|
||||
$this->assertNotSame($first, $second);
|
||||
$this->assertMatchesRegularExpression('/^IR-\d{4}-[0-9A-Z]{26}$/', $first);
|
||||
$this->assertDatabaseHas('interest_requests', ['reference' => $first, 'opportunity_id' => $opportunity->id, 'privacy_consent' => true]);
|
||||
$this->postJson('/api/v1/interest-requests', [...$payload, 'privacyConsent' => false])->assertUnprocessable()->assertJsonValidationErrors('privacyConsent');
|
||||
$this->assertDatabaseCount('interest_requests', 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Jobs\NotifyInterestReceived;
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\PortalAudit;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Mail\MailManager;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PortalOperationsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_audit_records_actor_and_changes_without_free_text(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$sector = new Sector;
|
||||
PortalAudit::save($sector, ['name' => 'Nome privado', 'slug' => 'test', 'description' => 'Texto confidencial', 'is_active' => true], $user->id);
|
||||
PortalAudit::save($sector, ['is_active' => false], $user->id);
|
||||
$events = DB::table('audit_events')->where('source_system', 'portal-management')->get();
|
||||
$this->assertCount(2, $events);
|
||||
$this->assertSame($user->id, $events[0]->actor_user_id);
|
||||
$this->assertStringNotContainsString('Texto confidencial', json_encode($events));
|
||||
$this->assertStringNotContainsString('Nome privado', json_encode($events));
|
||||
$updated = $events->firstWhere('action', 'updated');
|
||||
$this->assertFalse(json_decode($updated->after_data, true)['values']['is_active']);
|
||||
$this->actingAs($user)->get('/management/history')->assertForbidden();
|
||||
config(['portal.managers' => [$user->email]]);
|
||||
$this->get('/management/history')->assertOk();
|
||||
}
|
||||
|
||||
public function test_audit_failure_rolls_back_the_business_change(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Energia', 'slug' => 'energia', 'is_active' => true]);
|
||||
try {
|
||||
PortalAudit::save($sector, ['is_active' => false], 9999999);
|
||||
$this->fail('Expected invalid actor foreign key to reject event.');
|
||||
} catch (QueryException) {
|
||||
$this->assertTrue($sector->fresh()->is_active);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_public_notifications_are_disabled_by_default_and_enqueued_when_enabled(): void
|
||||
{
|
||||
$payload = ['fullName' => 'Pessoa de teste', 'email' => 'portal-integration-test@gmail.com',
|
||||
'investorType' => 'empresa', 'country' => 'Moçambique', 'sectorInterest' => 'Energia',
|
||||
'message' => 'Pedido de teste na base isolada.', 'privacyConsent' => true];
|
||||
config(['portal.notifications_enabled' => false]);
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertCreated();
|
||||
$this->assertDatabaseCount('jobs', 0);
|
||||
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => ['team@example.invalid']]);
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertCreated();
|
||||
$this->assertDatabaseCount('jobs', 1);
|
||||
$this->assertDatabaseCount('interest_requests', 2);
|
||||
config(['queue.connections.database.after_commit' => true]);
|
||||
$this->postJson('/api/v1/interest-requests', $payload)->assertStatus(500);
|
||||
$this->assertDatabaseCount('jobs', 1);
|
||||
$this->assertDatabaseCount('interest_requests', 2);
|
||||
}
|
||||
|
||||
public function test_job_checks_current_configuration_and_excludes_personal_data(): void
|
||||
{
|
||||
$interest = InterestRequest::create(['reference' => 'IR-TEST', 'full_name' => 'Pessoa confidencial',
|
||||
'email' => 'personal@example.invalid', 'investor_type' => 'empresa', 'country' => 'Moçambique',
|
||||
'sector_interest' => 'Energia', 'message' => 'Mensagem confidencial', 'privacy_consent' => true]);
|
||||
$job = new NotifyInterestReceived($interest->id, 'team@example.invalid');
|
||||
config(['portal.notifications_enabled' => false]);
|
||||
Mail::shouldReceive('raw')->never();
|
||||
$job->handle();
|
||||
Mail::clearResolvedInstance('mail.manager');
|
||||
Mail::swap(\Mockery::mock(MailManager::class));
|
||||
config(['portal.notifications_enabled' => true, 'portal.notification_recipients' => ['team@example.invalid']]);
|
||||
Mail::shouldReceive('raw')->once()->withArgs(function ($body, $callback) {
|
||||
$this->assertStringContainsString('IR-TEST', $body);
|
||||
$this->assertStringContainsString('/management/interests/', $body);
|
||||
$this->assertStringNotContainsString('confidencial', $body);
|
||||
$this->assertStringNotContainsString('personal@example.invalid', $body);
|
||||
|
||||
return is_callable($callback);
|
||||
});
|
||||
$job->handle();
|
||||
}
|
||||
|
||||
public function test_readiness_reports_non_production_without_mutating_data(): void
|
||||
{
|
||||
$this->artisan('portal:readiness')->expectsOutput('[PENDENTE] Ambiente production')->assertExitCode(1);
|
||||
$this->assertDatabaseCount('users', 0);
|
||||
$this->assertDatabaseCount('jobs', 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InterestRequest;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PortalServicesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_public_sections_render_and_desk_requires_login(): void
|
||||
{
|
||||
foreach (['sectores', 'como-investir', 'legislacao', 'documentos', 'apoio', 'parcerias', 'simulador-fiscal', 'formularios/investidor', 'formularios/empresa'] as $path) {
|
||||
$this->get('/'.$path)->assertOk()->assertInertia(fn (Assert $page) => $page->component('portal/services'));
|
||||
}
|
||||
$this->get('/balcao-virtual')->assertRedirect('/login');
|
||||
$this->get('/management/portal-services')->assertRedirect('/login');
|
||||
}
|
||||
|
||||
public function test_support_receipt_is_idempotent_private_and_requires_consent(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$payload = ['kind' => 'company', 'fullName' => 'Pessoa de Teste', 'email' => 'test@example.com', 'country' => 'Moçambique',
|
||||
'company' => 'Empresa de teste', 'sectorInterest' => 'Agricultura', 'message' => 'Pretendo orientação sobre este investimento.',
|
||||
'privacyConsent' => true, 'submission_key' => (string) Str::uuid()];
|
||||
$this->actingAs($owner)->post('/apoio', [...$payload, 'privacyConsent' => false])->assertSessionHasErrors('privacyConsent');
|
||||
$this->post('/apoio', $payload)->assertSessionHasNoErrors()->assertSessionHas('success');
|
||||
$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->post('/apoio', $payload)->assertStatus(409);
|
||||
}
|
||||
|
||||
public function test_partnership_requires_moderation_and_hides_owner_identity(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$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->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));
|
||||
}
|
||||
|
||||
public function test_document_download_rechecks_classification_checksum_and_publication(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', ['file' => UploadedFile::fake()->createWithContent('exemplo.txt', 'Documento sintético de teste.'),
|
||||
'publication_consent' => true])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->first();
|
||||
$this->post('/management/portal-services/resources', ['document_id' => $document->id, 'title' => 'Guia de teste', 'category' => 'Guia', 'topic' => 'Investimento',
|
||||
'source_reference' => 'Fonte sintética apenas para testes', 'legislation' => true, 'essential' => true, 'published' => true])->assertSessionHasNoErrors();
|
||||
$id = DB::table('portal_resources')->value('id');
|
||||
$this->get('/documentos/'.$id.'/download')->assertOk()->assertDownload('exemplo.txt');
|
||||
$this->get('/')->assertInertia(fn (Assert $page) => $page->has('essentialResources', 1));
|
||||
$this->get('/legislacao')->assertInertia(fn (Assert $page) => $page->has('resources.data', 1)->missing('resources.data.0.storage_key'));
|
||||
DB::table('documents')->where('id', $document->id)->update(['data_classification' => 'internal']);
|
||||
$this->get('/documentos/'.$id.'/download')->assertNotFound();
|
||||
$this->get('/documentos')->assertInertia(fn (Assert $page) => $page->has('resources.data', 0));
|
||||
$this->get('/')->assertInertia(fn (Assert $page) => $page->has('essentialResources', 0));
|
||||
DB::table('documents')->where('id', $document->id)->update(['data_classification' => 'public']);
|
||||
Storage::disk('local')->put($document->storage_key, 'Conteúdo alterado');
|
||||
$this->get('/documentos/'.$id.'/download')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_amount_filters_do_not_mix_currencies_or_expose_drafts(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Sector de teste', 'slug' => 'sector-teste', 'is_active' => true]);
|
||||
foreach ([['USD', 'published'], ['MZN', 'published'], ['USD', 'draft']] as [$currency, $status]) {
|
||||
Opportunity::create(['sector_id' => $sector->id, 'reference' => (string) Str::uuid(), 'slug' => (string) Str::uuid(), 'title' => 'Teste de dimensão',
|
||||
'status' => $status, 'published_at' => now(), 'estimated_investment_amount' => 500, 'estimated_investment_currency' => $currency]);
|
||||
}
|
||||
$this->getJson('/api/v1/opportunities/search?min_amount=100')->assertUnprocessable();
|
||||
$this->getJson('/api/v1/opportunities/search?currency=USD&min_amount=100&max_amount=600')->assertOk()->assertJsonPath('total', 1);
|
||||
$this->getJson('/api/v1/opportunities/search?currency=USD&min_amount=600&max_amount=100')->assertUnprocessable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PublicPortalNavigationTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_home_cache_contains_only_plain_data_and_survives_restricted_unserialization(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Energia', 'slug' => 'energia', 'is_active' => true]);
|
||||
Opportunity::create(['sector_id' => $sector->id, 'reference' => 'CACHE-1', 'title' => 'Solar',
|
||||
'slug' => 'solar', 'status' => 'published', 'published_at' => now()->subMinute(), 'is_featured' => true]);
|
||||
$first = $this->getJson('/api/v1/home')->assertOk()->json();
|
||||
$cached = Cache::get('portal_home_v2_pt');
|
||||
$this->assertIsArray($cached['sectors']);
|
||||
$this->assertIsArray($cached['featuredOpportunities']);
|
||||
$restored = unserialize(serialize($cached), ['allowed_classes' => false]);
|
||||
$this->assertSame($cached, $restored);
|
||||
Cache::put('portal_home_v2_pt', $restored);
|
||||
$this->assertSame($first, $this->getJson('/api/v1/home')->assertOk()->json());
|
||||
$sector->update(['name' => 'Energia actualizada']);
|
||||
$this->assertNull(Cache::get('portal_home_v2_pt'));
|
||||
$this->getJson('/api/v1/home')->assertJsonPath('data.sectors.0.name', 'Energia actualizada');
|
||||
}
|
||||
|
||||
public function test_public_links_open_the_expected_views_without_authentication(): void
|
||||
{
|
||||
$sector = Sector::create(['name' => 'Energia', 'slug' => 'energia', 'is_active' => true]);
|
||||
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'NAV-1', 'title' => 'Solar',
|
||||
'slug' => 'solar', 'status' => 'published', 'published_at' => now()->subMinute()]);
|
||||
$this->get('/oportunidades?q=solar')->assertInertia(fn (Assert $page) => $page
|
||||
->component('investment/catalogue')->where('filters.q', 'solar')->has('results.data', 1));
|
||||
$this->get('/sectores/energia')->assertInertia(fn (Assert $page) => $page->component('portal/services')->where('section', 'sector')->where('sector.slug', 'energia')->has('opportunities', 1));
|
||||
$this->get('/oportunidades/solar')->assertInertia(fn (Assert $page) => $page
|
||||
->component('investment/detail')->where('record.reference', 'NAV-1'));
|
||||
$this->get('/manifestar-interesse/solar')->assertInertia(fn (Assert $page) => $page
|
||||
->where('initialView', 'interest')->where('initialOpportunity.reference', 'NAV-1'));
|
||||
$this->get('/manifestar-interesse')->assertInertia(fn (Assert $page) => $page
|
||||
->where('initialView', 'interest')->missing('initialOpportunity'));
|
||||
$opportunity->update(['status' => 'draft']);
|
||||
$this->get('/oportunidades/solar')->assertNotFound();
|
||||
$this->get('/manifestar-interesse/solar')->assertNotFound();
|
||||
$sector->update(['is_active' => false]);
|
||||
$this->get('/sectores/energia')->assertNotFound();
|
||||
$this->get('/oportunidades/inexistente')->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Settings;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ProfileUpdateTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_profile_page_is_displayed()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->get(route('profile.edit'));
|
||||
|
||||
$response->assertOk();
|
||||
}
|
||||
|
||||
public function test_profile_information_can_be_updated()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->patch(route('profile.update'), [
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('profile.edit'));
|
||||
|
||||
$user->refresh();
|
||||
|
||||
$this->assertSame('Test User', $user->name);
|
||||
$this->assertSame('test@example.com', $user->email);
|
||||
$this->assertNull($user->email_verified_at);
|
||||
}
|
||||
|
||||
public function test_email_verification_status_is_unchanged_when_the_email_address_is_unchanged()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->patch(route('profile.update'), [
|
||||
'name' => 'Test User',
|
||||
'email' => $user->email,
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('profile.edit'));
|
||||
|
||||
$this->assertNotNull($user->refresh()->email_verified_at);
|
||||
}
|
||||
|
||||
public function test_user_can_delete_their_account()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->delete(route('profile.destroy'), [
|
||||
'password' => 'password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('home'));
|
||||
|
||||
$this->assertGuest();
|
||||
$this->assertNull($user->fresh());
|
||||
}
|
||||
|
||||
public function test_correct_password_must_be_provided_to_delete_account()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->from(route('profile.edit'))
|
||||
->delete(route('profile.destroy'), [
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasErrors('password')
|
||||
->assertRedirect(route('profile.edit'));
|
||||
|
||||
$this->assertNotNull($user->fresh());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Settings;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Laravel\Fortify\Features;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SecurityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_security_page_is_displayed()
|
||||
{
|
||||
$this->skipUnlessFortifyHas(Features::twoFactorAuthentication());
|
||||
|
||||
Features::twoFactorAuthentication([
|
||||
'confirm' => true,
|
||||
'confirmPassword' => true,
|
||||
]);
|
||||
/* @chisel-passkeys */
|
||||
Features::passkeys([
|
||||
'confirmPassword' => true,
|
||||
]);
|
||||
/* @end-chisel-passkeys */
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->actingAs($user)
|
||||
/* @chisel-password-confirmation */
|
||||
->withSession(['auth.password_confirmed_at' => time()])
|
||||
/* @end-chisel-password-confirmation */
|
||||
->get(route('security.edit'))
|
||||
->assertInertia(fn (Assert $page) => $page
|
||||
->component('settings/security')
|
||||
/* @chisel-passkeys */
|
||||
->where('canManagePasskeys', true)
|
||||
->where('passkeys', [])
|
||||
/* @end-chisel-passkeys */
|
||||
->where('canManageTwoFactor', true)
|
||||
->where('twoFactorEnabled', false),
|
||||
);
|
||||
}
|
||||
|
||||
/* @chisel-password-confirmation */
|
||||
public function test_security_page_requires_password_confirmation_when_enabled()
|
||||
{
|
||||
$this->skipUnlessFortifyHas(Features::twoFactorAuthentication());
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
Features::twoFactorAuthentication([
|
||||
'confirm' => true,
|
||||
'confirmPassword' => true,
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->get(route('security.edit'));
|
||||
|
||||
$response->assertRedirect(route('password.confirm'));
|
||||
}
|
||||
/* @end-chisel-password-confirmation */
|
||||
|
||||
public function test_security_page_renders_without_two_factor_when_feature_is_disabled()
|
||||
{
|
||||
$this->skipUnlessFortifyHas(Features::twoFactorAuthentication());
|
||||
|
||||
config(['fortify.features' => []]);
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->actingAs($user)
|
||||
/* @chisel-password-confirmation */
|
||||
->withSession(['auth.password_confirmed_at' => time()])
|
||||
/* @end-chisel-password-confirmation */
|
||||
->get(route('security.edit'))
|
||||
->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page
|
||||
->component('settings/security')
|
||||
/* @chisel-passkeys */
|
||||
->where('canManagePasskeys', false)
|
||||
->where('passkeys', [])
|
||||
/* @end-chisel-passkeys */
|
||||
->where('canManageTwoFactor', false)
|
||||
->missing('twoFactorEnabled')
|
||||
->missing('requiresConfirmation'),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_password_can_be_updated()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->from(route('security.edit'))
|
||||
->put(route('user-password.update'), [
|
||||
'current_password' => 'password',
|
||||
'password' => 'new-password',
|
||||
'password_confirmation' => 'new-password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasNoErrors()
|
||||
->assertRedirect(route('security.edit'));
|
||||
|
||||
$this->assertTrue(Hash::check('new-password', $user->refresh()->password));
|
||||
}
|
||||
|
||||
public function test_correct_password_must_be_provided_to_update_password()
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$response = $this
|
||||
->actingAs($user)
|
||||
->from(route('security.edit'))
|
||||
->put(route('user-password.update'), [
|
||||
'current_password' => 'wrong-password',
|
||||
'password' => 'new-password',
|
||||
'password_confirmation' => 'new-password',
|
||||
]);
|
||||
|
||||
$response
|
||||
->assertSessionHasErrors('current_password')
|
||||
->assertRedirect(route('security.edit'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\SuiteCrm;
|
||||
|
||||
use App\Integrations\SuiteCrm\SuiteCrmClient;
|
||||
use App\Integrations\SuiteCrm\SuiteCrmException;
|
||||
use Carbon\CarbonInterval;
|
||||
use Illuminate\Http\Client\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Sleep;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SuiteCrmClientTest extends TestCase
|
||||
{
|
||||
private SuiteCrmClient $client;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
config(['suitecrm.enabled' => true, 'suitecrm.base_url' => 'https://crm.example.invalid/legacy',
|
||||
'suitecrm.client_id' => 'test-client', 'suitecrm.client_secret' => 'secret-not-for-logs',
|
||||
'suitecrm.cache_store' => 'array', 'suitecrm.retry_delay_ms' => 0]);
|
||||
Cache::store('array')->flush();
|
||||
Http::preventStrayRequests();
|
||||
Log::spy();
|
||||
Sleep::fake();
|
||||
$this->client = new SuiteCrmClient;
|
||||
}
|
||||
|
||||
private function tokenResponse(string $token = 'test-token'): array
|
||||
{
|
||||
return ['access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => 3600];
|
||||
}
|
||||
|
||||
private function tokenKey(): string
|
||||
{
|
||||
return 'suitecrm:'.hash('sha256', 'https://crm.example.invalid/legacy|test-client|secret-not-for-logs').':token';
|
||||
}
|
||||
|
||||
public function test_disabled_client_and_insecure_configuration_never_send_requests(): void
|
||||
{
|
||||
Http::fake();
|
||||
config(['suitecrm.enabled' => false]);
|
||||
try {
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->fail('Expected disabled client');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('disabled', $e->reason);
|
||||
}
|
||||
config(['suitecrm.enabled' => true]);
|
||||
foreach (['http://crm.example.invalid', 'https://user:pass@crm.example.invalid', 'https://crm.example.invalid?token=secret'] as $url) {
|
||||
config(['suitecrm.base_url' => $url]);
|
||||
try {
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->fail('Expected URL rejection');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('invalid_base_url', $e->reason);
|
||||
}
|
||||
}
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_authentication_contract_and_token_cache_are_encrypted(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/module/Contacts/contact-1' => Http::response(['data' => ['id' => 'contact-1', 'type' => 'Contacts']]),
|
||||
]);
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
Http::assertSentCount(3);
|
||||
Http::assertSent(fn (Request $r) => str_ends_with($r->url(), '/Api/access_token') && $r['grant_type'] === 'client_credentials'
|
||||
&& $r['client_id'] === 'test-client' && $r['client_secret'] === 'secret-not-for-logs');
|
||||
Http::assertSent(fn (Request $r) => str_contains($r->url(), '/Api/V8/') && $r->hasHeader('Authorization', 'Bearer test-token'));
|
||||
$encrypted = Cache::store('array')->get($this->tokenKey());
|
||||
$this->assertNotSame('test-token', $encrypted);
|
||||
$this->assertSame('test-token', Crypt::decryptString($encrypted));
|
||||
}
|
||||
|
||||
public function test_401_renews_once_and_replays_the_unauthorised_request(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*/Api/access_token' => Http::sequence()->push($this->tokenResponse('old'))->push($this->tokenResponse('new')),
|
||||
'*/Api/V8/*' => Http::sequence()->push([], 401)->push(['data' => ['id' => 'contact-1']]),
|
||||
]);
|
||||
$result = $this->client->find('Contacts', 'contact-1');
|
||||
$this->assertSame('contact-1', $result['data']['id']);
|
||||
Http::assertSentCount(4);
|
||||
Http::assertSent(fn (Request $r) => $r->hasHeader('Authorization', 'Bearer new'));
|
||||
}
|
||||
|
||||
public function test_second_401_is_not_retried(): void
|
||||
{
|
||||
Http::fake([
|
||||
'*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::response(['errors' => [['detail' => 'personal@example.invalid']]], 401),
|
||||
]);
|
||||
try {
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->fail('Expected authentication failure');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('unauthenticated', $e->reason);
|
||||
$this->assertFalse($e->retryable);
|
||||
$this->assertStringNotContainsString('personal@', $e->getMessage());
|
||||
$this->assertNull($e->getPrevious());
|
||||
}
|
||||
Http::assertSentCount(4);
|
||||
}
|
||||
|
||||
public function test_json_api_create_update_relationship_and_exact_search_contracts(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()), '*' => Http::response(['data' => ['id' => 'record-1']])]);
|
||||
$this->client->create('Accounts', ['name' => 'Example']);
|
||||
$this->client->update('Accounts', 'account-1', ['name' => 'Revised']);
|
||||
$this->client->relate('Accounts', 'account-1', 'contacts', 'Contacts', 'contact-1');
|
||||
$this->client->search('Contacts', ['email1' => 'person@example.invalid'], 2, 10);
|
||||
Http::assertSent(fn (Request $r) => $r->method() === 'POST' && str_ends_with($r->url(), '/V8/module')
|
||||
&& $r['data'] === ['type' => 'Accounts', 'attributes' => ['name' => 'Example']]);
|
||||
Http::assertSent(fn (Request $r) => $r->method() === 'PATCH' && $r['data']['id'] === 'account-1');
|
||||
Http::assertSent(fn (Request $r) => str_ends_with($r->url(), '/Accounts/account-1/relationships/contacts') && $r['data'] === ['type' => 'Contacts', 'id' => 'contact-1']);
|
||||
Http::assertSent(fn (Request $r) => $r->method() === 'GET' && $r['filter']['email1']['eq'] === 'person@example.invalid' && $r['page']['number'] === 2);
|
||||
}
|
||||
|
||||
public function test_read_retries_transient_failures_but_create_does_not(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::sequence()->push([], 503)->push([], 503)->push(['data' => []])->push([], 503)]);
|
||||
$this->assertSame(['data' => []], $this->client->search('Contacts', []));
|
||||
try {
|
||||
$this->client->create('Leads', ['last_name' => 'Example']);
|
||||
$this->fail('Expected uncertain write');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertTrue($e->outcomeUnknown);
|
||||
$this->assertSame(503, $e->httpStatus);
|
||||
}
|
||||
Http::assertSentCount(5);
|
||||
}
|
||||
|
||||
public function test_write_timeout_is_not_replayed_and_transport_exception_is_not_retained(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()), '*/Api/V8/*' => Http::failedConnection('secret-not-for-logs')]);
|
||||
try {
|
||||
$this->client->create('Leads', ['last_name' => 'Private Name']);
|
||||
$this->fail('Expected transport failure');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertTrue($e->outcomeUnknown);
|
||||
$this->assertSame('transport_failure', $e->reason);
|
||||
$this->assertNull($e->getPrevious());
|
||||
$this->assertStringNotContainsString('secret-not-for-logs', $e->getMessage());
|
||||
}
|
||||
Log::shouldHaveReceived('info')->with('suitecrm.http', \Mockery::on(fn ($context) => array_keys($context) === ['operation', 'status', 'duration_ms']))->twice();
|
||||
}
|
||||
|
||||
public function test_retry_after_is_returned_without_immediate_retry_for_long_delays(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()), '*/Api/V8/*' => Http::response([], 429, ['Retry-After' => '120'])]);
|
||||
try {
|
||||
$this->client->search('Contacts', []);
|
||||
$this->fail('Expected rate limit');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame(120, $e->retryAfter);
|
||||
$this->assertSame('rate_limited', $e->reason);
|
||||
}
|
||||
Http::assertSentCount(2);
|
||||
}
|
||||
|
||||
public function test_circuit_opens_then_allows_recovery_after_cooldown(): void
|
||||
{
|
||||
config(['suitecrm.circuit_threshold' => 1, 'suitecrm.read_retries' => 0]);
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::sequence()->push([], 503)->push(['data' => []])]);
|
||||
foreach (['unavailable', 'circuit_open'] as $expected) {
|
||||
try {
|
||||
$this->client->search('Contacts', []);
|
||||
$this->fail('Expected circuit failure');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame($expected, $e->reason);
|
||||
}
|
||||
}
|
||||
Http::assertSentCount(2);
|
||||
$this->travel(61)->seconds();
|
||||
$this->assertSame(['data' => []], $this->client->search('Contacts', []));
|
||||
Http::assertSentCount(3);
|
||||
}
|
||||
|
||||
public function test_identifiers_modules_and_page_limits_are_rejected_before_network(): void
|
||||
{
|
||||
Http::fake();
|
||||
foreach ([fn () => $this->client->find('Users', '1'), fn () => $this->client->find('Contacts', '../Accounts'),
|
||||
fn () => $this->client->search('Contacts', [], 1, 1000)] as $operation) {
|
||||
try {
|
||||
$operation();
|
||||
$this->fail('Expected rejection');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertContains($e->reason, ['module_not_allowed', 'invalid_identifier', 'invalid_pagination']);
|
||||
}
|
||||
}
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_invalid_token_response_and_redirect_are_rejected(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::sequence()->push(['access_token' => 'secret', 'expires_in' => 0])->push($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::response('', 302, ['Location' => 'https://untrusted.example.invalid'])]);
|
||||
try {
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->fail('Expected invalid token');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('invalid_token_response', $e->reason);
|
||||
}
|
||||
try {
|
||||
$this->client->find('Contacts', 'contact-1');
|
||||
$this->fail('Expected redirect rejection');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('unexpected_status', $e->reason);
|
||||
$this->assertSame(302, $e->httpStatus);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_token_expiration_and_credential_rotation_obtain_new_tokens(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::sequence()->push($this->tokenResponse('first'))
|
||||
->push($this->tokenResponse('renewed'))->push($this->tokenResponse('rotated')),
|
||||
'*/Api/V8/*' => Http::response(['data' => []])]);
|
||||
$this->client->search('Contacts', []);
|
||||
$this->travel(3601)->seconds();
|
||||
$this->client->search('Contacts', []);
|
||||
config(['suitecrm.client_secret' => 'rotated-secret']);
|
||||
$this->client->search('Contacts', []);
|
||||
Http::assertSentCount(6);
|
||||
Http::assertSent(fn (Request $r) => $r->hasHeader('Authorization', 'Bearer rotated'));
|
||||
}
|
||||
|
||||
public function test_forbidden_and_invalid_input_responses_are_permanent_and_sanitised(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::sequence()->push(['errors' => [['detail' => 'private@example.invalid']]], 403)
|
||||
->push(['errors' => [['detail' => 'Private Name']]], 422)]);
|
||||
foreach (['forbidden', 'validation_failed'] as $reason) {
|
||||
try {
|
||||
$this->client->create('Contacts', ['last_name' => 'Private Name']);
|
||||
$this->fail('Expected permanent failure');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame($reason, $e->reason);
|
||||
$this->assertFalse($e->retryable);
|
||||
$this->assertFalse($e->outcomeUnknown);
|
||||
$this->assertNull($e->getPrevious());
|
||||
}
|
||||
}
|
||||
Http::assertSentCount(3);
|
||||
}
|
||||
|
||||
public function test_a_malformed_successful_write_is_treated_as_ambiguous(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()), '*/Api/V8/*' => Http::response('<html>Private data</html>', 200)]);
|
||||
try {
|
||||
$this->client->create('Contacts', ['last_name' => 'Private Name']);
|
||||
$this->fail('Expected invalid response');
|
||||
} catch (SuiteCrmException $e) {
|
||||
$this->assertSame('invalid_response', $e->reason);
|
||||
$this->assertTrue($e->outcomeUnknown);
|
||||
}
|
||||
Http::assertSentCount(2);
|
||||
}
|
||||
|
||||
public function test_retry_after_short_delay_is_respected_and_logs_have_no_payload(): void
|
||||
{
|
||||
Http::fake(['*/Api/access_token' => Http::response($this->tokenResponse()),
|
||||
'*/Api/V8/*' => Http::sequence()->push([], 429, ['Retry-After' => '2'])->push(['data' => []])]);
|
||||
$this->client->search('Contacts', ['email1' => 'private@example.invalid']);
|
||||
Sleep::assertSlept(function (CarbonInterval $duration) {
|
||||
return $duration->totalMilliseconds >= 2000;
|
||||
});
|
||||
Log::shouldHaveReceived('info')->with('suitecrm.http', \Mockery::on(fn ($context) => array_keys($context) === ['operation', 'status', 'duration_ms']))->times(3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\SuiteCrm;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SuiteCrmProbeTest extends TestCase
|
||||
{
|
||||
public function test_disabled_probe_does_not_contact_crm(): void
|
||||
{
|
||||
Http::preventStrayRequests();
|
||||
config(['suitecrm.enabled' => false]);
|
||||
$this->artisan('suitecrm:probe')->expectsOutput('SuiteCRM indisponivel: disabled')->assertFailed();
|
||||
Http::assertNothingSent();
|
||||
}
|
||||
|
||||
public function test_probe_reads_metadata_without_writing_business_records(): void
|
||||
{
|
||||
config(['suitecrm.enabled' => true, 'suitecrm.base_url' => 'https://crm.example.invalid/legacy',
|
||||
'suitecrm.client_id' => 'probe', 'suitecrm.client_secret' => 'private-probe-secret', 'suitecrm.cache_store' => 'array']);
|
||||
Http::preventStrayRequests();
|
||||
Http::fake([
|
||||
'*/Api/access_token' => Http::response(['access_token' => 'private-token', 'token_type' => 'Bearer', 'expires_in' => 3600]),
|
||||
'*/Api/V8/meta/fields/Contacts' => Http::response(['data' => ['type' => 'fields', 'attributes' => ['last_name' => ['type' => 'varchar']]]]),
|
||||
]);
|
||||
$this->artisan('suitecrm:probe')->assertSuccessful();
|
||||
Http::assertSentCount(2);
|
||||
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/module'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\InvestMoz;
|
||||
|
||||
use App\Models\Investor;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SchemaLifecycleTest extends TestCase
|
||||
{
|
||||
private function rejected(string $sql, array $bindings, string $sqlState): void
|
||||
{
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::statement($sql, $bindings);
|
||||
$this->fail('The database accepted an invalid operation: '.$sql);
|
||||
} catch (QueryException $exception) {
|
||||
$this->assertSame($sqlState, $exception->errorInfo[0]);
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
}
|
||||
|
||||
public function test_schema_constraints_events_and_rollback_in_isolated_postgis(): void
|
||||
{
|
||||
if (getenv('INVESTMOZ_SCHEMA_TESTS') !== '1') {
|
||||
$this->markTestSkipped('Set INVESTMOZ_SCHEMA_TESTS=1 only for an isolated disposable *_test database.');
|
||||
}
|
||||
$this->assertSame('testing', app()->environment());
|
||||
$this->assertSame('pgsql', DB::connection()->getDriverName());
|
||||
$this->assertStringEndsWith('_test', DB::connection()->getDatabaseName());
|
||||
$this->assertSame(DB::connection()->getDatabaseName(), DB::selectOne('SELECT current_database() AS name')->name);
|
||||
$this->assertFileDoesNotExist(base_path('bootstrap/cache/config.php'), 'Clear cached configuration before the destructive test.');
|
||||
// This manifest describes the reconciled 24 September baseline. Later
|
||||
// additive upgrades are exercised by their feature/migration tests.
|
||||
$baselinePaths = array_values(array_filter(glob(database_path('migrations/*.php')),
|
||||
fn ($path) => strcmp(basename($path), '2026_09_25') < 0));
|
||||
$this->artisan('migrate:fresh', ['--seed' => true, '--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
|
||||
$manifest = json_decode(file_get_contents(base_path('docs/investmoz/schema.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
|
||||
$legacy = json_decode(file_get_contents(base_path('docs/investmoz/legacy-schema.json')), true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach (array_merge($manifest['tables'], $legacy['tables']) as $table) {
|
||||
$actual = DB::select(
|
||||
"SELECT a.attname AS column_name, CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END AS is_nullable, format_type(a.atttypid,a.atttypmod) AS pg_type, pg_get_expr(d.adbin,d.adrelid) AS default_expression FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid=a.attrelid AND d.adnum=a.attnum JOIN pg_class c ON c.oid=a.attrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relname=? AND a.attnum>0 AND NOT a.attisdropped ORDER BY a.attnum",
|
||||
[$table['name']],
|
||||
);
|
||||
$this->assertSame(array_column($table['columns'], 'name'), array_column($actual, 'column_name'), $table['name']);
|
||||
foreach ($actual as $position => $column) {
|
||||
$this->assertSame($table['columns'][$position]['nullable'] ? 'YES' : 'NO', $column->is_nullable);
|
||||
$expectedType = str_replace(['timestamptz', 'char('], ['timestamp with time zone', 'character('], $table['columns'][$position]['type']);
|
||||
$this->assertSame($expectedType, $column->pg_type, $table['name'].'.'.$column->column_name);
|
||||
$expectedDefault = $table['columns'][$position]['default'];
|
||||
$actualDefault = $column->default_expression === null ? null : str_replace(['::text', '::character varying'], '', $column->default_expression);
|
||||
$this->assertSame($expectedDefault, $actualDefault, $table['name'].'.'.$column->column_name.' default');
|
||||
}
|
||||
}
|
||||
$expectedIndexes = array_merge(array_column($manifest['indexes'], 'name'), array_column($legacy['indexes'], 'name'));
|
||||
foreach ($manifest['constraints'] as $constraint) {
|
||||
if ($constraint['kind'] === 'PRIMARY KEY') {
|
||||
$expectedIndexes[] = $constraint['name'];
|
||||
}
|
||||
}
|
||||
foreach ($legacy['tables'] as $table) {
|
||||
$expectedIndexes[] = $table['name'].'_pkey';
|
||||
}
|
||||
sort($expectedIndexes);
|
||||
$actualIndexes = DB::table('pg_indexes')->where('schemaname', 'public')->whereIn('tablename', array_column(array_merge($manifest['tables'], $legacy['tables']), 'name'))->orderBy('indexname')->pluck('indexname')->all();
|
||||
$this->assertSame($expectedIndexes, $actualIndexes);
|
||||
foreach ($manifest['indexes'] as $index) {
|
||||
$row = DB::selectOne("SELECT indexdef FROM pg_indexes WHERE schemaname='public' AND indexname=?", [$index['name']]);
|
||||
$this->assertNotNull($row, $index['name']);
|
||||
$this->assertStringContainsString('USING '.$index['method'], $row->indexdef);
|
||||
}
|
||||
foreach ($manifest['constraints'] as $constraint) {
|
||||
$this->assertNotNull(DB::selectOne(
|
||||
"SELECT oid FROM pg_constraint WHERE connamespace='public'::regnamespace AND conname=?",
|
||||
[$constraint['name']],
|
||||
), $constraint['name']);
|
||||
}
|
||||
$actions = ['CASCADE' => 'c', 'RESTRICT' => 'r', 'SET NULL' => 'n', 'NO ACTION' => 'a'];
|
||||
foreach (array_merge($manifest['relationships'], $legacy['relationships']) as $relationship) {
|
||||
$actualFk = DB::selectOne("SELECT confdeltype, confupdtype FROM pg_constraint WHERE connamespace='public'::regnamespace AND conname=?", [$relationship['name']]);
|
||||
$this->assertNotNull($actualFk, $relationship['name']);
|
||||
$this->assertSame($actions[$relationship['on_delete']], $actualFk->confdeltype);
|
||||
$this->assertSame($actions[$relationship['on_update']], $actualFk->confupdtype);
|
||||
}
|
||||
foreach ($manifest['triggers'] as $trigger) {
|
||||
$this->assertNotNull(DB::selectOne('SELECT oid FROM pg_trigger WHERE tgname=? AND NOT tgisinternal', [$trigger['name']]));
|
||||
}
|
||||
|
||||
$project = DB::selectOne("INSERT INTO projects(code,name,status,source_system,external_id,budget_amount,budget_currency) VALUES ('TEST-P','Fictício','draft','test','P-1',123456789012345678.90,'MZN') RETURNING id,budget_amount");
|
||||
$this->assertSame('123456789012345678.90', $project->budget_amount);
|
||||
$this->rejected("INSERT INTO projects(code,name,status) VALUES ('TEST-P','Duplicado','draft')", [], '23505');
|
||||
$this->rejected("INSERT INTO projects(code,name,status) VALUES ('BAD-S','Fictício','unknown')", [], '23514');
|
||||
$this->rejected("INSERT INTO projects(code,name,status,budget_amount,budget_currency) VALUES ('BAD-M','Fictício','draft',-1,'MZN')", [], '23514');
|
||||
$this->rejected("INSERT INTO projects(code,name,status,budget_amount) VALUES ('BAD-C','Fictício','draft',1)", [], '23514');
|
||||
DB::update('UPDATE projects SET deleted_at=now() WHERE id=?', [$project->id]);
|
||||
DB::insert("INSERT INTO projects(code,name,status) VALUES ('TEST-P','Código reutilizado','draft')");
|
||||
$this->rejected("INSERT INTO projects(code,name,status,source_system,external_id) VALUES ('NEW-CODE','Fictício','draft','test','P-1')", [], '23505');
|
||||
|
||||
$location = DB::selectOne("INSERT INTO geo_locations(name,location_type,code) VALUES ('Local fictício','site','TEST-GEO') RETURNING id");
|
||||
DB::insert("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'point',ST_GeomFromText('POINT(32 -25)',4326))", [$location->id]);
|
||||
$this->rejected("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'line',ST_GeomFromText('POINT(32 -25)',4326))", [$location->id], '23514');
|
||||
$this->rejected("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'polygon',ST_GeomFromText('POLYGON((0 0,1 1,1 0,0 1,0 0))',4326))", [$location->id], '23514');
|
||||
$this->rejected("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'point',ST_GeomFromText('POINT EMPTY',4326))", [$location->id], '23514');
|
||||
$this->rejected("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'point',ST_GeomFromText('POINT(181 0)',4326))", [$location->id], '23514');
|
||||
$this->rejected("INSERT INTO geo_geometries(geo_location_id,geometry_type,geom) VALUES (?,'point',ST_GeomFromText('POINT(1 1)',3857))", [$location->id], '22023');
|
||||
$this->rejected("INSERT INTO project_locations(project_id,geo_location_id,role) VALUES (gen_random_uuid(),?,'primary')", [$location->id], '23503');
|
||||
|
||||
$i1 = Investor::factory()->create();
|
||||
$i2 = Investor::factory()->create();
|
||||
$contact = DB::selectOne("INSERT INTO contacts(full_name) VALUES ('Contacto fictício') RETURNING id");
|
||||
DB::insert('INSERT INTO investor_contacts(investor_id,contact_id) VALUES (?,?),(?,?)', [$i1->id, $contact->id, $i2->id, $contact->id]);
|
||||
$this->rejected('INSERT INTO investor_contacts(investor_id,contact_id) VALUES (?,?)', [$i1->id, $contact->id], '23505');
|
||||
$this->rejected('INSERT INTO project_documents(project_id,document_id) VALUES (?,gen_random_uuid())', [$project->id], '23503');
|
||||
|
||||
$audit = DB::selectOne("INSERT INTO audit_events(entity_type,action) VALUES ('test','created') RETURNING id");
|
||||
$this->rejected("UPDATE audit_events SET action='tampered' WHERE id=?", [$audit->id], '42501');
|
||||
$this->rejected('DELETE FROM audit_events WHERE id=?', [$audit->id], '42501');
|
||||
$this->rejected('TRUNCATE audit_events', [], '42501');
|
||||
$event = DB::selectOne("INSERT INTO outbox_events(aggregate_type,aggregate_id,event_type,payload,status) VALUES ('test',?,'test.created','{}','pending') RETURNING id", [$project->id]);
|
||||
DB::update("UPDATE outbox_events SET status='published',published_at=now() WHERE id=?", [$event->id]);
|
||||
$this->rejected("UPDATE outbox_events SET payload='{\"changed\":true}' WHERE id=?", [$event->id], '42501');
|
||||
$this->rejected('DELETE FROM outbox_events WHERE id=?', [$event->id], '42501');
|
||||
$this->rejected('TRUNCATE outbox_events', [], '42501');
|
||||
DB::insert("INSERT INTO inbox_events(message_id,event_type,payload,status) VALUES ('TEST-MESSAGE','test','{}','received')");
|
||||
$this->rejected("INSERT INTO inbox_events(message_id,event_type,payload,status) VALUES ('TEST-MESSAGE','test','{}','received')", [], '23505');
|
||||
|
||||
DB::statement("SET TIME ZONE 'Africa/Maputo'");
|
||||
try {
|
||||
DB::update("UPDATE projects SET name='Actualizado' WHERE id=?", [$project->id]);
|
||||
$age = DB::selectOne('SELECT abs(extract(epoch FROM (CURRENT_TIMESTAMP-updated_at))) AS age FROM projects WHERE id=?', [$project->id]);
|
||||
$this->assertLessThan(5.0, (float) $age->age);
|
||||
} finally {
|
||||
DB::statement("SET TIME ZONE 'UTC'");
|
||||
}
|
||||
// Index eligibility, not a latency/SLO claim on tiny fixtures.
|
||||
DB::statement('SET enable_seqscan = off');
|
||||
try {
|
||||
$plan = json_encode(DB::select('EXPLAIN (FORMAT JSON) SELECT id FROM geo_geometries WHERE geom && ST_MakeEnvelope(31,-26,33,-24,4326)'));
|
||||
$this->assertStringContainsString('imz_geo_geometries_geom_idx', $plan);
|
||||
} finally {
|
||||
DB::statement('RESET enable_seqscan');
|
||||
}
|
||||
$this->artisan('migrate', ['--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0); // Ledger idempotency.
|
||||
$this->artisan('db:seed', ['--class' => 'InvestMozReferenceSeeder'])->assertExitCode(0);
|
||||
$this->assertSame(1, DB::table('projects')->where('source_system', 'example')->where('external_id', 'PROJECT-001')->count());
|
||||
$this->artisan('migrate:rollback', ['--step' => 15, '--force' => true])->assertExitCode(0);
|
||||
foreach ($manifest['tables'] as $table) {
|
||||
$this->assertFalse(Schema::hasTable($table['name']));
|
||||
}
|
||||
$this->assertTrue(Schema::hasTable('users'));
|
||||
$this->assertTrue(Schema::hasTable('opportunities'));
|
||||
$this->assertCount(2, DB::select("SELECT extname FROM pg_extension WHERE extname IN ('postgis','pgcrypto')"));
|
||||
$this->artisan('migrate', ['--seed' => true, '--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
|
||||
// This is a separate upgrade batch: ordinary rollback must now revert it.
|
||||
$this->artisan('migrate:rollback', ['--force' => true])->assertExitCode(0);
|
||||
$this->assertFalse(Schema::hasTable('projects'));
|
||||
$this->assertTrue(Schema::hasTable('users'));
|
||||
$this->artisan('migrate', ['--force' => true, '--path' => $baselinePaths, '--realpath' => true])->assertExitCode(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
|
||||
use Laravel\Fortify\Features;
|
||||
|
||||
abstract class TestCase extends BaseTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// HTTP feature tests must not depend on the developer's Vite SSR server.
|
||||
config(['inertia.ssr.enabled' => false]);
|
||||
}
|
||||
|
||||
protected function skipUnlessFortifyHas(string $feature, ?string $message = null): void
|
||||
{
|
||||
if (! Features::enabled($feature)) {
|
||||
$this->markTestSkipped($message ?? "Fortify feature [{$feature}] is not enabled.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\Ai\HybridFusion;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class AiHybridFusionTest extends TestCase
|
||||
{
|
||||
public function test_fusion_excludes_unauthorised_ids_and_does_not_double_count_duplicates(): void
|
||||
{
|
||||
$fusion = new HybridFusion;
|
||||
$ranking = $fusion->rank(['secret', 'a', 'a', 'b'], ['b', 'secret'], ['a', 'b']);
|
||||
$this->assertSame(['b', 'a'], array_column($ranking, 'id'));
|
||||
$this->assertEqualsWithDelta(1 / 62, $ranking[1]['score'], 0.000001);
|
||||
$this->assertSame([], $fusion->rank(['a'], ['b'], []));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Services\EducationGapCalculator;
|
||||
use InvalidArgumentException;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class EducationGapCalculatorTest extends TestCase
|
||||
{
|
||||
public function test_unknown_supply_is_not_zero_and_invalid_comparisons_are_not_gaps(): void
|
||||
{
|
||||
$calculator = new EducationGapCalculator;
|
||||
$this->assertSame(['state' => 'insufficient_data', 'people' => null], $calculator->observed(100, null, true, true));
|
||||
$this->assertSame(['state' => 'insufficient_data', 'people' => null], $calculator->observed(null, 10, true, true));
|
||||
$this->assertSame(['state' => 'incomparable', 'people' => null], $calculator->observed(100, 10, false, true));
|
||||
$this->assertSame(['state' => 'expired', 'people' => null], $calculator->observed(100, 10, true, false));
|
||||
}
|
||||
|
||||
public function test_comparable_people_produce_only_an_unvalidated_nonnegative_gap(): void
|
||||
{
|
||||
$calculator = new EducationGapCalculator;
|
||||
$this->assertSame(['state' => 'observed_unvalidated', 'people' => 60], $calculator->observed(100, 40, true, true));
|
||||
$this->assertSame(0, $calculator->observed(10, 40, true, true)['people']);
|
||||
$this->assertSame(10, $calculator->observed(10, 0, true, true)['people']);
|
||||
}
|
||||
|
||||
public function test_negative_quantities_are_rejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
(new EducationGapCalculator)->observed(10, -1, true, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\TestCase;
|
||||
|
||||
class ExampleTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_that_true_is_true()
|
||||
{
|
||||
$this->assertTrue(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
PortalApiError,
|
||||
fieldErrors,
|
||||
interestPayload,
|
||||
newSubmissionKey,
|
||||
money,
|
||||
portalRequest,
|
||||
searchUrl,
|
||||
toFeaturedOpportunity,
|
||||
toOpportunity,
|
||||
} from '../../resources/js/lib/portal-api.ts';
|
||||
|
||||
await test('submission keys are distinct UUIDv4 values', () => {
|
||||
const first = newSubmissionKey();
|
||||
assert.match(
|
||||
first,
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
|
||||
);
|
||||
assert.notEqual(first, newSubmissionKey());
|
||||
});
|
||||
|
||||
await test('filters preserve one-based maturity and pagination and escape query text', () => {
|
||||
const url = new URL(
|
||||
searchUrl(
|
||||
{
|
||||
query: ' energia & solar ',
|
||||
sector: 'energia',
|
||||
province: 'Zambézia',
|
||||
maturity: '4',
|
||||
},
|
||||
2,
|
||||
),
|
||||
'http://localhost',
|
||||
);
|
||||
assert.equal(url.searchParams.get('q'), 'energia & solar');
|
||||
assert.equal(url.searchParams.get('maturity_level'), '4');
|
||||
assert.equal(url.searchParams.get('page'), '2');
|
||||
assert.equal(url.searchParams.get('province'), 'Zambézia');
|
||||
});
|
||||
|
||||
await test('empty filters do not restrict results', () => {
|
||||
const url = searchUrl(
|
||||
{ query: '', sector: '', province: '', maturity: '' },
|
||||
1,
|
||||
);
|
||||
assert.equal(url, '/api/v1/opportunities/search?page=1&per_page=12');
|
||||
});
|
||||
|
||||
await test('request uses fullName and transmits consent without inventing a reference', () => {
|
||||
const payload = interestPayload({
|
||||
name: ' Teste fictício ',
|
||||
email: 'teste@example.invalid',
|
||||
phone: '',
|
||||
investorType: 'empresa',
|
||||
country: 'Moçambique',
|
||||
sectorInterest: 'Energia',
|
||||
opportunityReference: 'TEST-1',
|
||||
investmentRange: '',
|
||||
message: 'Mensagem fictícia para teste.',
|
||||
privacyConsent: true,
|
||||
});
|
||||
assert.equal(payload.fullName, 'Teste fictício');
|
||||
assert.equal(payload.privacyConsent, true);
|
||||
assert.equal(payload.opportunityReference, 'TEST-1');
|
||||
assert.equal('reference' in payload, false);
|
||||
assert.equal('name' in payload, false);
|
||||
});
|
||||
|
||||
await test('server validation maps fullName back to the name field', () => {
|
||||
assert.deepEqual(
|
||||
fieldErrors(
|
||||
new PortalApiError(422, {
|
||||
fullName: ['Nome obrigatório'],
|
||||
email: ['Email inválido'],
|
||||
unexpected: ['ignored'],
|
||||
}),
|
||||
),
|
||||
{ name: 'Nome obrigatório', email: 'Email inválido' },
|
||||
);
|
||||
});
|
||||
|
||||
await test('monetary rendering preserves large decimal values and the API currency', () => {
|
||||
const amount = money('123456789012345678.90', 'MZN');
|
||||
assert.match(amount, /MZN|MTn?/);
|
||||
assert.equal(amount.replace(/\D/g, ''), '12345678901234567890');
|
||||
assert.notEqual(money('1000.00', 'EUR'), money('1000.00', 'USD'));
|
||||
assert.equal(money(null, 'USD'), 'Por indicar');
|
||||
assert.notEqual(money('0.00', 'USD'), 'Por indicar');
|
||||
});
|
||||
|
||||
await test('database records map without changing maturity or amount precision', () => {
|
||||
const item = toOpportunity({
|
||||
slug: 'test',
|
||||
reference: 'TEST',
|
||||
title: 'Teste',
|
||||
sector: null,
|
||||
province: null,
|
||||
maturity_label: 'Projecto estruturado',
|
||||
estimated_investment_amount: '1000.25',
|
||||
estimated_investment_currency: 'MZN',
|
||||
financing_modality: null,
|
||||
expected_impact: null,
|
||||
summary: null,
|
||||
description: 'Descrição completa',
|
||||
is_featured: false,
|
||||
});
|
||||
assert.equal(item.sectorName, 'Sector não indicado');
|
||||
assert.equal(item.maturity, 'Projecto estruturado');
|
||||
assert.equal(item.amount, '1000.25');
|
||||
assert.equal(item.description, 'Descrição completa');
|
||||
});
|
||||
|
||||
await test('home cards retain the slug needed to fetch the full detail', () => {
|
||||
const item = toFeaturedOpportunity({
|
||||
reference: 'TEST',
|
||||
title: 'Teste',
|
||||
sector: 'Energia',
|
||||
province: null,
|
||||
maturity: null,
|
||||
estimatedInvestment: { amount: null, currency: 'USD' },
|
||||
url: '/oportunidades/projecto-teste',
|
||||
});
|
||||
assert.equal(item.slug, 'projecto-teste');
|
||||
assert.equal(item.description, null);
|
||||
});
|
||||
|
||||
await test('fetch accepts a real server confirmation', async (t) => {
|
||||
t.mock.method(globalThis, 'fetch', async (_url, options) => {
|
||||
assert.equal(options.headers.get('Accept'), 'application/json');
|
||||
assert.equal(options.credentials, 'same-origin');
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
data: { reference: 'IR-SERVER-001' },
|
||||
}),
|
||||
{ status: 201 },
|
||||
);
|
||||
});
|
||||
const response = await portalRequest('/api/v1/interest-requests', {
|
||||
method: 'POST',
|
||||
});
|
||||
assert.equal(response.data.reference, 'IR-SERVER-001');
|
||||
});
|
||||
|
||||
for (const status of [422, 429, 500]) {
|
||||
await test(`HTTP ${status} never becomes a successful confirmation`, async (t) => {
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
errors: { email: ['Inválido'] },
|
||||
message: 'Internal diagnostic',
|
||||
}),
|
||||
{ status },
|
||||
),
|
||||
);
|
||||
await assert.rejects(
|
||||
portalRequest('/api/v1/interest-requests'),
|
||||
(error) => {
|
||||
assert.equal(error.status, status);
|
||||
assert.doesNotMatch(error.message, /Internal diagnostic/);
|
||||
if (status === 422)
|
||||
assert.equal(error.errors.email[0], 'Inválido');
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
await test('invalid JSON and network errors remain failures', async (t) => {
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () => new Response('<html>Error</html>', { status: 200 }),
|
||||
);
|
||||
await assert.rejects(portalRequest('/api/v1/home'), PortalApiError);
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
});
|
||||
await assert.rejects(portalRequest('/api/v1/home'), TypeError);
|
||||
});
|
||||
Reference in New Issue
Block a user