Improve investor quick search with typed counts, product categories and licensing guidance

This commit is contained in:
2026-11-13 15:06:11 +02:00
parent f53a308327
commit d325b72fad
11 changed files with 508 additions and 21 deletions
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace Tests\Feature;
use App\Models\DevelopmentCorridor;
use App\Models\InvestmentDossier;
use App\Models\Project;
use App\Models\Sector;
use App\Models\User;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
final class GlobalSearchCountTest extends TestCase
{
use DatabaseTransactions;
public function test_licensing_question_opens_existing_guidance_without_mixing_catalogue_matches(): void
{
$this->withoutVite();
$this->get('/pesquisa?'.http_build_query(['q' => 'como licenciar uma empresa']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'guide')->where('results.total', 2)
->where('results.data.0.url', '/como-investir#planeamento')
->where('results.data.1.url', '/investimentos/iniciar?step=S08'));
}
public function test_physical_product_search_keeps_the_product_and_documented_location_in_its_link(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
config(['portal.legacy_content_enabled' => false, 'portal.legacy_content_qa_enabled' => false]);
$sector = Sector::firstOrCreate(['slug' => 'mineracao'], ['name' => 'Mineração']);
$sector->forceFill(['is_active' => true, 'published_at' => now()->subMinute()])->save();
$this->get('/pesquisa?'.http_build_query(['q' => 'onde encontrar grafite em Cabo Delgado']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
->where('results.data.0.title', 'Grafite')->where('results.data.0.category', 'Produtos e localizações')
->where('results.data.0.location', fn ($text) => str_contains($text, 'Cabo Delgado'))
->where('results.data.0.url', fn ($url) => str_contains($url, 'resource_group=') && str_contains($url, 'resource_location=Cabo+Delgado')));
$this->get('/pesquisa?'.http_build_query(['q' => 'grafite Cabo Delgado', 'category' => 'physical']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.category', 'physical')->where('results.total', 1)
->where('results.data.0.category', 'Produtos e localizações'));
$this->get('/pesquisa?category=invalid')->assertRedirect();
}
public function test_financial_product_search_excludes_drafts_and_future_publications_and_distinguishes_coverage(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
if (! Schema::hasTable('funding_programmes')) {
// Only this transaction in the isolated QA database; no active schema changes.
(require database_path('migrations/2026_11_02_210000_funding_programme_catalogue.php'))->up();
}
$actor = User::factory()->create();
$marker = 'SYNTHFIN'.Str::random(8);
foreach (['published', 'draft', 'future'] as $state) {
$id = (string) Str::uuid();
$version = (string) Str::uuid();
$payload = json_encode(['title' => $marker.' '.$state, 'kind' => 'institution', 'summary' => 'Nota de preparação: ficha e documento gerador.',
'institution_nature' => 'bank', 'institution_services' => ['investment'],
'locations' => [['location_text' => 'Nampula']], 'products' => [['title' => 'Crédito PME', 'coverage' => 'national', 'needs' => ['investment']]]], JSON_THROW_ON_ERROR);
DB::table('funding_programmes')->insert(['id' => $id, 'code' => $marker.$state, 'draft' => $payload, 'created_by' => $actor->id]);
DB::table('funding_programme_versions')->insert(['id' => $version, 'programme_id' => $id, 'version' => 1, 'payload' => $payload,
'reason' => 'Synthetic QA only', 'actor_id' => $actor->id, 'published_at' => $state === 'future' ? now()->addDay() : now()->subMinute()]);
if ($state !== 'draft') {
DB::table('funding_programmes')->where('id', $id)->update(['published_version_id' => $version]);
}
}
$this->get('/pesquisa?'.http_build_query(['q' => 'produtos financeiros '.$marker.' em Nampula']))->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.type', 'products')->where('results.total', 1)->where('results.unavailable', [])
->where('results.data.0.category', 'Produtos financeiros')->where('results.data.0.description', 'Crédito PME')
->where('results.data.0.location', 'Presença física: Nampula')
->where('results.data.0.coverage', fn ($text) => str_contains($text, 'nacional')));
}
public function test_corridor_count_excludes_other_types_drafts_and_deleted_entities(): void
{
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
$marker = 'SYNTHCOUNT'.Str::random(10);
foreach (range(1, 4) as $n) {
$corridor = DevelopmentCorridor::create(['code' => $marker.$n, 'name' => $marker.$n, 'status' => 'active', 'data_classification' => 'public']);
InvestmentDossier::create(['corridor_id' => $corridor->id, 'title' => $marker.' '.$n,
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => $n === 3 ? 'draft' : 'published',
'published_at' => now()->subMinute(), 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
if ($n === 4) {
$corridor->delete();
}
}
InvestmentDossier::create(['project_id' => Project::factory()->create()->id, 'title' => $marker.' corredor relacionado',
'content' => [], 'source' => 'Synthetic QA only', 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA only']);
$query = 'quantos corredores existem '.$marker;
$this->get('/pesquisa?'.http_build_query(['q' => $query]))->assertOk()->assertInertia(fn (Assert $page) => $page
->component('portal/search')->where('query', $query)->where('answer.count', 2)->where('answer.label', 'corredores')
->where('results.total', 2)->has('results.data', 2)->where('results.unavailable', []));
$this->get('/pesquisa?'.http_build_query(['q' => 'quantos corredores existem '.$marker.' inexistente']))
->assertOk()->assertInertia(fn (Assert $page) => $page->where('answer.count', 0)->where('results.total', 0));
$this->get('/pesquisa?q=quantos+corredores+existem')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('answer.label', 'corredores')->where('answer.count', fn ($count) => $count >= 2)
->where('results.unavailable', []));
}
}
+13
View File
@@ -7,6 +7,7 @@ use App\Services\FederatedSearch;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
final class GlobalSearchTest extends TestCase
@@ -35,6 +36,18 @@ final class GlobalSearchTest extends TestCase
$this->assertSame('Como investir', $result['data'][0]['title']);
}
public function test_unavailable_public_reference_does_not_hide_other_sources_or_swallow_forbidden_access(): void
{
$result = app(FederatedSearch::class)->page([
'Referências' => fn () => throw new HttpException(503),
'Páginas' => fn () => ['count' => 1, 'fetch' => fn () => [['title' => 'Como investir', 'url' => '/como-investir']]],
], 1);
$this->assertSame(1, $result['total']);
$this->assertSame(['Referências'], $result['unavailable']);
$this->expectException(HttpException::class);
app(FederatedSearch::class)->page(['Restrito' => fn () => throw new HttpException(403)], 1);
}
public function test_public_search_uses_the_existing_portfolio_visibility_scope(): void
{
if (getenv('GLOBAL_SEARCH_QA') !== '1') {
+27
View File
@@ -9,6 +9,33 @@ use PHPUnit\Framework\TestCase;
final class SearchTermsTest extends TestCase
{
public function test_count_questions_select_a_category_instead_of_searching_question_words(): void
{
$search = new SearchTerms;
$intent = $search->countIntent('Quantos corredores existem?');
$this->assertSame('corridor', $intent['kind']);
$this->assertSame('', $intent['filter']);
$this->assertSame('corredores', $intent['label']);
$this->assertSame('Oportunidades', $search->countIntent('Quantas oportunidades existem no portal?')['category']);
$this->assertSame('em nampula', $search->countIntent('Quantos corredores existem em Nampula?')['filter']);
$this->assertSame('cluster', $search->countIntent('Qual é o número de clusters disponíveis?')['kind']);
$this->assertNull($search->countIntent('oportunidades nos corredores'));
$this->assertNull($search->countIntent('documentos sobre quantos corredores existem'));
}
public function test_investor_requests_distinguish_products_guidance_and_lists(): void
{
$search = new SearchTerms;
$this->assertSame('guide', $search->requestIntent('como licenciar uma empresa')['type']);
$this->assertSame('guide', $search->requestIntent('como faço para licenciar a empresa em Nampula?')['type']);
$this->assertNull($search->requestIntent('como licenciar software'));
$this->assertSame('list', $search->requestIntent('quais são os corredores existentes')['type']);
$this->assertSame('Produtos financeiros', $search->requestIntent('produtos financeiros em Nampula')['category']);
$this->assertNull($search->requestIntent('tipo de produtos e sua localização')['category']);
$this->assertSame('', $search->requestIntent('tipo de produtos e sua localização')['filter']);
$this->assertSame('grafite em cabo delgado', $search->requestIntent('onde encontrar grafite em Cabo Delgado?')['filter']);
}
public function test_matches_all_words_in_any_order_without_case_or_accents(): void
{
$search = new SearchTerms;
+47
View File
@@ -35,6 +35,53 @@ new Function('require', 'module', 'exports', compiled)(
);
const Search = module.exports.default;
test('product categories preserve the location filter and pagination even without a query', () => {
const results = { data: [{ title: 'Grafite', description: '', category: 'Produtos e localizações', url: '/sectores/mineracao' }], total: 6, current_page: 1, last_page: 2, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'Nampula', results,
answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: 'Nampula', category: 'physical' },
}));
assert.match(html, /q=Nampula&amp;category=financial/);
assert.match(html, /q=Nampula&amp;page=2&amp;category=physical/);
assert.match(html, /name="category" value="physical"/);
const all = renderToStaticMarkup(React.createElement(Search, {
query: '', results, answer: { type: 'products', label: 'Produtos e localização', count: 6, filter: '', category: 'all' },
}));
assert.match(all, /href="\/sectores\/mineracao"/);
});
test('count answer is explicit and zero is distinct from an unavailable count', () => {
const results = { data: [], total: 0, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'quantos corredores existem', results,
answer: { type: 'count', label: 'corredores', count: 0, filter: '' },
}));
assert.match(html, /0 corredores/);
assert.match(html, /registos publicados/);
const failed = renderToStaticMarkup(React.createElement(Search, {
query: 'quantos corredores existem', results,
answer: { type: 'count', label: 'corredores', count: null, filter: '' },
}));
assert.match(failed, /Contagem indisponível/);
assert.doesNotMatch(failed, /0 corredores/);
});
test('products show their location separately from financial coverage and guidance has no invented count', () => {
const results = { data: [{ title: 'Banco de ensaio', description: 'Crédito PME', location: 'Presença física: Maputo', coverage: 'Cobertura nacional', category: 'Produtos financeiros', url: '/fundos/qa' }], total: 1, current_page: 1, last_page: 1, per_page: 5, unavailable: [] };
const html = renderToStaticMarkup(React.createElement(Search, {
query: 'produtos financeiros', results, answer: { type: 'products', label: 'Produtos e localização', count: 1, filter: '' },
}));
assert.match(html, /Produtos financeiros/);
assert.match(html, /Presença física: Maputo/);
assert.match(html, /Cobertura nacional/);
assert.match(html, /não determina a cobertura/);
const guide = renderToStaticMarkup(React.createElement(Search, {
query: 'como licenciar empresa', results: { ...results, data: [] }, answer: { type: 'guide', label: 'Licenciamento da empresa', count: 2, filter: 'licenciamento' },
}));
assert.match(guide, /Licenciamento da empresa/);
assert.doesNotMatch(guide, /2 Licenciamento/);
});
test('shows five results in one sequence with numbered pagination and the query preserved', () => {
const results = {
data: [