Files
Investidor-V2/app/Services/PortfolioLinkReviews.php
T
Claude eb21e12793 Carteira 4.3: ligações oportunidade↔carteira propostas e aprovadas na gestão
89 propostas, segundo os critérios aprovados pelo proprietário a partir da simulação do PII,
ficam «por decidir» com fonte e evidência. A página «Ligações da carteira» aprova ou rejeita
uma a uma ou por grupo; só a aprovação escreve a ligação, com registo de quem e quando, e
anular retira apenas a ligação que a aprovação criou.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzJmxFy3izprXr5dSq91jM
2026-12-05 09:58:25 +02:00

165 lines
8.0 KiB
PHP

<?php
namespace App\Services;
use App\Models\Opportunity;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* Carteira 4.3: proposed links between published opportunities and portfolio records (anchor projects,
* corridors, clusters). A proposal never shows on the portal; approval writes the link and records who
* approved it, when, and on which evidence.
*/
class PortfolioLinkReviews
{
public const PROPOSALS = 'data/portfolio-link-proposals-20261205.json';
/** target_type => [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<string>}
*/
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<array<string, mixed>> */
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<string> $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;
});
}
}