Files
Investidor-V2/app/Services/PiiPortfolioImportSimulation.php
T
Claude 299fb08d44 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
2026-12-05 09:00:57 +02:00

356 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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)))));
}
}