[link table, link column, target table] */ public const TARGETS = [ 'project' => ['opportunity_projects', 'project_id', 'projects'], 'corridor' => ['opportunity_corridors', 'corridor_id', 'development_corridors'], 'cluster' => ['opportunity_clusters', 'cluster_id', 'economic_clusters'], ]; public const RELATIONS = [ 'same_project' => 'Mesma iniciativa que um projecto integrado do âncora', 'within_anchor_area' => 'Na área e no sector do projecto âncora', 'related_supplier' => 'Relacionada — fornecedora da cadeia, não faz parte do projecto', 'corridor_context' => 'Enquadrada no corredor', 'cluster_context' => 'Enquadrada no cluster', ]; public const STATUSES = ['pending' => 'Por decidir', 'approved' => 'Aprovadas', 'rejected' => 'Rejeitadas']; public function installed(): bool { return Schema::hasTable('portfolio_link_reviews'); } /** * Registers the proposals of the data file as pending. Idempotent: an existing proposal (any status) is kept. * * @return array{created: int, existing: int, problems: list} */ public function load(bool $execute): array { $data = json_decode(File::get(database_path(self::PROPOSALS)), true, 512, JSON_THROW_ON_ERROR); $report = ['created' => 0, 'existing' => 0, 'problems' => []]; $run = function () use ($data, $execute, &$report) { foreach ($data['proposals'] as $proposal) { $label = $proposal['reference'].' → '.$proposal['target_code']; $opportunity = Opportunity::published()->where('reference', $proposal['reference'])->first(['id', 'title']); if (! $opportunity) { $report['problems'][] = $label.': oportunidade não publicada ou inexistente'; continue; } if ($opportunity->title !== $proposal['title']) { $report['problems'][] = $label.': título diferente do proposto («'.$opportunity->title.'»)'; continue; } $target = DB::table(self::TARGETS[$proposal['target_type']][2])->where('code', $proposal['target_code'])->whereNull('deleted_at')->value('id'); if (! $target) { $report['problems'][] = $label.': destino inexistente'; continue; } $key = ['opportunity_id' => $opportunity->id, 'target_type' => $proposal['target_type'], 'target_id' => $target]; if (DB::table('portfolio_link_reviews')->where($key)->exists()) { $report['existing']++; continue; } $report['created']++; if ($execute) { DB::table('portfolio_link_reviews')->insert([...$key, 'id' => (string) Str::uuid(), 'relation' => $proposal['relation'], 'source' => $data['source'], 'evidence' => $proposal['evidence'], 'status' => 'pending', 'created_at' => now(), 'updated_at' => now()]); } } }; DB::transaction($run); return $report; } /** @return list> */ public function list(?string $status): array { $rows = DB::table('portfolio_link_reviews as r')->join('opportunities as o', 'o.id', '=', 'r.opportunity_id') ->leftJoin('users as u', 'u.id', '=', 'r.decided_by') ->when($status, fn ($q) => $q->where('r.status', $status)) ->orderBy('r.target_type')->orderBy('o.title') ->get(['r.id', 'r.target_type', 'r.target_id', 'r.relation', 'r.source', 'r.evidence', 'r.status', 'r.decided_at', 'r.decision_note', 'u.name as decided_by', 'o.id as opportunity_id', 'o.reference', 'o.slug', 'o.title', 'o.province']); $names = []; foreach (self::TARGETS as $type => [, , $table]) { $ids = $rows->where('target_type', $type)->pluck('target_id')->unique()->values(); foreach (DB::table($table)->whereIn('id', $ids)->get(['id', 'code', 'name']) as $target) { $names[$target->id] = $target->code.' — '.$target->name; } } return array_values($rows->map(fn ($r) => [...(array) $r, 'target' => $names[$r->target_id] ?? $r->target_id, 'relation_label' => self::RELATIONS[$r->relation] ?? $r->relation])->all()); } /** * approve: writes the link (unless it already existed); reject: no link; undo: back to pending and removes * the link only when this review had created it. * * @param list $ids * @return int number of reviews changed */ public function decide(User $actor, array $ids, string $decision, ?string $note): int { abort_unless(in_array($decision, ['approve', 'reject', 'undo'], true), 422, 'Decisão inválida.'); return DB::transaction(function () use ($actor, $ids, $decision, $note) { $changed = 0; foreach (DB::table('portfolio_link_reviews')->whereIn('id', $ids)->lockForUpdate()->get() as $review) { [$table, $column] = self::TARGETS[$review->target_type]; $link = ['opportunity_id' => $review->opportunity_id, $column => $review->target_id]; $update = match ($decision) { 'approve' => $review->status === 'pending' ? (function () use ($table, $link) { $exists = DB::table($table)->where($link)->exists(); if (! $exists) { DB::table($table)->insert($link); } return ['status' => 'approved', 'link_created' => ! $exists]; })() : null, 'reject' => $review->status === 'pending' ? ['status' => 'rejected', 'link_created' => false] : null, 'undo' => $review->status !== 'pending' ? (function () use ($review, $table, $link) { if ($review->status === 'approved' && $review->link_created) { DB::table($table)->where($link)->delete(); } return ['status' => 'pending', 'link_created' => false]; })() : null, }; if ($update === null) { continue; } $pending = $update['status'] === 'pending'; DB::table('portfolio_link_reviews')->where('id', $review->id)->update([...$update, 'decided_by' => $pending ? null : $actor->id, 'decided_at' => $pending ? null : now(), 'decision_note' => $pending ? null : $note, 'updated_at' => now()]); DB::table('audit_events')->insert(['source_system' => 'portfolio-link-reviews', 'entity_type' => 'portfolio_link_reviews', 'entity_id' => $review->id, 'actor_user_id' => $actor->id, 'action' => 'portfolio_link_'.$decision, 'after_data' => json_encode(['opportunity_id' => $review->opportunity_id, 'target_type' => $review->target_type, 'target_id' => $review->target_id, 'relation' => $review->relation, 'previous_status' => $review->status, ...$update, 'note' => $note], JSON_THROW_ON_ERROR)]); $changed++; } return $changed; }); } }