oportunidades 5
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-10 14:15:28 +02:00
parent 6ddafc95ba
commit 01405cbf8a
144 changed files with 28903 additions and 1103 deletions
@@ -0,0 +1,76 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityManagement;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class DashboardOpportunityAccessTest extends TestCase
{
use RefreshDatabase;
public function test_dashboard_exposes_authorized_destinations_and_complete_draft_archive_recovery(): void
{
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email], 'portal.opportunity_dashboard_access_enabled' => true]);
$this->actingAs($manager)->get('/dashboard')->assertOk()->assertInertia(fn (Assert $page) => $page
->component('dashboard')->where('auth.canManagePortal', true)
->where('opportunityManagement.installed', true)
->where('opportunityManagement.manage.label', 'Gestão de Oportunidades')
->where('opportunityManagement.create.label', 'Nova oportunidade'));
// Discover destinations from the dashboard response, rather than assuming
// a successful direct request proves dashboard navigation.
$dashboard = $this->get('/dashboard')->viewData('page')['props']['opportunityManagement'];
$this->get($dashboard['manage']['href'])->assertInertia(fn (Assert $page) => $page->component('management/opportunities'));
$this->get($dashboard['create']['href'])->assertInertia(fn (Assert $page) => $page->component('management/opportunity-draft')->where('record', null));
$draft = $this->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid(), 'title' => 'QA dashboard draft', 'reason' => 'Criação de rascunho pelo painel de gestão QA'])->assertCreated()->json();
$id = $draft['id'];
$this->get('/management/opportunities/'.$id.'/edit')->assertInertia(fn (Assert $page) => $page->where('values.title', 'QA dashboard draft'));
$update = $this->putJson('/management/opportunities/'.$id.'/draft', ['etag' => $draft['etag'], 'title' => 'QA dashboard edited', 'reason' => 'Edição e recuperação autorizadas no ensaio QA'])->assertOk()->json();
$request = ['etag' => $update['etag'], 'action' => 'archive', 'reason' => 'Arquivo explícito sem eliminar o rascunho QA', 'confirm' => true];
$this->postJson('/management/opportunities/'.$id.'/lifecycle', [...$request, 'confirm' => false])->assertUnprocessable();
$this->postJson('/management/opportunities/'.$id.'/lifecycle', $request)->assertOk();
$this->assertDatabaseHas('opportunities', ['id' => $id, 'status' => 'archived', 'title' => 'QA dashboard edited', 'deleted_at' => null, 'first_submitted_at' => null, 'management_closed_once' => false]);
$this->get($dashboard['manage']['href'].'?status=archived')->assertInertia(fn (Assert $page) => $page->where('records.data.0.id', $id));
$this->putJson('/management/opportunities/'.$id.'/draft', ['etag' => $update['etag'], 'reason' => $request['reason']])->assertConflict();
$this->postJson('/management/opportunities/'.$id.'/lifecycle', [...$request, 'action' => 'restore', 'etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id))])->assertOk();
$this->get('/management/opportunities/'.$id.'/edit')->assertInertia(fn (Assert $page) => $page->where('record.status', 'draft')->where('values.title', 'QA dashboard edited'));
$this->assertSame(0, Opportunity::published()->count());
$this->assertSame(4, DB::table('audit_events')->where('source_system', 'opportunity-management')->where('after_data->record_id', $id)->count());
}
public function test_investor_unverified_manager_and_guest_do_not_gain_management_access(): void
{
$manager = User::factory()->unverified()->create();
$investor = User::factory()->create();
config(['portal.managers' => [$manager->email], 'portal.opportunity_dashboard_access_enabled' => true]);
$this->actingAs($investor)->get('/dashboard')->assertInertia(fn (Assert $page) => $page->where('summary', null)->where('opportunityManagement', null)->where('auth.canManagePortal', false));
$this->get('/management/opportunities')->assertForbidden();
$this->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid()])->assertForbidden();
$this->actingAs($manager)->get('/dashboard')->assertRedirect('/email/verify');
$this->getJson('/management/opportunities')->assertForbidden();
$this->assertSame(0, Opportunity::count());
auth()->forgetGuards();
$this->flushSession();
$this->get('/dashboard')->assertRedirect('/login');
}
public function test_missing_installation_is_explicit_and_disabled_increment_preserves_compatibility(): void
{
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email], 'portal.opportunity_dashboard_access_enabled' => false]);
$this->actingAs($manager)->get('/dashboard')->assertInertia(fn (Assert $page) => $page->where('opportunityManagement', null));
$this->postJson('/management/opportunities/1/lifecycle', ['etag' => str_repeat('a', 64), 'action' => 'archive', 'reason' => 'Incremento ainda não disponibilizado nesta configuração', 'confirm' => true])->assertUnprocessable();
config(['portal.opportunity_dashboard_access_enabled' => true]);
$migration = require database_path('migrations/2026_10_09_020000_extend_opportunity_management.php');
$migration->down();
$this->get('/dashboard')->assertInertia(fn (Assert $page) => $page->where('opportunityManagement.installed', false)->where('opportunityManagement.installationHref', '/management/opportunity-management-install'));
$this->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid()])->assertServiceUnavailable();
}
}
+50
View File
@@ -5,12 +5,14 @@ namespace Tests\Feature;
use App\Console\Commands\ImportDocumentBatch;
use App\Jobs\ScanDocumentForMalware;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\Support\SyntheticDocument;
use Tests\TestCase;
class ImportDocumentBatchTest extends TestCase
@@ -50,6 +52,7 @@ class ImportDocumentBatchTest extends TestCase
];
file_put_contents($this->staging.'/manifest.json', json_encode(['documents' => [$record, $record]], JSON_THROW_ON_ERROR));
$actor = User::factory()->create();
config(['portal.managers' => [$actor->email]]);
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json'])->assertSuccessful();
$this->assertDatabaseCount('documents', 0);
@@ -87,4 +90,51 @@ class ImportDocumentBatchTest extends TestCase
$this->artisan(new ImportDocumentBatch, ['manifest' => $this->batchName.'/manifest.json'])->assertFailed();
$this->assertDatabaseCount('documents', 0);
}
public function test_qa_batch_real_scan_preserves_original_replay_identity_conflict_and_profile_guards(): void
{
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1', 'services.malware.port' => 3310]);
$scanner = app(MalwareScanner::class);
if (! $scanner->health()['available']) {
$this->markTestSkipped('Real ClamD required for batch evidence.');
}
$bytes = SyntheticDocument::pdf('Synthetic QA batch - no official or legal value');
file_put_contents($this->staging.'/source.pdf', $bytes);
$record = ['external_id' => 'qa-batch-v1', 'relative_path' => $this->batchName.'/source.pdf', 'title' => 'Synthetic QA batch',
'issuer' => 'Synthetic QA issuer', 'source_url' => 'https://example.invalid/qa', 'version_label' => 'QA-1'];
file_put_contents($this->staging.'/manifest.json', json_encode(['documents' => [$record, $record]], JSON_THROW_ON_ERROR));
$actor = User::factory()->create();
$options = ['manifest' => $this->batchName.'/manifest.json', '--apply' => true, '--actor' => (string) $actor->id];
$this->artisan(new ImportDocumentBatch, $options)->assertFailed();
$this->assertDatabaseCount('documents', 0);
$this->assertSame([], Storage::disk('local')->allFiles('portal-documents'));
config(['portal.managers' => [$actor->email]]);
$this->app->detectEnvironment(fn () => 'production');
$this->artisan(new ImportDocumentBatch, $options)->assertFailed();
$this->app->detectEnvironment(fn () => 'testing');
$this->assertDatabaseCount('documents', 0);
$this->artisan(new ImportDocumentBatch, $options)->assertSuccessful();
$document = DB::table('documents')->firstOrFail();
$this->assertSame($bytes, Storage::disk('local')->get($document->storage_key));
$this->assertDatabaseCount('documents', 1);
$this->assertDatabaseCount('portal_resources', 1);
(new ScanDocumentForMalware($document->id))->handle($scanner);
$scanned = DB::table('documents')->where('id', $document->id)->first();
$this->assertSame('clean', $scanned->malware_scan_status);
$this->assertSame('ClamAV', $scanned->malware_engine);
$this->assertSame(hash('sha256', $bytes), $scanned->malware_scanned_sha256);
$response = $this->actingAs($actor)->get('/management/documents/'.$document->id.'/download')->assertOk();
$this->assertSame($bytes, file_get_contents($response->baseResponse->getFile()->getPathname()));
$resource = DB::table('portal_resources')->first();
$this->get('/documentos/'.$resource->id.'/download')->assertNotFound();
$this->artisan(new ImportDocumentBatch, $options)->assertSuccessful();
file_put_contents($this->staging.'/source.pdf', SyntheticDocument::pdf('Different QA bytes - same identity'));
$this->artisan(new ImportDocumentBatch, $options)->assertSuccessful();
$this->assertDatabaseCount('documents', 1);
$this->assertDatabaseCount('portal_resources', 1);
$this->assertSame($bytes, Storage::disk('local')->get($document->storage_key));
$this->assertDatabaseHas('portal_resources', ['id' => $resource->id, 'published' => false]);
$this->assertSame(1, DB::table('audit_events')->where('action', 'private_document_batch_imported')->count());
$this->actingAs(User::factory()->create())->get('/management/documents/'.$document->id.'/download')->assertForbidden();
}
}
@@ -0,0 +1,149 @@
<?php
namespace Tests\Feature;
use App\Jobs\ScanDocumentForMalware;
use App\Models\LandAssistanceCase;
use App\Models\User;
use App\Services\Malware\MalwareScanner;
use App\Services\PartnershipExchange;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\Support\SyntheticDocument;
use Tests\TestCase;
class IndependentDocumentOperationsTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
Queue::fake();
config(['services.malware.scanner' => 'clamd', 'services.malware.host' => '127.0.0.1', 'services.malware.port' => 3310]);
if (! app(MalwareScanner::class)->health()['available']) {
$this->markTestSkipped('Real ClamD required; no fabricated scan proof.');
}
}
private function files(): array
{
$image = imagecreatetruecolor(16, 16);
ob_start();
imagepng($image);
$png = ob_get_clean();
ob_start();
imagejpeg($image);
$jpeg = ob_get_clean();
imagedestroy($image);
return ['qa.pdf' => SyntheticDocument::pdf(), 'qa.png' => $png, 'qa.jpg' => $jpeg];
}
private function scan(string $id): object
{
(new ScanDocumentForMalware($id))->handle(app(MalwareScanner::class));
$document = DB::table('documents')->where('id', $id)->first();
$this->assertSame('active', $document->status);
$this->assertSame('clean', $document->malware_scan_status);
$this->assertSame('ClamAV', $document->malware_engine);
$this->assertSame(trim($document->sha256), $document->malware_scanned_sha256);
$this->assertNotNull($document->malware_signatures_at);
return $document;
}
public function test_land_pdf_png_jpeg_scan_recovery_print_and_profile_permissions_preserve_originals(): void
{
$owner = User::factory()->create();
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAs($owner)->postJson('/investidor/terra-duat', ['payload' => ['full_name' => 'Synthetic QA investor']])->assertCreated();
$case = LandAssistanceCase::firstOrFail();
$base = '/investidor/terra-duat/'.$case->id;
foreach ($this->files() as $name => $bytes) {
$this->post($base.'/documentos', ['version' => $case->fresh()->version, 'category' => str_ends_with($name, '.pdf') ? 'prior_right' : 'photo',
'file' => UploadedFile::fake()->createWithContent($name, $bytes)], ['Accept' => 'application/json'])->assertCreated();
$documentId = DB::table('documents')->where('file_name', $name)->value('id');
$link = DB::table('land_assistance_documents')->where('case_id', $case->id)->where('document_id', $documentId)->first();
$url = $base.'/documentos/'.$link->id;
$this->get($url)->assertNotFound();
$document = $this->scan($link->document_id);
$response = $this->get($url)->assertOk()->assertDownload($name);
$this->assertSame($bytes, file_get_contents($response->baseResponse->getFile()->getPathname()));
// Existing canonical encrypted originals must remain readable without making plaintext copies.
Storage::disk('local')->put($document->storage_key, Crypt::encryptString($bytes));
DB::table('documents')->where('id', $document->id)->update(['storage_encryption' => 'laravel']);
$this->get($url)->assertOk()->assertContent($bytes);
$this->assertSame($owner->id, $document->uploaded_by);
$this->assertSame(strlen($bytes), $document->size_bytes);
$this->actingAs($manager)->get($url)->assertNotFound();
$this->actingAs(User::factory()->create())->get($url)->assertNotFound();
$this->actingAs($owner)->getJson($base)->assertOk();
$this->assertSame($bytes, Crypt::decryptString(Storage::disk('local')->get($document->storage_key)));
Storage::disk('local')->put($document->storage_key, Crypt::encryptString('Tampered QA only'));
$this->get($url)->assertNotFound();
}
$this->get($base.'/imprimir')->assertOk(); // Printable response; browser PDF rendering remains pending.
$this->assertSame(3, DB::table('documents')->count());
$this->assertSame(3, DB::table('document_malware_scans')->where('result', 'clean')->count());
}
public function test_partnership_real_scans_sharing_revocation_new_session_and_encrypted_originals(): void
{
$owner = User::factory()->create();
$candidate = User::factory()->create();
$manager = User::factory()->create();
$outsider = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$exchange = app(PartnershipExchange::class);
$record = $exchange->save($owner, ['client_key' => (string) Str::uuid(), 'title' => 'Synthetic document QA partnership', 'kind' => 'seeking', 'partnership_type' => 'joint_venture',
'offer' => 'Synthetic QA capacity', 'seeking' => 'Synthetic QA contribution', 'payload' => ['summary' => 'Synthetic QA only', 'consent' => true], 'origins' => [], 'locations' => []]);
$record = $exchange->transition($owner, $record->id, $record->version, 'submit', 'QA private document test');
$record = $exchange->transition($manager, $record->id, $record->version, 'publish', 'QA fixture only; no active disclosure');
$interest = $exchange->interest($candidate, $record->id, ['proposal' => 'Synthetic QA proposal', 'payload' => ['consent' => true]]);
$interest = $exchange->decideInterest($owner, $interest->id, $interest->version, 'shortlist', 'QA room preparation');
$exchange->decideInterest($owner, $interest->id, $interest->version, 'connect', 'QA private room access');
$room = DB::table('partnership_rooms')->where('interest_id', $interest->id)->first();
$base = '/parcerias/salas/'.$room->id;
foreach ($this->files() as $name => $bytes) {
$this->actingAs($owner)->post($base.'/documentos', ['shared' => false, 'file' => UploadedFile::fake()->createWithContent($name, $bytes)], ['Accept' => 'application/json'])->assertOk();
$link = DB::table('partnership_documents')->where('room_id', $room->id)->orderByDesc('id')->first();
$url = $base.'/documentos/'.$link->id;
$this->get($url)->assertNotFound();
$document = $this->scan($link->document_id);
$response = $this->get($url)->assertOk()->assertDownload($name);
$this->assertSame($bytes, file_get_contents($response->baseResponse->getFile()->getPathname()));
$this->actingAs($candidate)->get($url)->assertNotFound();
$this->postJson($url.'/partilha', ['shared' => true])->assertForbidden();
$this->actingAs($owner)->postJson($url.'/partilha', ['shared' => true])->assertOk();
Storage::disk('local')->put($document->storage_key, Crypt::encryptString($bytes));
DB::table('documents')->where('id', $document->id)->update(['storage_encryption' => 'laravel']);
$this->actingAs($candidate)->get($url)->assertOk()->assertContent($bytes);
$this->assertSame($owner->id, $document->uploaded_by);
$this->assertSame(strlen($bytes), $document->size_bytes);
// A new authentication context recovers shared documents from the repository.
auth()->logout();
$this->actingAs($candidate->fresh())->getJson($base)->assertOk()->assertJsonCount(1, 'documents');
$this->get($url)->assertOk()->assertContent($bytes);
$this->actingAs($manager)->get($url)->assertForbidden();
$this->actingAs($outsider)->get($url)->assertForbidden();
$this->actingAs($owner)->postJson($url.'/partilha', ['shared' => false])->assertOk();
$this->actingAs($candidate)->get($url)->assertNotFound();
$this->getJson($base)->assertOk()->assertJsonCount(0, 'documents');
$this->actingAs($owner)->get($url)->assertOk()->assertContent($bytes);
$this->assertSame($bytes, Crypt::decryptString(Storage::disk('local')->get($document->storage_key)));
Storage::disk('local')->put($document->storage_key, Crypt::encryptString('Tampered QA only'));
$this->get($url)->assertNotFound();
}
$this->assertSame(3, DB::table('documents')->count());
$this->assertSame(6, DB::table('partnership_events')->where('event_type', 'partnership.document_sharing_changed.v1')->count());
$this->assertSame(3, DB::table('document_malware_scans')->where('result', 'clean')->count());
}
}
@@ -0,0 +1,257 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityCanonicalContract;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAdministration;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class OpportunityCanonicalWorkflowTest extends TestCase
{
use RefreshDatabase;
private const REASON = 'Ensaio sintético de contratos e workflow independente em QA';
protected function setUp(): void
{
parent::setUp();
config(['portal.profile_access_enabled' => true, 'portal.opportunity_specialized_drafts_enabled' => true]);
}
/** @param list<string> $responsibilities */
private function actor(string $role, string $org, array $responsibilities = []): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()])->save();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), [
'user_id' => $user->id, 'role' => $role, 'organization_id' => $role === 'promoter' ? $org : null,
'opportunity_types' => OpportunityManagement::CATEGORIES, 'responsibilities' => $responsibilities, 'source' => 'synthetic-policy-test-fixture']);
return $user;
}
private function loginFixture(User $user): static
{
// Policy fixture only. Real Fortify/ClamD evidence comes from the QA HTTP scenario.
return $this->actingAs($user)->withSession(['portal.mfa_actor' => $user->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $user->portal_access_revision]);
}
/** @param array<string,mixed> $extra
* @return array<string,mixed> */
private function action(User $user, int $id, string $action, array $extra = [], int $status = 200): array
{
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
if ($action === 'publish') {
$extra = ['confirm_publication' => true, 'preview_hash' => Opportunity::findOrFail($id)->workflow_context['approval']['hash'] ?? str_repeat('0', 64), ...$extra];
}
return $this->loginFixture($user)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $etag, 'action' => $action, 'reason' => self::REASON, ...$extra])->assertStatus($status)->json();
}
public function test_incomplete_drafts_preserve_category_rules_and_block_client_certification(): void
{
$service = app(OpportunityCanonicalContract::class);
foreach (OpportunityManagement::CATEGORIES as $category) {
$this->assertSame(['opportunity_category' => $category], $service->draft(['opportunity_category' => $category]));
}
$this->assertSame(['real_estate' => ['transaction_type' => 'sale', 'valuation' => []]], $service->draft(['real_estate' => ['transaction_type' => 'sale', 'valuation' => []]]));
$this->assertSame(['real_estate' => ['transaction_type' => null, 'land_area' => null, 'property_type' => null]], $service->draft(['real_estate' => ['transaction_type' => null, 'land_area' => null, 'property_type' => null]]));
foreach ([['land_rights' => ['operation_type' => 'land_sale']], ['business_transaction' => ['percentage_offered' => 101]], ['real_estate' => ['land_area' => -1]], ['approved_by' => 99], ['evidences' => [['verified' => true]]]] as $invalid) {
try {
$service->draft($invalid);
$this->fail('Invalid provided data or response metadata must be rejected.');
} catch (ValidationException $e) {
$this->assertNotEmpty($e->errors());
}
}
$schema = $service->schema();
$this->assertNotEmpty($schema['$defs']['opportunityCreate']['allOf']);
$this->assertNotEmpty($schema['$defs']['realEstateCreate']['allOf']);
$this->assertNotEmpty($schema['$defs']['landRightsCreate']['allOf']);
$this->assertNotEmpty($schema['$defs']['businessTransactionCreate']['allOf']);
}
public function test_correction_approval_publication_material_revision_and_suspension_preserve_authorization(): void
{
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
$this->action($promoter, $id, 'submit');
$this->action($validator, $id, 'approve', [], 422);
$this->action($validator, $id, 'start_review');
$firstReview = Opportunity::findOrFail($id)->workflow_context['review_task_id'];
$this->action($validator, $id, 'request_correction', ['correction_items' => ['canonical.executive_summary']]);
$this->assertDatabaseHas('tasks', ['id' => $firstReview, 'status' => 'done']);
$payload['executive_summary'] .= ' Corrigido em QA.';
// Primary is deliberately second: array order must not change the public territory.
$primary = DB::table('opportunity_location_drafts')->where('id', $payload['locations'][0])->first();
$primaryData = json_decode($primary->payload, true);
$secondaryId = (string) Str::uuid();
$secondaryDistrict = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $secondaryDistrict, 'code' => $secondaryDistrict, 'name' => 'Non-primary QA district', 'location_type' => 'district', 'parent_id' => $primaryData['province_id'], 'data_classification' => 'internal']);
DB::table('opportunity_location_drafts')->insert(['id' => $secondaryId, 'opportunity_id' => $id, 'version' => 1, 'created_by' => $promoter->id, 'payload' => json_encode([...$primaryData, 'district_id' => $secondaryDistrict, 'is_primary' => false])]);
$payload['locations'] = [$secondaryId, $payload['locations'][0]];
$payload['location_mode'] = 'multiple';
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
$this->action($promoter, $id, 'submit');
$this->assertArrayNotHasKey('assignment', Opportunity::findOrFail($id)->workflow_context);
$this->action($validator, $id, 'start_review');
foreach (['property_review', 'registry_urban_review', 'building_compliance_review'] as $gate) {
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
}
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $promoter->id, 'role' => 'validator', 'opportunity_types' => ['real_estate'], 'responsibilities' => ['technical_reviewer', 'legal_reviewer']]);
$this->action($promoter, $id, 'approve', [], 403);
$this->action($validator, $id, 'approve');
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), User::factory()->create(), ['user_id' => $validator->id, 'role' => 'publisher', 'opportunity_types' => ['real_estate']]);
$this->action($validator, $id, 'publish', [], 403);
$this->action($publisher, $id, 'assign_publication', ['assignee_user_id' => $publisher->id]);
$otherPublisher = $this->actor('publisher', 'unused');
$this->action($otherPublisher, $id, 'publish', [], 403);
$grants = DB::table('portal_role_assignments')->where('user_id', $validator->id)->where('role', 'validator')->whereNull('revoked_at')->pluck('id');
DB::table('portal_role_assignments')->whereIn('id', $grants)->update(['revoked_at' => now()]);
$this->action($publisher, $id, 'publish', [], 403);
DB::table('portal_role_assignments')->whereIn('id', $grants)->update(['revoked_at' => null]);
$this->action($publisher, $id, 'publish');
$this->assertSame($primaryData['district_id'], Opportunity::findOrFail($id)->primary_territory_id);
$publicTitle = Opportunity::findOrFail($id)->title;
$this->assertSame(0, Opportunity::published()->count(), 'Internal publication must not leak to public consumers.');
$this->action($promoter, $id, 'request_revision');
$payload['official_title'] = 'Título materialmente alterado, ainda privado';
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
$record = Opportunity::findOrFail($id);
$this->assertSame('published', $record->status);
$this->assertSame($publicTitle, $record->title);
$this->assertArrayNotHasKey('approval', $record->workflow_context);
$this->assertSame('needs_information', $record->workflow_context['working_state']);
$this->get('/minhas-oportunidades?status=needs_information&q=materialmente')->assertInertia(fn (Assert $p) => $p->where('records.total', 1)->where('records.data.0.draft_title', 'Título materialmente alterado, ainda privado')->where('counts.needs_information', 1));
$this->action($publisher, $id, 'publish', [], 409);
$this->action($publisher, $id, 'suspend');
$this->assertSame('suspended', Opportunity::findOrFail($id)->status);
$this->assertDatabaseHas('tasks', ['source_system' => 'opportunity-workflow', 'task_type' => 'opportunity_review', 'assignee_user_id' => $validator->id, 'due_at' => null, 'status' => 'done']);
$this->assertSame('clean', DB::table('documents')->where('id', DB::table('opportunity_documents')->where('id', $document)->value('document_id'))->value('malware_scan_status'));
}
public function test_invalid_binding_reason_and_original_integrity_cannot_be_bypassed(): void
{
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
$bad = $payload;
$bad['real_estate']['price'] = null;
$bad['documents'] = [(string) Str::uuid()];
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $bad, 'reason' => self::REASON])->assertOk();
$this->action($promoter, $id, 'submit', [], 422);
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
$this->action($promoter, $id, 'submit');
$this->action($validator, $id, 'reject', ['reason' => 'curto'], 422);
$this->action($validator, $id, 'reject');
$this->assertDatabaseHas('tasks', ['id' => Opportunity::findOrFail($id)->workflow_context['review_task_id'], 'status' => 'done']);
$this->assertSame(self::REASON, Opportunity::findOrFail($id)->workflow_context['rejection']['reason']);
$this->action($promoter, $id, 'appeal');
$this->action($validator, $id, 'appeal_reopen', [], 403);
$appeal = $this->actor('validator', $promoter->id.'unused', ['appeal_reviewer']);
$this->action($appeal, $id, 'appeal_reopen');
$this->assertFalse(Opportunity::findOrFail($id)->workflow_context['appeal']['pending']);
$storageKey = DB::table('documents')->where('id', DB::table('opportunity_documents')->where('id', $document)->value('document_id'))->value('storage_key');
Storage::disk('local')->put($storageKey, 'Invalid ciphertext - synthetic QA only');
$this->action($promoter, $id, 'submit', [], 404);
$this->loginFixture($promoter)->get('/minhas-oportunidades/'.$id.'/resources/documents/'.$document.'/download')->assertNotFound();
}
public function test_semantic_errors_are_keyed_to_fields_and_incomplete_drafts_remain_recoverable(): void
{
[$id,$promoter,$validator,$publisher,$payload,$document] = $this->fixture();
foreach (['utilities', 'title_document_id', 'occupancy_document_id', 'valuation.value'] as $field) {
$bad = $payload;
if ($field === 'utilities') {
$bad['real_estate']['utilities'] = [];
} elseif ($field === 'title_document_id') {
unset($bad['real_estate'][$field]);
} elseif ($field === 'valuation.value') {
$bad['real_estate']['valuation']['value'] = 0;
} else {
$bad['real_estate']['occupancy_status'] = 'tenant_occupied';
}
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $bad, 'reason' => self::REASON])->assertOk();
$this->get('/minhas-oportunidades/'.$id.'/edit')->assertInertia(fn (Assert $page) => $page->where('values.canonical', $bad));
$this->loginFixture($promoter)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'action' => 'submit', 'reason' => self::REASON])->assertUnprocessable()->assertJsonValidationErrors('canonical.real_estate.'.$field);
}
}
public function test_scoped_opinion_tasks_require_the_recipient_and_do_not_approve_a_gate(): void
{
[$id,$promoter,$validator,$publisher,$payload,$document] = $this->fixture();
$opinionReviewer = $this->actor('validator', 'unused', ['technical_reviewer']);
$this->action($promoter, $id, 'submit');
$this->action($validator, $id, 'start_review');
$this->action($validator, $id, 'pending_opinion', ['gate' => 'property_review', 'recipient_user_id' => $opinionReviewer->id]);
$context = Opportunity::findOrFail($id)->workflow_context;
$opinion = array_key_first($context['opinions']);
$this->action($validator, $id, 'approve', [], 422);
$this->action($validator, $id, 'respond_opinion', ['opinion_id' => $opinion, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]], 403);
$this->loginFixture($opinionReviewer)->get('/minhas-oportunidades?queue=assigned')->assertInertia(fn (Assert $p) => $p->where('records.total', 1));
$this->action($opinionReviewer, $id, 'respond_opinion', ['opinion_id' => $opinion, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
$context = Opportunity::findOrFail($id)->workflow_context;
$this->assertSame('answered', $context['opinions'][$opinion]['status']);
$this->assertArrayNotHasKey('reviews', $context);
$this->assertDatabaseHas('tasks', ['id' => $context['opinions'][$opinion]['task_id'], 'status' => 'done']);
$this->action($validator, $id, 'approve', [], 422);
}
/** @return array{int,User,User,User,array<string,mixed>,string} */
private function fixture(): array
{
$org = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $org, 'name' => 'Synthetic QA organization', 'organization_type' => 'private']);
$promoter = $this->actor('promoter', $org);
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $promoter->id, 'organization_id' => $org, 'role' => 'officer']);
$validator = $this->actor('validator', $org, ['technical_reviewer', 'legal_reviewer', 'validation_coordinator']);
$publisher = $this->actor('publisher', $org, ['publication_coordinator']);
$version = (string) Str::uuid();
DB::table('reference_catalog_versions')->insert(['id' => $version, 'catalog_code' => 'qa-only', 'version_no' => 1, 'source_system' => 'synthetic-policy-fixture', 'source_version' => 'qa', 'source_reference' => 'Not official', 'status' => 'published']);
$ids = [];
$parent = null;
foreach (range(1, 3) as $i) {
$sector = DB::table('sectors')->insertGetId(['name' => 'QA '.$i, 'slug' => 'qa-'.$i, 'is_active' => true]);
$id = (string) Str::uuid();
DB::table('economic_activities')->insert(['id' => $id, 'parent_id' => $parent, 'sector_id' => $sector, 'catalog_version_id' => $version, 'code' => 'qa-'.$i, 'label_pt_mz' => 'QA '.$i, 'status' => 'published', 'valid_from' => today()]);
$ids[] = [$id, $sector];
$parent = $id;
}
$contact = (string) Str::uuid();
$investor = (string) Str::uuid();
DB::table('contacts')->insert(['id' => $contact, 'full_name' => 'Synthetic QA contact']);
DB::table('investors')->insert(['id' => $investor, 'organization_id' => $org, 'legal_name' => 'Synthetic QA entity', 'investor_type' => 'institutional', 'status' => 'active']);
DB::table('investor_contacts')->insert(['investor_id' => $investor, 'contact_id' => $contact]);
$draft = $this->loginFixture($promoter)->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => $org, 'opportunity_category' => 'real_estate', 'reason' => self::REASON])->assertCreated()->json();
$id = $draft['id'];
$location = (string) Str::uuid();
$provinceId = (string) Str::uuid();
$districtId = (string) Str::uuid();
DB::table('geo_locations')->insert([['id' => $provinceId, 'code' => $provinceId, 'name' => 'Synthetic QA province', 'location_type' => 'province', 'parent_id' => null, 'data_classification' => 'internal'], ['id' => $districtId, 'code' => $districtId, 'name' => 'Synthetic QA district', 'location_type' => 'district', 'parent_id' => $provinceId, 'data_classification' => 'internal']]);
$province = DB::table('geo_locations')->where('id', $provinceId)->first();
$district = DB::table('geo_locations')->where('id', $districtId)->first();
DB::table('opportunity_location_drafts')->insert(['id' => $location, 'opportunity_id' => $id, 'version' => 1, 'created_by' => $promoter->id, 'payload' => json_encode(['country_code' => 'MZ', 'province_id' => $province->id, 'district_id' => $district->id, 'role' => 'headquarters', 'is_primary' => true])]);
$document = (string) Str::uuid();
$file = (string) Str::uuid();
$bytes = 'Synthetic policy fixture, not a real scanner result.';
$key = 'opportunity-contract-test/'.$file;
Storage::disk('local')->put($key, Crypt::encryptString($bytes));
DB::table('documents')->insert(['id' => $file, 'file_name' => 'qa-fixture.txt', 'storage_key' => $key, 'storage_encryption' => 'laravel', 'media_type' => 'text/plain', 'sha256' => hash('sha256', $bytes), 'status' => 'active', 'malware_scan_status' => 'clean', 'malware_engine' => 'synthetic-policy-fixture', 'malware_scanned_sha256' => hash('sha256', $bytes), 'uploaded_by' => $promoter->id]);
DB::table('opportunity_documents')->insert(['id' => $document, 'opportunity_id' => $id, 'document_id' => $file, 'version' => 1, 'created_by' => $promoter->id, 'payload' => json_encode(['title' => 'QA', 'category' => 'qa', 'visibility' => 'internal'])]);
$payload = ['opportunity_category' => 'real_estate', 'official_title' => 'Imóvel sintético para ensaio QA', 'promoter_id' => $org, 'promoter_type' => 'private', 'internal_contact_id' => $contact, 'sector_id' => $ids[0][1], 'subsector_id' => $ids[1][0], 'economic_activity_id' => $ids[2][0], 'location_mode' => 'single', 'geographic_scope' => 'district', 'locations' => [$location], 'executive_summary' => trim(str_repeat('Resumo sintético QA. ', 20)), 'demand_statement' => trim(str_repeat('Necessidade sintética QA. ', 6)), 'documents' => [$document], 'evidences' => [['title' => 'QA', 'evidence_type' => 'qa', 'document_id' => $document]], 'publication_languages' => [['language_code' => 'pt-MZ', 'title' => 'QA', 'summary' => 'QA']], 'visibility' => 'internal', 'currency' => 'MZN', 'truth_declaration' => true, 'real_estate' => ['transaction_type' => 'sale', 'property_type' => 'warehouse', 'construction_status' => 'completed', 'property_condition' => 'good', 'land_area' => 1000, 'built_area' => 500, 'area_unit' => 'sqm', 'utilities' => [['type' => 'water', 'status' => 'existing']], 'occupancy_status' => 'vacant', 'title_type' => 'QA', 'registration_number' => 'QA-'.$id, 'encumbrances' => [['type' => 'none']], 'valuation' => ['value' => 1000, 'date' => '2026-10-10', 'method' => 'qa', 'appraiser' => 'QA', 'document_id' => $document], 'price' => 1000, 'use_license_document_id' => $document]];
$authority = (string) Str::uuid();
DB::table('authorities')->insert(['id' => $authority, 'catalog_version_id' => $version, 'organization_id' => $org, 'code' => 'QA-'.$id, 'authority_type' => 'qa-synthetic', 'label_pt_mz' => 'Entidade sintética QA', 'source_reference' => 'Synthetic policy fixture; not official', 'valid_from' => '2026-01-01', 'status' => 'published']);
$payload['real_estate']['utilities'] = array_map(fn ($type) => ['type' => $type, 'status' => 'existing'], ['electricity', 'water', 'sanitation', 'telecommunications', 'access']);
$payload['real_estate'] += ['title_document_id' => $document, 'title_holder_name' => 'Synthetic QA organization', 'issuing_authority_id' => $authority];
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $draft['etag'], 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
return [$id, $promoter, $validator, $publisher, $payload, $document];
}
}
@@ -0,0 +1,34 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class OpportunityPublicationScopeTest extends TestCase
{
use RefreshDatabase;
public function test_approval_restricted_and_public_labels_follow_actual_catalog_policy(): void
{
$owner = User::factory()->create();
$id = DB::table('opportunities')->insertGetId(['reference' => 'QA-publication-scope', 'slug' => 'qa-publication-scope', 'status' => 'approved',
'owner_user_id' => $owner->id, 'workflow_context' => json_encode(['publication' => ['visibility' => 'public']])]);
$record = Opportunity::findOrFail($id);
$this->assertSame('unpublished', $record->publicationPresentation()['scope']);
$record->forceFill(['status' => 'published', 'published_at' => now(), 'workflow_context' => ['publication' => ['visibility' => 'internal']]])->save();
$this->assertSame('restricted', $record->publicationPresentation()['scope']);
$this->assertFalse($record->publicationPresentation()['public_catalog']);
$this->assertFalse(Opportunity::published()->whereKey($id)->exists());
$record->forceFill(['workflow_context' => ['publication' => ['visibility' => 'public']]])->save();
$this->assertTrue($record->publicationPresentation()['public_catalog']);
$this->assertSame('public', $record->publicationPresentation()['scope']);
$record->forceFill(['status' => 'suspended'])->save();
$this->assertSame('unpublished', $record->publicationPresentation()['scope']);
$record->forceFill(['status' => 'published', 'published_at' => now()->addDay()])->save();
$this->assertFalse($record->publicationPresentation()['public_catalog']);
}
}
@@ -0,0 +1,56 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Models\User;
use App\Services\OpportunityManagement;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class OpportunityRealEstateDraftTest extends TestCase
{
use RefreshDatabase;
public function test_partial_real_estate_draft_is_private_recoverable_and_patch_preserves_other_fields(): void
{
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email], 'portal.opportunity_specialized_drafts_enabled' => true]);
$payload = ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'real_estate', 'title' => 'QA imóvel incompleto', 'real_estate' => ['transaction_type' => 'lease', 'land_area' => 250.5, 'area_unit' => 'sqm'], 'reason' => 'Rascunho imobiliário incompleto sem decisão externa'];
$draft = $this->actingAs($manager)->postJson('/management/opportunities/drafts', $payload)->assertCreated()->json();
$this->postJson('/management/opportunities/drafts', $payload)->assertCreated()->assertJsonPath('id', $draft['id']);
$this->assertSame(1, Opportunity::count());
$path = '/management/opportunities/'.$draft['id'].'/edit';
$this->get($path)->assertInertia(fn (Assert $page) => $page->where('values.real_estate.land_area', 250.5)->where('record.status', 'draft'));
$this->putJson('/management/opportunities/'.$draft['id'].'/draft', ['etag' => $draft['etag'], 'real_estate' => ['rent' => 1000, 'rent_periodicity' => 'monthly'], 'reason' => 'Complemento de renda no mesmo rascunho imobiliário'])->assertOk();
$this->get($path)->assertInertia(fn (Assert $page) => $page->where('values.real_estate.land_area', 250.5)->where('values.real_estate.rent', 1000));
$record = Opportunity::findOrFail($draft['id']);
$before = $record->getRawOriginal();
foreach ([['price' => 0], ['price' => '100'], ['transaction_type' => 'sell_duat'], ['id' => (string) Str::uuid()], ['utilities' => ['invalid scalar']], ['planning_permit_document_id' => 'not-uuid']] as $invalid) {
$this->putJson('/management/opportunities/'.$draft['id'].'/draft', ['etag' => app(OpportunityManagement::class)->etag($record), 'real_estate' => $invalid, 'reason' => 'Negativo contratual que deve conservar o rascunho'])->assertUnprocessable();
$this->assertSame($before, $record->fresh()->getRawOriginal());
}
$this->actingAs(User::factory()->create())->get($path)->assertForbidden();
$this->assertSame(0, Opportunity::published()->count());
}
public function test_specialized_draft_never_changes_published_version_and_is_disabled_by_default(): void
{
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAs($manager)->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'real_estate', 'real_estate' => ['transaction_type' => 'sale'], 'reason' => 'Incremento desativado mantém compatibilidade ativa'])->assertUnprocessable();
$this->assertSame(0, Opportunity::count());
config(['portal.opportunity_specialized_drafts_enabled' => true]);
$sector = Sector::create(['name' => 'QA imóveis', 'slug' => 'qa-real-estate', 'is_active' => true, 'sort_order' => 1]);
$record = Opportunity::create(['title' => 'QA published original', 'reference' => 'QA-RE-PUBLISHED', 'slug' => 'qa-re-published', 'sector_id' => $sector->id, 'status' => 'published', 'published_at' => now(), 'opportunity_category' => 'real_estate', 'management_version' => 1]);
$record->forceFill(['opportunity_category' => 'real_estate'])->save();
$this->putJson('/management/opportunities/'.$record->id.'/draft', ['etag' => app(OpportunityManagement::class)->etag($record), 'real_estate' => ['transaction_type' => 'sale', 'price' => 50000], 'reason' => 'Nova proposta privada sem alteração da ficha publicada'])->assertOk();
$this->assertSame('QA published original', $record->fresh()->title);
$this->assertSame('published', $record->fresh()->status);
$this->getJson('/api/v1/opportunities/qa-re-published')->assertOk()->assertJsonMissingPath('data.real_estate')->assertJsonMissingPath('data.management_draft');
$this->assertSame(50000, json_decode($record->fresh()->management_draft, true)['real_estate']['price']);
}
}
+12 -1
View File
@@ -21,6 +21,7 @@ class OpportunityResourcesTest extends TestCase
{
use RefreshDatabase;
/** @return array{User,Opportunity} */
private function setupDraft(): array
{
Storage::fake('local');
@@ -28,10 +29,15 @@ class OpportunityResourcesTest extends TestCase
$user = User::factory()->create();
config(['portal.managers' => [$user->email]]);
$id = $this->actingAs($user)->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid(), 'reason' => 'Rascunho de recursos em QA isolada'])->assertCreated()->json('id');
if (! is_int($id)) {
throw new \RuntimeException('O cadastro QA deve devolver um ID inteiro de oportunidade.');
}
return [$user, Opportunity::findOrFail($id)];
}
/** @param array<string,mixed> $payload
* @return array<string,mixed> */
private function payload(Opportunity $opportunity, array $payload = []): array
{
return ['etag' => app(OpportunityManagement::class)->etag($opportunity), 'creation_key' => (string) Str::uuid(), 'payload' => $payload, 'reason' => 'Preparação e conferência em QA isolada'];
@@ -64,6 +70,7 @@ class OpportunityResourcesTest extends TestCase
$life = ['etag' => app(OpportunityManagement::class)->etag($o->fresh()), 'version' => 2, 'action' => 'delete', 'confirm' => true, 'reason' => 'Exclusão lógica de anexo apenas QA'];
$this->postJson('/management/opportunities/'.$o->id.'/resources/documents/'.$r->id.'/lifecycle', $life)->assertOk();
$this->assertSoftDeleted('opportunity_documents', ['id' => $r->id]);
$this->get('/management/opportunities/'.$o->id.'/resources/documents/'.$r->id.'/download')->assertNotFound();
$this->postJson('/management/opportunities/'.$o->id.'/resources/documents/'.$r->id.'/lifecycle', [...$life, 'etag' => app(OpportunityManagement::class)->etag($o->fresh()), 'version' => 3, 'action' => 'restore'])->assertOk();
$this->assertDatabaseHas('opportunity_documents', ['id' => $r->id, 'deleted_at' => null, 'version' => 4]);
$this->assertSame(4, DB::table('audit_events')->where('source_system', 'opportunity-resources')->count());
@@ -122,7 +129,11 @@ class OpportunityResourcesTest extends TestCase
$this->assertSame('pending', $document->malware_scan_status);
$webp = Crypt::decryptString(Storage::disk('local')->get($document->storage_key));
$this->assertStringNotContainsString('EXIF', $webp);
$this->assertSame('image/webp', getimagesizefromstring($webp)['mime']);
$size = getimagesizefromstring($webp);
if ($size === false) {
throw new \RuntimeException('Derivada QA não contém uma imagem válida.');
}
$this->assertSame('image/webp', $size['mime']);
(new ScanDocumentForMalware($document->id))->handle(new CleanScannerFixture);
}
$preview = URL::temporarySignedRoute('management.opportunity-image-preview', now()->addMinutes(10), ['id' => $o->id, 'resourceId' => $image->id, 'documentId' => $payload['derivatives'][0]['document_id']]);
+263
View File
@@ -0,0 +1,263 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\OpportunityManagement;
use App\Services\PortalProfileAccess;
use App\Services\PortalProfileAdministration;
use App\Services\PortalSuperusers;
use Illuminate\Database\QueryException;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class PortalProfileAccessTest extends TestCase
{
use RefreshDatabase;
private const REASON = 'Verificação sintética de permissões na base QA isolada';
protected function setUp(): void
{
parent::setUp();
config(['portal.profile_access_enabled' => true]);
}
private function actor(): User
{
$user = User::factory()->create();
$user->forceFill(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()])->save();
return $user;
}
private function organization(User ...$users): string
{
$id = (string) Str::uuid();
DB::table('organizations')->insert(['id' => $id, 'name' => 'QA synthetic organization', 'organization_type' => 'private']);
foreach ($users as $user) {
DB::table('memberships')->insert(['id' => (string) Str::uuid(), 'user_id' => $user->id, 'organization_id' => $id, 'role' => 'officer']);
}
return $id;
}
private function grant(User $user, string $role, ?string $organization = null, array $types = ['investment_project']): string
{
$id = (string) Str::uuid();
app(PortalProfileAdministration::class)->insertGrant($id, $this->actor(), ['user_id' => $user->id, 'role' => $role, 'organization_id' => $organization,
'opportunity_types' => $types, 'source' => 'synthetic-test-fixture']);
return $id;
}
private function mfa(User $user): static
{
return $this->actingAs($user)->withSession(['portal.mfa_actor' => $user->id, 'portal.mfa_at' => time(), 'portal.access_revision' => (int) $user->fresh()->portal_access_revision]);
}
private function draft(User $user, ?string $organization = null): array
{
return $this->actingAs($user)->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => $organization,
'opportunity_category' => 'investment_project', 'title' => 'QA private opportunity', 'reason' => self::REASON])->assertCreated()->json();
}
public function test_public_profile_requests_are_owned_idempotent_and_not_self_activating(): void
{
$user = User::factory()->create();
$other = User::factory()->create();
$this->actingAs($user)->get('/dashboard')->assertInertia(fn (Assert $p) => $p->where('profileAccess.mine', null)->where('profileAccess.request', '/perfil/promotor'));
$this->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'opportunity_category' => 'investment_project'])->assertForbidden();
$doc = (string) Str::uuid();
// This is an authorization fixture, not evidence of a real antimalware scan.
DB::table('documents')->insert(['id' => $doc, 'file_name' => 'synthetic.txt', 'storage_key' => 'synthetic/'.$doc, 'media_type' => 'text/plain',
'sha256' => str_repeat('a', 64), 'malware_scanned_sha256' => str_repeat('a', 64), 'status' => 'active', 'malware_scan_status' => 'clean', 'uploaded_by' => $user->id]);
$payload = ['creation_key' => (string) Str::uuid(), 'representation_type' => 'individual', 'opportunity_types' => ['investment_project'], 'document_ids' => [$doc], 'reason' => self::REASON];
$id = $this->postJson('/perfil/promotor', $payload)->assertCreated()->json('id');
$this->postJson('/perfil/promotor', $payload)->assertCreated()->assertJsonPath('id', $id);
$this->postJson('/perfil/promotor', [...$payload, 'reason' => self::REASON.' changed'])->assertConflict();
$this->getJson('/perfil/promotor/'.$id)->assertOk()->assertJsonPath('status', 'pending');
$this->assertFalse(app(PortalProfileAccess::class)->has($user, 'promoter'));
$this->getJson('/minhas-oportunidades/territory-options?type=province')->assertForbidden();
$this->actingAs($other)->getJson('/perfil/promotor/'.$id)->assertForbidden();
$this->postJson('/perfil/promotor', [...$payload, 'creation_key' => (string) Str::uuid()])->assertUnprocessable();
}
public function test_promoters_share_authorized_organization_drafts_but_not_other_scopes_or_types(): void
{
$author = $this->actor();
$colleague = $this->actor();
$outsider = $this->actor();
$organization = $this->organization($author, $colleague);
$otherOrganization = $this->organization($outsider);
$this->grant($author, 'promoter', $organization);
$this->grant($colleague, 'promoter', $organization);
$this->grant($outsider, 'promoter', $otherOrganization);
$draft = $this->draft($author, $organization);
$id = $draft['id'];
$this->get('/dashboard')->assertInertia(fn (Assert $p) => $p->where('profileAccess.mine', '/minhas-oportunidades')->where('profileAccess.create', '/minhas-oportunidades/create'));
$this->actingAs($colleague)->get('/minhas-oportunidades/'.$id.'/edit')->assertInertia(fn (Assert $p) => $p->where('values.title', 'QA private opportunity')->where('readOnly', false));
$update = $this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $draft['etag'], 'title' => 'QA shared edit', 'reason' => self::REASON])->assertOk()->json();
$this->assertSame($author->id, (int) Opportunity::findOrFail($id)->owner_user_id);
$this->assertSame([$author->id, $colleague->id], Opportunity::findOrFail($id)->workflow_context['contributors']);
$this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $update['etag'], 'organization_id' => $otherOrganization, 'reason' => self::REASON])->assertForbidden();
$this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $update['etag'], 'opportunity_category' => 'financing', 'reason' => self::REASON])->assertForbidden();
$this->actingAs($outsider)->get('/minhas-oportunidades/'.$id.'/view')->assertForbidden();
$this->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => $organization, 'opportunity_category' => 'investment_project', 'reason' => self::REASON])->assertForbidden();
$this->get('/minhas-oportunidades')->assertInertia(fn (Assert $p) => $p->where('records.total', 0));
DB::table('memberships')->where('user_id', $colleague->id)->update(['deleted_at' => now()]);
$this->actingAs($colleague)->get('/minhas-oportunidades/'.$id.'/view')->assertForbidden();
}
public function test_profile_decisions_do_not_fabricate_checks_and_privileged_grants_require_confirmed_mfa(): void
{
$first = $this->actor();
$second = $this->actor();
$bootstrap = $this->actor();
config(['portal_profiles.bootstrap_authorized' => true]);
$this->mfa($bootstrap);
app(PortalSuperusers::class)->initialize($first, $second, $bootstrap);
$doc = (string) Str::uuid();
DB::table('documents')->insert(['id' => $doc, 'file_name' => 'synthetic-authorization-fixture.txt', 'storage_key' => 'synthetic/'.$doc,
'media_type' => 'text/plain', 'sha256' => str_repeat('b', 64), 'malware_scanned_sha256' => str_repeat('b', 64),
'status' => 'active', 'malware_scan_status' => 'clean', 'uploaded_by' => $first->id]);
$request = $this->mfa($first)->postJson('/perfil/promotor', ['creation_key' => (string) Str::uuid(), 'representation_type' => 'individual',
'opportunity_types' => ['investment_project'], 'document_ids' => [$doc], 'reason' => self::REASON])->assertCreated()->json('id');
$decision = ['version' => 1, 'decision' => 'rejected', 'reason' => self::REASON, 'approved_types' => [],
'verified_identity' => false, 'verified_representation' => false, 'verified_documents' => false];
$this->postJson('/perfis/pedidos/'.$request.'/decisao', $decision)->assertForbidden();
$this->mfa($second)->postJson('/perfis/pedidos/'.$request.'/decisao', $decision)->assertOk();
$this->assertDatabaseHas('portal_profile_requests', ['id' => $request, 'status' => 'rejected']);
$this->assertFalse(app(PortalProfileAccess::class)->has($first, 'promoter'));
$event = json_decode(DB::table('audit_events')->where('action', 'promoter_request_decided')->value('after_data'), true);
$this->assertFalse($event['checks']['verified_documents']);
$unenrolled = User::factory()->create();
$this->postJson('/perfis/atribuicoes', ['user_id' => $unenrolled->id, 'role' => 'validator',
'opportunity_types' => ['investment_project'], 'reason' => self::REASON])->assertUnprocessable();
$this->postJson('/perfis/atribuicoes', ['user_id' => $bootstrap->id, 'role' => 'auditor', 'responsibilities' => ['validation_coordinator'],
'opportunity_types' => ['investment_project'], 'reason' => self::REASON])->assertUnprocessable();
$expired = $this->grant($bootstrap, 'validator');
DB::table('portal_role_assignments')->where('id', $expired)->update(['starts_at' => now()->subDays(2), 'expires_at' => now()->subDay()]);
$this->assertFalse(app(PortalProfileAccess::class)->has($bootstrap, 'validator'));
}
public function test_role_accumulation_does_not_override_author_auditor_or_state_denials(): void
{
$user = $this->actor();
$this->grant($user, 'promoter');
$draft = $this->draft($user);
$id = $draft['id'];
$this->grant($user, 'validator');
$this->grant($user, 'publisher');
DB::table('opportunities')->where('id', $id)->update(['status' => 'submitted']);
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
$this->mfa($user)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $etag, 'action' => 'approve', 'reason' => self::REASON])->assertForbidden();
$this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $etag, 'reason' => self::REASON])->assertForbidden();
DB::table('opportunities')->where('id', $id)->update(['status' => 'draft']);
config(['portal.managers' => [$user->email], 'portal.opportunity_dashboard_access_enabled' => true]);
$this->get('/management/opportunities/create')->assertForbidden();
$this->postJson('/management/opportunities/drafts', ['creation_key' => (string) Str::uuid(), 'title' => 'Legacy bypass'])->assertForbidden();
$this->get('/dashboard')->assertInertia(fn (Assert $p) => $p->where('opportunityManagement', null)->where('summary.canCreateOpportunity', false));
$this->grant($user, 'auditor');
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
$this->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $etag, 'title' => 'forbidden', 'reason' => self::REASON])->assertForbidden();
$this->get('/minhas-oportunidades/'.$id.'/view')->assertOk();
$this->postJson('/management/sectors', ['name' => 'Auditor bypass'])->assertForbidden();
$this->assertSame('QA private opportunity', Opportunity::findOrFail($id)->title);
}
public function test_independent_review_preserves_versions_and_normative_gates_remain_closed(): void
{
$promoter = $this->actor();
$validator = $this->actor();
$publisher = $this->actor();
$this->grant($promoter, 'promoter');
$this->grant($validator, 'validator');
$this->grant($publisher, 'publisher');
$draft = $this->draft($promoter);
$id = $draft['id'];
$this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $draft['etag'], 'action' => 'submit', 'reason' => self::REASON])->assertUnprocessable();
$this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $draft['etag'], 'action' => 'request_archive', 'reason' => self::REASON])->assertOk()->assertJsonPath('status', 'draft');
$this->assertNotNull(Opportunity::findOrFail($id)->workflow_context['request_archive']);
// Explicit review-state fixture exercises the developing workflow, not a complete submission.
$context = Opportunity::findOrFail($id)->workflow_context;
$context['working_state'] = 'submitted';
DB::table('opportunities')->where('id', $id)->update(['status' => 'submitted', 'workflow_context' => json_encode($context)]);
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
$this->actingAs($validator)->withSession(['portal.mfa_actor' => null])->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $etag, 'action' => 'start_review', 'reason' => self::REASON])->assertForbidden();
$review = $this->mfa($validator)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $etag, 'action' => 'start_review', 'reason' => self::REASON])->assertOk()->json();
$this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $review['etag'], 'action' => 'approve', 'reason' => self::REASON])->assertUnprocessable();
$correction = $this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $review['etag'], 'action' => 'request_correction', 'reason' => self::REASON, 'correction_items' => ['summary']])->assertOk()->json();
$this->actingAs($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $correction['etag'], 'summary' => 'QA correction', 'reason' => self::REASON])->assertOk();
$etag = app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id));
$this->mfa($publisher)->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => $etag, 'action' => 'publish', 'reason' => self::REASON])->assertConflict();
$this->assertSame(0, Opportunity::published()->count());
}
public function test_revocation_invalidates_existing_session_and_legacy_manager_cannot_bypass_scope(): void
{
$first = $this->actor();
$second = $this->actor();
$approver = $this->actor();
config(['portal_profiles.bootstrap_authorized' => true]);
$this->mfa($approver);
app(PortalSuperusers::class)->initialize($first, $second, $approver);
$promoter = $this->actor();
$assignment = $this->grant($promoter, 'promoter');
$draft = $this->draft($promoter);
$manager = $this->actor();
config(['portal.managers' => [$manager->email]]);
$this->actingAs($manager)->get('/management/opportunities/'.$draft['id'].'/edit')->assertForbidden();
$this->get('/management/opportunities')->assertInertia(fn (Assert $p) => $p->where('records.total', 0));
$this->putJson('/api/v1/investment/admin/opportunities/'.$draft['id'].'/context', [])->assertForbidden();
$this->getJson('/management/territories/opportunities/'.$draft['id'])->assertForbidden();
$this->getJson('/management/territory-subjects?kind=opportunities')->assertJsonCount(0, 'data');
$this->postJson('/management/opportunity-origin/preview', ['id' => $draft['id'], 'classification' => 'real', 'reason' => self::REASON])->assertForbidden();
$this->mfa($first)->postJson('/perfis/atribuicoes/'.$assignment.'/revogar', ['reason' => self::REASON])->assertOk();
$this->actingAs($promoter)->withSession(['portal.access_revision' => 0])->getJson('/minhas-oportunidades/'.$draft['id'].'/view')->assertUnauthorized();
$this->assertDatabaseHas('portal_role_assignments', ['id' => $assignment]);
$this->assertFalse(app(PortalProfileAccess::class)->has($promoter, 'promoter'));
}
public function test_superuser_pair_is_initialized_once_and_replaced_atomically_with_independent_approval(): void
{
$first = $this->actor();
$second = $this->actor();
$approver = $this->actor();
$candidate = $this->actor();
config(['portal_profiles.bootstrap_authorized' => true]);
$this->mfa($approver);
$service = app(PortalSuperusers::class);
$service->initialize($first, $second, $approver);
$service->initialize($first, $second, $approver);
$this->assertSame(1, DB::table('portal_superuser_pair')->count());
$this->mfa($first)->deleteJson('/user/two-factor-authentication')->assertForbidden();
$this->deleteJson('/settings/profile')->assertForbidden();
$this->patchJson('/settings/profile', ['email' => 'changed-qa@example.invalid'])->assertForbidden();
$this->assertNotNull($first->fresh()->two_factor_secret);
try {
DB::transaction(fn () => DB::table('portal_superuser_pair')->delete());
$this->fail('Removal of the pair must be blocked by PostgreSQL.');
} catch (QueryException $error) {
$this->assertStringContainsString('Superuser pair cannot be removed', $error->getMessage());
}
$this->assertSame(1, DB::table('portal_superuser_pair')->count());
$this->mfa($first)->postJson('/perfis/atribuicoes', ['user_id' => $candidate->id, 'role' => 'superuser', 'opportunity_types' => ['investment_project'], 'reason' => self::REASON])->assertUnprocessable();
$id = $this->postJson('/perfis/substituicoes', ['old_user_id' => $second->id, 'new_user_id' => $candidate->id, 'reason' => self::REASON])->assertCreated()->json('id');
$this->postJson('/perfis/seguranca/'.$id.'/aprovar')->assertForbidden();
$this->postJson('/perfis/substituicoes/'.$id.'/aplicar')->assertConflict();
$this->mfa($second)->postJson('/perfis/seguranca/'.$id.'/aprovar')->assertOk();
$this->mfa($first)->postJson('/perfis/substituicoes/'.$id.'/aplicar')->assertOk();
$pair = DB::table('portal_superuser_pair')->first();
$this->assertSame([$first->id, $candidate->id], [(int) $pair->first_user_id, (int) $pair->second_user_id]);
$this->assertFalse(app(PortalProfileAccess::class)->superuser($second));
$this->assertSame(1, (int) $second->fresh()->portal_access_revision);
$this->postJson('/perfis/substituicoes/'.$id.'/aplicar')->assertConflict();
$this->assertSame(1, DB::table('audit_events')->where('action', 'superuser_replaced')->count());
}
}
@@ -0,0 +1,221 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\PortalProfileAdministration;
use App\Services\PortalProfileInstallation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Tests\TestCase;
class PortalProfileInstallationTest extends TestCase
{
use RefreshDatabase;
private string $proofDirectory;
protected function setUp(): void
{
parent::setUp();
$this->proofDirectory = storage_path('framework/testing/profile-install-'.Str::uuid());
mkdir($this->proofDirectory, 0700, true);
config(['portal_profiles.proof_directory' => $this->proofDirectory, 'portal.profile_access_enabled' => false]);
}
protected function tearDown(): void
{
foreach (glob($this->proofDirectory.'/*') ?: [] as $file) {
unlink($file);
}
rmdir($this->proofDirectory);
parent::tearDown();
}
private function manager(): User
{
$user = $this->actor();
config(['portal.managers' => [$user->email]]);
return $user;
}
private function actor(): User
{
return User::factory()->create(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP'), 'two_factor_confirmed_at' => now()]);
}
private function login(User $user, bool $mfa = true): static
{
return $this->actingAs($user)->withSession(['portal.mfa_actor' => $mfa ? $user->id : null, 'portal.mfa_at' => $mfa ? time() : 0]);
}
private function emptySchema(): void
{
(require database_path('migrations/'.PortalProfileInstallation::MIGRATION.'.php'))->down();
DB::table('migrations')->where('migration', PortalProfileInstallation::MIGRATION)->delete();
}
private function data(): array
{
return ['hash' => $this->getJson('/management/profile-install')->assertOk()->json('hash'), 'confirm' => true,
'idempotency_key' => (string) Str::uuid(), 'reason' => 'Instalação sintética em base isolada de testes'];
}
private function readinessFixture(): void
{
// Synthetic files exercise validation; they are never deployment backup evidence.
file_put_contents($this->proofDirectory.'/dump', 'unit-fixture-not-a-real-dump');
file_put_contents($this->proofDirectory.'/files', 'unit-fixture-not-real-files');
$target = DB::selectOne('SELECT current_database() AS database,inet_server_port() AS port');
file_put_contents($this->proofDirectory.'/readiness.json', json_encode(['verified_at' => gmdate('c'), 'target' => $target,
'code_hash' => app(PortalProfileInstallation::class)->fingerprint(), 'restore_verified' => true, 'files_verified' => true,
'qa_passed' => true, 'compatibility_verified' => true, 'dump_path' => $this->proofDirectory.'/dump', 'dump_sha256' => hash_file('sha256', $this->proofDirectory.'/dump'),
'files_path' => $this->proofDirectory.'/files', 'files_sha256' => hash_file('sha256', $this->proofDirectory.'/files')], JSON_THROW_ON_ERROR));
}
public function test_cold_install_repetition_empty_reversal_and_reinstallation_preserve_accounts(): void
{
$actor = $this->manager();
$this->emptySchema();
$this->assertFalse(Schema::hasColumn('users', 'portal_access_revision'));
$this->login($actor);
$this->getJson('/management/profile-install')->assertOk()->assertJsonPath('installed', false)->assertJsonPath('consistent', true)->assertJsonPath('ready', false);
$this->postJson('/management/profile-install', $this->data())->assertUnprocessable();
$this->readinessFixture();
$users = DB::table('users')->count();
$data = $this->data();
$result = $this->postJson('/management/profile-install', $data)->assertOk()->assertJsonPath('changed', true)->json();
$this->postJson('/management/profile-install', $data)->assertOk()->assertExactJson($result);
$this->postJson('/management/profile-install', [...$data, 'reason' => $data['reason'].' different'])->assertConflict();
$this->postJson('/management/profile-install', $this->data())->assertOk()->assertJsonPath('changed', false);
$this->assertSame($users, DB::table('users')->count());
$this->assertSame(0, DB::table('portal_role_assignments')->count());
$this->assertSame(0, DB::table('portal_superuser_pair')->count());
$this->assertFalse(config('portal.profile_access_enabled'));
$this->assertFalse(config('portal_profiles.authenticated_installation'));
$this->assertSame(2, DB::table('audit_events')->where('source_system', 'portal-profile-installation')->count());
$this->emptySchema();
$this->postJson('/management/profile-install', $this->data())->assertOk()->assertJsonPath('changed', true);
}
public function test_dependencies_integrity_stale_preview_and_partial_schema_fail_closed(): void
{
$actor = $this->manager();
$this->emptySchema();
$this->login($actor);
$this->readinessFixture();
$data = $this->data();
file_put_contents($this->proofDirectory.'/dump', 'tampered');
$this->postJson('/management/profile-install', $data)->assertConflict();
$this->postJson('/management/profile-install', $this->data())->assertUnprocessable();
$this->readinessFixture();
DB::table('migrations')->where('migration', '2026_10_09_030000_extend_opportunity_resources')->delete();
$this->getJson('/management/profile-install')->assertOk()->assertJsonPath('dependencies.resources_030000', false);
$this->postJson('/management/profile-install', $this->data())->assertUnprocessable();
Schema::table('users', fn ($t) => $t->unsignedBigInteger('portal_access_revision')->default(0));
$this->getJson('/management/profile-install')->assertOk()->assertJsonPath('consistent', false);
$this->postJson('/management/profile-install', $this->data())->assertConflict();
}
public function test_failed_audit_rolls_back_schema_and_ledger_and_can_retry(): void
{
$actor = $this->manager();
$this->emptySchema();
$this->login($actor);
$this->readinessFixture();
DB::statement("ALTER TABLE audit_events ADD CONSTRAINT qa_reject_profile_install CHECK (source_system <> 'portal-profile-installation')");
$this->postJson('/management/profile-install', $this->data())->assertStatus(503);
$this->assertFalse(Schema::hasTable('portal_role_assignments'));
$this->assertFalse(Schema::hasColumn('users', 'portal_access_revision'));
$this->assertFalse(DB::table('migrations')->where('migration', PortalProfileInstallation::MIGRATION)->exists());
DB::statement('ALTER TABLE audit_events DROP CONSTRAINT qa_reject_profile_install');
$this->postJson('/management/profile-install', $this->data())->assertOk()->assertJsonPath('changed', true);
}
public function test_bootstrap_is_explicit_independent_separate_and_cannot_replace_existing_pair(): void
{
$actor = $this->manager();
$first = $this->actor();
$second = $this->actor();
$this->login($actor, false);
$this->postJson('/management/profile-install', $this->data())->assertForbidden();
$this->login($actor);
$this->postJson('/management/profile-install/bootstrap', [...$this->data(), 'first_user_id' => $actor->id, 'second_user_id' => $second->id])->assertUnprocessable();
$this->postJson('/management/profile-install/bootstrap', [...$this->data(), 'first_user_id' => $first->id, 'second_user_id' => $second->id])->assertOk()->assertJsonPath('holders', [$first->id, $second->id]);
$this->getJson('/management/profile-install')->assertForbidden();
$this->login($first);
$this->getJson('/management/profile-install')->assertOk()->assertJsonPath('bootstrap.initialized', true);
$this->postJson('/management/profile-install/bootstrap', [...$this->data(), 'first_user_id' => $first->id, 'second_user_id' => $actor->id])->assertConflict();
$this->assertSame(1, DB::table('portal_superuser_pair')->count());
$this->assertSame(0, DB::table('portal_role_assignments')->count());
$this->assertFalse(config('portal_profiles.bootstrap_authorized'));
}
public function test_auditor_restriction_and_history_prevent_privilege_or_destructive_rollback(): void
{
$actor = $this->manager();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $this->actor(), [
'user_id' => $actor->id, 'role' => 'auditor', 'opportunity_types' => [], 'source' => 'unit-synthetic-fixture']);
$this->login($actor);
$this->getJson('/management/profile-install')->assertForbidden();
$this->postJson('/management/profile-install', ['hash' => str_repeat('a', 64), 'confirm' => true, 'idempotency_key' => (string) Str::uuid(), 'reason' => 'Instalação sintética vedada ao Auditor'])->assertForbidden();
try {
(require database_path('migrations/'.PortalProfileInstallation::MIGRATION.'.php'))->down();
$this->fail('Used authorization schema must not be dropped.');
} catch (\RuntimeException $e) {
$this->assertStringContainsString('Preserve authorization history', $e->getMessage());
}
$this->assertSame(1, DB::table('portal_role_assignments')->count());
$this->assertTrue(Schema::hasColumn('users', 'portal_access_revision'));
}
public function test_rollback_preserves_context_even_without_author_or_grants(): void
{
DB::table('opportunities')->insert(['reference' => 'QA-rollback-context', 'slug' => 'qa-rollback-context', 'workflow_context' => '{"history":["synthetic-preserve"]}']);
try {
(require database_path('migrations/'.PortalProfileInstallation::MIGRATION.'.php'))->down();
$this->fail('Context must survive rollback even without an owner.');
} catch (\RuntimeException $e) {
$this->assertSame('Preserve scoped opportunities', $e->getMessage());
}
$this->assertTrue(Schema::hasColumn('opportunities', 'workflow_context'));
$this->assertSame(1, DB::table('opportunities')->whereNotNull('workflow_context')->count());
}
public function test_bootstrap_rejects_unreadable_mfa_and_auditor_candidate_without_creating_pair(): void
{
$manager = $this->manager();
$first = $this->actor();
$second = $this->actor();
$first->forceFill(['two_factor_secret' => 'synthetic-invalid-ciphertext'])->save();
$this->login($manager);
$this->postJson('/management/profile-install/bootstrap', [...$this->data(), 'first_user_id' => $first->id, 'second_user_id' => $second->id])->assertUnprocessable();
$this->assertSame(0, DB::table('portal_superuser_pair')->count());
$first->forceFill(['two_factor_secret' => Crypt::encryptString('JBSWY3DPEHPK3PXP')])->save();
app(PortalProfileAdministration::class)->insertGrant((string) Str::uuid(), $manager, [
'user_id' => $first->id, 'role' => 'auditor', 'opportunity_types' => [], 'source' => 'unit-synthetic-fixture']);
$this->postJson('/management/profile-install/bootstrap', [...$this->data(), 'first_user_id' => $first->id, 'second_user_id' => $second->id])->assertUnprocessable();
$this->assertSame(0, DB::table('portal_superuser_pair')->count());
$this->assertFalse(config('portal_profiles.bootstrap_authorized'));
}
public function test_partial_schema_cannot_disable_identity_write_controls_but_recovery_is_accessible(): void
{
$manager = $this->manager();
$before = $manager->two_factor_secret;
$this->login($manager);
config(['portal.profile_access_enabled' => true]);
Schema::table('users', fn ($t) => $t->dropColumn('portal_access_revision'));
$this->deleteJson('/user/two-factor-authentication')->assertStatus(503);
$this->deleteJson('/settings/profile', ['password' => 'not-a-credential'])->assertStatus(503);
$this->assertSame($before, $manager->fresh()->two_factor_secret);
$this->getJson('/management/profile-install')->assertOk()->assertJsonPath('consistent', false);
$this->postJson('/management/profile-install', $this->data())->assertConflict();
$this->post('/logout')->assertRedirect('/');
$this->assertGuest();
}
}
@@ -145,4 +145,79 @@ class TerritoryGeometryImportTest extends TestCase
$this->assertSame(2, DB::table('geo_geometries')->whereNull('deleted_at')->count());
$this->assertSame(0, DB::table('audit_events')->where('action', 'geometry_import_reversed')->count());
}
public function test_explicit_maputo_correspondences_preserve_the_catalogue_and_are_bound_to_parent_and_exemplar(): void
{
$this->setupImport();
$country = DB::table('geo_locations')->where('code', 'MZ')->value('id');
$hash = config('geometry-correspondences.catalogue_sha256');
foreach (config('geometry-correspondences.rows.1') as $entry) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'code' => 'QA-'.$id, 'source_system' => 'cartografia-workbook', 'external_id' => $hash.':'.$id,
'source_code' => $entry['target_source_code'], 'name' => $entry['target_name'], 'location_type' => 'province', 'parent_id' => $country, 'data_classification' => 'internal']);
}
$before = DB::table('geo_locations')->orderBy('id')->get()->toJson();
$plan = $this->getJson('/management/territory-geometry-import?level=1')->assertOk()->assertJsonPath('resolved', 4)->json();
$rows = collect($plan['rows'])->filter(fn ($row) => $row['correspondence'] !== null);
$this->assertCount(2, $rows);
$this->assertSame(2, $rows->where('match_basis', 'explicit_versioned_correspondence')->count());
// Change the mapping, not the source: the original preview can no longer be applied.
config(['geometry-correspondences.version' => 'changed-qa-version']);
$this->postJson('/management/territory-geometry-import', $this->input($plan))->assertConflict();
config(['geometry-correspondences.version' => $plan['correspondence_version']]);
$result = $this->postJson('/management/territory-geometry-import', $this->input($plan))->assertOk()->assertJsonPath('inserted', 4)->json();
$this->assertSame($before, DB::table('geo_locations')->orderBy('id')->get()->toJson());
foreach ($rows as $row) {
$geometry = DB::table('geo_geometries')->where('external_id', $row['external_id'])->first();
$properties = json_decode($geometry->properties, true);
$this->assertSame('internal', $geometry->data_classification);
$this->assertSame($row['location_id'], $geometry->geo_location_id);
$this->assertEquals($row['correspondence'], $properties['correspondence']);
$this->assertSame($plan['correspondence_sha256'], $properties['correspondence_sha256']);
}
$this->assertCount(4, $result['created']);
// A matching display name under a foreign parent must never acquire MZ06.
DB::table('geo_locations')->where('source_code', '11')->update(['parent_id' => DB::table('geo_locations')->where('code', 'QA-FOREIGN')->value('id')]);
$new = $this->getJson('/management/territory-geometry-import?level=1')->assertOk()->json();
$city = collect($new['rows'])->firstWhere('external_id', '2019-06-07:adm1:MZ06');
$this->assertNull($city['location_id']);
$this->assertSame('name_unresolved', $city['status']);
config(['geometry-correspondences.source_sha256.1' => str_repeat('a', 64)]);
$this->getJson('/management/territory-geometry-import?level=1')->assertStatus(422);
}
public function test_ambiguous_names_remain_pending_without_blocking_independent_unique_matches(): void
{
$this->setupImport();
$location = DB::table('geo_locations')->where('location_type', 'province')->where('parent_id', DB::table('geo_locations')->where('code', 'MZ')->value('id'))->first();
DB::table('geo_locations')->insert(['id' => (string) Str::uuid(), 'code' => 'QA-DUPLICATE-NAME', 'name' => $location->name,
'parent_id' => $location->parent_id, 'location_type' => 'province', 'data_classification' => 'internal']);
$before = DB::table('geo_locations')->orderBy('id')->get()->toJson();
$plan = $this->getJson('/management/territory-geometry-import?level=1')->assertOk()->assertJsonPath('resolved', 1)->json();
$ambiguous = collect($plan['rows'])->firstWhere('status', 'ambiguous_name');
$this->assertNull($ambiguous['location_id']);
$this->assertCount(2, $ambiguous['candidates']);
$this->postJson('/management/territory-geometry-import', $this->input($plan))->assertOk()->assertJsonPath('inserted', 1)->assertJsonPath('pending', 10);
$this->assertSame($before, DB::table('geo_locations')->orderBy('id')->get()->toJson());
$this->assertFalse(DB::table('geo_geometries')->where('geo_location_id', $location->id)->exists());
}
public function test_reversal_preserves_parent_correspondences_needed_by_active_descendant_boundaries(): void
{
$this->setupImport();
$plan = $this->getJson('/management/territory-geometry-import?level=1')->assertOk()->json();
$result = $this->postJson('/management/territory-geometry-import', $this->input($plan))->assertOk()->json();
$parent = DB::table('geo_geometries')->where('id', $result['created'][0]['id'])->first();
$properties = json_decode($parent->properties, true);
$provinceCode = $properties['source_properties']['ADM1_PCODE'];
$child = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $child, 'code' => 'QA-'.$child, 'name' => 'Synthetic QA district', 'location_type' => 'district', 'parent_id' => $parent->geo_location_id, 'data_classification' => 'internal']);
DB::insert('INSERT INTO geo_geometries(id,source_system,external_id,geo_location_id,geometry_type,geom,properties,data_classification) SELECT ?,?,?,?,geometry_type,geom,?::jsonb,? FROM geo_geometries WHERE id=?',
[(string) Str::uuid(), 'ine-cod-ab', '2019-06-07:adm2:'.$provinceCode.'99', $child,
json_encode(['source_version' => '2019-06-07', 'source_properties' => ['ADM1_PCODE' => $provinceCode]], JSON_THROW_ON_ERROR), 'internal', $parent->id]);
$this->postJson('/management/territory-geometry-import/'.$result['batch_id'].'/reverse',
['idempotency_key' => (string) Str::uuid(), 'reason' => 'Recusar reversão do pai enquanto descendentes QA dependem dele', 'confirm' => true])->assertConflict();
$this->assertSame(3, DB::table('geo_geometries')->whereNull('deleted_at')->count());
$this->assertSame(0, DB::table('audit_events')->where('action', 'geometry_import_reversed')->count());
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Tests\Support;
/** Valid original bytes for QA only; never an official/legal document. */
final class SyntheticDocument
{
public static function pdf(string $text = 'Synthetic QA document - no official or legal value'): string
{
$text = str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $text);
$stream = 'BT /F1 12 Tf 12 60 Td ('.$text.') Tj ET';
$objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids [3 0 R] /Count 1 >>',
'<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 100] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>',
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',
'<< /Length '.strlen($stream)." >>\nstream\n".$stream."\nendstream",
];
$pdf = "%PDF-1.4\n% Synthetic QA original\n";
$offsets = [];
foreach ($objects as $index => $object) {
$offsets[] = strlen($pdf);
$pdf .= ($index + 1)." 0 obj\n".$object."\nendobj\n";
}
$xref = strlen($pdf);
$pdf .= "xref\n0 6\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$pdf .= sprintf('%010d 00000 n ', $offset)."\n";
}
return $pdf."trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n".$xref."\n%%EOF\n";
}
}