@@ -50,6 +50,36 @@ class InvestorPathTest extends TestCase
|
||||
'incomes' => [['label' => 'Receitas QA', 'amount' => '100']], 'expenses' => [['label' => 'Custos QA', 'amount' => '50']]]])]];
|
||||
}
|
||||
|
||||
public function test_existing_empty_desk_draft_can_explicitly_reuse_current_contextual_summary_without_overwriting_data(): void
|
||||
{
|
||||
$service = $this->actingAs($this->manager)->postJson('/management/balcao/servicos', ['code' => 'project-preparation', 'confirm' => true])->assertCreated()->json('id');
|
||||
$id = $this->context('Dossier anterior à ferramenta');
|
||||
$support = $this->postJson('/balcao-virtual/dossiers/'.$id.'/pedidos', ['service_version_id' => $service, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$data = [...$this->snapshot('Resumo posterior'), 'context' => $id];
|
||||
$draft = $this->postJson('/api/v1/simulation-drafts', $data, ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
|
||||
$initial = $this->getJson('/balcao-virtual/pedidos/'.$support)->assertOk()->assertJsonPath('request.payload.description', '')->json();
|
||||
$preview = $initial['toolPrefill'] ?? null;
|
||||
$this->assertNotNull($preview, 'The existing empty draft needs an explicit contextual reuse action.');
|
||||
$this->assertSame($draft, $preview['draft_id']);
|
||||
$this->assertSame($data['economic_snapshot']['project_summary'], $preview['description']);
|
||||
$this->actingAs($this->manager)->getJson('/balcao-virtual/pedidos/'.$support)->assertJsonPath('toolPrefill', null);
|
||||
$this->actingAs($this->owner);
|
||||
$payload = [...$initial['request']['payload'], 'description' => $preview['description'], 'country' => 'PT', 'declared_origin_country_code' => 'ZA'];
|
||||
$source = ['draft_id' => $preview['draft_id'], 'draft_version' => $preview['draft_version'], 'snapshot_sha256' => $preview['snapshot_sha256']];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$support, ['version' => $initial['request']['version'], 'payload' => $payload, 'tool_prefill' => [...$source, 'draft_id' => (string) Str::uuid()]])->assertUnprocessable();
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$support, ['version' => $initial['request']['version'], 'payload' => $payload, 'tool_prefill' => [...$source, 'draft_version' => $source['draft_version'] + 1]])->assertUnprocessable();
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$support)->assertJsonPath('request.version', $initial['request']['version'])->assertJsonPath('request.payload.description', '');
|
||||
$this->assertDatabaseCount('desk_revisions', 0);
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$support, ['version' => $initial['request']['version'], 'payload' => $payload, 'tool_prefill' => $source])->assertOk()->assertJsonPath('status', 'draft');
|
||||
$recovered = $this->getJson('/balcao-virtual/pedidos/'.$support)->assertJsonPath('request.payload.description', $preview['description'])->assertJsonPath('request.payload.country', 'PT')->assertJsonPath('request.payload.declared_origin_country_code', 'ZA')->assertJsonPath('toolPrefill', null)->json();
|
||||
$this->assertSame('Dossier anterior à ferramenta', $recovered['request']['payload']['title']);
|
||||
$this->assertDatabaseCount('desk_requests', 1);
|
||||
$this->assertDatabaseCount('desk_revisions', 1);
|
||||
$this->assertDatabaseHas('desk_events', ['request_id' => $support, 'action' => 'request_prefill_reused']);
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$support, ['version' => $recovered['request']['version'], 'payload' => [...$payload, 'description' => 'Tentativa de substituir texto existente'], 'tool_prefill' => $source])->assertUnprocessable();
|
||||
$this->actingAs(User::factory()->create())->putJson('/balcao-virtual/pedidos/'.$support, ['version' => $recovered['request']['version'], 'payload' => $payload, 'tool_prefill' => $source])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_two_independent_investments_recover_tool_evidence_support_and_internal_tasks_without_external_calls(): void
|
||||
{
|
||||
$service = $this->actingAs($this->manager)->postJson('/management/balcao/servicos', ['code' => 'project-preparation', 'confirm' => true])->assertCreated()->json('id');
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\LegacyContent;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LegacyContentTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private int $resource;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
Storage::fake('local');
|
||||
config(['portal.legacy_content_qa_enabled' => true, 'investor-path.enabled' => true]);
|
||||
$bytes = json_encode(['format' => 'investmoz-legacy-article-v1', 'source_url' => 'https://investemoz.tempo.co.mz/agronegocio',
|
||||
'content_html' => '<p>Conhecer corredores</p><script>secret()</script><a href="javascript:alert(1)" onclick="bad()">Link</a>',
|
||||
'title' => 'Agronegocio', 'author' => 'Autor sintético', 'legacy_id' => 171985, 'legacy_category' => 'Oportunidades',
|
||||
'published_at' => '2026-04-06T09:19:07+00:00', 'modified_at' => '2026-04-20T12:41:43+00:00'], JSON_THROW_ON_ERROR);
|
||||
$id = (string) Str::uuid();
|
||||
Storage::disk('local')->put('legacy/'.$id, $bytes);
|
||||
DB::table('documents')->insert(['id' => $id, 'source_system' => 'synthetic-test', 'external_id' => 'legacy-tempo-post-171985-20260420',
|
||||
'file_name' => 'source.json', 'media_type' => 'application/json', 'storage_key' => 'legacy/'.$id,
|
||||
'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes), 'malware_scan_status' => 'clean',
|
||||
'size_bytes' => strlen($bytes), 'status' => 'active', 'rights_status' => 'authorized', 'data_classification' => 'public']);
|
||||
$this->resource = DB::table('portal_resources')->insertGetId(['document_id' => $id, 'title' => 'Agronegocio',
|
||||
'category' => 'education', 'topic' => 'agronegocio', 'published' => true, 'rights_status' => 'authorized',
|
||||
'source_url' => 'https://investemoz.tempo.co.mz/agronegocio', 'source_reference' => 'Exemplar sintético; não oficial.', 'metadata_version' => 1]);
|
||||
}
|
||||
|
||||
public function test_public_read_search_and_sanitization_do_not_create_opportunities_and_private_sources_are_hidden(): void
|
||||
{
|
||||
$count = DB::table('opportunities')->count();
|
||||
$this->get('/agronegocio')->assertOk()->assertInertia(fn (Assert $page) => $page->component('portal/legacy')
|
||||
->where('article.id', $this->resource)->where('article.calculation_use', false));
|
||||
$html = app(LegacyContent::class)->article()['html'];
|
||||
$this->assertStringNotContainsString('script', $html);
|
||||
$this->assertStringNotContainsString('javascript', $html);
|
||||
$this->assertStringNotContainsString('onclick', $html);
|
||||
$this->get('/explorar/agronegocio?q=corredores')->assertOk()->assertInertia(fn (Assert $page) => $page->where('match', true));
|
||||
$this->get('/explorar/agronegocio?q=absent')->assertOk()->assertInertia(fn (Assert $page) => $page->where('match', false));
|
||||
$this->getJson('/investimentos/a-partir-de/agronegocio')->assertUnauthorized();
|
||||
$this->assertSame($count, DB::table('opportunities')->count());
|
||||
DB::table('portal_resources')->where('id', $this->resource)->update(['published' => false]);
|
||||
$this->get('/agronegocio')->assertNotFound();
|
||||
config(['portal.legacy_content_qa_enabled' => false]);
|
||||
$this->get('/explorar/agronegocio')->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_original_heading_text_is_preserved_with_an_accessible_article_hierarchy(): void
|
||||
{
|
||||
$source = '<h3>Turismo</h3><h3>Territórios</h3><h4>Localizações</h4><script>unsafe()</script>';
|
||||
$html = app(LegacyContent::class)->sanitize($source);
|
||||
$this->assertSame('<h2>Turismo</h2><h2>Territórios</h2><h3>Localizações</h3>', $html);
|
||||
$this->assertSame('<h2>Secção</h2><h3>Subsecção</h3>', app(LegacyContent::class)->sanitize('<h1>Secção</h1><h3>Subsecção</h3>'));
|
||||
$this->assertStringContainsString('<h3>Turismo</h3>', $source);
|
||||
}
|
||||
|
||||
public function test_source_is_saved_once_in_existing_dossier_recovered_and_isolated_from_other_accounts_and_projects(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
$data = ['title' => 'Ideia sintética', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true, 'content_resource_id' => $this->resource];
|
||||
$case = $this->actingAs($owner)->postJson('/investimentos', $data)->assertCreated()->json('id');
|
||||
$first = $this->getJson('/investimentos/'.$case)->assertOk()->json();
|
||||
$this->assertCount(19, $first['steps']);
|
||||
$this->assertCount(5, $first['phases']);
|
||||
$this->assertSame($this->resource, $first['content_sources'][0]['resource_id']);
|
||||
$this->postJson('/investimentos/'.$case.'/conteudos', ['version' => $first['case']['version'], 'resource_id' => $this->resource])->assertOk();
|
||||
$again = $this->getJson('/investimentos/'.$case)->assertOk()->json();
|
||||
$this->assertSame($first['case']['version'], $again['case']['version']);
|
||||
$this->assertSame($first['content_sources'], $again['content_sources']);
|
||||
$this->assertSame($case, $this->postJson('/investimentos', $data)->assertCreated()->json('id'));
|
||||
$this->actingAs($other)->getJson('/investimentos/'.$case)->assertForbidden();
|
||||
$this->postJson('/investimentos/'.$case.'/conteudos', ['version' => $first['case']['version'], 'resource_id' => $this->resource])->assertForbidden();
|
||||
$this->actingAs($owner);
|
||||
unset($data['content_resource_id']);
|
||||
$data['client_key'] = (string) Str::uuid();
|
||||
$independent = $this->postJson('/investimentos', $data)->assertCreated()->json('id');
|
||||
$this->assertSame([], $this->getJson('/investimentos/'.$independent)->assertOk()->json('content_sources'));
|
||||
$before = DB::table('desk_cases')->count();
|
||||
$data['client_key'] = (string) Str::uuid();
|
||||
$data['content_resource_id'] = $this->resource + 100;
|
||||
$this->postJson('/investimentos', $data)->assertUnprocessable();
|
||||
$this->assertSame($before, DB::table('desk_cases')->count());
|
||||
}
|
||||
|
||||
private function sectorArticle(string $slug, string $title, string $body): int
|
||||
{
|
||||
$identity = config('legacy_content.articles.'.$slug);
|
||||
$document = (string) Str::uuid();
|
||||
$bytes = json_encode(['format' => 'investmoz-legacy-article-v1', 'source_url' => $identity['source_url'],
|
||||
'content_html' => $body, 'title' => $title, 'author' => 'Autor sintético', 'legacy_id' => 123,
|
||||
'legacy_category' => 'Turismo', 'published_at' => '2026-04-01T00:00:00+00:00', 'modified_at' => '2026-04-02T00:00:00+00:00'], JSON_THROW_ON_ERROR);
|
||||
Storage::disk('local')->put('legacy/'.$document, $bytes);
|
||||
DB::table('documents')->insert(['id' => $document, 'source_system' => 'synthetic-test', 'external_id' => $identity['external_id'],
|
||||
'file_name' => 'source.json', 'media_type' => 'application/json', 'storage_key' => 'legacy/'.$document,
|
||||
'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes), 'malware_scan_status' => 'clean',
|
||||
'size_bytes' => strlen($bytes), 'status' => 'active', 'rights_status' => 'authorized', 'data_classification' => 'public']);
|
||||
return DB::table('portal_resources')->insertGetId(['document_id' => $document, 'title' => $title, 'category' => 'education',
|
||||
'topic' => $identity['sector_slug'], 'published' => true, 'rights_status' => 'authorized',
|
||||
'source_url' => $identity['source_url'], 'source_reference' => 'Exemplar sintético.', 'metadata_version' => 1]);
|
||||
}
|
||||
|
||||
public function test_energy_and_mining_remain_distinct_and_each_reference_returns_to_its_article(): void
|
||||
{
|
||||
$this->sectorArticle('energia-mineracao', 'Energia e Mineração', '<a href="https://investemoz.tempo.co.mz/energia/">Energia</a><a href="https://investemoz.tempo.co.mz/mineracao">Mineração</a>');
|
||||
$energy = $this->sectorArticle('energia', 'Energia', '<p>Rede e geração.</p>');
|
||||
$mining = $this->sectorArticle('mineracao', 'Mineração', '<p>Recursos minerais.</p>');
|
||||
$this->get('/explorar/energia-mineracao?q=geração')->assertOk()->assertInertia(fn (Assert $page) =>
|
||||
$page->has('articles', 1)->where('articles.0.id', $energy));
|
||||
$index = app(LegacyContent::class)->article('energia-mineracao');
|
||||
$this->assertStringContainsString('href="/energia"', $index['html']);
|
||||
$this->assertStringContainsString('href="/mineracao"', $index['html']);
|
||||
$owner = User::factory()->create();
|
||||
$case = $this->actingAs($owner)->postJson('/investimentos', ['title' => 'Energia sintética', 'client_key' => (string) Str::uuid(),
|
||||
'reuse_consent' => true, 'content_resource_id' => $energy])->assertCreated()->json('id');
|
||||
$first = $this->getJson('/investimentos/'.$case)->assertOk()->json();
|
||||
$this->postJson('/investimentos/'.$case.'/conteudos', ['version' => $first['case']['version'], 'resource_id' => $mining])->assertOk();
|
||||
$sources = $this->getJson('/investimentos/'.$case)->assertOk()->json('content_sources');
|
||||
$this->assertSame(['/energia', '/mineracao'], array_column($sources, 'return_href'));
|
||||
$this->assertSame([$energy, $mining], array_column($sources, 'resource_id'));
|
||||
DB::table('portal_resources')->where('id', $mining)->update(['published' => false]);
|
||||
$this->get('/mineracao')->assertNotFound();
|
||||
$this->assertStringContainsString('https://investemoz.tempo.co.mz/mineracao', app(LegacyContent::class)->article('energia-mineracao')['html']);
|
||||
}
|
||||
|
||||
public function test_tourism_is_textual_and_empty_financial_source_is_not_a_published_article(): void
|
||||
{
|
||||
$this->sectorArticle('turismo', 'Turismo', '<p>Província da Zambézia e turismo.</p>');
|
||||
$tourism = app(LegacyContent::class)->article('turismo');
|
||||
$this->assertSame([], $tourism['territorial_references']);
|
||||
$this->assertFalse(DB::table('portal_resource_links')->where('target_type', 'territory')->exists());
|
||||
$finance = $this->sectorArticle('mercado-financeiro', 'Mercado Financeiro', '');
|
||||
$this->get('/mercado-financeiro')->assertNotFound();
|
||||
$this->get('/explorar/mercado-financeiro')->assertNotFound();
|
||||
$this->actingAs(User::factory()->create())->postJson('/investimentos', ['title' => 'Ideia', 'client_key' => (string) Str::uuid(),
|
||||
'reuse_consent' => true, 'content_resource_id' => $finance])->assertUnprocessable();
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,10 @@ namespace Tests\Feature;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\User;
|
||||
use App\Services\OpportunityCanonicalContract;
|
||||
use App\Services\OpportunityCanonicalResponse;
|
||||
use App\Services\OpportunityCategoryFields;
|
||||
use App\Services\OpportunityManagement;
|
||||
use App\Services\OpportunityModularProfiles;
|
||||
use App\Services\PortalProfileAdministration;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
@@ -81,6 +84,69 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
$this->assertNotEmpty($schema['$defs']['businessTransactionCreate']['allOf']);
|
||||
}
|
||||
|
||||
public function test_read_response_preserves_ids_resources_permissions_and_does_not_invent_validation(): void
|
||||
{
|
||||
[$id, $promoter, $validator, , $payload, $document] = $this->fixture();
|
||||
$url = '/minhas-oportunidades/'.$id.'/response';
|
||||
$record = Opportunity::findOrFail($id);
|
||||
$before = $record->getRawOriginal();
|
||||
$response = $this->loginFixture($promoter)->getJson($url)->assertOk()
|
||||
->assertHeader('Cache-Control', 'no-store, private')->json();
|
||||
$this->assertSame(OpportunityCanonicalResponse::VERSION, $response['adapter_version']);
|
||||
$this->assertSame($id, $response['data']['id']);
|
||||
$this->assertSame($record->reference, $response['data']['opportunity_code']);
|
||||
$this->assertSame($document, $response['data']['documents'][0]['id']);
|
||||
$this->assertSame($payload['locations'], $response['resource_references']['locations']);
|
||||
$this->assertNull($response['data']['approved_by']);
|
||||
$this->assertFalse($response['compatibility']['normative_response_complete']);
|
||||
$this->assertFalse($response['validation_result']['revalidated_on_read']);
|
||||
$this->assertArrayNotHasKey('storage_key', $response['data']['documents'][0]);
|
||||
$this->assertArrayNotHasKey('completion_percentage', $response['data']);
|
||||
$this->assertSame($before, $record->fresh()->getRawOriginal());
|
||||
$this->loginFixture($validator)->getJson($url)->assertOk();
|
||||
$otherOrg = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $otherOrg, 'name' => 'Other synthetic QA organization', 'organization_type' => 'private']);
|
||||
$other = $this->actor('promoter', $otherOrg);
|
||||
$this->loginFixture($other)->getJson($url)->assertForbidden();
|
||||
$this->action($promoter, $id, 'submit');
|
||||
$submitted = $this->loginFixture($promoter)->getJson($url)->assertOk()->json();
|
||||
$this->assertSame($promoter->id, $submitted['data']['submitted_by']);
|
||||
$this->assertNotNull($submitted['data']['submitted_at']);
|
||||
$this->assertNull($submitted['data']['approved_by']);
|
||||
$this->assertNotNull($submitted['validation_result']['submission_hash']);
|
||||
$this->assertEquals($payload['real_estate'], $submitted['data']['real_estate']);
|
||||
$this->assertArrayNotHasKey('id', $submitted['data']['real_estate']);
|
||||
}
|
||||
|
||||
public function test_cadastral_uniqueness_and_original_succession_modality_are_enforced_without_filling_drafts(): void
|
||||
{
|
||||
$fields = app(OpportunityCategoryFields::class);
|
||||
$record = new Opportunity;
|
||||
$record->id = 1;
|
||||
$payload = ['opportunity_category' => 'land_rights', 'land_rights' => ['duat_status' => 'none',
|
||||
'operation_type' => 'investment_with_duat', 'exploitation_plan_required' => false, 'communities_affected' => false,
|
||||
'parcels' => [['cadastral_number' => 'QA-001'], ['cadastral_number' => 'QA-001']]]];
|
||||
$errors = [];
|
||||
$fields->validate($payload, $record, [], $errors);
|
||||
$this->assertSame(['canonical.land_rights.parcels.1.cadastral_number'], array_keys($errors));
|
||||
foreach ([[null, null], ['QA-001', 'QA-002']] as $numbers) {
|
||||
$payload['land_rights']['parcels'] = array_map(fn ($number) => ['cadastral_number' => $number], $numbers);
|
||||
$errors = [];
|
||||
$fields->validate($payload, $record, [], $errors);
|
||||
$this->assertSame([], $errors);
|
||||
}
|
||||
$business = ['transaction_type' => 'succession', 'available_financial_years' => 1,
|
||||
'financial_periods' => [['year' => (int) date('Y') - 1]], 'litigation_contingencies' => [['type' => 'none']],
|
||||
'confidentiality_level' => 'internal', 'valuation' => ['value' => 100, 'date' => today()->toDateString()]];
|
||||
$errors = [];
|
||||
$fields->validate(['opportunity_category' => 'business_sale', 'currency' => 'MZN', 'visibility' => 'internal', 'business_transaction' => $business], $record, [], $errors);
|
||||
$this->assertSame([], $errors);
|
||||
$errors = [];
|
||||
$fields->validate(['opportunity_category' => 'business_partnership', 'currency' => 'MZN', 'visibility' => 'internal', 'business_transaction' => $business], $record, [], $errors);
|
||||
$this->assertArrayHasKey('canonical.business_transaction.transaction_type', $errors);
|
||||
$this->assertSame(['land_rights' => ['parcels' => [['cadastral_number' => null]]]], app(OpportunityCanonicalContract::class)->draft(['land_rights' => ['parcels' => [['cadastral_number' => null]]]]));
|
||||
}
|
||||
|
||||
public function test_correction_approval_publication_material_revision_and_suspension_preserve_authorization(): void
|
||||
{
|
||||
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture();
|
||||
@@ -204,8 +270,129 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
$this->action($validator, $id, 'approve', [], 422);
|
||||
}
|
||||
|
||||
public function test_qa_modular_paths_use_distinct_semantics_and_existing_independent_workflow(): void
|
||||
{
|
||||
config(['portal.opportunity_modular_profiles_qa_enabled' => true]);
|
||||
foreach (['concession' => ['intention_call', 'awarded_right'], 'financing' => ['seeking_funding', 'funding_offer'],
|
||||
'supply' => ['purchase_request', 'supply_offer'], 'other' => ['classified_other']] as $category => $modes) {
|
||||
foreach ($modes as $mode) {
|
||||
[$id, $promoter, $validator, $publisher, $payload, $document] = $this->fixture($category, $mode);
|
||||
$this->assertEquals($payload, app(OpportunityManagement::class)->values(Opportunity::findOrFail($id))['canonical']);
|
||||
if ($category === 'other') {
|
||||
$this->action($promoter, $id, 'submit', [], 422);
|
||||
config(['portal.opportunity_other_qa_subtypes.qa-example' => ['approved' => true, 'version' => 'synthetic-acceptance-v1',
|
||||
'decision_reference' => 'Synthetic policy test only; not a real approved business subtype', 'gates' => ['technical_review', 'legal_territorial_review']]]);
|
||||
}
|
||||
$this->action($promoter, $id, 'submit');
|
||||
$this->action($validator, $id, 'start_review');
|
||||
$this->action($validator, $id, 'request_correction', ['correction_items' => ['canonical.executive_summary']]);
|
||||
$payload['executive_summary'] .= ' Correção QA recuperável.';
|
||||
$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');
|
||||
foreach (app(OpportunityCanonicalContract::class)->gates(Opportunity::findOrFail($id)) as $gate) {
|
||||
$this->action($validator, $id, 'review_gate', ['gate' => $gate, 'gate_decision' => 'approved', 'evidence_document_ids' => [$document]]);
|
||||
}
|
||||
$this->action($validator, $id, 'approve');
|
||||
$this->action($publisher, $id, 'publish');
|
||||
$response = $this->loginFixture($promoter)->getJson('/minhas-oportunidades/'.$id.'/response')->assertOk()->json();
|
||||
$this->assertSame($mode, $response['data']['module_details']['mode']);
|
||||
$this->assertSame('restricted', $response['publication']['scope']);
|
||||
$this->assertSame(0, Opportunity::published()->whereKey($id)->count());
|
||||
$this->assertLessThanOrEqual(500, mb_strlen(Opportunity::findOrFail($id)->summary));
|
||||
$this->assertSame($payload['executive_summary'], $response['data']['executive_summary']);
|
||||
$this->assertNotEmpty(Opportunity::findOrFail($id)->workflow_context['approval']['gates']);
|
||||
if ($mode === 'intention_call') {
|
||||
$this->assertStringContainsString('não é direito atribuído', Opportunity::findOrFail($id)->summary);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_modular_semantic_failures_are_field_local_and_never_block_incomplete_draft_recovery(): void
|
||||
{
|
||||
config(['portal.opportunity_modular_profiles_qa_enabled' => true]);
|
||||
foreach ([['financing', 'seeking_funding', 'funding_sought', 999999],
|
||||
['financing', 'funding_offer', 'total_investment', 100],
|
||||
['concession', 'awarded_right', 'module_details.external_decision_document_id', null],
|
||||
['supply', 'supply_offer', 'module_details.total_price', 99]] as [$category, $mode, $path, $value]) {
|
||||
[$id, $promoter, , , $payload] = $this->fixture($category, $mode);
|
||||
data_set($payload, $path, $value);
|
||||
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
|
||||
$this->getJson('/minhas-oportunidades/'.$id.'/response')->assertOk()->assertJsonPath('data.module_details.mode', $mode);
|
||||
$this->assertEquals($payload, app(OpportunityManagement::class)->values(Opportunity::findOrFail($id))['canonical']);
|
||||
$this->postJson('/minhas-oportunidades/'.$id.'/workflow', ['etag' => app(OpportunityManagement::class)->etag(Opportunity::findOrFail($id)), 'action' => 'submit', 'reason' => self::REASON])->assertUnprocessable()->assertJsonValidationErrors('canonical.'.$path);
|
||||
}
|
||||
$service = app(OpportunityCanonicalContract::class);
|
||||
$this->assertSame(['module_details' => ['mode' => 'funding_offer']], $service->draft(['module_details' => ['mode' => 'funding_offer']]));
|
||||
config(['portal.opportunity_modular_profiles_qa_enabled' => false]);
|
||||
$this->assertFalse(app(OpportunityModularProfiles::class)->enabled());
|
||||
$this->assertArrayNotHasKey('module_details', $service->schema(true)['$defs']['opportunityCreate']['properties']);
|
||||
}
|
||||
|
||||
public function test_new_entity_history_is_opt_in_and_does_not_fabricate_accounts(): void
|
||||
{
|
||||
config(['portal.opportunity_modular_profiles_qa_enabled' => true]);
|
||||
$schema = app(OpportunityCanonicalContract::class)->schema();
|
||||
$this->assertSame(0, $schema['$defs']['businessTransactionCreate']['properties']['available_financial_years']['minimum']);
|
||||
$bt = ['transaction_type' => 'succession', 'available_financial_years' => 0, 'financial_periods' => [],
|
||||
'history_status' => 'no_completed_years', 'history_declaration' => 'Entidade sintética recém-criada sem exercícios completos.',
|
||||
'history_declaration_document_id' => 'qa-doc', 'projections' => ['scenario' => 'Projeção QA', 'source' => 'Plano QA', 'date' => '2026-10-10', 'document_id' => 'qa-doc'],
|
||||
'litigation_contingencies' => [['type' => 'none']], 'confidentiality_level' => 'internal', 'valuation' => ['value' => 100, 'date' => '2026-10-10']];
|
||||
$p = ['opportunity_category' => 'business_sale', 'module_profile_version' => OpportunityModularProfiles::HISTORY_VERSION, 'business_transaction' => $bt, 'visibility' => 'internal', 'currency' => 'MZN'];
|
||||
$errors = [];
|
||||
app(OpportunityCategoryFields::class)->validate($p, new Opportunity, ['documents' => ['qa-doc' => []]], $errors);
|
||||
$this->assertSame([], $errors);
|
||||
unset($p['module_profile_version']);
|
||||
$errors = [];
|
||||
app(OpportunityCategoryFields::class)->validate($p, new Opportunity, ['documents' => ['qa-doc' => []]], $errors);
|
||||
$this->assertArrayHasKey('canonical.module_profile_version', $errors);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $payload
|
||||
* @return array<string,mixed> */
|
||||
private function modularPayload(string $category, string $mode, array $payload, string $document): array
|
||||
{
|
||||
unset($payload['real_estate']);
|
||||
$payload['opportunity_category'] = $category;
|
||||
$payload['module_profile_version'] = OpportunityModularProfiles::PROFILES[$category];
|
||||
$m = ['mode' => $mode, 'object' => 'Objeto sintético QA', 'representation_document_id' => $document, 'object_document_id' => $document];
|
||||
if ($category === 'concession') {
|
||||
$m += ['granting_entity' => 'Entidade sintética, não autoridade real', 'procedure_regime' => 'Procedimento sintético QA', 'scope' => 'Distrito QA',
|
||||
'term_value' => 12, 'term_unit' => 'months', 'remuneration_obligations' => 'Obrigações sintéticas QA', 'participation_conditions' => 'Condições sintéticas QA',
|
||||
'land_required' => false, 'construction_required' => false, 'disclosure_authorization_document_id' => $document];
|
||||
if ($mode === 'awarded_right') {
|
||||
$m['external_decision_document_id'] = $document;
|
||||
}
|
||||
}
|
||||
if (in_array($category, ['financing', 'supply'], true)) {
|
||||
$m += ['conditions_status' => 'proposed', 'terms' => 'Condições indicativas QA, sem compromisso', 'scenario' => 'Cenário QA', 'source' => 'Fonte sintética QA', 'terms_date' => '2026-10-10'];
|
||||
}
|
||||
if ($category === 'financing') {
|
||||
$m += ['instrument' => 'debt', 'term_value' => 12, 'term_unit' => 'months', 'repayment_periodicity' => 'mensal', 'disbursement_calendar' => 'Calendário proposto QA'];
|
||||
if ($mode === 'seeking_funding') {
|
||||
$payload += ['total_investment' => 1000, 'investment_breakdown' => [['label' => 'QA', 'amount' => 1000, 'currency' => 'MZN']], 'secured_financing' => [], 'funding_sought' => 500];
|
||||
$m += ['use_of_funds' => 'Preparação QA', 'financial_plan_document_id' => $document];
|
||||
} else {
|
||||
$m += ['offered_capacity' => 100000, 'eligibility_criteria' => 'Critérios propostos QA', 'capacity_document_id' => $document];
|
||||
}
|
||||
}
|
||||
if ($category === 'supply') {
|
||||
$m += ['quantity' => 10, 'unit' => 'unidade', 'destination' => 'Distrito QA', 'start_date' => '2026-10-11', 'end_date' => '2026-11-11',
|
||||
'acceptance_criteria' => 'Critérios QA', 'unit_price' => 10, 'total_price' => 100, 'advance_or_guarantee' => false];
|
||||
if ($mode === 'supply_offer') {
|
||||
$m['capacity_document_id'] = $document;
|
||||
}
|
||||
}
|
||||
if ($category === 'other') {
|
||||
$m += ['subtype' => 'qa-example', 'purpose' => 'Ensaio QA', 'recipients' => 'Destinatários sintéticos', 'expected_output' => 'Resultado sintético', 'risks' => 'Riscos declarados QA'];
|
||||
}
|
||||
$payload['module_details'] = $m;
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/** @return array{int,User,User,User,array<string,mixed>,string} */
|
||||
private function fixture(): array
|
||||
private function fixture(string $category = 'real_estate', string $mode = ''): array
|
||||
{
|
||||
$org = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $org, 'name' => 'Synthetic QA organization', 'organization_type' => 'private']);
|
||||
@@ -214,11 +401,11 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
$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']);
|
||||
DB::table('reference_catalog_versions')->insert(['id' => $version, 'catalog_code' => 'qa-only-'.$org, '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]);
|
||||
$sector = DB::table('sectors')->insertGetId(['name' => 'QA '.$i, 'slug' => 'qa-'.$org.'-'.$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];
|
||||
@@ -229,7 +416,7 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
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();
|
||||
$draft = $this->loginFixture($promoter)->postJson('/minhas-oportunidades/drafts', ['creation_key' => (string) Str::uuid(), 'organization_id' => $org, 'opportunity_category' => $category, 'reason' => self::REASON])->assertCreated()->json();
|
||||
$id = $draft['id'];
|
||||
$location = (string) Str::uuid();
|
||||
$provinceId = (string) Str::uuid();
|
||||
@@ -250,6 +437,9 @@ class OpportunityCanonicalWorkflowTest extends TestCase
|
||||
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];
|
||||
if ($category !== 'real_estate') {
|
||||
$payload = $this->modularPayload($category, $mode, $payload, $document);
|
||||
}
|
||||
$this->loginFixture($promoter)->putJson('/minhas-oportunidades/'.$id.'/draft', ['etag' => $draft['etag'], 'canonical' => $payload, 'reason' => self::REASON])->assertOk();
|
||||
|
||||
return [$id, $promoter, $validator, $publisher, $payload, $document];
|
||||
|
||||
@@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Queue;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia;
|
||||
use Tests\Support\CleanScannerFixture;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -96,6 +97,38 @@ class OpportunityResourcesTest extends TestCase
|
||||
$this->assertDatabaseHas('opportunity_location_drafts', ['id' => $id, 'deleted_at' => null]);
|
||||
}
|
||||
|
||||
public function test_foreign_country_rejects_mozambican_hierarchy_without_changing_the_saved_draft(): void
|
||||
{
|
||||
[$user, $o] = $this->setupDraft();
|
||||
$province = (string) Str::uuid();
|
||||
$district = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert([
|
||||
['id' => $province, 'code' => $province, 'name' => 'Synthetic QA Mozambique province', 'location_type' => 'province', 'parent_id' => null, 'data_classification' => 'public'],
|
||||
['id' => $district, 'code' => $district, 'name' => 'Synthetic QA Mozambique district', 'location_type' => 'district', 'parent_id' => $province, 'data_classification' => 'public'],
|
||||
]);
|
||||
$payload = ['title' => 'Synthetic QA saved location', 'country_code' => 'MZ', 'province_id' => $province, 'district_id' => $district, 'role' => 'market'];
|
||||
$id = $this->postJson('/management/opportunities/'.$o->id.'/resources/locations', $this->payload($o, $payload))->assertCreated()->json('id');
|
||||
$before = DB::table('opportunity_location_drafts')->where('id', $id)->first();
|
||||
$auditBefore = DB::table('audit_events')->where('source_system', 'opportunity-resources')->count();
|
||||
|
||||
$input = [...$this->payload($o->fresh(), [...$payload, 'country_code' => 'PT']), 'version' => 1];
|
||||
$this->postJson('/management/opportunities/'.$o->id.'/resources/locations/'.$id, $input)
|
||||
->assertUnprocessable()->assertJsonValidationErrors('country_code');
|
||||
$after = DB::table('opportunity_location_drafts')->where('id', $id)->first();
|
||||
$this->assertSame($before->payload, $after->payload);
|
||||
$this->assertSame(1, $after->version);
|
||||
$this->assertSame($auditBefore, DB::table('audit_events')->where('source_system', 'opportunity-resources')->count());
|
||||
|
||||
$foreign = $this->postJson('/management/opportunities/'.$o->id.'/resources/locations',
|
||||
$this->payload($o->fresh(), ['title' => 'Synthetic QA foreign incomplete location', 'country_code' => 'PT', 'role' => 'market']))->assertCreated()->json('id');
|
||||
$saved = json_decode(DB::table('opportunity_location_drafts')->where('id', $foreign)->value('payload'), true);
|
||||
$this->assertSame('PT', $saved['country_code']);
|
||||
$this->assertEmpty($saved['province_id'] ?? null);
|
||||
$this->assertSame(0, DB::table('opportunity_locations')->count());
|
||||
$this->get('/management/opportunities/'.$o->id.'/resources')->assertInertia(fn (AssertableInertia $page) => $page
|
||||
->where('assessment', fn ($issues) => collect($issues)->every(fn ($issue) => ! str_contains($issue, 'província') && ! str_contains($issue, 'distrito'))));
|
||||
}
|
||||
|
||||
public function test_invalid_upload_and_cross_opportunity_links_do_not_create_resources(): void
|
||||
{
|
||||
[$user,$o] = $this->setupDraft();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Session\ArraySessionHandler;
|
||||
use Illuminate\Session\Store;
|
||||
use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
|
||||
use PragmaRX\Google2FA\Google2FA;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Tests\TestCase;
|
||||
|
||||
class PortalQaMfaTracePrivacyTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_diagnostic_distinguishes_replay_without_consuming_code_or_authenticating(): void
|
||||
{
|
||||
require_once base_path('tools/portal-qa-auth-trace.php');
|
||||
config(['cache.default' => 'array']);
|
||||
$engine = new Google2FA;
|
||||
$secret = $engine->generateSecretKey();
|
||||
User::factory()->create(['id' => 18, 'email' => 'investor-mfa-qa@example.invalid', 'two_factor_secret' => encrypt($secret), 'two_factor_confirmed_at' => now()]);
|
||||
$code = $engine->getCurrentOtp($secret);
|
||||
$request = Request::create('/two-factor-challenge', 'POST', ['code' => $code]);
|
||||
$session = new Store('qa_trace_unit', new ArraySessionHandler(120));
|
||||
$session->start();
|
||||
$session->put('login.id', 18);
|
||||
$request->setLaravelSession($session);
|
||||
$request->attributes->set('qa_auth_trace', 'unit');
|
||||
$trace = new \PortalQaSessionTrace;
|
||||
$trace->handle($request, fn () => new Response('controlled'));
|
||||
$first = $request->attributes->get('qa_mfa_input_check');
|
||||
$this->assertTrue($first['secret_decrypts']);
|
||||
$this->assertTrue($first['matches_configured_time_window']);
|
||||
$this->assertFalse($first['previously_used_in_cache']);
|
||||
$this->assertTrue($first['accepted_by_replay_check']);
|
||||
$this->assertFalse(auth()->check());
|
||||
// Fortify must still accept the unused code: the diagnostic cannot consume it.
|
||||
$this->assertTrue(app(TwoFactorAuthenticationProvider::class)->verify($secret, $code));
|
||||
$trace->handle($request, fn () => new Response('controlled'));
|
||||
$second = $request->attributes->get('qa_mfa_input_check');
|
||||
$this->assertTrue($second['matches_configured_time_window']);
|
||||
$this->assertTrue($second['previously_used_in_cache']);
|
||||
$this->assertFalse($second['accepted_by_replay_check']);
|
||||
$this->assertFalse(auth()->check());
|
||||
$encoded = json_encode($second, JSON_THROW_ON_ERROR);
|
||||
foreach ([$secret, $code, md5($code)] as $value) $this->assertStringNotContainsString($value, $encoded);
|
||||
$this->assertSame(18, $session->get('login.id'));
|
||||
}
|
||||
}
|
||||
@@ -290,6 +290,30 @@ class PortalServicesTest extends TestCase
|
||||
$this->assertDatabaseCount('portal_resource_revisions', 8);
|
||||
}
|
||||
|
||||
public function test_qa_library_preserves_an_original_without_inventing_a_topic_or_auto_publishing(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
$manager = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email], 'portal.legacy_content_qa_enabled' => false]);
|
||||
$this->actingAs($manager)->post('/management/portal-services/upload', [
|
||||
'file' => UploadedFile::fake()->createWithContent('original-image-reference.txt', 'Synthetic original without a thematic classification.'),
|
||||
])->assertSessionHasNoErrors();
|
||||
$document = DB::table('documents')->firstOrFail();
|
||||
$payload = [...$this->documentResourcePayload($document->id, 'Original sem assunto'), 'topic' => '', 'category' => 'media',
|
||||
'associations' => [], 'data_classification' => 'public'];
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasErrors('topic');
|
||||
$this->assertDatabaseCount('portal_resources', 0);
|
||||
config(['portal.legacy_content_qa_enabled' => true]);
|
||||
$this->post('/management/portal-services/resources', $payload)->assertSessionHasNoErrors();
|
||||
$resource = DB::table('portal_resources')->firstOrFail();
|
||||
$this->assertSame('', $resource->topic);
|
||||
$this->assertFalse($resource->published);
|
||||
$this->assertDatabaseCount('portal_resource_links', 0);
|
||||
$this->get('/documentos/'.$resource->id.'/download')->assertNotFound();
|
||||
$this->post('/management/portal-services/resources/'.$resource->id, ['published' => true])->assertSessionHasNoErrors();
|
||||
$this->get('/documentos/'.$resource->id.'/download')->assertOk();
|
||||
}
|
||||
|
||||
public function test_manager_classifies_a_reviewed_document_public_before_separate_publication(): void
|
||||
{
|
||||
Storage::fake('local');
|
||||
|
||||
Reference in New Issue
Block a user