commit16
This commit is contained in:
@@ -111,7 +111,8 @@ class BusinessMarketplacePublicTest extends TestCase
|
||||
->where('filters.modality', 'real_estate')->has('results.data', 1));
|
||||
$this->get('/negocios/'.$business['public_slug'])->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('investment/business-opportunity')
|
||||
->where('record.modality', 'real_estate'));
|
||||
->where('record.modality', 'real_estate')
|
||||
->where('similarCatalogueUrl', '/negocios?modality=real_estate'));
|
||||
$this->get('/negocios/'.$business['public_slug'].'/manifestar-interesse')->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('investment/business-interest')
|
||||
->where('record.modality', 'real_estate'));
|
||||
@@ -138,6 +139,45 @@ class BusinessMarketplacePublicTest extends TestCase
|
||||
$this->assertDatabaseHas('interest_requests', ['existing_business_id' => $business['id'], 'modality' => 'real_estate', 'status' => 'received']);
|
||||
}
|
||||
|
||||
public function test_similar_catalogue_uses_only_disclosed_primary_province_and_preserves_publication_limits(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$country = (string) Str::uuid();
|
||||
$province = (string) Str::uuid();
|
||||
DB::table('geo_locations')->insert([
|
||||
['id' => $country, 'name' => 'Synthetic country', 'code' => $country, 'location_type' => 'country', 'parent_id' => null],
|
||||
['id' => $province, 'name' => 'Synthetic province', 'code' => $province, 'location_type' => 'province', 'parent_id' => $country],
|
||||
]);
|
||||
foreach ([$country, $province] as $location) {
|
||||
DB::table('geo_locations')->where('id', $location)->update([
|
||||
'data_classification' => 'public', 'source_system' => 'cartografia-workbook',
|
||||
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$location,
|
||||
]);
|
||||
}
|
||||
$origin = $this->publishedBusiness();
|
||||
$match = $this->publishedBusiness();
|
||||
$reserved = $this->publishedBusiness();
|
||||
$expired = $this->publishedBusiness();
|
||||
foreach ([$origin, $match, $reserved, $expired] as $business) {
|
||||
DB::table('existing_business_locations')->insert([
|
||||
'id' => (string) Str::uuid(), 'existing_business_id' => $business['id'],
|
||||
'province_id' => $province, 'precision_level' => 'province',
|
||||
'is_primary' => true, 'is_public' => $business['id'] !== $reserved['id'],
|
||||
]);
|
||||
}
|
||||
DB::table('existing_businesses')->where('id', $expired['id'])->update(['expires_at' => now()->subDay()]);
|
||||
$url = '/negocios?modality=company_sale&province_id='.$province;
|
||||
$this->get('/negocios/'.$origin['public_slug'])->assertInertia(fn (Assert $page) => $page
|
||||
->where('similarCatalogueUrl', $url)->where('record.province', 'Synthetic province'));
|
||||
$this->get('/negocios/'.$reserved['public_slug'])->assertInertia(fn (Assert $page) => $page
|
||||
->where('similarCatalogueUrl', '/negocios?modality=company_sale')->where('record.province', null));
|
||||
$this->getJson('/api/v1/business-opportunities?modality=company_sale&province_id='.$province)->assertOk()
|
||||
->assertJsonCount(2, 'data')->assertJsonMissing(['id' => $reserved['id']])->assertJsonMissing(['id' => $expired['id']]);
|
||||
DB::table('geo_locations')->where('id', $province)->update(['source_system' => 'unpublished-synthetic']);
|
||||
$this->get('/negocios/'.$origin['public_slug'])->assertInertia(fn (Assert $page) => $page
|
||||
->where('similarCatalogueUrl', '/negocios?modality=company_sale'));
|
||||
}
|
||||
|
||||
/** @return array{id:string,public_slug:string} */
|
||||
private function publishedBusiness(string $modality = 'company_sale'): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskFormAnalysisScopeTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
private User $investor;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->manager = User::factory()->create();
|
||||
$this->investor = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
}
|
||||
|
||||
private function publish(string $code, array $definition, int $version = 0): string
|
||||
{
|
||||
return $this->actingAs($this->manager)->putJson('/management/balcao/servicos/'.$code, [
|
||||
'base_version' => $version, 'definition' => $definition, 'confirm' => true,
|
||||
'reason' => 'Synthetic QA analysis scope, without actual applicants.',
|
||||
])->assertCreated()->json('id');
|
||||
}
|
||||
|
||||
private function requestUrl(string $service): string
|
||||
{
|
||||
$case = $this->actingAs($this->investor)->postJson('/balcao-virtual/dossiers', [
|
||||
'title' => 'Synthetic analysis scope', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true,
|
||||
])->assertCreated()->json('id');
|
||||
$id = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', [
|
||||
'service_version_id' => $service, 'client_key' => (string) Str::uuid(),
|
||||
])->assertCreated()->json('id');
|
||||
|
||||
return '/balcao-virtual/pedidos/'.$id;
|
||||
}
|
||||
|
||||
public function test_checks_do_not_ask_for_finance_or_location_fields_absent_from_the_form(): void
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
unset($definition['fields']['territory_id'], $definition['fields']['location_source']);
|
||||
$url = $this->requestUrl($this->publish('project-change', $definition));
|
||||
$view = $this->getJson($url)->assertOk()->json();
|
||||
$codes = array_column($view['findings'], 'code');
|
||||
$this->assertNotContains('finance_unknown', $codes);
|
||||
$this->assertNotContains('finance_difference', $codes);
|
||||
$this->assertNotContains('location_unknown', $codes);
|
||||
$this->assertContains('official_form_pending', $codes);
|
||||
}
|
||||
|
||||
public function test_inactive_answers_are_preserved_without_blocking_submission_and_receipt_distinguishes_their_scope(): void
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-preparation');
|
||||
$definition['fields']['financial_branch'] = ['label' => 'Synthetic branch', 'type' => 'select', 'required' => true,
|
||||
'options' => ['no' => 'No', 'yes' => 'Yes']];
|
||||
foreach (['investment_amount', 'own_finance', 'other_finance', 'currency', 'territory_id', 'location_source'] as $key) {
|
||||
$definition['fields'][$key]['when'] = ['field' => 'financial_branch', 'equals' => 'yes'];
|
||||
}
|
||||
$definition['fields']['investment_amount']['label'] = 'Valor sintético preservado';
|
||||
$url = $this->requestUrl($this->publish('project-preparation', $definition));
|
||||
$answers = ['title' => 'Synthetic investment', 'description' => 'Synthetic description', 'regime' => 'unknown',
|
||||
'financial_branch' => 'no', 'investment_amount' => '100.00', 'own_finance' => '20.00', 'other_finance' => '30.00',
|
||||
'currency' => 'MZN', 'location_source' => 'Synthetic stored source'];
|
||||
$this->putJson($url, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$view = $this->getJson($url)->assertOk()->json();
|
||||
$this->assertSame($answers, $view['request']['payload']);
|
||||
$this->assertNotContains('finance_difference', array_column($view['findings'], 'code'));
|
||||
$this->assertNotContains('finance_unknown', array_column($view['findings'], 'code'));
|
||||
$this->assertNotContains('location_unknown', array_column($view['findings'], 'code'));
|
||||
$id = basename($url);
|
||||
$snapshot = DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot');
|
||||
$definition['fields']['investment_amount']['label'] = 'A later version must not relabel old receipts';
|
||||
$this->publish('project-preparation', $definition, 1);
|
||||
$this->actingAs($this->investor);
|
||||
$html = $this->get($url.'/recibo?format=html')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertSee('Respostas conservadas de perguntas não aplicáveis')->assertSee('Valor sintético preservado')
|
||||
->assertDontSee('A later version must not relabel old receipts')->getContent();
|
||||
[$applicable, $preserved] = explode('Respostas conservadas de perguntas não aplicáveis', $html, 2);
|
||||
$this->assertStringNotContainsString('Valor sintético preservado', $applicable);
|
||||
$this->assertStringContainsString('Valor sintético preservado', $preserved);
|
||||
$this->assertStringContainsString('100,00 MZN', $preserved);
|
||||
$technical = $this->get($url.'/recibo')->assertOk()->streamedContent();
|
||||
$this->assertStringContainsString('100.00', $technical);
|
||||
$this->assertSame($snapshot, DB::table('desk_requests')->where('id', $id)->value('submitted_snapshot'));
|
||||
$this->actingAs(User::factory()->create())->get($url.'/recibo?format=html')->assertForbidden();
|
||||
|
||||
$active = $this->requestUrl(DB::table('desk_service_versions')->where('code', 'project-preparation')->where('version', 2)->value('id'));
|
||||
$answers['financial_branch'] = 'yes';
|
||||
$this->putJson($active, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('payload.investment_amount');
|
||||
$answers['own_finance'] = '40.00';
|
||||
$answers['other_finance'] = '60.00';
|
||||
$this->putJson($active, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\VirtualDesk;
|
||||
use Database\Seeders\TerritoryReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskLocationApplicabilityTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_a_preserved_inactive_location_does_not_require_a_hidden_source_but_an_active_location_still_does(): void
|
||||
{
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$territory = app(InvestmentGeography::class)->publicReferences()->where('location_type', 'province')->value('id');
|
||||
$this->assertNotEmpty($territory);
|
||||
$definition = ['fields' => [
|
||||
'branch' => ['label' => 'Synthetic branch', 'type' => 'select', 'required' => true, 'options' => ['yes' => 'Yes', 'no' => 'No']],
|
||||
'territory_id' => ['label' => 'Location', 'type' => 'territory', 'required' => false, 'when' => ['field' => 'branch', 'equals' => 'yes']],
|
||||
'location_source' => ['label' => 'Source', 'type' => 'text', 'required' => false, 'when' => ['field' => 'branch', 'equals' => 'yes']],
|
||||
]];
|
||||
$desk = app(VirtualDesk::class);
|
||||
$payload = ['branch' => 'no', 'territory_id' => $territory];
|
||||
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
|
||||
$payload['branch'] = 'yes';
|
||||
try {
|
||||
$desk->validateFields($payload, $definition, true);
|
||||
$this->fail('An applicable selected location must retain its source requirement.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.location_source', $error->errors());
|
||||
}
|
||||
$payload['location_source'] = 'Synthetic QA use of the packaged reference';
|
||||
$this->assertSame($payload, $desk->validateFields($payload, $definition, true));
|
||||
$this->assertSame(['branch' => 'yes'], $desk->validateFields(['branch' => 'yes'], $definition, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskReceiptCompatibilityTest extends TestCase
|
||||
{
|
||||
public function test_existing_direct_receipt_consumers_keep_their_contract_and_escape_preserved_answers(): void
|
||||
{
|
||||
$definition = ['title' => 'Synthetic receipt', 'fields' => [
|
||||
'branch' => ['label' => 'Synthetic branch', 'type' => 'select', 'options' => ['no' => 'No', 'yes' => 'Yes']],
|
||||
'detail' => ['label' => 'Synthetic preserved detail', 'type' => 'text', 'when' => ['field' => 'branch', 'equals' => 'yes']],
|
||||
]];
|
||||
$payload = ['branch' => 'no', 'detail' => '<script>alert("synthetic")</script>'];
|
||||
$record = (object) ['id' => 'synthetic-id', 'protocol' => 'SYNTHETIC-QA', 'submitted_at' => '2026-11-02 10:00:00', 'version' => 2];
|
||||
$html = view('desk.receipt', ['record' => $record, 'snapshot' => ['payload' => $payload], 'definition' => $definition])->render();
|
||||
[$active, $preserved] = explode('Respostas conservadas de perguntas não aplicáveis', $html, 2);
|
||||
$this->assertStringNotContainsString('Synthetic preserved detail', $active);
|
||||
$this->assertStringContainsString('Synthetic preserved detail', $preserved);
|
||||
$this->assertStringContainsString('<script>', $preserved);
|
||||
$this->assertStringNotContainsString('<script>', $html);
|
||||
$payload['branch'] = 'yes';
|
||||
$html = view('desk.receipt', ['record' => $record, 'snapshot' => ['payload' => $payload], 'definition' => $definition])->render();
|
||||
$this->assertStringNotContainsString('Respostas conservadas de perguntas não aplicáveis', $html);
|
||||
$this->assertStringContainsString('Synthetic preserved detail', $html);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\VirtualDesk;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskServiceEditorTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $manager;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->manager = User::factory()->create();
|
||||
config(['portal.managers' => [$this->manager->email]]);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function input(int $version = 0): array
|
||||
{
|
||||
return ['base_version' => $version, 'definition' => config('virtual-desk.services.project-change'),
|
||||
'reason' => 'Synthetic QA definition change; no actual service or applicant.', 'confirm' => true];
|
||||
}
|
||||
|
||||
public function test_numeric_choice_values_do_not_bypass_conditional_requirements(): void
|
||||
{
|
||||
$definition = ['fields' => [
|
||||
'choice' => ['label' => 'Choice', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes']],
|
||||
'detail' => ['label' => 'Detail', 'type' => 'text', 'required' => true, 'when' => ['field' => 'choice', 'equals' => '1']],
|
||||
]];
|
||||
$desk = app(VirtualDesk::class);
|
||||
try {
|
||||
$desk->validateFields(['choice' => 1], $definition, true);
|
||||
$this->fail('A numeric option identifier must not bypass the required dependent answer.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.detail', $error->errors());
|
||||
}
|
||||
$valid = $desk->validateFields(['choice' => 1, 'detail' => 'Synthetic detail'], $definition, true);
|
||||
$this->assertSame('1', $valid['choice']);
|
||||
$this->assertSame('Synthetic detail', $valid['detail']);
|
||||
}
|
||||
|
||||
public function test_hidden_parent_answers_do_not_activate_nested_required_questions(): void
|
||||
{
|
||||
// Children deliberately precede parents: field order must not change applicability.
|
||||
$definition = ['fields' => [
|
||||
'detail' => ['label' => 'Deep detail', 'type' => 'text', 'required' => true, 'when' => ['field' => 'branch', 'equals' => '1']],
|
||||
'branch' => ['label' => 'Branch', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes'], 'when' => ['field' => 'root', 'equals' => '1']],
|
||||
'root' => ['label' => 'Root', 'type' => 'select', 'required' => true, 'options' => ['0' => 'No', '1' => 'Yes']],
|
||||
]];
|
||||
$desk = app(VirtualDesk::class);
|
||||
$inactive = $desk->validateFields(['root' => '0', 'branch' => '1'], $definition, true);
|
||||
$this->assertSame('1', $inactive['branch'], 'Keep previous answers without making their descendants applicable.');
|
||||
$this->assertArrayNotHasKey('detail', $inactive);
|
||||
$saved = $desk->validateFields(['root' => '0', 'branch' => '1', 'detail' => 'Preserved answer'], $definition, true);
|
||||
$this->assertSame('Preserved answer', $saved['detail']);
|
||||
$draft = $desk->validateFields(['root' => '1', 'branch' => 1], $definition, false);
|
||||
$this->assertSame('1', $draft['branch']);
|
||||
try {
|
||||
$desk->validateFields(['root' => '1', 'branch' => 1], $definition, true);
|
||||
$this->fail('An applicable nested question must still be required on submission.');
|
||||
} catch (ValidationException $error) {
|
||||
$this->assertArrayHasKey('payload.detail', $error->errors());
|
||||
}
|
||||
$active = $desk->validateFields(['root' => '1', 'branch' => '1', 'detail' => 'Applicable answer'], $definition, true);
|
||||
$this->assertSame('Applicable answer', $active['detail']);
|
||||
}
|
||||
|
||||
public function test_published_versions_preserve_existing_request_schema_payload_and_source_and_retry_without_duplicates(): void
|
||||
{
|
||||
$url = '/management/balcao/servicos/project-change';
|
||||
$v1 = $this->actingAs($this->manager)->putJson($url, $this->input())->assertCreated()->assertJsonPath('version', 1)->json('id');
|
||||
$before = DB::table('desk_service_versions')->where('id', $v1)->first();
|
||||
$investor = User::factory()->create();
|
||||
$case = $this->actingAs($investor)->postJson('/balcao-virtual/dossiers', ['title' => 'Synthetic schema preservation', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true])->assertCreated()->json('id');
|
||||
$request = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v1, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$answers = ['title' => 'Existing synthetic answer', 'description' => 'Synthetic description of the proposed change',
|
||||
'original_reference' => 'SYNTHETIC-REF', 'change_reason' => 'Synthetic justification for version preservation'];
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$request, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$saved = DB::table('desk_requests')->where('id', $request)->first();
|
||||
$input = $this->input(1);
|
||||
$input['definition']['fields']['extra_question'] = ['label' => 'Additional email', 'type' => 'email', 'required' => true];
|
||||
$v2 = $this->actingAs($this->manager)->putJson($url, $input)->assertCreated()->assertJsonPath('version', 2)->json('id');
|
||||
$this->putJson($url, $input)->assertCreated()->assertJsonPath('id', $v2);
|
||||
$this->assertSame(2, DB::table('desk_service_versions')->where('code', 'project-change')->count());
|
||||
$this->assertSame($before->definition, DB::table('desk_service_versions')->where('id', $v1)->value('definition'));
|
||||
$this->assertSame($before->source, DB::table('desk_service_versions')->where('id', $v2)->value('source'));
|
||||
$after = DB::table('desk_requests')->where('id', $request)->first();
|
||||
$this->assertSame($saved->payload, $after->payload);
|
||||
$this->assertSame($saved->submitted_snapshot, $after->submitted_snapshot);
|
||||
$this->assertSame('submitted', $after->status);
|
||||
$this->assertSame($v1, $after->service_version_id);
|
||||
$this->actingAs($investor)->getJson('/balcao-virtual/pedidos/'.$request)->assertOk()->assertJsonMissingPath('definition.fields.extra_question');
|
||||
$next = $this->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', ['service_version_id' => $v2, 'client_key' => (string) Str::uuid()])->assertCreated()->json('id');
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$next)->assertOk()->assertJsonPath('definition.fields.extra_question.required', true);
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('payload.extra_question');
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => [...$answers, 'extra_question' => 'invalid-email'], 'submit' => true, 'consent' => true])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('payload.extra_question');
|
||||
$this->putJson('/balcao-virtual/pedidos/'.$next, ['version' => 1, 'payload' => [...$answers, 'extra_question' => 'synthetic@example.invalid'], 'submit' => true, 'consent' => true])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->assertSame(2, DB::table('audit_events')->where('action', 'service_definition_version_published')->count());
|
||||
$history = '/management/balcao/servicos/project-change/versoes';
|
||||
$this->getJson($history)->assertForbidden();
|
||||
$this->actingAs($this->manager)->getJson($history)->assertOk()->assertJsonPath('total', 2)
|
||||
->assertJsonPath('data.0.id', $v2)->assertJsonPath('data.1.id', $v1)
|
||||
->assertJsonPath('data.0.reason', $input['reason'])->assertJsonPath('data.0.author_id', $this->manager->id)
|
||||
->assertJsonPath('data.0.definition.fields.extra_question.type', 'email')
|
||||
->assertJsonMissingPath('data.1.definition.fields.extra_question')->assertJsonMissingPath('data.0.payload')
|
||||
->assertDontSee('Existing synthetic answer', false);
|
||||
$this->assertSame($saved->submitted_snapshot, DB::table('desk_requests')->where('id', $request)->value('submitted_snapshot'));
|
||||
}
|
||||
|
||||
public function test_authority_conflicts_conditions_reserved_keys_and_stage_changes_are_checked_on_server(): void
|
||||
{
|
||||
$url = '/management/balcao/servicos/project-change';
|
||||
$this->actingAs(User::factory()->create())->getJson('/management/balcao/servicos')->assertForbidden();
|
||||
$this->putJson($url, $this->input())->assertForbidden();
|
||||
$this->actingAs($this->manager)->getJson('/management/balcao/servicos')->assertOk()->assertJsonCount(3, 'services');
|
||||
$this->putJson($url, $this->input())->assertCreated();
|
||||
$this->putJson($url, $this->input(1))->assertUnprocessable()->assertJsonValidationErrors('definition');
|
||||
$stale = $this->input();
|
||||
$stale['definition']['title'] = 'Stale alternative';
|
||||
$this->putJson($url, $stale)->assertConflict();
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['fields']['regime']['type'] = 'text';
|
||||
unset($invalid['definition']['fields']['regime']['options']);
|
||||
$this->putJson($url, $invalid)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.regime.type');
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['stage'] = 'E1';
|
||||
$this->putJson($url, $invalid)->assertUnprocessable()->assertJsonValidationErrors('definition.stage');
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['fields']['context_reuse'] = ['label' => 'Reserved', 'type' => 'text', 'required' => false];
|
||||
$this->putJson($url, $invalid)->assertUnprocessable();
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['fields']['title']['when'] = ['field' => 'description', 'equals' => 'x'];
|
||||
$invalid['definition']['fields']['description']['when'] = ['field' => 'title', 'equals' => 'x'];
|
||||
$this->putJson($url, $invalid)->assertUnprocessable();
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['fields']['description']['when'] = ['field' => 'regime', 'equals' => 'missing-option'];
|
||||
$this->putJson($url, $invalid)->assertUnprocessable();
|
||||
$invalid = $this->input(1);
|
||||
$invalid['definition']['fields']['regime']['options'] = [];
|
||||
$this->putJson($url, $invalid)->assertUnprocessable();
|
||||
$this->assertSame(1, DB::table('desk_service_versions')->where('code', 'project-change')->count());
|
||||
}
|
||||
|
||||
public function test_history_pagination_is_bounded_and_does_not_mix_service_definitions(): void
|
||||
{
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
for ($version = 1; $version <= 12; $version++) {
|
||||
DB::table('desk_service_versions')->insert(['id' => (string) Str::uuid(), 'code' => 'project-change', 'version' => $version,
|
||||
'status' => 'published', 'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')),
|
||||
'author_id' => $this->manager->id, 'published_by' => $this->manager->id, 'published_at' => now()]);
|
||||
}
|
||||
$url = '/management/balcao/servicos/project-change/versoes';
|
||||
$this->actingAs($this->manager)->getJson($url)->assertOk()->assertJsonCount(10, 'data')->assertJsonPath('total', 12)
|
||||
->assertJsonPath('data.0.version', 12)->assertJsonPath('data.9.version', 3);
|
||||
$this->getJson($url.'?page=2')->assertOk()->assertJsonCount(2, 'data')->assertJsonPath('data.0.version', 2)->assertJsonPath('data.1.version', 1);
|
||||
$this->getJson($url.'?page=999999999')->assertOk()->assertJsonPath('page', 2)->assertJsonCount(2, 'data');
|
||||
$this->getJson($url.'?page=0')->assertUnprocessable();
|
||||
$this->getJson('/management/balcao/servicos/project-follow-up/versoes')->assertOk()->assertJsonCount(0, 'data')->assertJsonPath('total', 0);
|
||||
$this->getJson('/management/balcao/servicos/missing-service/versoes')->assertNotFound();
|
||||
$this->assertSame(12, DB::table('desk_service_versions')->count());
|
||||
DB::table('desk_service_versions')->insert(['id' => (string) Str::uuid(), 'code' => 'historical-service', 'version' => 1,
|
||||
'status' => 'published', 'definition' => json_encode($definition), 'source' => json_encode(config('virtual-desk.source')), 'author_id' => $this->manager->id]);
|
||||
$this->getJson('/management/balcao/servicos/historical-service/versoes')->assertOk()->assertJsonCount(1, 'data');
|
||||
$this->getJson('/management/balcao/servicos')->assertOk()->assertJsonPath('services.3.code', 'historical-service')->assertJsonPath('services.3.editable', false);
|
||||
$this->putJson('/management/balcao/servicos/historical-service', $this->input(1))->assertNotFound();
|
||||
$this->assertSame(13, DB::table('desk_service_versions')->count());
|
||||
}
|
||||
|
||||
public function test_location_source_remains_available_whenever_a_configured_location_applies(): void
|
||||
{
|
||||
$url = '/management/balcao/servicos/project-change';
|
||||
$this->actingAs($this->manager);
|
||||
$missing = $this->input();
|
||||
unset($missing['definition']['fields']['location_source']);
|
||||
$this->putJson($url, $missing)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.location_source');
|
||||
$narrower = $this->input();
|
||||
$narrower['definition']['fields']['location_source']['when'] = ['field' => 'regime', 'equals' => 'special'];
|
||||
$this->putJson($url, $narrower)->assertUnprocessable()->assertJsonValidationErrors('definition.fields.location_source.when');
|
||||
$this->assertDatabaseCount('desk_service_versions', 0);
|
||||
|
||||
// The source can have broader applicability than the location, including ancestor conditions.
|
||||
$broader = $this->input();
|
||||
$broader['definition']['fields']['branch'] = ['label' => 'Synthetic branch', 'type' => 'select', 'required' => false,
|
||||
'options' => ['yes' => 'Yes', 'no' => 'No'], 'when' => ['field' => 'regime', 'equals' => 'special']];
|
||||
$broader['definition']['fields']['territory_id']['when'] = ['field' => 'branch', 'equals' => 'yes'];
|
||||
$broader['definition']['fields']['location_source']['when'] = ['field' => 'regime', 'equals' => 'special'];
|
||||
$this->putJson($url, $broader)->assertCreated();
|
||||
$same = $broader;
|
||||
$same['base_version'] = 1;
|
||||
$same['definition']['fields']['location_source']['when'] = ['field' => 'branch', 'equals' => 'yes'];
|
||||
$this->putJson($url, $same)->assertCreated();
|
||||
$unconditional = $same;
|
||||
$unconditional['base_version'] = 2;
|
||||
unset($unconditional['definition']['fields']['location_source']['when']);
|
||||
$this->putJson($url, $unconditional)->assertCreated();
|
||||
$withoutLocation = $this->input(3);
|
||||
unset($withoutLocation['definition']['fields']['territory_id'], $withoutLocation['definition']['fields']['location_source']);
|
||||
$this->putJson($url, $withoutLocation)->assertCreated();
|
||||
$this->assertDatabaseCount('desk_service_versions', 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class DeskServiceSchemaPrefillTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_new_requests_reuse_only_fields_and_default_options_present_in_their_own_definition(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$manager = User::factory()->create();
|
||||
$investor = User::factory()->create();
|
||||
config(['portal.managers' => [$manager->email]]);
|
||||
$url = '/management/balcao/servicos/project-change';
|
||||
$definition = config('virtual-desk.services.project-change');
|
||||
$publish = fn (int $base, array $schema) => $this->actingAs($manager)->putJson($url, [
|
||||
'base_version' => $base, 'definition' => $schema, 'confirm' => true,
|
||||
'reason' => 'Synthetic QA schema configuration, without actual applicants.',
|
||||
])->assertCreated()->json('id');
|
||||
$v1 = $publish(0, $definition);
|
||||
$case = $this->actingAs($investor)->postJson('/balcao-virtual/dossiers', [
|
||||
'title' => 'Synthetic project title', 'client_key' => (string) Str::uuid(), 'reuse_consent' => true,
|
||||
])->assertCreated()->json('id');
|
||||
$create = fn (string $version) => $this->actingAs($investor)->postJson('/balcao-virtual/dossiers/'.$case.'/pedidos', [
|
||||
'service_version_id' => $version, 'client_key' => (string) Str::uuid(),
|
||||
])->assertCreated()->json('id');
|
||||
$old = $create($v1);
|
||||
$oldPayload = DB::table('desk_requests')->where('id', $old)->value('payload');
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$old)->assertOk()->assertJsonPath('request.payload.title', 'Synthetic project title')
|
||||
->assertJsonPath('request.payload.regime', 'unknown');
|
||||
unset($definition['fields']['title'], $definition['fields']['description'], $definition['fields']['regime']);
|
||||
$v2 = $publish(1, $definition);
|
||||
$next = $create($v2);
|
||||
$requestUrl = '/balcao-virtual/pedidos/'.$next;
|
||||
$view = $this->getJson($requestUrl)->assertOk()->assertJsonMissingPath('request.payload.title')
|
||||
->assertJsonMissingPath('request.payload.description')->assertJsonMissingPath('request.payload.regime')->json();
|
||||
$answers = [...$view['request']['payload'], 'original_reference' => 'SYNTHETIC-REFERENCE', 'change_reason' => 'Synthetic reason'];
|
||||
$this->putJson($requestUrl, ['version' => 1, 'payload' => [...$answers, 'unconfigured' => 'not allowed']])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('payload');
|
||||
$this->putJson($requestUrl, ['version' => 1, 'payload' => $answers])->assertOk()->assertJsonPath('status', 'draft');
|
||||
$this->putJson($requestUrl, ['version' => 2, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->assertSame($oldPayload, DB::table('desk_requests')->where('id', $old)->value('payload'));
|
||||
$this->getJson('/balcao-virtual/pedidos/'.$old)->assertOk()->assertJsonPath('request.payload.title', 'Synthetic project title')
|
||||
->assertJsonPath('request.payload.regime', 'unknown')->assertJsonPath('definition.fields.title.required', true);
|
||||
|
||||
$definition['fields']['regime'] = ['label' => 'Synthetic configured choice', 'type' => 'select', 'required' => true,
|
||||
'options' => ['configured' => 'Synthetic configured option']];
|
||||
$v3 = $publish(2, $definition);
|
||||
$configured = $create($v3);
|
||||
$configuredUrl = '/balcao-virtual/pedidos/'.$configured;
|
||||
$view = $this->getJson($configuredUrl)->assertOk()->assertJsonMissingPath('request.payload.regime')->json();
|
||||
$answers = [...$view['request']['payload'], 'original_reference' => 'SYNTHETIC-REFERENCE', 'change_reason' => 'Synthetic reason'];
|
||||
$this->putJson($configuredUrl, ['version' => 1, 'payload' => $answers, 'submit' => true, 'consent' => true])
|
||||
->assertUnprocessable()->assertJsonValidationErrors('payload.regime');
|
||||
$this->putJson($configuredUrl, ['version' => 1, 'payload' => [...$answers, 'regime' => 'configured'], 'submit' => true, 'consent' => true])
|
||||
->assertOk()->assertJsonPath('status', 'submitted');
|
||||
$this->assertSame(3, DB::table('desk_service_versions')->count());
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ class ExistingBusinessIntakeTest extends TestCase
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
config(['existing-business.enabled' => true]);
|
||||
// This suite exercises the explicit legacy designation lists, not profile grants.
|
||||
config(['existing-business.enabled' => true, 'portal.profile_access_enabled' => false,
|
||||
'portal.profile_administration_enabled' => false]);
|
||||
}
|
||||
|
||||
private function reviewer(): User
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\FundingProgrammeReferences;
|
||||
use App\Services\FundingProgrammes;
|
||||
use Database\Seeders\TerritoryReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class FundingProgrammesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private function draft(): array
|
||||
{
|
||||
return ['title' => 'SINTÉTICO QA — Fundo de ensaio', 'kind' => 'fund', 'summary' => 'Referência fictícia para validação técnica.',
|
||||
'manager_name' => 'Entidade sintética', 'source_url' => 'https://example.invalid/fund', 'source_reference' => 'Documento sintético QA',
|
||||
'source_checked_on' => today()->toDateString(), 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'unknown',
|
||||
'criteria' => [['code' => 'registration', 'question' => 'A entidade tem registo?', 'applies_to' => 'entity', 'expected' => 'yes',
|
||||
'source_reference' => 'Critério sintético 1', 'explanation' => 'Exigência fictícia para ensaio.']],
|
||||
'windows' => [['code' => 'closed-call', 'title' => 'Chamada histórica sintética', 'mode' => 'dated',
|
||||
'end_on' => today()->subDay()->toDateString(), 'coverage' => 'programme', 'source_url' => 'https://example.invalid/call',
|
||||
'source_reference' => 'Chamada fictícia QA', 'checked_on' => today()->toDateString()]]];
|
||||
}
|
||||
|
||||
private function publishDraft(User $editor, string $code, array $draft): string
|
||||
{
|
||||
$service = app(FundingProgrammes::class);
|
||||
$id = $service->save($editor, null, ['version' => 0, 'code' => $code, 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
|
||||
$plan = $service->preview($editor, $id);
|
||||
$service->publish($editor, $id, ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true]);
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function test_packaged_official_reference_prepares_only_a_draft_and_reuses_existing_fiche_without_overwriting(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$this->travelTo(Carbon::parse('2026-11-02 12:00:00'));
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$this->actingAs($editor)->get('/management/fundos/referencias/fdel')->assertOk()
|
||||
->assertInertia(fn ($page) => $page->component('funding/reference')->where('reference.draft.coverage', 'national')
|
||||
->where('reference.draft.windows.0.end_on', '2025-10-20')->where('reference.draft.windows.0.coverage', 'unknown'));
|
||||
$references = app(FundingProgrammeReferences::class);
|
||||
$plan = $references->preview($editor, 'fdel');
|
||||
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => str_repeat('0', 64)])->assertConflict();
|
||||
$this->assertSame(0, DB::table('funding_programmes')->count());
|
||||
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertRedirect();
|
||||
$row = DB::table('funding_programmes')->where('code', 'fdel')->first();
|
||||
$this->assertNotNull($row);
|
||||
$this->assertNull($row->published_version_id);
|
||||
$this->assertSame(0, DB::table('funding_programme_versions')->count());
|
||||
$service = app(FundingProgrammes::class);
|
||||
$publication = $service->preview($editor, $row->id);
|
||||
$this->assertSame('closed', $service->windowState($publication['payload']['windows'][0]));
|
||||
$this->assertSame([], $publication['payload']['windows'][0]['territory_ids']);
|
||||
$this->assertSame([], $publication['payload']['resource_ids']);
|
||||
$audit = DB::table('audit_events')->where('entity_id', $row->id)->where('action', 'reference_prepared')->first();
|
||||
$this->assertSame($plan['package_sha256'], json_decode($audit->after_data, true)['package_sha256']);
|
||||
$draft = json_decode($row->draft, true);
|
||||
$draft['summary'] = 'Alteração editorial deliberada de ensaio; preservar sem substituição pela referência.';
|
||||
$service->save($editor, $row->id, ['version' => 1, 'code' => 'fdel', 'reason' => 'Actualização deliberada de ensaio antes de repetir.', 'draft' => $draft]);
|
||||
$before = DB::table('funding_programmes')->where('id', $row->id)->first();
|
||||
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertRedirect('/management/fundos/'.$row->id);
|
||||
$this->assertSame($before->draft, DB::table('funding_programmes')->where('id', $row->id)->value('draft'));
|
||||
$this->assertSame(1, DB::table('funding_programmes')->count());
|
||||
$this->assertSame(1, DB::table('audit_events')->where('entity_id', $row->id)->where('action', 'reference_prepared')->count());
|
||||
$this->actingAs(User::factory()->create())->get('/management/fundos/referencias/fdel')->assertForbidden();
|
||||
$this->post('/management/fundos/referencias/fdel/preparar', ['hash' => $plan['hash']])->assertForbidden();
|
||||
$this->travelBack();
|
||||
}
|
||||
|
||||
public function test_download_is_pinned_to_published_library_version_and_rechecks_rights_scan_and_actual_bytes(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
Storage::fake('local');
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$document = (string) Str::uuid();
|
||||
$bytes = 'SINTÉTICO QA — Condições fictícias, versão um.';
|
||||
$key = 'funding-qa/'.$document.'.txt';
|
||||
Storage::disk('local')->put($key, $bytes);
|
||||
DB::table('documents')->insert(['id' => $document, 'source_system' => 'synthetic-funding-test', 'file_name' => 'funding-qa.txt', 'media_type' => 'text/plain',
|
||||
'storage_key' => $key, 'size_bytes' => strlen($bytes), 'sha256' => hash('sha256', $bytes), 'malware_scanned_sha256' => hash('sha256', $bytes),
|
||||
'malware_scan_status' => 'clean', 'status' => 'active', 'rights_status' => 'authorized', 'data_classification' => 'public', 'version_no' => 1]);
|
||||
$resource = DB::table('portal_resources')->insertGetId(['document_id' => $document, 'title' => 'SINTÉTICO QA — Condições', 'category' => 'funding-qa', 'topic' => 'Ensaio sintético de financiamento',
|
||||
'published' => true, 'rights_status' => 'authorized', 'source_url' => 'https://example.invalid/funding-qa', 'source_reference' => 'Referência sintética QA', 'metadata_version' => 1]);
|
||||
$id = $this->publishDraft($editor, 'qa-document', [...$this->draft(), 'resource_ids' => [$resource]]);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$published = $service->published($id);
|
||||
$url = '/fundos/'.$id.'/versoes/'.$published['version_id'].'/documentos/'.$resource;
|
||||
$this->get($url)->assertOk()->assertDownload('funding-qa.txt');
|
||||
$this->assertTrue($published['payload']['documents'][0]['available']);
|
||||
Storage::disk('local')->put($key, 'SINTÉTICO QA — Ficheiro alterado sem nova análise.');
|
||||
$this->get($url)->assertNotFound();
|
||||
Storage::disk('local')->put($key, $bytes);
|
||||
foreach ([['malware_scan_status' => 'pending'], ['rights_status' => 'restricted'], ['data_classification' => 'confidential'], ['malware_scanned_sha256' => str_repeat('0', 64)]] as $patch) {
|
||||
DB::table('documents')->where('id', $document)->update($patch);
|
||||
$this->get($url)->assertNotFound();
|
||||
$this->assertFalse($service->published($id)['payload']['documents'][0]['available']);
|
||||
DB::table('documents')->where('id', $document)->update(['malware_scan_status' => 'clean', 'rights_status' => 'authorized', 'data_classification' => 'public', 'malware_scanned_sha256' => hash('sha256', $bytes)]);
|
||||
}
|
||||
$oldPlan = $service->preview($editor, $id);
|
||||
DB::table('documents')->where('id', $document)->update(['version_no' => 2]);
|
||||
$this->get($url)->assertNotFound();
|
||||
$this->assertFalse($service->published($id)['payload']['documents'][0]['available']);
|
||||
$newPlan = $service->preview($editor, $id);
|
||||
$this->assertNotSame($oldPlan['hash'], $newPlan['hash']);
|
||||
$this->actingAs($editor)->post('/management/fundos/'.$id.'/publicar', ['version' => 1, 'hash' => $oldPlan['hash'], 'reason' => 'Publicação sintética para ensaio de versão.', 'confirm' => true])->assertConflict();
|
||||
$version = $service->publish($editor, $id, ['version' => 1, 'hash' => $newPlan['hash'], 'reason' => 'Publicação sintética para ensaio de versão.', 'confirm' => true]);
|
||||
$this->get('/fundos/'.$id.'/versoes/'.$version.'/documentos/'.$resource)->assertOk();
|
||||
$this->get($url)->assertNotFound();
|
||||
DB::table('portal_resources')->where('id', $resource)->update(['published' => false]);
|
||||
$this->get('/fundos/'.$id.'/versoes/'.$version.'/documentos/'.$resource)->assertNotFound();
|
||||
$this->assertSame(1, json_decode(DB::table('funding_programme_versions')->where('id', $published['version_id'])->value('payload'), true)['document_snapshots'][0]['version']);
|
||||
}
|
||||
|
||||
public function test_filters_explain_unknown_and_partial_coverage_preserve_scopes_and_distinguish_window_dates(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$sector = Sector::create(['name' => 'SINTÉTICO QA — Agricultura', 'slug' => 'qa-funding-agriculture', 'is_active' => true, 'published_at' => now()]);
|
||||
$otherSector = Sector::create(['name' => 'SINTÉTICO QA — Indústria', 'slug' => 'qa-funding-industry', 'is_active' => true, 'published_at' => now()]);
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
|
||||
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Tete')->value('id');
|
||||
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
|
||||
$national = $this->publishDraft($editor, 'qa-national', [...$this->draft(), 'sectors_scope' => 'all', 'windows' => []]);
|
||||
$unknown = $this->publishDraft($editor, 'qa-unknown', [...$this->draft(), 'coverage' => 'unknown', 'windows' => []]);
|
||||
$window = [...$this->draft()['windows'][0], 'mode' => 'dated', 'start_on' => today()->toDateString(), 'end_on' => today()->toDateString()];
|
||||
$local = $this->publishDraft($editor, 'qa-local', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$province], 'sectors_scope' => 'selected', 'sector_ids' => [$sector->id], 'windows' => [$window]]);
|
||||
$outside = $this->publishDraft($editor, 'qa-outside', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$otherProvince], 'sectors_scope' => 'selected', 'sector_ids' => [$sector->id]]);
|
||||
$partial = $this->publishDraft($editor, 'qa-district', [...$this->draft(), 'coverage' => 'territorial', 'territory_ids' => [$district], 'sectors_scope' => 'selected', 'sector_ids' => [$otherSector->id],
|
||||
'windows' => [[...$window, 'start_on' => today()->addDay()->toDateString(), 'end_on' => today()->addWeek()->toDateString()]]]);
|
||||
$get = fn (array $filters) => $this->get('/fundos?'.http_build_query($filters))->assertOk();
|
||||
$filters = ['sector' => $sector->id, 'territory' => $province];
|
||||
$get($filters)->assertInertia(fn ($page) => $page->has('items.data', 3)->where('items.data', fn ($rows) => collect($rows)->pluck('id')->sort()->values()->all() === collect([$national, $unknown, $local])->sort()->values()->all()));
|
||||
$get([...$filters, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
|
||||
$get([...$filters, 'territory' => $district, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
|
||||
$get(['sector' => $otherSector->id, 'territory' => $province, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2)
|
||||
->where('items.data', fn ($rows) => str_contains(collect($rows)->firstWhere('id', $partial)['filter_explanation']['territory'], 'uma parte')));
|
||||
$get(['state' => 'open'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $local));
|
||||
$get(['state' => 'closed'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $outside));
|
||||
$get(['state' => 'upcoming'])->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.id', $partial));
|
||||
$get(['state' => 'unknown'])->assertInertia(fn ($page) => $page->has('items.data', 2));
|
||||
$get(['territory' => $otherProvince, 'sector' => $sector->id, 'certainty' => 'documented'])->assertInertia(fn ($page) => $page->has('items.data', 2));
|
||||
$this->getJson('/fundos?territory='.Str::uuid())->assertUnprocessable();
|
||||
$snapshot = app(FundingProgrammes::class)->published($local);
|
||||
DB::table('geo_locations')->where('id', $province)->update(['name' => 'SINTÉTICO QA — Nome alterado']);
|
||||
$this->assertSame($snapshot['payload']['territory_paths'], app(FundingProgrammes::class)->published($local)['payload']['territory_paths']);
|
||||
}
|
||||
|
||||
public function test_public_versions_and_private_interests_preserve_the_original_snapshot(): void
|
||||
{
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$input = ['version' => 0, 'code' => 'synthetic-fund', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $this->draft()];
|
||||
$id = $service->save($editor, null, $input);
|
||||
$plan = $service->preview($editor, $id);
|
||||
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true];
|
||||
$first = $service->publish($editor, $id, $publication);
|
||||
$this->withoutVite();
|
||||
$this->get('/fundos')->assertOk();
|
||||
$this->get('/fundos/'.$id)->assertOk();
|
||||
$this->get('/fundos?q=sem-correspondencia')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
|
||||
$this->put('/fundos/'.$id.'/interesse', ['version_id' => $first, 'consent' => true])->assertRedirect('/login');
|
||||
$this->postJson('/fundos/'.$id.'/criterios', ['version_id' => $first, 'applicant_kind' => 'entity', 'answers' => ['registration' => 'no']])
|
||||
->assertOk()->assertJsonPath('criteria.0.status', 'does_not_match');
|
||||
$this->assertSame($first, $service->publish($editor, $id, $publication));
|
||||
$this->assertSame(1, DB::table('funding_programme_versions')->count());
|
||||
$this->assertSame('closed', $service->published($id)['payload']['windows'][0]['state']);
|
||||
$person = User::factory()->create();
|
||||
$service->saveInterest($person, $id, $first, true);
|
||||
$this->actingAs($person)->get('/fundos/guardados')->assertOk()->assertHeader('Cache-Control', 'no-store, private')
|
||||
->assertInertia(fn ($page) => $page->has('items.data', 1)->where('items.data.0.saved_version', 1));
|
||||
$this->actingAs(User::factory()->create())->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
|
||||
$input['version'] = 1;
|
||||
$input['draft']['summary'] = 'Descrição sintética actualizada.';
|
||||
$service->save($editor, $id, $input);
|
||||
$this->assertSame($first, $service->published($id)['version_id']);
|
||||
$plan = $service->preview($editor, $id);
|
||||
$second = $service->publish($editor, $id, [...$publication, 'version' => 2, 'hash' => $plan['hash']]);
|
||||
$this->assertNotSame($first, $second);
|
||||
$service->saveInterest($person, $id, $second, true);
|
||||
$this->assertSame($first, DB::table('funding_programme_interests')->where('user_id', $person->id)->value('version_id'));
|
||||
$service->removeInterest(User::factory()->create(), $id);
|
||||
$this->assertNull(DB::table('funding_programme_interests')->where('user_id', $person->id)->value('removed_at'));
|
||||
$result = $service->assess($id, ['version_id' => $second, 'applicant_kind' => 'unknown', 'answers' => ['registration' => 'yes']]);
|
||||
$this->assertSame('unknown', $result['criteria'][0]['status']);
|
||||
$result = $service->assess($id, ['version_id' => $second, 'applicant_kind' => 'individual', 'answers' => []]);
|
||||
$this->assertSame('not_applicable', $result['criteria'][0]['status']);
|
||||
$service->withdraw($editor, $id, 2, 'Retirada sintética para verificar conservação privada.');
|
||||
$this->actingAs($person)->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page
|
||||
->has('items.data', 1)->where('items.data.0.available', false)->where('items.data.0.saved_version', 1));
|
||||
$this->get('/fundos/'.$id)->assertNotFound();
|
||||
$this->delete('/fundos/'.$id.'/interesse')->assertRedirect();
|
||||
$this->get('/fundos/guardados')->assertOk()->assertInertia(fn ($page) => $page->has('items.data', 0));
|
||||
}
|
||||
|
||||
public function test_example_content_cannot_be_published_as_an_actual_programme(): void
|
||||
{
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$draft = [...$this->draft(), 'source_status' => 'example'];
|
||||
$id = $service->save($editor, null, ['version' => 0, 'code' => 'synthetic-example', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
|
||||
$this->expectException(ValidationException::class);
|
||||
$service->preview($editor, $id);
|
||||
}
|
||||
|
||||
public function test_editor_routes_enforce_authority_preview_and_stale_versions_independently_of_procurement(): void
|
||||
{
|
||||
$this->withoutVite();
|
||||
$editor = User::factory()->create();
|
||||
$outsider = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email], 'procurement.enabled' => false]);
|
||||
$this->actingAs($outsider)->get('/management/fundos')->assertForbidden();
|
||||
$this->post('/management/fundos', [])->assertForbidden();
|
||||
$this->actingAs($editor)->get('/management/fundos/novo')->assertOk();
|
||||
$input = ['version' => 0, 'code' => 'synthetic-http-editor', 'reason' => 'Preparação sintética de ensaio editorial.', 'draft' => $this->draft()];
|
||||
$this->post('/management/fundos', $input)->assertRedirect();
|
||||
$id = DB::table('funding_programmes')->where('code', $input['code'])->value('id');
|
||||
$this->get('/management/fundos/'.$id)->assertOk();
|
||||
$this->get('/management/fundos')->assertOk();
|
||||
$plan = $this->postJson('/management/fundos/'.$id.'/previa')->assertOk()->json();
|
||||
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética de ensaio editorial.', 'confirm' => true];
|
||||
$this->post('/management/fundos/'.$id.'/publicar', [...$publication, 'hash' => str_repeat('0', 64)])->assertConflict();
|
||||
$this->post('/management/fundos/'.$id.'/publicar', $publication)->assertRedirect();
|
||||
$this->put('/management/fundos/'.$id, $input)->assertConflict();
|
||||
$this->actingAs($outsider)->post('/management/fundos/'.$id.'/retirar', ['version' => 1, 'reason' => $input['reason']])->assertForbidden();
|
||||
$this->postJson('/management/fundos/'.$id.'/previa')->assertForbidden();
|
||||
$this->get('/management/fundos/'.$id)->assertForbidden();
|
||||
$this->assertSame(1, DB::table('funding_programme_versions')->count());
|
||||
}
|
||||
|
||||
public function test_changed_master_reference_invalidates_preview_and_publishes_a_distinct_snapshot_without_overwriting_history(): void
|
||||
{
|
||||
$editor = User::factory()->create();
|
||||
config(['portal.managers' => [$editor->email]]);
|
||||
$organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $organization, 'name' => 'SINTÉTICO QA — Gestor original', 'organization_type' => 'private']);
|
||||
$service = app(FundingProgrammes::class);
|
||||
$draft = [...$this->draft(), 'manager_organization_id' => $organization];
|
||||
$id = $service->save($editor, null, ['version' => 0, 'code' => 'synthetic-master-change', 'reason' => 'Preparação sintética isolada para ensaio.', 'draft' => $draft]);
|
||||
$plan = $service->preview($editor, $id);
|
||||
$publication = ['version' => 1, 'hash' => $plan['hash'], 'reason' => 'Publicação sintética isolada para ensaio.', 'confirm' => true];
|
||||
$first = $service->publish($editor, $id, $publication);
|
||||
DB::table('organizations')->where('id', $organization)->update(['name' => 'SINTÉTICO QA — Gestor actualizado']);
|
||||
$newPlan = $service->preview($editor, $id);
|
||||
$this->assertNotSame($plan['hash'], $newPlan['hash']);
|
||||
$this->assertSame('SINTÉTICO QA — Gestor original', $service->published($id)['payload']['manager_name']);
|
||||
$second = $service->publish($editor, $id, [...$publication, 'hash' => $newPlan['hash']]);
|
||||
$this->assertNotSame($first, $second);
|
||||
$this->assertSame(2, $service->published($id)['version']);
|
||||
$this->assertSame('SINTÉTICO QA — Gestor original', json_decode(DB::table('funding_programme_versions')->where('id', $first)->value('payload'), true)['manager_name']);
|
||||
$this->assertSame(2, DB::table('funding_programme_versions')->count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\FundingProgrammes;
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use App\Services\InvestmentWorkspace;
|
||||
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;
|
||||
|
||||
final class InvestmentFundingAlertsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private User $editor;
|
||||
|
||||
private Sector $sector;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->actor = User::factory()->create();
|
||||
$this->editor = User::factory()->create();
|
||||
config(['portal.managers' => [$this->editor->email]]);
|
||||
$this->sector = Sector::create(['name' => 'SYNTHETIC funding sector', 'slug' => 'synthetic-funding-sector', 'is_active' => true, 'published_at' => now()]);
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function preferences(array $sources = ['funding'], array $criteria = [], int $version = 0): array
|
||||
{
|
||||
return ['version' => $version, 'enabled' => true, 'frequency' => 'as_available', 'channel' => 'in_app', 'consent' => true, 'sources' => $sources, 'criteria' => $criteria];
|
||||
}
|
||||
|
||||
private function draft(array $patch = []): array
|
||||
{
|
||||
return [...['title' => 'SYNTHETIC funding QA', 'kind' => 'fund', 'summary' => 'SYNTHETIC QA only, not a real financing offer.',
|
||||
'manager_name' => 'Synthetic manager', 'source_url' => 'https://example.invalid/funding', 'source_reference' => 'Synthetic edition QA',
|
||||
'source_checked_on' => today()->toDateString(), 'source_status' => 'identified', 'coverage' => 'national', 'sectors_scope' => 'selected',
|
||||
'sector_ids' => [$this->sector->id], 'criteria' => [], 'windows' => []], ...$patch];
|
||||
}
|
||||
|
||||
private function publish(array $draft = [], ?string $id = null): array
|
||||
{
|
||||
$service = app(FundingProgrammes::class);
|
||||
$row = $id ? DB::table('funding_programmes')->where('id', $id)->firstOrFail() : null;
|
||||
$id = $service->save($this->editor, $id, ['code' => $row->code ?? 'synthetic-'.Str::uuid(), 'version' => $row->version ?? 0,
|
||||
'reason' => 'Synthetic preparation for isolated funding alert QA.', 'draft' => $this->draft($draft)]);
|
||||
$plan = $service->preview($this->editor, $id);
|
||||
$version = $service->publish($this->editor, $id, ['version' => $plan['version'], 'hash' => $plan['hash'], 'reason' => 'Synthetic publication for isolated funding alert QA.', 'confirm' => true]);
|
||||
|
||||
return ['id' => $id, 'version_id' => $version];
|
||||
}
|
||||
|
||||
private function opportunity(): void
|
||||
{
|
||||
Opportunity::create(['sector_id' => $this->sector->id, 'title' => 'SYNTHETIC opportunity QA', 'slug' => 'qa-'.Str::uuid(), 'reference' => 'QA-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subMinute()]);
|
||||
}
|
||||
|
||||
public function test_opt_in_baselines_existing_publications_and_matches_only_selected_public_scope(): void
|
||||
{
|
||||
$this->publish();
|
||||
$criteria = ['sector' => $this->sector->slug, 'funding_certainty' => 'documented', 'category' => 'irrelevant', 'tender_regime' => 'irrelevant'];
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: $criteria))->assertOk()
|
||||
->assertJsonMissingPath('criteria.category')->assertJsonMissingPath('criteria.tender_regime');
|
||||
$match = $this->publish(['title' => 'SYNTHETIC matching publication']);
|
||||
$this->publish(['sectors_scope' => 'unknown', 'sector_ids' => []]);
|
||||
$this->opportunity();
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$notification = DB::table('investment_notifications')->sole();
|
||||
$this->assertSame($match['version_id'], $notification->funding_version_id);
|
||||
$this->assertNull($notification->opportunity_id);
|
||||
$this->assertNull($notification->tender_version_id);
|
||||
$payload = json_decode(Crypt::decryptString($notification->payload), true);
|
||||
$this->assertSame($match['id'], $payload['programme_id']);
|
||||
$this->assertArrayNotHasKey('criteria_answers', $payload);
|
||||
$this->assertArrayNotHasKey('documents', $payload);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('notifications.data.0.kind', 'funding_match');
|
||||
$this->assertDatabaseCount('funding_programme_interests', 0);
|
||||
}
|
||||
|
||||
public function test_all_three_sources_can_be_selected_explicitly_without_opt_in_by_migration(): void
|
||||
{
|
||||
config(['procurement.enabled' => true]);
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'tenders', 'funding']))->assertOk()
|
||||
->assertJsonPath('sources', ['funding', 'opportunities', 'tenders']);
|
||||
$this->assertDatabaseCount('investment_notifications', 0);
|
||||
$this->assertSame(['funding', 'opportunities', 'tenders'], json_decode(DB::table('investment_alert_preferences')->sole()->sources, true));
|
||||
}
|
||||
|
||||
public function test_window_state_filter_uses_documented_dates_without_treating_unknown_windows_as_open(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: ['funding_state' => 'open']))->assertOk();
|
||||
$this->publish();
|
||||
$window = ['code' => 'synthetic-window', 'title' => 'Synthetic dated window', 'mode' => 'dated', 'coverage' => 'programme',
|
||||
'source_url' => 'https://example.invalid/window', 'source_reference' => 'Synthetic window edition', 'checked_on' => today()->toDateString(), 'end_on' => today()->toDateString(), 'criteria' => []];
|
||||
$match = $this->publish(['windows' => [$window]]);
|
||||
$this->publish(['windows' => [[...$window, 'end_on' => today()->subDay()->toDateString()]]]);
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$notice = DB::table('investment_notifications')->sole();
|
||||
$this->assertSame($match['version_id'], $notice->funding_version_id);
|
||||
$this->assertSame('open', json_decode(Crypt::decryptString($notice->payload), true)['window_states'][0]['state']);
|
||||
}
|
||||
|
||||
public function test_unknown_scope_is_explicit_and_new_versions_preserve_old_notices_until_withdrawal(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(criteria: ['sector' => $this->sector->slug, 'funding_certainty' => 'include_unknown']))->assertOk();
|
||||
$first = $this->publish(['sectors_scope' => 'unknown', 'sector_ids' => []]);
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$old = DB::table('investment_notifications')->sole();
|
||||
$payload = json_decode(Crypt::decryptString($old->payload), true);
|
||||
$this->assertStringContainsString('por confirmar', $payload['scope_explanation']['sector']);
|
||||
$this->publish(['title' => 'SYNTHETIC changed title'], $first['id']);
|
||||
$this->travel(5)->minutes();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertSame($old->payload, DB::table('investment_notifications')->where('id', $old->id)->value('payload'));
|
||||
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertOk();
|
||||
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
|
||||
$this->actingAs($this->actor);
|
||||
app(FundingProgrammes::class)->withdraw($this->editor, $first['id'], 2, 'Synthetic withdrawal for historical notice QA.');
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data');
|
||||
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
}
|
||||
|
||||
public function test_funding_unavailability_does_not_block_other_sources_or_cancellation(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'funding']))->assertOk();
|
||||
Schema::rename('investment_funding_alert_seen', 'investment_funding_alert_seen_unavailable_qa');
|
||||
$this->opportunity();
|
||||
$this->publish();
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.source_statuses.funding', false);
|
||||
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false, 'criteria' => ['funding_state' => 'retired']])->assertOk()->assertJsonPath('enabled', false);
|
||||
Schema::rename('investment_funding_alert_seen_unavailable_qa', 'investment_funding_alert_seen');
|
||||
}
|
||||
|
||||
public function test_batch_is_bounded_per_source_and_funding_failure_rolls_back_all_deliveries(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities', 'funding']))->assertOk();
|
||||
$sample = $this->publish();
|
||||
$payload = DB::table('funding_programme_versions')->where('id', $sample['version_id'])->value('payload');
|
||||
for ($index = 0; $index < 200; $index++) {
|
||||
$id = (string) Str::uuid();
|
||||
$version = (string) Str::uuid();
|
||||
DB::table('funding_programmes')->insert(['id' => $id, 'code' => 'batch-'.$index, 'draft' => $payload, 'created_by' => $this->editor->id]);
|
||||
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => 1, 'payload' => $payload, 'reason' => 'Synthetic batch fixture only', 'actor_id' => $this->editor->id]);
|
||||
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version]);
|
||||
}
|
||||
$this->opportunity();
|
||||
$mock = \Mockery::mock(InvestmentWorkspace::class)->makePartial();
|
||||
$mock->shouldReceive('notifyFunding')->andThrow(new \RuntimeException('Synthetic delivery failure'));
|
||||
$this->app->instance(InvestmentWorkspace::class, $mock);
|
||||
try {
|
||||
app(InvestmentOpportunityAlerts::class)->dispatchDue();
|
||||
$this->fail('Delivery failure must escape and roll back.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('Synthetic delivery failure', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('investment_notifications', 0);
|
||||
$this->assertDatabaseCount('investment_funding_alert_seen', 0);
|
||||
$this->assertDatabaseCount('investment_alert_seen', 0);
|
||||
$this->app->instance(InvestmentWorkspace::class, new InvestmentWorkspace);
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(201, $alerts->dispatchDue());
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->assertDatabaseCount('investment_notifications', 202);
|
||||
}
|
||||
|
||||
public function test_upgrade_preserves_preferences_and_rollback_refuses_funding_history(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(['opportunities']))->assertOk();
|
||||
$before = (array) DB::table('investment_alert_preferences')->sole();
|
||||
$migration = require database_path('migrations/2026_11_02_220000_investment_funding_alerts.php');
|
||||
$migration->down();
|
||||
$migration->up();
|
||||
$this->assertSame($before, (array) DB::table('investment_alert_preferences')->sole());
|
||||
$this->assertSame(['opportunities'], app(InvestmentOpportunityAlerts::class)->preferences($this->actor->id)['sources']);
|
||||
$this->putJson('/investidor/alert-preferences', $this->preferences(['funding'], version: 1))->assertOk();
|
||||
$this->publish();
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('Preserve funding');
|
||||
$migration->down();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InvestmentSubmission;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use App\Services\InvestmentWorkspace;
|
||||
use Database\Seeders\TerritoryReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestmentOpportunityAlertsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private Sector $sector;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->actor = User::factory()->create();
|
||||
$this->sector = Sector::create(['name' => 'Synthetic alert sector', 'slug' => 'synthetic-alert-sector', 'is_active' => true, 'published_at' => now()]);
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function input(array $criteria = [], string $frequency = 'as_available', int $version = 0): array
|
||||
{
|
||||
return ['version' => $version, 'enabled' => true, 'channel' => 'in_app', 'frequency' => $frequency, 'consent' => true, 'criteria' => $criteria];
|
||||
}
|
||||
|
||||
private function opportunity(array $attributes = []): Opportunity
|
||||
{
|
||||
$record = new Opportunity;
|
||||
$record->forceFill([...['sector_id' => $this->sector->id, 'title' => 'Synthetic public alert opportunity', 'slug' => 'synthetic-'.Str::uuid(),
|
||||
'reference' => 'SYNTHETIC-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subDay(), 'opportunity_category' => 'investment_project'], ...$attributes])->save();
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
public function test_opt_in_is_private_validated_versioned_and_idempotent_and_cancellation_does_not_need_retired_choices(): void
|
||||
{
|
||||
$url = '/investidor/alert-preferences';
|
||||
Sector::create(['name' => 'Synthetic unpublished private sector', 'slug' => 'synthetic-unpublished', 'is_active' => true]);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.enabled', false)->assertJsonPath('alertPreferences.version', 0);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertDontSee('Synthetic unpublished private sector');
|
||||
$this->putJson($url, $this->input(['sector' => 'synthetic-unpublished']))->assertUnprocessable();
|
||||
$this->putJson($url, [...$this->input(), 'consent' => false])->assertUnprocessable()->assertJsonValidationErrors('consent');
|
||||
$this->putJson($url, [...$this->input(), 'channel' => 'email'])->assertUnprocessable()->assertJsonValidationErrors('channel');
|
||||
$this->putJson($url, $this->input(['sector' => 'unknown']))->assertUnprocessable();
|
||||
$this->putJson($url, $this->input(['province_id' => (string) Str::uuid()]))->assertUnprocessable();
|
||||
$input = $this->input(['sector' => $this->sector->slug]);
|
||||
$this->putJson($url, $input)->assertOk()->assertJsonPath('version', 1)->assertJsonPath('enabled', true);
|
||||
$this->putJson($url, $input)->assertOk()->assertJsonPath('version', 1);
|
||||
$this->assertDatabaseCount('investment_alert_preferences', 1);
|
||||
$this->assertDatabaseCount('audit_events', 1);
|
||||
$this->putJson($url, $this->input([], 'weekly', 0))->assertConflict();
|
||||
$raw = DB::table('investment_alert_preferences')->value('criteria');
|
||||
$this->assertStringNotContainsString($this->sector->slug, $raw);
|
||||
$this->sector->update(['is_active' => false]);
|
||||
$this->putJson($url, ['version' => 1, 'enabled' => false, 'frequency' => 'retired-choice', 'channel' => 'retired-channel',
|
||||
'criteria' => ['sector' => 'retired-sector', 'category' => 'retired-category']])->assertOk()->assertJsonPath('version', 2)
|
||||
->assertJsonPath('enabled', false)->assertJsonPath('frequency', 'as_available')->assertJsonPath('channel', 'in_app')
|
||||
->assertJsonPath('criteria.sector', $this->sector->slug);
|
||||
$this->actingAs(User::factory()->create())->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.version', 0);
|
||||
$this->actingAs(User::factory()->unverified()->create())->putJson($url, $this->input())->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_matching_reuses_catalogue_geography_and_excludes_old_private_future_and_incompatible_records(): void
|
||||
{
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->first();
|
||||
$district = DB::table('geo_locations')->where('parent_id', $province->id)->where('location_type', 'district')->first();
|
||||
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('id', '<>', $province->id)->first();
|
||||
$old = $this->opportunity(['primary_territory_id' => $district->id]);
|
||||
$input = $this->input(['sector' => $this->sector->slug, 'province_id' => $province->id, 'category' => 'investment_project']);
|
||||
$this->putJson('/investidor/alert-preferences', $input)->assertOk();
|
||||
$match = $this->opportunity(['primary_territory_id' => $district->id]);
|
||||
$other = Sector::create(['name' => 'Other synthetic sector', 'slug' => 'other-synthetic', 'is_active' => true]);
|
||||
$this->opportunity(['sector_id' => $other->id, 'primary_territory_id' => $district->id]);
|
||||
$this->opportunity(['primary_territory_id' => $otherProvince->id]);
|
||||
$this->opportunity(['primary_territory_id' => $district->id, 'opportunity_category' => 'financing']);
|
||||
$this->opportunity(['primary_territory_id' => $district->id, 'status' => 'draft']);
|
||||
$future = $this->opportunity(['primary_territory_id' => $district->id, 'published_at' => now()->addDay()]);
|
||||
$this->opportunity(['primary_territory_id' => $district->id, 'owner_user_id' => $this->actor->id, 'workflow_context' => ['publication' => ['visibility' => 'private']]]);
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$notification = DB::table('investment_notifications')->sole();
|
||||
$this->assertSame($match->id, $notification->opportunity_id);
|
||||
$this->assertNull($notification->submission_id);
|
||||
$payload = json_decode(Crypt::decryptString($notification->payload), true);
|
||||
$this->assertSame(1, $payload['preference_version']);
|
||||
$this->assertSame($input['criteria']['province_id'], $payload['criteria']['province_id']);
|
||||
$this->assertArrayNotHasKey('workflow_context', $payload);
|
||||
$this->assertNotSame($old->id, $notification->opportunity_id);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('unread', 1)->assertJsonPath('notifications.data.0.payload.title', $match->title);
|
||||
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
|
||||
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
|
||||
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
|
||||
$this->actingAs($this->actor);
|
||||
$match->update(['status' => 'draft']);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data')->assertJsonPath('unread', 0);
|
||||
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
|
||||
$this->assertDatabaseCount('investment_notifications', 1);
|
||||
$this->travel(25)->hours();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $future->id]);
|
||||
}
|
||||
|
||||
public function test_frequency_cancellation_and_reactivation_preserve_history_without_backlog_or_duplicates(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input([], 'daily'))->assertOk();
|
||||
$first = $this->opportunity();
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->travel(24)->hours();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$second = $this->opportunity();
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk();
|
||||
$this->travel(8)->days();
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->putJson('/investidor/alert-preferences', $this->input([], 'weekly', 2))->assertOk();
|
||||
$third = $this->opportunity();
|
||||
$this->travel(6)->days();
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->travel(1)->days();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $first->id]);
|
||||
$this->assertDatabaseMissing('investment_notifications', ['opportunity_id' => $second->id]);
|
||||
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $third->id]);
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
}
|
||||
|
||||
public function test_failed_delivery_rolls_back_seen_marker_and_next_run_and_can_be_retried(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
|
||||
$record = $this->opportunity();
|
||||
$before = DB::table('investment_alert_preferences')->value('next_run_at');
|
||||
$workspace = \Mockery::mock(InvestmentWorkspace::class);
|
||||
$workspace->shouldReceive('notifyOpportunity')->once()->andThrow(new \RuntimeException('Synthetic delivery failure'));
|
||||
$this->app->instance(InvestmentWorkspace::class, $workspace);
|
||||
try {
|
||||
app(InvestmentOpportunityAlerts::class)->dispatchDue();
|
||||
$this->fail('Delivery failure must propagate without consuming the opportunity.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('Synthetic delivery failure', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseMissing('investment_alert_seen', ['opportunity_id' => $record->id]);
|
||||
$this->assertDatabaseCount('investment_notifications', 0);
|
||||
$this->assertSame($before, DB::table('investment_alert_preferences')->value('next_run_at'));
|
||||
$this->app->forgetInstance(InvestmentWorkspace::class);
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->artisan('investmoz:dispatch-opportunity-alerts')->assertSuccessful();
|
||||
$this->assertDatabaseCount('investment_notifications', 1);
|
||||
}
|
||||
|
||||
public function test_a_retired_reference_does_not_block_other_subscribers_or_prevent_cancellation(): void
|
||||
{
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->value('id');
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['province_id' => $province]))->assertOk();
|
||||
$other = User::factory()->create();
|
||||
$this->actingAs($other)->putJson('/investidor/alert-preferences', $this->input())->assertOk();
|
||||
$record = $this->opportunity();
|
||||
DB::table('geo_locations')->where('id', $province)->update(['data_classification' => 'internal']);
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->assertDatabaseHas('investment_notifications', ['user_id' => $other->id, 'opportunity_id' => $record->id]);
|
||||
$this->assertDatabaseMissing('investment_notifications', ['user_id' => $this->actor->id]);
|
||||
$this->actingAs($this->actor)->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.criteria_available', false)
|
||||
->assertJsonPath('alertPreferences.criteria.province_id', $province);
|
||||
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk()->assertJsonPath('enabled', false);
|
||||
}
|
||||
|
||||
public function test_a_batch_larger_than_one_run_is_drained_without_losing_or_repeating_notifications(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
|
||||
for ($index = 0; $index < 201; $index++) {
|
||||
$this->opportunity();
|
||||
}
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(200, $alerts->dispatchDue());
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->assertDatabaseCount('investment_notifications', 201);
|
||||
$this->assertDatabaseCount('investment_alert_seen', 201);
|
||||
}
|
||||
|
||||
public function test_upgrade_preserves_legacy_notifications_and_rollback_refuses_to_destroy_preferences(): void
|
||||
{
|
||||
$submission = $this->postJson('/api/v1/investment/submissions')->assertCreated()->json('id');
|
||||
app(InvestmentWorkspace::class)->notify($this->actor->id, InvestmentSubmission::findOrFail($submission), 'status', 'synthetic-upgrade', ['status' => 'draft']);
|
||||
$original = (array) DB::table('investment_notifications')->sole();
|
||||
$migration = require database_path('migrations/2026_11_02_190000_investment_opportunity_alerts.php');
|
||||
$tenderMigration = require database_path('migrations/2026_11_02_200000_investment_tender_alerts.php');
|
||||
$fundingMigration = require database_path('migrations/2026_11_02_220000_investment_funding_alerts.php');
|
||||
$fundingMigration->down();
|
||||
$tenderMigration->down();
|
||||
$migration->down();
|
||||
$this->assertFalse(app(InvestmentOpportunityAlerts::class)->installed());
|
||||
$migration->up();
|
||||
$tenderMigration->up();
|
||||
$fundingMigration->up();
|
||||
$this->assertSame($original, (array) DB::table('investment_notifications')->sole());
|
||||
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Preferences and notification history must be preserved before rollback.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertStringContainsString('Preserve alert preferences', $error->getMessage());
|
||||
}
|
||||
$this->assertTrue(app(InvestmentOpportunityAlerts::class)->installed());
|
||||
$this->assertDatabaseCount('investment_notifications', 1);
|
||||
$this->assertDatabaseCount('investment_alert_preferences', 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use App\Models\User;
|
||||
use App\Services\InvestmentOpportunityAlerts;
|
||||
use App\Services\InvestmentWorkspace;
|
||||
use App\Services\Procurement;
|
||||
use Database\Seeders\TerritoryReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class InvestmentTenderAlertsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private User $actor;
|
||||
|
||||
private User $editor;
|
||||
|
||||
private Sector $sector;
|
||||
|
||||
private string $organization;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->actor = User::factory()->create();
|
||||
$this->editor = User::factory()->create();
|
||||
config(['procurement.enabled' => true, 'portal.managers' => [$this->editor->email]]);
|
||||
$this->sector = Sector::create(['name' => 'Synthetic tender sector', 'slug' => 'synthetic-tender', 'is_active' => true, 'published_at' => now()]);
|
||||
$this->organization = (string) Str::uuid();
|
||||
DB::table('organizations')->insert(['id' => $this->organization, 'name' => 'SINTÉTICO QA — Entidade de ensaio', 'organization_type' => 'private']);
|
||||
$this->actingAs($this->actor);
|
||||
}
|
||||
|
||||
private function input(array $sources = ['tenders'], array $criteria = [], int $version = 0): array
|
||||
{
|
||||
return ['version' => $version, 'enabled' => true, 'frequency' => 'as_available', 'channel' => 'in_app', 'consent' => true, 'sources' => $sources, 'criteria' => $criteria];
|
||||
}
|
||||
|
||||
private function payload(array $overrides = []): array
|
||||
{
|
||||
return [...['title' => 'SINTÉTICO QA — Concurso de ensaio', 'reference' => 'QA-'.Str::uuid(), 'organization_id' => $this->organization,
|
||||
'sector_id' => $this->sector->id, 'regime' => 'private', 'modality' => 'Modalidade documentada de ensaio',
|
||||
'object' => 'Objecto sintético de ensaio; sem contratação real.', 'instrument' => 'Regras sintéticas documentadas', 'edition' => 'QA-2026',
|
||||
'rule_source' => 'https://example.invalid/synthetic-rules', 'origin_published_at' => now()->subDay()->format('Y-m-d\TH:i'),
|
||||
'deadline' => now()->addMonth()->format('Y-m-d\TH:i'), 'timezone' => 'Africa/Maputo', 'delivery_channel' => 'Canal externo documentado de ensaio',
|
||||
'public_reason' => 'Publicação sintética de ensaio, sem contratação ou proposta real.',
|
||||
'internal_notes' => 'SECRET-SYNTHETIC-DRAFT', 'public_contact' => 'synthetic-private@example.invalid', 'contact_authorized' => false,
|
||||
'attachments' => [], 'lots' => []], ...$overrides];
|
||||
}
|
||||
|
||||
/** @return array{id:string,version_id:string,payload:array} */
|
||||
private function publish(array $payload = [], ?string $id = null, string $act = 'initial'): array
|
||||
{
|
||||
$service = app(Procurement::class);
|
||||
$payload = $payload ?: $this->payload();
|
||||
$id = $service->save($this->editor, $id, ['version' => $id ? DB::table('portal_tenders')->where('id', $id)->value('version') : 0,
|
||||
'reason' => 'Preparação sintética documentada para ensaio QA.', 'draft' => $payload]);
|
||||
$plan = $service->preview($this->editor, $id, $act);
|
||||
$service->publish($this->editor, $id, ['act' => $act, 'hash' => $plan['hash'], 'reason' => $plan['payload']['public_reason']]);
|
||||
|
||||
return ['id' => $id, 'version_id' => DB::table('portal_tenders')->where('id', $id)->value('published_version_id'), 'payload' => $payload];
|
||||
}
|
||||
|
||||
private function opportunity(): Opportunity
|
||||
{
|
||||
return Opportunity::create(['sector_id' => $this->sector->id, 'title' => 'Synthetic opportunity', 'slug' => 'synthetic-'.Str::uuid(),
|
||||
'reference' => 'SYNTHETIC-'.Str::uuid(), 'status' => 'published', 'published_at' => now()]);
|
||||
}
|
||||
|
||||
public function test_new_tenders_match_public_sector_province_and_regime_without_drafts_or_private_data(): void
|
||||
{
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
|
||||
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
|
||||
$otherProvince = DB::table('geo_locations')->where('location_type', 'province')->where('id', '<>', $province)->value('id');
|
||||
$this->publish($this->payload(['territory_id' => $district]));
|
||||
$criteria = ['sector' => $this->sector->slug, 'province_id' => $province, 'tender_regime' => 'private', 'category' => 'not-applicable-to-tenders'];
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], $criteria))->assertOk()->assertJsonPath('sources', ['tenders'])->assertJsonMissingPath('criteria.category');
|
||||
$match = $this->publish($this->payload(['territory_id' => $district]));
|
||||
$this->publish($this->payload(['territory_id' => $otherProvince]));
|
||||
$this->publish($this->payload(['territory_id' => $district, 'regime' => 'external']));
|
||||
$otherSector = Sector::create(['name' => 'Other synthetic sector', 'slug' => 'other-synthetic-tender', 'is_active' => true]);
|
||||
$this->publish($this->payload(['territory_id' => $district, 'sector_id' => $otherSector->id]));
|
||||
app(Procurement::class)->save($this->editor, null, ['version' => 0, 'reason' => 'Rascunho sintético sem publicação de ensaio.', 'draft' => $this->payload(['territory_id' => $district])]);
|
||||
$this->opportunity();
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$notification = DB::table('investment_notifications')->sole();
|
||||
$this->assertSame($match['version_id'], $notification->tender_version_id);
|
||||
$this->assertNull($notification->submission_id);
|
||||
$this->assertNull($notification->opportunity_id);
|
||||
$payload = json_decode(Crypt::decryptString($notification->payload), true);
|
||||
$this->assertSame($match['id'], $payload['tender_id']);
|
||||
$this->assertSame('initial', $payload['act']);
|
||||
$this->assertSame(1, $payload['preference_version']);
|
||||
$this->assertArrayNotHasKey('internal_notes', $payload);
|
||||
$this->assertArrayNotHasKey('public_contact', $payload);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('notifications.data.0.kind', 'tender_match')->assertDontSee('SECRET-SYNTHETIC-DRAFT');
|
||||
$this->postJson('/investidor/notifications/'.$notification->id.'/read')->assertOk();
|
||||
$this->actingAs(User::factory()->create())->postJson('/investidor/notifications/'.$notification->id.'/read')->assertNotFound();
|
||||
$this->assertDatabaseCount('portal_tender_watches', 0);
|
||||
}
|
||||
|
||||
public function test_new_published_acts_preserve_old_alerts_and_draft_edits_do_not_generate_alerts(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input())->assertOk();
|
||||
$initial = $this->publish($this->payload());
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$old = DB::table('investment_notifications')->sole();
|
||||
$changed = $initial['payload'];
|
||||
$changed['deadline'] = now()->addMonths(2)->format('Y-m-d\TH:i');
|
||||
$service = app(Procurement::class);
|
||||
$service->save($this->editor, $initial['id'], ['version' => 2, 'reason' => 'Alteração sintética de prazo ainda em preparação.', 'draft' => $changed]);
|
||||
$this->travel(5)->minutes();
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$plan = $service->preview($this->editor, $initial['id'], 'extension');
|
||||
$service->publish($this->editor, $initial['id'], ['act' => 'extension', 'hash' => $plan['hash'], 'reason' => $plan['payload']['public_reason']]);
|
||||
$this->travel(5)->minutes();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(2, 'notifications.data');
|
||||
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertOk();
|
||||
$this->assertSame($old->payload, DB::table('investment_notifications')->where('id', $old->id)->value('payload'));
|
||||
DB::table('portal_tenders')->where('id', $initial['id'])->update(['published_version_id' => null]);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonCount(0, 'notifications.data');
|
||||
$this->postJson('/investidor/notifications/'.$old->id.'/read')->assertNotFound();
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
}
|
||||
|
||||
public function test_temporary_unavailability_only_pauses_tenders_and_cancellation_never_depends_on_that_catalogue(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
|
||||
$this->publish();
|
||||
$opportunity = $this->opportunity();
|
||||
config(['procurement.enabled' => false]);
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
$this->assertDatabaseHas('investment_notifications', ['opportunity_id' => $opportunity->id]);
|
||||
$this->getJson('/investidor/notifications')->assertOk()->assertJsonPath('alertPreferences.source_statuses.opportunities', true)
|
||||
->assertJsonPath('alertPreferences.source_statuses.tenders', false);
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], [], 1))->assertUnprocessable()->assertJsonValidationErrors('sources');
|
||||
config(['procurement.enabled' => true]);
|
||||
$this->travel(5)->minutes();
|
||||
$this->assertSame(1, $alerts->dispatchDue());
|
||||
config(['procurement.enabled' => false]);
|
||||
$this->putJson('/investidor/alert-preferences', ['version' => 1, 'enabled' => false])->assertOk()->assertJsonPath('enabled', false);
|
||||
$this->travel(8)->days();
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
}
|
||||
|
||||
public function test_delivery_failure_rolls_back_both_sources_and_retry_delivers_each_once(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
|
||||
$this->opportunity();
|
||||
$this->publish();
|
||||
$before = DB::table('investment_alert_preferences')->value('next_run_at');
|
||||
$workspace = \Mockery::mock(InvestmentWorkspace::class)->makePartial();
|
||||
$workspace->shouldReceive('notifyTender')->once()->andThrow(new \RuntimeException('Synthetic tender delivery failure'));
|
||||
$this->app->instance(InvestmentWorkspace::class, $workspace);
|
||||
try {
|
||||
app(InvestmentOpportunityAlerts::class)->dispatchDue();
|
||||
$this->fail('The shared delivery transaction must fail atomically.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertSame('Synthetic tender delivery failure', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('investment_notifications', 0);
|
||||
$this->assertDatabaseCount('investment_alert_seen', 0);
|
||||
$this->assertDatabaseCount('investment_tender_alert_seen', 0);
|
||||
$this->assertSame($before, DB::table('investment_alert_preferences')->value('next_run_at'));
|
||||
$this->app->forgetInstance(InvestmentWorkspace::class);
|
||||
$this->assertSame(2, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->assertDatabaseCount('investment_notifications', 2);
|
||||
}
|
||||
|
||||
public function test_source_selection_is_explicit_and_migration_preserves_existing_preferences_and_history(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities']))->assertOk();
|
||||
$before = (array) DB::table('investment_alert_preferences')->sole();
|
||||
$migration = require database_path('migrations/2026_11_02_200000_investment_tender_alerts.php');
|
||||
$migration->down();
|
||||
$this->assertFalse(app(InvestmentOpportunityAlerts::class)->tendersInstalled());
|
||||
$migration->up();
|
||||
$this->assertSame($before, (array) DB::table('investment_alert_preferences')->sole());
|
||||
$this->publish();
|
||||
$this->assertSame(0, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['tenders'], [], 1))->assertOk();
|
||||
$this->publish();
|
||||
$this->travel(5)->minutes();
|
||||
$this->assertSame(1, app(InvestmentOpportunityAlerts::class)->dispatchDue());
|
||||
try {
|
||||
$migration->down();
|
||||
$this->fail('Tender preferences and history must be preserved before rollback.');
|
||||
} catch (\RuntimeException $error) {
|
||||
$this->assertStringContainsString('Preserve tender alert preferences', $error->getMessage());
|
||||
}
|
||||
$this->assertDatabaseCount('investment_notifications', 1);
|
||||
}
|
||||
|
||||
public function test_opportunity_backlog_does_not_starve_tenders_or_lose_the_remaining_batch(): void
|
||||
{
|
||||
$this->putJson('/investidor/alert-preferences', $this->input(['opportunities', 'tenders']))->assertOk();
|
||||
for ($index = 0; $index < 201; $index++) {
|
||||
$this->opportunity();
|
||||
}
|
||||
$this->publish();
|
||||
$alerts = app(InvestmentOpportunityAlerts::class);
|
||||
$this->assertSame(201, $alerts->dispatchDue(), 'One tender is delivered alongside the bounded opportunity batch.');
|
||||
$this->assertDatabaseCount('investment_tender_alert_seen', 1);
|
||||
$this->assertSame(1, $alerts->dispatchDue(), 'The unconsumed opportunity remains due for the next run.');
|
||||
$this->assertSame(0, $alerts->dispatchDue());
|
||||
$this->assertDatabaseCount('investment_notifications', 202);
|
||||
$this->assertDatabaseCount('investment_alert_seen', 201);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Database\Seeders\TerritoryReferenceSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class QuickOpportunitySearchTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Sector $sector;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->withoutVite();
|
||||
$this->sector = Sector::create(['name' => 'Agronegócio sintético QA', 'slug' => 'agronegocio-synthetic', 'is_active' => true, 'published_at' => now()]);
|
||||
}
|
||||
|
||||
private function record(string $title, string $summary, array $attributes = []): Opportunity
|
||||
{
|
||||
return Opportunity::create([...['sector_id' => $this->sector->id, 'title' => $title, 'summary' => $summary,
|
||||
'reference' => 'SYNTHETIC-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(), 'status' => 'published', 'published_at' => now()->subMinute()], ...$attributes]);
|
||||
}
|
||||
|
||||
public function test_plantio_de_algodao_finds_cultivation_variants_without_relabelling_processing_and_combines_province_and_sector(): void
|
||||
{
|
||||
$this->seed(TerritoryReferenceSeeder::class);
|
||||
$province = DB::table('geo_locations')->where('location_type', 'province')->where('name', 'Nampula')->value('id');
|
||||
$district = DB::table('geo_locations')->where('parent_id', $province)->where('location_type', 'district')->value('id');
|
||||
$this->assertNotEmpty($district);
|
||||
$crop = $this->record('SINTÉTICO QA — exploração agrícola', 'Cultivo comercial de algodão, exemplo fictício para ensaio.', ['primary_territory_id' => $district]);
|
||||
$processing = $this->record('SINTÉTICO QA — unidade de transformação', 'Descaroçamento, fiação e produção de óleo de algodão.', ['primary_territory_id' => $district]);
|
||||
$this->record('SINTÉTICO QA — outra cultura', 'Cultivo de milho, sem relação com a pesquisa solicitada.');
|
||||
$this->record('SINTÉTICO QA — privado', 'Cultivo de algodão.', ['status' => 'draft']);
|
||||
$this->record('SINTÉTICO QA — futuro', 'Cultivo de algodão.', ['published_at' => now()->addDay()]);
|
||||
$deleted = $this->record('SINTÉTICO QA — eliminado', 'Cultivo de algodão.');
|
||||
$deleted->delete();
|
||||
$before = DB::table('opportunities')->orderBy('id')->get()->toJson();
|
||||
foreach (['plantio de algodao', 'PLANTIO DE ALGODÃO', 'algodao cultivo', 'plantação de algodão Nampula'] as $text) {
|
||||
foreach (['/api/v1/investment/search', '/api/v1/opportunities/search'] as $endpoint) {
|
||||
$this->getJson($endpoint.'?'.http_build_query(['q' => $text]))->assertOk()
|
||||
->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $crop->id);
|
||||
}
|
||||
}
|
||||
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'AGRONEGOCIO, NAMPULA']))->assertOk()->assertJsonPath('total', 2);
|
||||
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component('investment/catalogue')->where('filters.q', 'plantio de algodao')->where('results.total', 1)
|
||||
->where('results.data.0.id', $crop->id)->where('relatedSearch', null));
|
||||
$this->getJson('/api/v1/investment/map?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertJsonCount(1, 'unlocated');
|
||||
$csv = $this->get('/api/v1/investment/export?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->streamedContent();
|
||||
$this->assertStringContainsString($crop->title, $csv);
|
||||
$this->assertStringNotContainsString($processing->title, $csv);
|
||||
$this->assertSame($before, DB::table('opportunities')->orderBy('id')->get()->toJson());
|
||||
}
|
||||
|
||||
public function test_if_only_processing_exists_related_fiches_are_separate_and_never_widen_other_filters(): void
|
||||
{
|
||||
$processing = $this->record('SINTÉTICO QA — transformação de algodão', 'Descaroçamento e transformação de algodão.');
|
||||
$this->record('SINTÉTICO QA — privado', 'Descaroçamento de algodão.', ['status' => 'draft']);
|
||||
$this->record('SINTÉTICO QA — outra cadeia', 'Cultivo de milho.');
|
||||
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('results.total', 0)->where('relatedSearch.query', 'plantio de algodao')->where('relatedSearch.subject', 'algodao')
|
||||
->has('relatedSearch.items', 1)->where('relatedSearch.items.0.id', $processing->id)
|
||||
->where('relatedSearch.href', '/oportunidades?q=algodao'));
|
||||
$this->get('/oportunidades?'.http_build_query(['q' => 'plantio de algodao', 'category' => 'financing']))->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('results.total', 0)->has('relatedSearch.items', 0)->where('filters.category', 'financing')
|
||||
->where('relatedSearch.href', '/oportunidades?category=financing&q=algodao'));
|
||||
}
|
||||
|
||||
public function test_literal_wildcards_and_unmatched_words_do_not_return_unrelated_records(): void
|
||||
{
|
||||
$literal = $this->record('SINTÉTICO QA — 100% algodão', 'Referência sintética.', ['reference' => 'SYNTHETIC_REF_ABC']);
|
||||
$this->record('SINTÉTICO QA — 1000 algodão', 'Referência sintética.', ['reference' => 'SYNTHETICXREFXABC']);
|
||||
foreach (['100%', 'SYNTHETIC_REF_ABC'] as $query) {
|
||||
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => $query]))->assertOk()
|
||||
->assertJsonPath('total', 1)->assertJsonPath('data.0.id', $literal->id);
|
||||
}
|
||||
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'de e em']))->assertOk()->assertJsonPath('total', 0);
|
||||
$this->getJson('/api/v1/investment/search?'.http_build_query(['q' => 'palavra-inexistente-synthetic']))->assertOk()->assertJsonPath('total', 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user