Words of province, district and post names: they say where, not what. */ private array $placeWords = []; /** @return array */ public function data(): array { return json_decode(File::get(database_path(self::DATA)), true, 512, JSON_THROW_ON_ERROR); } /** @return array */ 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 $data * @return array */ 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} */ 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> */ 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> $places * @return array{state: string, resolved: list, ambiguous: list, unresolved: list, foreign: list} */ 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> $items * @return list> */ 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} $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, places: array{0: list, 1: list}} */ 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 */ 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))))); } }