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:
Claude
2026-12-05 09:00:57 +02:00
committed by nala
parent b521f7bdfe
commit 299fb08d44
5 changed files with 5069 additions and 0 deletions
@@ -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)))));
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,77 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\Sector;
use App\Services\PiiPortfolioImportSimulation;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class PiiPortfolioImportSimulationTest extends TestCase
{
use RefreshDatabase;
public function test_staging_keeps_every_pii_row_traceable_and_never_open(): void
{
$data = app(PiiPortfolioImportSimulation::class)->data();
$this->assertSame('review_only_not_importable', $data['status']);
$this->assertSame('bcbf8ec976100cc5e978aef54050c3e3e9d959b0d361fa80a788528a8e5049a6', $data['source']['sha256']);
$this->assertCount(15, $data['anchors']);
$this->assertCount(176, $data['integrated']);
$this->assertCount(161, array_filter($data['integrated'], fn ($r) => $r['role'] === 'complementary'));
$refs = array_map(fn ($r) => $r['source_table_index'].'/'.$r['source_table_row'], $data['integrated']);
$this->assertSame(count($refs), count(array_unique($refs)));
// Table 21 is A14 although its caption says A11: the anchor comes from the table order.
$this->assertSame(['A14'], array_values(array_unique(array_column(array_filter($data['integrated'], fn ($r) => $r['source_table_index'] === 24), 'anchor'))));
$this->assertCount(22, $data['secondary_inventory']['records']);
}
public function test_costs_are_read_literally_and_doubts_are_flagged(): void
{
$s = app(PiiPortfolioImportSimulation::class);
$this->assertSame(16100000.0, $s->cost('16.100.000', 'Custo Total (USD)')['value']);
$this->assertSame(550000000.0, $s->cost('550,000,000', 'Custo (USD)')['value']);
$this->assertSame(120000000.0, $s->cost('120 000 000', 'Custo (USD)')['value']);
$this->assertSame(['espaço dentro do número'], $s->cost('1.000.000. 000', 'Custo (USD)')['flags']);
$this->assertSame(67558964.79, $s->cost('67.558.964,79', 'Custo (USD)')['value']);
$this->assertNull($s->cost('Carece de estudos', 'Custo (USD)')['value']);
$this->assertNull($s->cost('800.000.000', 'Custo (USD/ MZN)')['currency']);
$this->assertSame(99200000.0, $s->cost('99.200.000 / /', 'Custo (USD)')['value']);
$this->assertNull($s->cost('1 / 2', 'Custo (USD)')['value']);
$this->assertContains('ordem de grandeza a confirmar', $s->cost('30,000,000,000', 'Custo (USD)')['flags']);
}
public function test_simulation_proposes_candidates_without_writing_anything(): void
{
foreach (['NACALA-PORTO', 'NACALA-VELHA', 'Cabo Delgado'] as $name) {
DB::table('geo_locations')->insert(['id' => $id = (string) Str::uuid(), 'code' => $id, 'name' => $name, 'location_type' => 'district', 'parent_id' => null]);
}
$sector = Sector::create(['name' => 'Energia sintética', 'slug' => 'energia-sintetica', 'is_active' => true]);
$opportunity = Opportunity::create(['sector_id' => $sector->id, 'reference' => 'SYNTHETIC-PII', 'slug' => 'synthetic-pii',
'title' => 'Fornecimento de agregados para Mphanda Nkuwa', 'status' => 'published', 'published_at' => now()->subMinute()]);
$before = [DB::table('opportunity_projects')->count(), DB::table('projects')->count(), DB::table('complementary_project_links')->count()];
$result = app(PiiPortfolioImportSimulation::class)->run();
$this->assertSame($before, [DB::table('opportunity_projects')->count(), DB::table('projects')->count(), DB::table('complementary_project_links')->count()]);
$this->assertSame('not_in_portal', $result['anchors'][0]['state']);
$candidate = collect($result['opportunity_candidates'])->firstWhere('opportunity.ref', 'SYNTHETIC-PII');
$this->assertNotNull($candidate);
$this->assertStringContainsString('Mphanda Nkuwa', $candidate['source']);
$this->assertSame(['mphanda', 'nkuwa'], array_values(array_intersect(['mphanda', 'nkuwa'], $candidate['opportunity']['shared'])));
$nacala = collect($result['rows'])->firstWhere('title', 'Estrada de Acesso ao Porto de Nacala');
$this->assertSame('parcial', $nacala['location']['state']);
$this->assertStringContainsString('NACALA-PORTO | NACALA-VELHA', $nacala['location']['ambiguous'][0]);
$containers = collect($result['duplicates'])->filter(fn ($d) => $d['a']['title'] === 'Terminal de Contentores – Porto de Nacala');
$this->assertCount(1, $containers);
// Two schools in different places are not duplicates.
$this->assertFalse(collect($result['duplicates'])->contains(fn ($d) => str_contains($d['a']['title'], 'Escola Técnico-Profissional')));
$this->assertSame($opportunity->id, Opportunity::published()->sole()->id);
$this->artisan('portfolio:simulate-pii-import')->expectsOutputToContain('só leitura; nada foi gravado')
->expectsOutputToContain('SYNTHETIC-PII «Fornecimento de agregados para Mphanda Nkuwa»')->assertSuccessful();
}
}
+123
View File
@@ -0,0 +1,123 @@
"""Builds database/data/pii-portfolio-staging.json for the read-only import simulation.
Usage:
python3 -I tools/prepare-pii-portfolio-staging.py <PII.docx> <staging.csv> <projecto_ancora.docx> <output.json>
The documents are only read. Every row keeps its table/row reference and literal values;
nothing is classified as approved, available or open for investment.
"""
import csv
import hashlib
import json
import re
import sys
import docx
PII, STAGING, ANCHOR_DOC, OUTPUT = sys.argv[1:5]
PII_SHA = 'bcbf8ec976100cc5e978aef54050c3e3e9d959b0d361fa80a788528a8e5049a6'
# Table order in word/document.xml (counted from 1, as in pii-extraction-review-2026-10-03.md).
# The anchor is taken from this order: several captions and keys in the source are wrong
# (e.g. table 11 is A03 but its rows use "A02 - Cxx"; table 21 is A14 but its caption says A11).
PROJECT_TABLES = {7: 'A01', 9: 'A02', 11: 'A03', 12: 'A04', 13: 'A05', 15: 'A06', 16: 'A07', 17: 'A08',
18: 'A09', 19: 'A10', 20: 'A11', 21: 'A12', 23: 'A13', 24: 'A14', 25: 'A15'}
def sha(path):
return hashlib.sha256(open(path, 'rb').read()).hexdigest()
def rows(table):
out = []
for row in table.rows:
cells, previous = [], None
for cell in row.cells:
if cell._tc is previous:
continue
previous = cell._tc
cells.append(' '.join(cell.text.split()))
out.append(cells)
return out
assert sha(PII) == PII_SHA, 'O DOCX do PII não coincide com o SHA-256 registado.'
document = docx.Document(PII)
tables = [rows(t) for t in document.tables]
anchors = []
for number, row in enumerate(tables[5][1:], start=2):
anchors.append({'code': row[0], 'name': row[1], 'region': row[2], 'sector': row[3],
'source_table_index': 6, 'source_table_row': number, 'source_table_caption': 'Tabela 1. Legitimidade e Prioridade dos Projectos Âncora do PII 2026–2030'})
assert [a['code'] for a in anchors] == [f'A{i:02d}' for i in range(1, 16)]
integrated = []
with open(STAGING, encoding='utf-8-sig', newline='') as handle:
staged = list(csv.DictReader(handle))
assert len(staged) == 174
for single in (7, 9):
header, row = tables[single - 1][0], tables[single - 1][1]
staged.insert(0 if single == 7 else 1, {
'source_table_index': str(single), 'source_table_row': '2',
'source_table_caption': f'Tabela {"2" if single == 7 else "4"}. Projecto {PROJECT_TABLES[single]}',
'source_key_literal': row[0], 'source_title_literal': row[1], 'source_type_literal': row[2],
'documented_relation_literal': row[3], 'source_location_literal': row[4], 'source_cost_literal': row[5],
'source_currency_header_literal': header[5], 'source_horizon_literal': row[6],
'review_flags': 'source_content_unverified|toponym_unverified|owner_review_required|currency_only_as_stated_in_table_header'})
for item in staged:
index = int(item['source_table_index'])
anchor = PROJECT_TABLES[index]
caption_code = re.search(r'Projecto (A?\d+)', item['source_table_caption'])
flags = [f for f in item['review_flags'].split('|') if f]
if caption_code and caption_code.group(1).lstrip('A').zfill(2) != anchor[1:]:
flags.append('caption_anchor_differs_from_table_order')
key = item['source_key_literal']
if not key.replace(' ', '').startswith(anchor) and key not in ('-', ''):
flags.append('source_key_differs_from_anchor')
integrated.append({
'anchor': anchor,
'role': 'anchor' if item['source_type_literal'].startswith('Âncora') else 'complementary',
'source_table_index': index, 'source_table_row': int(item['source_table_row']),
'source_table_caption': item['source_table_caption'], 'source_key_literal': key,
'title': item['source_title_literal'], 'type_literal': item['source_type_literal'],
'relation_literal': item['documented_relation_literal'], 'location_literal': item['source_location_literal'],
'cost_literal': item['source_cost_literal'], 'currency_header_literal': item['source_currency_header_literal'],
'horizon_literal': item['source_horizon_literal'], 'review_flags': flags,
})
provincial = []
for number, row in enumerate(tables[7][1:], start=2):
provincial.append({'province_literal': row[0], 'entries': [e.strip() for e in re.split(r',(?![^()]*\))', row[1]) if e.strip()],
'sector_literal': row[2], 'source_table_index': 8, 'source_table_row': number,
'source_table_caption': 'Tabela 3. Oportunidades de Projectos Integrados no Projecto Âncora Nacional',
'note': 'Fonte indicada: MozParks (2025). Nomes de empresas e projectos existentes; não são oportunidades abertas.'})
anchor_doc = docx.Document(ANCHOR_DOC)
anc_rows = rows(anchor_doc.tables[0])
header = anc_rows[1]
secondary = []
for number, row in enumerate(anc_rows[2:], start=3):
record = dict(zip(header, row))
secondary.append({'id': record['ID'], 'province_literal': record['Província'], 'name': record['Projecto'],
'sector_literal': record['Sector'], 'location_literal': record['Distrito/local'],
'latitude_literal': record['Latitude'], 'longitude_literal': record['Longitude'],
'investment_literal': record['Investimento divulgado'], 'promoter_literal': record['Promotor principal'],
'employment_literal': record['Emprego divulgado'], 'status_literal': record['Estado em 2026'],
'quality_literal': record['Qualidade'], 'source_table_row': number})
data = {
'status': 'review_only_not_importable',
'notice': 'Extracção para simulação de importação. Não é importação, validação institucional, aprovação oficial nem lista de oportunidades abertas.',
'source': {'file': 'MPD_Relatório Final do PII 26-30_2111.docx', 'sha256': PII_SHA,
'staging': 'docs/investmoz/source-staging/pii-26-30-review-only.csv (174 linhas) + tabelas 7 e 9 (A01, A02)',
'table_numbering': 'Ordem em word/document.xml, a partir de 1'},
'anchors': anchors,
'integrated': integrated,
'provincial_references': provincial,
'secondary_inventory': {'file': 'projecto_ancora.docx', 'sha256': sha(ANCHOR_DOC),
'notice': 'Inventário compilado de fontes diversas; não é o relatório do PII. Pontos são representativos e o próprio documento pede validação.',
'records': secondary},
}
with open(OUTPUT, 'w', encoding='utf-8') as handle:
json.dump(data, handle, ensure_ascii=False, indent=1)
handle.write('\n')
print(len(anchors), len(integrated), len(provincial), len(secondary))