Files
Investidor-V2/app/Services/PortfolioNearbyOpportunities.php
T

68 lines
3.3 KiB
PHP

<?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));
}
}