Carteira 4.3: ficha sem ligações mostra oportunidades da mesma província e sector, indicadas como não ligadas
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -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]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\InvestmentDossier;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Carteira 4.3: when a portfolio record has no linked opportunity, it lists published opportunities located in one
|
||||
* of its provinces whose sector matches the record's sector. They are shown as «not linked to this record»; this
|
||||
* never creates a link (links are decided in Ligações da carteira).
|
||||
*/
|
||||
class PortfolioNearbyOpportunities
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $geography InvestmentRelations::dossier() result
|
||||
* @param list<int> $linked opportunity ids already linked to the record
|
||||
* @return array{provinces: list<string>, sector: string, items: list<array<string, mixed>>}
|
||||
*/
|
||||
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<string> 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));
|
||||
}
|
||||
}
|
||||
@@ -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({
|
||||
<p>{opportunity.summary}</p>
|
||||
</article>
|
||||
))}
|
||||
{!opportunities.length && (
|
||||
{!opportunities.length && !nearby?.items.length && (
|
||||
<PublishedOpportunitiesEmpty
|
||||
href={searchTerritoryHref('/oportunidades', pageUrl)}
|
||||
/>
|
||||
)}
|
||||
{!opportunities.length && !!nearby?.items.length && (
|
||||
<div
|
||||
className="space-y-3"
|
||||
aria-label="Oportunidades não ligadas"
|
||||
>
|
||||
<p role="status">
|
||||
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.
|
||||
</p>
|
||||
{nearby.items.map((opportunity) => (
|
||||
<article key={opportunity.id}>
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={searchTerritoryHref(
|
||||
`/oportunidades/${opportunity.slug}`,
|
||||
pageUrl,
|
||||
)}
|
||||
>
|
||||
{opportunity.title}
|
||||
</Link>
|
||||
<p className="text-sm">
|
||||
{opportunity.province} ·{' '}
|
||||
{opportunity.sector}
|
||||
</p>
|
||||
<p>{opportunity.summary}</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
{management ? (
|
||||
<>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\InvestmentDossier;
|
||||
use App\Models\Opportunity;
|
||||
use App\Models\Sector;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tests\TestCase;
|
||||
|
||||
final class PortfolioNearbyOpportunitiesTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_record_without_links_lists_same_province_and_sector_opportunities_as_not_linked(): void
|
||||
{
|
||||
$this->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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user