From e6888e790f7bf40d5ad8a36757a97c83c9619333 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 10:55:04 +0200 Subject: [PATCH] =?UTF-8?q?Carteira=204.3:=20ficha=20sem=20liga=C3=A7?= =?UTF-8?q?=C3=B5es=20mostra=20oportunidades=20da=20mesma=20prov=C3=ADncia?= =?UTF-8?q?=20e=20sector,=20indicadas=20como=20n=C3=A3o=20ligadas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM --- .../InvestmentPortfolioController.php | 6 +- app/Services/PortfolioNearbyOpportunities.php | 67 +++++++++++++++++++ resources/js/pages/portfolio/show.tsx | 46 ++++++++++++- .../PortfolioNearbyOpportunitiesTest.php | 50 ++++++++++++++ 4 files changed, 167 insertions(+), 2 deletions(-) create mode 100644 app/Services/PortfolioNearbyOpportunities.php create mode 100644 tests/Feature/PortfolioNearbyOpportunitiesTest.php diff --git a/app/Http/Controllers/InvestmentPortfolioController.php b/app/Http/Controllers/InvestmentPortfolioController.php index 4be9da80..28236848 100644 --- a/app/Http/Controllers/InvestmentPortfolioController.php +++ b/app/Http/Controllers/InvestmentPortfolioController.php @@ -16,6 +16,7 @@ use App\Services\InvestmentRelations; use App\Services\InvestmentZones; use App\Services\PortalAudit; use App\Services\PortalEditorialWorkflow; +use App\Services\PortfolioNearbyOpportunities; use App\Services\PublicSearchMetrics; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -179,6 +180,7 @@ class InvestmentPortfolioController extends Controller $anchorProject = $record->project_id ? Project::whereKey($record->project_id)->whereNull('deleted_at')->where('status', '!=', 'draft')->first(['id', 'code', 'name', 'status', 'budget_amount', 'budget_currency', 'start_date', 'end_date']) : null; + $geography = app(InvestmentRelations::class)->dossier($record, $management); $existingSubmissions = ! $management && $request->user() ? InvestmentSubmission::where('user_id', $request->user()->id)->where('dossier_id', $record->id)->where('status', 'draft') ->orderByDesc('updated_at')->limit(10)->get(['id', 'version', 'updated_at']) @@ -187,7 +189,9 @@ class InvestmentPortfolioController extends Controller return Inertia::render('portfolio/show', ['publicReferenceNames' => $management ? [] : $this->publicReferenceNames(), 'editorialEnabled' => $editorial, 'complements' => $management ? [] : app(InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones, 'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions, 'competitiveness' => $record->cluster_id ? app(ClusterCompetitiveness::class)->publicData($record->cluster_id) : null, - 'geography' => app(InformationGaps::class)->annotate($record->id, app(InvestmentRelations::class)->dossier($record, $management)), + 'geography' => app(InformationGaps::class)->annotate($record->id, $geography), + // Carteira 4.3: with nothing linked, show same-province/same-sector opportunities, labelled as not linked. + 'nearby' => $opportunities->isEmpty() ? app(PortfolioNearbyOpportunities::class)->for($record, $geography, []) : null, 'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]); } diff --git a/app/Services/PortfolioNearbyOpportunities.php b/app/Services/PortfolioNearbyOpportunities.php new file mode 100644 index 00000000..dfc9378a --- /dev/null +++ b/app/Services/PortfolioNearbyOpportunities.php @@ -0,0 +1,67 @@ + $geography InvestmentRelations::dossier() result + * @param list $linked opportunity ids already linked to the record + * @return array{provinces: list, sector: string, items: list>} + */ + public function for(InvestmentDossier $record, array $geography, array $linked): array + { + $provinces = []; + foreach ($geography['locations'] ?? [] as $location) { + foreach ($location['path'] ?? [] as $node) { + $node = (array) $node; + if (($node['location_type'] ?? null) === 'province') { + $provinces[$node['id']] = $node['name']; + } + } + } + $content = $record->content; + $sector = trim(implode(' · ', array_filter([$content['sector'] ?? null, $content['clusters'] ?? null]))); + $empty = ['provinces' => array_values($provinces), 'sector' => $sector, 'items' => []]; + if ($provinces === [] || $sector === '') { + return $empty; + } + $stems = $this->stems($sector.' '.$record->title); + $items = []; + foreach ($provinces as $id => $name) { + $found = app(InvestmentCatalogue::class)->query(['province_id' => $id, 'territory_basis' => 'direct']) + ->whereNotIn('opportunities.id', $linked)->limit(200)->get(['opportunities.id', 'title', 'slug', 'summary', 'sector_id']); + foreach ($found as $opportunity) { + $sectorName = (string) $opportunity->sector?->name; + if ($sectorName !== '' && array_intersect($this->stems($sectorName), $stems) !== []) { + $items[$opportunity->id] = ['id' => $opportunity->id, 'title' => $opportunity->title, 'slug' => $opportunity->slug, + 'summary' => $opportunity->summary, 'sector' => $sectorName, 'province' => $name]; + } + } + } + $items = array_values($items); + usort($items, fn ($a, $b) => strcmp($a['title'], $b['title'])); + + return [...$empty, 'items' => array_slice($items, 0, 12)]; + } + + /** Stems too general to say two sectors are the same («Zona Económica Especial» is not «Economia Azul»). */ + private const GENERIC = ['economi', 'especia', 'desenvo', 'integra', 'servico', 'naciona', 'regiona', 'program', 'project', 'cadeia', 'valor']; + + /** @return list seven-letter stems, so «Infraestruturas» meets «Infra-Estrutura». */ + private function stems(string $text): array + { + $normal = preg_replace('/[^a-z ]+/', ' ', str_replace('-', '', strtolower(Str::ascii($text)))); + $words = array_filter(explode(' ', (string) $normal), fn ($w) => strlen($w) >= 5); + + return array_values(array_diff(array_unique(array_map(fn ($w) => substr($w, 0, 7), $words)), self::GENERIC)); + } +} diff --git a/resources/js/pages/portfolio/show.tsx b/resources/js/pages/portfolio/show.tsx index 4c60774b..e57bf179 100644 --- a/resources/js/pages/portfolio/show.tsx +++ b/resources/js/pages/portfolio/show.tsx @@ -68,6 +68,18 @@ type Props = { summary: string; }[]; chains?: { id: string; name: string; stage: string }[]; + nearby?: { + provinces: string[]; + sector: string; + items: { + id: number; + title: string; + slug: string; + summary: string; + sector: string; + province: string; + }[]; + } | null; }; function Editor({ @@ -80,6 +92,7 @@ function Editor({ management, origin, opportunities = [], + nearby = null, chains = [], zones = [], anchorProject = null, @@ -393,11 +406,42 @@ function Editor({

{opportunity.summary}

))} - {!opportunities.length && ( + {!opportunities.length && !nearby?.items.length && ( )} + {!opportunities.length && !!nearby?.items.length && ( +
+

+ Esta ficha ainda não tem oportunidades ligadas. + Estas oportunidades publicadas são da mesma + província ({nearby.provinces.join(', ')}) e de um + sector próximo; não estão ligadas a esta ficha. +

+ {nearby.items.map((opportunity) => ( +
+ + {opportunity.title} + +

+ {opportunity.province} ·{' '} + {opportunity.sector} +

+

{opportunity.summary}

+
+ ))} +
+ )} {management ? ( <> diff --git a/tests/Feature/PortfolioNearbyOpportunitiesTest.php b/tests/Feature/PortfolioNearbyOpportunitiesTest.php new file mode 100644 index 00000000..1f521cec --- /dev/null +++ b/tests/Feature/PortfolioNearbyOpportunitiesTest.php @@ -0,0 +1,50 @@ +withoutVite(); + $ids = []; + $parent = null; + foreach (['country' => 'SYNTHETIC Moçambique', 'province' => 'SYNTHETIC Inhambane', 'district' => 'SYNTHETIC Vilankulo'] as $type => $name) { + $id = (string) Str::uuid(); + DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => $name, 'code' => $id, 'location_type' => $type, + 'source_system' => 'cartografia-workbook', 'data_classification' => 'public', + 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]); + $ids[$type] = $parent = $id; + } + $project = (string) Str::uuid(); + DB::table('projects')->insert(['id' => $project, 'code' => 'SYNTHETIC-A13', 'name' => 'Projecto fictício', 'status' => 'draft', + 'primary_territory_id' => $ids['district'], 'metadata' => '{}', 'data_classification' => 'public']); + $dossier = InvestmentDossier::create(['project_id' => $project, 'title' => 'SYNTHETIC Região de Turismo', 'source' => 'Synthetic fixture only', + 'content' => ['sector' => 'Turismo / Serviços'], 'publication_status' => 'published', 'published_at' => now()->subMinute(), + 'data_classification' => 'public', 'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA fixture only']); + $make = fn (string $sector, string $title) => Opportunity::create(['sector_id' => Sector::firstOrCreate(['slug' => Str::slug($sector)], ['name' => $sector, 'is_active' => true])->id, + 'reference' => 'SYNTHETIC-'.Str::uuid(), 'slug' => 'synthetic-'.Str::uuid(), 'title' => $title, 'status' => 'published', + 'published_at' => now()->subMinute(), 'primary_territory_id' => $ids['district'], 'geography_scope' => 'specific']); + $tourism = $make('Turismo', 'SYNTHETIC hotel'); + $make('Economia Azul', 'SYNTHETIC conservação'); + + $nearby = fn () => $this->get('/carteira/'.$dossier->id)->assertOk()->viewData('page')['props']['nearby']; + $result = $nearby(); + $this->assertSame(['SYNTHETIC Inhambane'], $result['provinces']); + $this->assertSame([$tourism->id], array_column($result['items'], 'id')); + $this->assertSame(0, DB::table('opportunity_projects')->count()); + + DB::table('opportunity_projects')->insert(['opportunity_id' => $tourism->id, 'project_id' => $project]); + $this->assertNull($nearby()); + } +}