Carteira 4.3: projectos integrados do PII como projectos planeados internos, por confirmar

Decisões do proprietário de 05/12: duplicados separados e referenciados, moeda do A10
indefinida, ANC fora do PII excluídos, registos internos e não publicados. O comando
portfolio:load-pii-integrated simula por omissão e só cria com --execute.

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 12:03:47 +02:00
committed by nala
parent bad7df1b6c
commit 87017986e1
3 changed files with 208 additions and 0 deletions
@@ -0,0 +1,32 @@
<?php
namespace App\Console\Commands;
use App\Services\PiiIntegratedProjects;
use Illuminate\Console\Command;
class LoadPiiIntegratedProjects extends Command
{
protected $signature = 'portfolio:load-pii-integrated {--execute : Cria os projectos; sem esta opção só mostra o que faria}';
protected $description = 'Cria os 161 projectos integrados do PII 2026–2030 como projectos planeados internos, não publicados e por confirmar';
public function handle(PiiIntegratedProjects $load): int
{
$execute = (bool) $this->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;
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Carteira 4.3, decisão do proprietário de 05/12/2026: the 161 integrated projects of the PII 2026–2030 become
* internal, unpublished planned projects «por confirmar» with the competent entity. Duplicates stay separate,
* the A10 currency stays undefined, ANC records not in the PII stay out, dates and places are not inferred.
* Planned investments are never opportunities. Idempotent: rows are keyed by the source table/row.
*/
class PiiIntegratedProjects
{
public const SOURCE_SYSTEM = 'pii-2026-2030';
/** @return array{create: list<array<string, mixed>>, existing: int, collisions: list<string>, links: int, without_relation: list<string>} */
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;
}
}
@@ -0,0 +1,59 @@
<?php
namespace Tests\Feature;
use App\Services\PiiIntegratedProjects;
use Database\Seeders\InvestmentPortfolioSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
final class PiiIntegratedProjectsTest extends TestCase
{
use RefreshDatabase;
public function test_integrated_projects_are_created_internal_planned_and_unconfirmed_without_inventing_values(): void
{
$this->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());
}
}