diff --git a/app/Console/Commands/LoadPiiIntegratedProjects.php b/app/Console/Commands/LoadPiiIntegratedProjects.php new file mode 100644 index 00000000..8613a4c5 --- /dev/null +++ b/app/Console/Commands/LoadPiiIntegratedProjects.php @@ -0,0 +1,32 @@ +option('execute'); + $r = $load->run($execute); + $budgets = count(array_filter($r['create'], fn ($p) => $p['budget'] !== null)); + $duplicates = count(array_filter($r['create'], fn ($p) => $p['duplicate_of'] !== [])); + $this->line(($execute ? 'Criados: ' : 'Por criar (simulação): ').count($r['create']).' projectos · já existentes: '.$r['existing'] + .' · com conflito: '.count($r['collisions'])); + $this->line("Com orçamento numérico: {$budgets} (os restantes guardam o valor literal da fonte) · marcados como possível duplicado: {$duplicates}"); + $this->line("Relações com o âncora: {$r['links']} com tipo sugerido pela fonte (internas, por validar) · sem tipo, só no registo: ".count($r['without_relation'])); + foreach ($r['collisions'] as $collision) { + $this->line('- conflito: '.$collision); + } + $this->line($execute ? 'Nada foi publicado: os projectos são internos e ficam «por confirmar».' + : 'Nada foi gravado. Repita com --execute para criar os projectos.'); + + return self::SUCCESS; + } +} diff --git a/app/Services/PiiIntegratedProjects.php b/app/Services/PiiIntegratedProjects.php new file mode 100644 index 00000000..301cbd20 --- /dev/null +++ b/app/Services/PiiIntegratedProjects.php @@ -0,0 +1,117 @@ +>, existing: int, collisions: list, links: int, without_relation: list} */ + public function run(bool $execute): array + { + $simulation = app(PiiPortfolioImportSimulation::class); + $data = $simulation->data(); + $sha = substr($data['source']['sha256'], 0, 8); + $anchors = DB::table('projects')->whereNull('deleted_at')->whereIn('code', array_column($data['anchors'], 'code'))->pluck('id', 'code'); + $names = array_column($data['anchors'], 'name', 'code'); + + // Possible duplicates found by the simulation: kept separate (owner, 05/12) and cross-referenced. + $duplicates = []; + foreach ($simulation->run()['duplicates'] as $pair) { + [$a, $b] = [strtok($pair['a']['ref'], ' '), strtok($pair['b']['ref'], ' ')]; + $duplicates[$a][] = $pair['b']['ref'].' «'.$pair['b']['title'].'»'; + $duplicates[$b][] = $pair['a']['ref'].' «'.$pair['a']['title'].'»'; + } + + $report = ['create' => [], 'existing' => 0, 'collisions' => [], 'links' => 0, 'without_relation' => []]; + $counter = []; + $rows = []; + foreach ($data['integrated'] as $row) { + if ($row['role'] !== 'complementary') { + continue; + } + $counter[$row['anchor']] = ($counter[$row['anchor']] ?? 0) + 1; + $rows[] = [$row, sprintf('%s-C%02d', $row['anchor'], $counter[$row['anchor']])]; + } + + $work = function () use ($rows, $anchors, $names, $duplicates, $sha, $simulation, $data, $execute, &$report) { + foreach ($rows as [$row, $code]) { + $external = $sha.':T'.$row['source_table_index'].'/L'.$row['source_table_row']; + $ref = 'T'.$row['source_table_index'].'/L'.$row['source_table_row']; + if (DB::table('projects')->where('source_system', self::SOURCE_SYSTEM)->where('external_id', $external)->exists()) { + $report['existing']++; + + continue; + } + if (DB::table('projects')->whereNull('deleted_at')->where('code', $code)->exists()) { + $report['collisions'][] = $code.' ('.$ref.')'; + + continue; + } + $anchorId = $anchors[$row['anchor']] ?? null; + if (! $anchorId) { + $report['collisions'][] = $code.' ('.$ref.'): âncora '.$row['anchor'].' inexistente'; + + continue; + } + $cost = $simulation->cost($row['cost_literal'], $row['currency_header_literal']); + // Only a clean figure becomes a budget; every doubt keeps the amount literal in the metadata. + $budget = $cost['value'] !== null && $cost['currency'] !== null && $cost['flags'] === []; + $relation = $simulation->relationType($row['relation_literal']); + $duplicateOf = $duplicates[$ref] ?? []; + $id = (string) Str::uuid(); + $report['create'][] = ['code' => $code, 'ref' => $ref, 'title' => $row['title'], 'budget' => $budget ? $cost['value'] : null, + 'relation' => $relation, 'duplicate_of' => $duplicateOf]; + if ($relation === null) { + $report['without_relation'][] = $code.' «'.$row['title'].'»'; + } else { + $report['links']++; + } + if (! $execute) { + continue; + } + DB::table('projects')->insert(['id' => $id, 'source_system' => self::SOURCE_SYSTEM, 'external_id' => $external, + 'data_classification' => 'internal', 'code' => $code, 'name' => Str::limit($row['title'], 250, '…'), 'status' => 'planned', + 'description' => 'Projecto integrado do PII 2026–2030, complementar ao '.$row['anchor'].' «'.$names[$row['anchor']].'». ' + .'Investimento planeado; não é uma oportunidade aberta. Responsável, estado e localização por confirmar com a entidade competente.', + 'budget_amount' => $budget ? $cost['value'] : null, 'budget_currency' => $budget ? $cost['currency'] : null, + 'metadata' => json_encode([ + 'anchor_code' => $row['anchor'], + 'confirmation_status' => 'por_confirmar', + 'confirmation_note' => 'Decisão do proprietário de 05/12/2026: criado como interno e não publicado; publicação só depois da confirmação do responsável, estado e localização pela entidade competente.', + 'possible_duplicate_of' => $duplicateOf, + 'anchor_relation' => ['literal' => $row['relation_literal'], 'suggested_type' => $relation, 'status' => 'por_validar'], + 'pii' => ['source_file' => $data['source']['file'], 'source_sha256' => $data['source']['sha256'], + 'table' => $row['source_table_index'], 'row' => $row['source_table_row'], 'caption' => $row['source_table_caption'], + 'key_literal' => $row['source_key_literal'], 'type_literal' => $row['type_literal'], + 'location_literal' => $row['location_literal'], 'cost_literal' => $row['cost_literal'], + 'currency_header_literal' => $row['currency_header_literal'], 'cost_flags' => $cost['flags'], + 'horizon_literal' => $row['horizon_literal'], 'review_flags' => $row['review_flags']], + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'created_at' => now(), 'updated_at' => now()]); + if ($relation !== null) { + DB::table('complementary_project_links')->insert(['id' => (string) Str::uuid(), 'source_system' => self::SOURCE_SYSTEM, + 'external_id' => $external, 'data_classification' => 'internal', 'anchor_project_id' => $anchorId, + 'complementary_project_id' => $id, 'relation_type' => $relation]); + } + } + if ($execute && $report['create'] !== []) { + DB::table('audit_events')->insert(['source_system' => self::SOURCE_SYSTEM, 'entity_type' => 'projects', 'action' => 'pii_integrated_projects_loaded', + 'after_data' => json_encode(['created' => count($report['create']), 'links' => $report['links'], + 'source_sha256' => $data['source']['sha256']], JSON_THROW_ON_ERROR)]); + } + }; + DB::transaction($work); + + return $report; + } +} diff --git a/tests/Feature/PiiIntegratedProjectsTest.php b/tests/Feature/PiiIntegratedProjectsTest.php new file mode 100644 index 00000000..f693dbbb --- /dev/null +++ b/tests/Feature/PiiIntegratedProjectsTest.php @@ -0,0 +1,59 @@ +seed(InvestmentPortfolioSeeder::class); + $load = app(PiiIntegratedProjects::class); + $before = DB::table('projects')->count(); + + $dry = $load->run(false); + $this->assertCount(161, $dry['create']); + $this->assertSame($before, DB::table('projects')->count()); + + $result = $load->run(true); + $this->assertCount(161, $result['create']); + $this->assertSame([], $result['collisions']); + $created = DB::table('projects')->where('source_system', PiiIntegratedProjects::SOURCE_SYSTEM); + $this->assertSame(161, (clone $created)->count()); + $this->assertSame(0, (clone $created)->where(fn ($q) => $q->where('status', '!=', 'planned')->orWhere('data_classification', '!=', 'internal'))->count()); + $this->assertSame(0, (clone $created)->whereNotNull('start_date')->count()); + $this->assertSame(0, DB::table('investment_dossiers')->whereIn('project_id', (clone $created)->select('id'))->count()); + $this->assertSame(0, DB::table('opportunities')->count()); + + // A10 table has a «USD/MZN» header: no currency is chosen, the literal is kept. + $mphanda = (clone $created)->where('code', 'A10-C01')->first(); + $this->assertNull($mphanda->budget_amount); + $this->assertSame('800.000.000', json_decode($mphanda->metadata, true)['pii']['cost_literal']); + $this->assertSame('Cahora Bassa Norte (HCB)', $mphanda->name); + + // Both container terminals stay, each pointing at the other. + foreach (['A07-C02', 'A08-C02'] as $code) { + $meta = json_decode((clone $created)->where('code', $code)->value('metadata'), true); + $this->assertSame('por_confirmar', $meta['confirmation_status']); + $this->assertCount(1, $meta['possible_duplicate_of']); + $this->assertStringContainsString('Terminal de Contentores – Porto de Nacala', $meta['possible_duplicate_of'][0]); + } + $this->assertSame('16100000.00', (clone $created)->where('code', 'A03-C01')->value('budget_amount')); + + $links = DB::table('complementary_project_links')->where('source_system', PiiIntegratedProjects::SOURCE_SYSTEM); + $this->assertSame($result['links'], (clone $links)->count()); + $this->assertSame(161, $result['links'] + count($result['without_relation'])); + $this->assertSame(0, (clone $links)->where('data_classification', '!=', 'internal')->count()); + + $again = $load->run(true); + $this->assertSame([[], 161], [$again['create'], $again['existing']]); + $this->assertSame(161, (clone $created)->count()); + } +}