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
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\PortfolioLinkReviews;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class LoadPortfolioLinkProposals extends Command
|
||||
{
|
||||
protected $signature = 'portfolio:load-link-proposals {--execute : Regista as propostas; sem esta opção só mostra o que faria}';
|
||||
|
||||
protected $description = 'Regista como «por decidir» as ligações oportunidade↔carteira propostas; nenhuma ligação fica activa sem aprovação na gestão';
|
||||
|
||||
public function handle(PortfolioLinkReviews $reviews): int
|
||||
{
|
||||
if (! $reviews->installed()) {
|
||||
$this->error('Falta a migração 2026_12_05_120000_create_portfolio_link_reviews.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$execute = (bool) $this->option('execute');
|
||||
$r = $reviews->load($execute);
|
||||
$this->line(($execute ? 'Registadas: ' : 'Por registar (simulação): ').$r['created'].' · já existentes: '.$r['existing'].' · com problema: '.count($r['problems']));
|
||||
foreach ($r['problems'] as $problem) {
|
||||
$this->line('- '.$problem);
|
||||
}
|
||||
if (! $execute) {
|
||||
$this->line('Nada foi gravado. Repita com --execute para registar as propostas.');
|
||||
} else {
|
||||
$this->line('Decida em /management/ligacoes-carteira.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\PortfolioLinkReviews;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class PortfolioLinkReviewController extends Controller
|
||||
{
|
||||
public function index(Request $request, PortfolioLinkReviews $reviews): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['status' => ['nullable', Rule::in([...array_keys(PortfolioLinkReviews::STATUSES), 'all'])]]);
|
||||
$status = $data['status'] ?? 'pending';
|
||||
$payload = ['items' => $reviews->installed() ? $reviews->list($status === 'all' ? null : $status) : [], 'status' => $status,
|
||||
'statuses' => PortfolioLinkReviews::STATUSES, 'installed' => $reviews->installed()];
|
||||
|
||||
return $request->expectsJson() ? response()->json($payload) : Inertia::render('management/portfolio-link-reviews', $payload);
|
||||
}
|
||||
|
||||
public function store(Request $request, PortfolioLinkReviews $reviews): JsonResponse
|
||||
{
|
||||
abort_unless($reviews->installed(), 503, 'A revisão de ligações ainda não está instalada.');
|
||||
$data = $request->validate(['ids' => 'required|array|min:1|max:200', 'ids.*' => 'uuid',
|
||||
'decision' => ['required', Rule::in(['approve', 'reject', 'undo'])], 'note' => 'nullable|string|max:2000']);
|
||||
|
||||
return response()->json(['changed' => $reviews->decide($request->user(), $data['ids'], $data['decision'], $data['note'] ?? null)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?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;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user