Carteira 4.3: simulação só de leitura da importação dos projectos âncora do PII
Junta os 15 âncoras e os 161 projectos integrados do relatório final do PII 2026–2030, as referências provinciais da MozParks e o inventário ANC (não oficial) num ficheiro de staging rastreável, e o comando portfolio:simulate-pii-import compara-os com a base: correspondências, candidatas oportunidade↔projecto, duplicações, localizações, custos ambíguos, relações pendentes e campos ausentes. Não grava nada. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\PiiPortfolioImportSimulation;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class SimulatePiiPortfolioImport extends Command
|
||||
{
|
||||
protected $signature = 'portfolio:simulate-pii-import {--json= : Também grava o resultado completo em JSON neste caminho}';
|
||||
|
||||
protected $description = 'Simula, só em leitura, a importação dos projectos âncora e integrados do PII 2026–2030 e lista o que falta decidir';
|
||||
|
||||
public function handle(PiiPortfolioImportSimulation $simulation): int
|
||||
{
|
||||
$r = $simulation->run();
|
||||
$c = $r['counts'];
|
||||
$line = fn (string $text = '') => $this->line($text);
|
||||
|
||||
$line('# Simulação de importação — PII 2026–2030 (só leitura; nada foi gravado)');
|
||||
$line('Fonte: '.$r['source']['file'].' · SHA-256 '.$r['source']['sha256']);
|
||||
$line('Fonte secundária (não oficial): '.$r['secondary_source']['file'].' · SHA-256 '.$r['secondary_source']['sha256']);
|
||||
$line();
|
||||
$line('## 1. Registos extraídos');
|
||||
$line("Projectos âncora (Tabela 1): {$c['anchors']} · linhas âncora nas tabelas de projecto: {$c['anchor_rows']} · projectos integrados/complementares: {$c['integrated']}");
|
||||
$line("Referências provinciais da MozParks (Tabela 3): {$c['provincial_entries']} · registos ANC do inventário secundário: {$c['secondary']}");
|
||||
$line("Base actual: {$c['portal_projects']} projectos · {$c['published_opportunities']} oportunidades publicadas · {$c['opportunity_project_links']} ligações oportunidade↔projecto");
|
||||
$line('Nenhum projecto integrado é uma oportunidade aberta: são investimentos planeados no PII.');
|
||||
$line();
|
||||
|
||||
$line('## 2. Correspondências com dados existentes');
|
||||
$line('### Projectos âncora');
|
||||
foreach ($r['anchors'] as $a) {
|
||||
$state = ['same_name' => 'mesmo código e nome', 'same_code_different_name' => 'mesmo código, nome diferente', 'not_in_portal' => 'não existe no portal'][$a['state']];
|
||||
$line("- {$a['code']}: {$state}".($a['state'] === 'same_code_different_name' ? " (PII «{$a['pii_name']}» / portal «{$a['portal_name']}»)" : '')
|
||||
.($a['portal_status'] ? " · estado {$a['portal_status']} · ficha {$a['dossier_publication']}" : ''));
|
||||
}
|
||||
$existing = array_filter($r['rows'], fn ($row) => $row['existing_projects'] !== []);
|
||||
$line('### Integrados parecidos com projectos já existentes no portal: '.count($existing));
|
||||
foreach ($existing as $row) {
|
||||
$line("- {$row['ref']} {$row['anchor']} «{$row['title']}» ≈ ".collect($row['existing_projects'])->map(fn ($m) => "{$m['ref']} «{$m['title']}» ({$m['overlap']})")->join('; '));
|
||||
}
|
||||
$line('### Candidatas a ligação oportunidade↔projecto (para revisão, nenhuma ligação criada): '.count($r['opportunity_candidates']));
|
||||
foreach ($r['opportunity_candidates'] as $m) {
|
||||
$o = $m['opportunity'];
|
||||
$line("- {$m['source']} ⇄ {$o['ref']} «{$o['title']}» · ".($o['province'] ?: 'sem província').' · '.($o['sector'] ?: 'sem sector').' · comum: '.implode(', ', $o['shared'])." ({$o['overlap']})");
|
||||
}
|
||||
$line();
|
||||
|
||||
$line('## 3. Possíveis duplicações (não fundidas)');
|
||||
foreach ($r['duplicates'] as $d) {
|
||||
$line("- {$d['a']['ref']} «{$d['a']['title']}» ≈ {$d['b']['ref']} «{$d['b']['title']}» ({$d['overlap']})");
|
||||
}
|
||||
$line('### Inventário secundário (ANC) face ao PII e ao portal');
|
||||
foreach ($r['secondary'] as $s) {
|
||||
$pii = collect($s['pii'])->map(fn ($m) => "{$m['ref']} «{$m['title']}»")->join('; ');
|
||||
$portal = collect($s['portal'])->map(fn ($m) => "{$m['ref']} «{$m['title']}»")->join('; ');
|
||||
$line("- {$s['id']} «{$s['name']}» ({$s['province']}): PII ".($pii ?: 'sem correspondência').' · portal '.($portal ?: 'sem correspondência'));
|
||||
}
|
||||
$line();
|
||||
|
||||
$line('## 4. Localizações não resolvidas');
|
||||
$states = collect($r['rows'])->countBy(fn ($row) => $row['location']['state']);
|
||||
$line('Resumo: '.$states->map(fn ($n, $s) => "{$s}: {$n}")->join(' · '));
|
||||
foreach ($r['rows'] as $row) {
|
||||
$l = $row['location'];
|
||||
if ($l['unresolved'] || $l['ambiguous'] || $l['foreign']) {
|
||||
$line("- {$row['ref']} {$row['anchor']} «{$row['title']}»: "
|
||||
.collect(['não reconhecido' => $l['unresolved'], 'ambíguo' => $l['ambiguous'], 'fora do país' => $l['foreign']])
|
||||
->filter()->map(fn ($v, $k) => $k.' '.implode('; ', $v))->join(' · '));
|
||||
}
|
||||
}
|
||||
$line();
|
||||
|
||||
$line('## 5. Valores ambíguos');
|
||||
foreach ($r['rows'] as $row) {
|
||||
if ($row['cost']['flags'] !== []) {
|
||||
$value = $row['cost']['value'] === null ? 'sem valor' : number_format($row['cost']['value'], 0, ',', '.').' '.($row['cost']['currency'] ?? '?');
|
||||
$line("- {$row['ref']} {$row['anchor']} «{$row['title']}»: {$value} — ".implode('; ', $row['cost']['flags']));
|
||||
}
|
||||
}
|
||||
$line();
|
||||
|
||||
$line('## 6. Relações pendentes (todas por validar)');
|
||||
$byType = collect($r['rows'])->where('role', 'complementary')->countBy(fn ($row) => $row['proposed_relation'] ?? 'sem proposta');
|
||||
$line('Relação integrado→âncora sugerida pelo texto da fonte: '.$byType->map(fn ($n, $t) => "{$t}: {$n}")->join(' · '));
|
||||
foreach ($r['rows'] as $row) {
|
||||
if ($row['role'] === 'complementary' && $row['proposed_relation'] === null) {
|
||||
$line("- {$row['ref']} {$row['anchor']} «{$row['title']}»: relação literal «{$row['relation_literal']}»");
|
||||
}
|
||||
}
|
||||
$line();
|
||||
|
||||
$line('## 7. Campos ausentes na fonte');
|
||||
$line('Responsável, fase/estado de execução e coordenadas: ausentes nas '.count($r['rows']).' linhas (não preenchidos por inferência).');
|
||||
$keys = collect($r['rows'])->filter(fn ($row) => in_array('source_key_differs_from_anchor', $row['flags'], true))->count();
|
||||
$captions = collect($r['rows'])->filter(fn ($row) => in_array('caption_anchor_differs_from_table_order', $row['flags'], true))->count();
|
||||
$line("Chave da fonte diferente do âncora da tabela: {$keys} linhas · legenda com código errado: {$captions} linhas (âncora atribuído pela ordem das tabelas).");
|
||||
|
||||
if ($path = $this->option('json')) {
|
||||
file_put_contents($path, json_encode($r, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||||
$line();
|
||||
$line('JSON completo: '.$path);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Opportunity;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Read-only simulation of importing the PII 2026–2030 anchor and integrated projects.
|
||||
*
|
||||
* It only compares database/data/pii-portfolio-staging.json with what the database already
|
||||
* holds and lists what a reviewer must decide. It never writes, never links an opportunity
|
||||
* and never treats a planned investment as an open opportunity.
|
||||
*/
|
||||
class PiiPortfolioImportSimulation
|
||||
{
|
||||
public const DATA = 'data/pii-portfolio-staging.json';
|
||||
|
||||
private const STOPWORDS = ['a', 'o', 'as', 'os', 'e', 'de', 'da', 'do', 'das', 'dos', 'em', 'no', 'na', 'nos', 'nas', 'para',
|
||||
'com', 'por', 'ao', 'aos', 'the', 'of', 'and', 'kv', 'mw', 'mva', 'km', 'fase', 'ii', 'i', 'iii'];
|
||||
|
||||
/** Words too common in this portfolio to identify a project on their own. */
|
||||
private const GENERIC = ['porto', 'portos', 'corredor', 'zona', 'zonas', 'economica', 'especial', 'projecto', 'projectos', 'programa',
|
||||
'parque', 'parques', 'industrial', 'industriais', 'linha', 'linhas', 'transmissao', 'estrada', 'estradas', 'ferrovia',
|
||||
'ferroviario', 'ferroviaria', 'ferroviarias', 'portuario', 'sistema', 'centro', 'expansao', 'modernizacao', 'reabilitacao',
|
||||
'construcao', 'desenvolvimento', 'terminal', 'agua', 'abastecimento', 'subestacao', 'subestacoes', 'barragem',
|
||||
'irrigacao', 'bacia', 'rio', 'mina', 'areias', 'pesadas', 'central', 'termica', 'gas', 'nacional', 'regional',
|
||||
'melhoria', 'infra', 'estrutura', 'estruturas', 'estructura', 'estructuras', 'logistica', 'logistico', 'integrado',
|
||||
'integrada', 'acesso', 'rede', 'formacao', 'tecnico', 'tecnica', 'instituto', 'escola', 'plataforma', 'agro',
|
||||
'agroindustrial', 'industria', 'energia', 'electrificacao', 'turismo', 'turistico', 'turistica', 'servicos',
|
||||
'producao', 'processamento', 'cadeia', 'valor', 'contentores', 'urbano', 'urbana', 'gestao', 'apoio', 'certificacao',
|
||||
'mineracao', 'exploracao', 'mining', 'mine', 'resources', 'project', 'gold', 'alta', 'tensao', 'norte', 'sul', 'centro', 'oportunidade', 'investimento', 'empresa',
|
||||
'fabrica', 'complexo', 'plano', 'novo', 'nova', 'local', 'locais', 'provincia', 'distrito', 'cidade', 'resorts'];
|
||||
|
||||
private const NON_TERRITORIAL = ['nacional', 'regiao do corredor', 'nacional regiao', 'areas menos acessiveis', 'zonas rurais',
|
||||
'regiao', 'corredores beira nacala', 'corredor de nacala', 'fronteiras regionais', 'sadc', 'n13', 'n13 regiao'];
|
||||
|
||||
private const FOREIGN = ['malawi', 'zambia', 'chipata', 'zimbabwe', 'sadc'];
|
||||
|
||||
/** @var list<string> Words of province, district and post names: they say where, not what. */
|
||||
private array $placeWords = [];
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function data(): array
|
||||
{
|
||||
return json_decode(File::get(database_path(self::DATA)), true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function run(): array
|
||||
{
|
||||
$data = $this->data();
|
||||
// A read-only snapshot when run on its own (artisan); inside an outer transaction it can only read along.
|
||||
$outer = DB::transactionLevel() > 0;
|
||||
|
||||
return DB::transaction(function () use ($data, $outer) {
|
||||
if (! $outer && DB::connection()->getDriverName() === 'pgsql') {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
}
|
||||
|
||||
return $this->simulate($data);
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function simulate(array $data): array
|
||||
{
|
||||
$projects = DB::table('projects')->whereNull('deleted_at')->get(['id', 'code', 'name', 'status', 'source_system']);
|
||||
$dossiers = DB::table('investment_dossiers')->whereNull('deleted_at')->whereNotNull('project_id')
|
||||
->get(['project_id', 'publication_status'])->keyBy('project_id');
|
||||
$places = $this->places();
|
||||
$this->placeWords = array_values(array_unique(array_merge(self::FOREIGN, ...array_map(fn ($name) => explode(' ', $name), array_keys($places)))));
|
||||
$opportunities = Opportunity::published()->with('sector:id,name')->get(['id', 'reference', 'title', 'province', 'district', 'sector_id']);
|
||||
$integrated = $data['integrated'];
|
||||
$anchorCosts = [];
|
||||
foreach ($integrated as $row) {
|
||||
if ($row['role'] === 'anchor') {
|
||||
$anchorCosts[$row['anchor']] = $this->cost($row['cost_literal'], $row['currency_header_literal'])['value'];
|
||||
}
|
||||
}
|
||||
|
||||
$anchors = [];
|
||||
foreach ($data['anchors'] as $anchor) {
|
||||
$project = $projects->firstWhere('code', $anchor['code']);
|
||||
$anchors[] = [
|
||||
'code' => $anchor['code'], 'pii_name' => $anchor['name'], 'portal_name' => $project?->name,
|
||||
'state' => match (true) {
|
||||
$project === null => 'not_in_portal',
|
||||
$this->normal($project->name) === $this->normal($anchor['name']) => 'same_name',
|
||||
default => 'same_code_different_name',
|
||||
},
|
||||
'portal_status' => $project?->status,
|
||||
'dossier_publication' => $project ? ($dossiers[$project->id]->publication_status ?? 'sem ficha') : null,
|
||||
];
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
foreach ($integrated as $index => $row) {
|
||||
$cost = $this->cost($row['cost_literal'], $row['currency_header_literal']);
|
||||
if ($row['role'] === 'complementary' && $cost['value'] !== null && $cost['value'] === ($anchorCosts[$row['anchor']] ?? null)) {
|
||||
$cost['flags'][] = 'igual ao custo total do âncora';
|
||||
}
|
||||
$location = $this->location($row['location_literal'], $places);
|
||||
$existing = $row['role'] === 'anchor' ? [] : $this->similar($row['title'], $projects->map(fn ($p) => ['ref' => $p->code, 'title' => $p->name])->all(), 0.6);
|
||||
$rows[] = [
|
||||
'ref' => 'T'.$row['source_table_index'].'/L'.$row['source_table_row'], 'anchor' => $row['anchor'], 'role' => $row['role'],
|
||||
'title' => $row['title'], 'cost' => $cost, 'location' => $location, 'existing_projects' => $existing,
|
||||
'relation_literal' => $row['relation_literal'], 'proposed_relation' => $this->relationType($row['relation_literal']),
|
||||
'flags' => $row['review_flags'], 'index' => $index,
|
||||
];
|
||||
}
|
||||
|
||||
$duplicates = [];
|
||||
$titles = array_map(fn ($r) => ['ref' => $r['ref'].' '.$r['anchor'], 'title' => $r['title']], $rows);
|
||||
foreach ($titles as $i => $a) {
|
||||
foreach (array_slice($titles, $i + 1, null, true) as $b) {
|
||||
$score = $this->score($a['title'], $b['title']);
|
||||
// Same kind of facility in different places (e.g. two schools) is not a duplicate.
|
||||
$differentPlaces = $score['places'][0] !== [] && $score['places'][1] !== [] && array_intersect(...$score['places']) === [];
|
||||
if ($this->matches($score) && $score['overlap'] >= 0.75 && ! $differentPlaces) {
|
||||
$duplicates[] = ['a' => $a, 'b' => $b, 'overlap' => $score['overlap']];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$candidates = [];
|
||||
$opportunityTitles = $opportunities->map(fn ($o) => ['ref' => $o->reference ?: '#'.$o->id, 'title' => $o->title,
|
||||
'province' => $o->province, 'sector' => $o->sector?->name])->all();
|
||||
foreach ($rows as $row) {
|
||||
foreach ($this->similar($row['title'], $opportunityTitles, 0.5) as $match) {
|
||||
$candidates[] = ['source' => $row['ref'].' '.$row['anchor'].' — '.$row['title'], 'opportunity' => $match];
|
||||
}
|
||||
}
|
||||
foreach ($data['provincial_references'] as $reference) {
|
||||
foreach ($reference['entries'] as $entry) {
|
||||
foreach ($this->similar($entry, $opportunityTitles, 0.5) as $match) {
|
||||
$candidates[] = ['source' => 'T8/L'.$reference['source_table_row'].' A01 ('.$reference['province_literal'].') — '.$entry, 'opportunity' => $match];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$secondary = [];
|
||||
$piiTitles = array_merge(
|
||||
array_map(fn ($r) => ['ref' => $r['ref'].' '.$r['anchor'], 'title' => $r['title']], $rows),
|
||||
collect($data['provincial_references'])->flatMap(fn ($ref) => array_map(fn ($e) => ['ref' => 'T8/L'.$ref['source_table_row'].' A01 '.$ref['province_literal'], 'title' => $e], $ref['entries']))->all(),
|
||||
);
|
||||
foreach ($data['secondary_inventory']['records'] as $record) {
|
||||
$secondary[] = ['id' => $record['id'], 'name' => $record['name'], 'province' => $record['province_literal'],
|
||||
'pii' => $this->similar($record['name'], $piiTitles, 0.5),
|
||||
'portal' => $this->similar($record['name'], $projects->map(fn ($p) => ['ref' => $p->code, 'title' => $p->name])->all(), 0.5),
|
||||
'location' => $this->location($record['location_literal'].', '.$record['province_literal'], $places)];
|
||||
}
|
||||
|
||||
return [
|
||||
'source' => $data['source'], 'secondary_source' => ['file' => $data['secondary_inventory']['file'], 'sha256' => $data['secondary_inventory']['sha256']],
|
||||
'counts' => [
|
||||
'anchors' => count($data['anchors']),
|
||||
'integrated' => count(array_filter($rows, fn ($r) => $r['role'] === 'complementary')),
|
||||
'anchor_rows' => count(array_filter($rows, fn ($r) => $r['role'] === 'anchor')),
|
||||
'provincial_entries' => collect($data['provincial_references'])->sum(fn ($r) => count($r['entries'])),
|
||||
'secondary' => count($data['secondary_inventory']['records']),
|
||||
'portal_projects' => $projects->count(), 'published_opportunities' => $opportunities->count(),
|
||||
'opportunity_project_links' => DB::table('opportunity_projects')->count(),
|
||||
],
|
||||
'anchors' => $anchors, 'rows' => $rows, 'duplicates' => $duplicates,
|
||||
'opportunity_candidates' => $candidates, 'secondary' => $secondary,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{value: float|null, currency: string|null, flags: list<string>} */
|
||||
public function cost(string $literal, string $header): array
|
||||
{
|
||||
$flags = [];
|
||||
$currency = match (true) {
|
||||
str_contains($header, 'USD') && str_contains($header, 'MZN') => null,
|
||||
str_contains($header, 'USD') => 'USD',
|
||||
str_contains($header, 'MZN') => 'MZN',
|
||||
default => null,
|
||||
};
|
||||
if ($currency === null) {
|
||||
$flags[] = 'moeda indefinida no cabeçalho («'.$header.'»)';
|
||||
}
|
||||
$text = trim(preg_replace('/\x{00A0}/u', ' ', $literal));
|
||||
// The staging joins the cell's paragraphs with « / »; empty paragraphs leave stray bars.
|
||||
$parts = array_values(array_filter(array_map('trim', explode('/', $text)), fn ($p) => $p !== ''));
|
||||
if (count($parts) > 1) {
|
||||
return ['value' => null, 'currency' => $currency, 'flags' => [...$flags, 'vários valores na mesma célula («'.$literal.'»)']];
|
||||
}
|
||||
$text = $parts[0] ?? '';
|
||||
if (! preg_match('/\d/', $text)) {
|
||||
return ['value' => null, 'currency' => $currency, 'flags' => [...$flags, 'sem valor numérico («'.$literal.'»)']];
|
||||
}
|
||||
if (preg_match('/[.,]\s+\d/', $text)) {
|
||||
$flags[] = 'espaço dentro do número';
|
||||
}
|
||||
$compact = preg_replace('/\s+/', '', $text);
|
||||
if (! preg_match('/^\d[\d.,]*$/', $compact)) {
|
||||
return ['value' => null, 'currency' => $currency, 'flags' => [...$flags, 'formato não reconhecido («'.$literal.'»)']];
|
||||
}
|
||||
$decimal = null;
|
||||
if (preg_match('/^(.*)([.,])(\d{1,2})$/', $compact, $m)) {
|
||||
$decimal = $m[3];
|
||||
$compact = $m[1];
|
||||
$flags[] = 'casas decimais';
|
||||
}
|
||||
if (str_contains($compact, '.') && str_contains($compact, ',')) {
|
||||
$flags[] = 'separadores mistos';
|
||||
}
|
||||
$groups = preg_split('/[.,]/', $compact) ?: [];
|
||||
if (count($groups) > 1 && collect(array_slice($groups, 1))->contains(fn ($g) => strlen($g) !== 3)) {
|
||||
return ['value' => null, 'currency' => $currency, 'flags' => [...$flags, 'agrupamento irregular («'.$literal.'»)']];
|
||||
}
|
||||
$value = (float) (implode('', $groups).($decimal !== null ? '.'.$decimal : ''));
|
||||
if ($value < 100_000 || $value > 10_000_000_000) {
|
||||
$flags[] = 'ordem de grandeza a confirmar';
|
||||
}
|
||||
|
||||
return ['value' => $value, 'currency' => $currency, 'flags' => $flags];
|
||||
}
|
||||
|
||||
/** @return array<string, list<array{name: string, type: string}>> */
|
||||
private function places(): array
|
||||
{
|
||||
$places = [];
|
||||
foreach (DB::table('geo_locations')->whereNull('deleted_at')->whereIn('location_type', ['province', 'district', 'admin_post'])->get(['name', 'location_type']) as $place) {
|
||||
$names = [$this->normal($place->name)];
|
||||
$names[] = preg_replace('/^cidade (de |da |do )?/', '', $names[0]);
|
||||
if ($names[0] === 'vilankulo') {
|
||||
$names[] = 'vilanculos'; // spelling used in the PII
|
||||
}
|
||||
if (str_starts_with($names[0], 'maputo ')) {
|
||||
$names[] = 'maputo';
|
||||
}
|
||||
if (preg_match('/^([a-z]+)[ -]/', $names[1], $m) && $place->location_type === 'district') {
|
||||
$names[] = $m[1];
|
||||
}
|
||||
foreach (array_unique($names) as $name) {
|
||||
$places[$name][] = ['name' => $place->name, 'type' => $place->location_type];
|
||||
}
|
||||
}
|
||||
|
||||
return $places;
|
||||
}
|
||||
|
||||
/** @param array<string, list<array{name: string, type: string}>> $places
|
||||
* @return array{state: string, resolved: list<string>, ambiguous: list<string>, unresolved: list<string>, foreign: list<string>}
|
||||
*/
|
||||
public function location(string $literal, array $places): array
|
||||
{
|
||||
$out = ['resolved' => [], 'ambiguous' => [], 'unresolved' => [], 'foreign' => []];
|
||||
$fragments = preg_split('/[(),;\/&+–—]|\s-\s|\s+e\s+|^prov[ií]ncia de\s+/iu', $literal) ?: [];
|
||||
foreach ($fragments as $fragment) {
|
||||
$key = trim(preg_replace('/^(provincia (de|da) |porto (de|da) |regiao (de|do|da) |montante de |zona do |trecho |rio )/', '', $this->normal($fragment)));
|
||||
if ($key === '' || in_array($key, self::NON_TERRITORIAL, true) || in_array($this->normal($fragment), self::NON_TERRITORIAL, true)) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($key, self::FOREIGN, true)) {
|
||||
$out['foreign'][] = trim($fragment);
|
||||
|
||||
continue;
|
||||
}
|
||||
$matches = $places[$key] ?? [];
|
||||
$byType = collect($matches)->groupBy('type');
|
||||
$best = $byType->get('province') ?? $byType->get('district') ?? $byType->get('admin_post');
|
||||
if (! $best) {
|
||||
$out['unresolved'][] = trim($fragment);
|
||||
} elseif ($best->count() > 1) {
|
||||
$out['ambiguous'][] = trim($fragment).' → '.$best->pluck('name')->join(' | ');
|
||||
} else {
|
||||
$out['resolved'][] = $best->first()['name'];
|
||||
}
|
||||
}
|
||||
$out = array_map(fn ($l) => array_values(array_unique($l)), $out);
|
||||
$out['state'] = match (true) {
|
||||
$out['resolved'] === [] && $out['ambiguous'] === [] && $out['unresolved'] === [] && $out['foreign'] === [] => 'sem território (nacional/regional)',
|
||||
$out['unresolved'] === [] && $out['ambiguous'] === [] && $out['foreign'] === [] => 'resolvida',
|
||||
$out['resolved'] === [] && $out['ambiguous'] === [] => $out['foreign'] !== [] && $out['unresolved'] === [] ? 'fora de Moçambique' : 'não resolvida',
|
||||
default => 'parcial',
|
||||
};
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Suggestion only; every relation stays pending until a reviewer validates it. */
|
||||
public function relationType(string $literal): ?string
|
||||
{
|
||||
$text = $this->normal($literal);
|
||||
|
||||
return match (true) {
|
||||
str_contains($text, 'e alimentad') || str_contains($text, 'procura') => 'market',
|
||||
str_contains($text, 'integra a cadeia') || str_contains($text, 'fornec') => 'supplier',
|
||||
str_contains($text, 'alimenta') || str_contains($text, 'suporta') => 'enabler',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** @param array<int, array<string, mixed>> $items
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function similar(string $title, array $items, float $threshold): array
|
||||
{
|
||||
$found = [];
|
||||
foreach ($items as $item) {
|
||||
$score = $this->score($title, (string) $item['title']);
|
||||
if ($this->matches($score) && $score['overlap'] >= $threshold) {
|
||||
$found[] = [...$item, 'overlap' => $score['overlap'], 'shared' => $score['shared']];
|
||||
}
|
||||
}
|
||||
usort($found, fn ($a, $b) => $b['overlap'] <=> $a['overlap']);
|
||||
|
||||
return array_slice($found, 0, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* A shared name that is neither a common word nor a place is enough to look; otherwise
|
||||
* the titles must be almost the same (e.g. «Porto de Nacala» and «Porto e Corredor de Nacala»).
|
||||
*
|
||||
* @param array{overlap: float, distinct: int, shared: list<string>} $score
|
||||
*/
|
||||
private function matches(array $score): bool
|
||||
{
|
||||
return $score['distinct'] >= 1 || (count($score['shared']) >= 2 && $score['overlap'] >= 0.8);
|
||||
}
|
||||
|
||||
/** @return array{overlap: float, distinct: int, shared: list<string>, places: array{0: list<string>, 1: list<string>}} */
|
||||
private function score(string $a, string $b): array
|
||||
{
|
||||
[$ta, $tb] = [$this->tokens($a), $this->tokens($b)];
|
||||
$places = [array_values(array_intersect($ta, $this->placeWords)), array_values(array_intersect($tb, $this->placeWords))];
|
||||
if ($ta === [] || $tb === []) {
|
||||
return ['overlap' => 0.0, 'distinct' => 0, 'shared' => [], 'places' => $places];
|
||||
}
|
||||
$shared = array_values(array_intersect($ta, $tb));
|
||||
|
||||
return ['overlap' => round(count($shared) / min(count($ta), count($tb)), 2),
|
||||
'distinct' => count(array_diff($shared, self::GENERIC, $this->placeWords)), 'shared' => $shared, 'places' => $places];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function tokens(string $text): array
|
||||
{
|
||||
$words = array_filter(explode(' ', $this->normal($text)), fn ($w) => strlen($w) > 1 && ! in_array($w, self::STOPWORDS, true) && ! ctype_digit($w));
|
||||
|
||||
return array_values(array_unique($words));
|
||||
}
|
||||
|
||||
private function normal(string $text): string
|
||||
{
|
||||
return trim(preg_replace('/\s+/', ' ', preg_replace('/[^a-z0-9]+/', ' ', strtolower(Str::ascii($text)))));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user