>, 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; } }