Files
Investidor-V2/app/Services/PiiIntegratedProjects.php
T
Claude 87017986e1 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
2026-12-05 12:03:47 +02:00

118 lines
7.2 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 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;
}
}