Carteira 4.3: página para validar a relação de cada projecto integrado do PII com o âncora
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,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\PiiAnchorRelations;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
final class PiiAnchorRelationController extends Controller
|
||||
{
|
||||
public function index(Request $request, PiiAnchorRelations $relations): Response|JsonResponse
|
||||
{
|
||||
$data = $request->validate(['status' => ['nullable', Rule::in([...array_keys(PiiAnchorRelations::STATUSES), 'all'])]]);
|
||||
$status = $data['status'] ?? 'por_validar';
|
||||
$payload = ['items' => $relations->list($status === 'all' ? null : $status), 'status' => $status,
|
||||
'statuses' => PiiAnchorRelations::STATUSES, 'types' => PiiAnchorRelations::TYPES];
|
||||
|
||||
return $request->expectsJson() ? response()->json($payload) : Inertia::render('management/pii-anchor-relations', $payload);
|
||||
}
|
||||
|
||||
public function store(Request $request, PiiAnchorRelations $relations): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['ids' => 'required|array|min:1|max:200', 'ids.*' => 'uuid',
|
||||
'decision' => ['required', Rule::in(['validate', 'reject', 'reopen'])],
|
||||
'type' => ['nullable', Rule::in(array_keys(PiiAnchorRelations::TYPES))], 'note' => 'nullable|string|max:2000']);
|
||||
|
||||
return response()->json(['changed' => $relations->decide($request->user(), $data['ids'], $data['decision'], $data['type'] ?? null, $data['note'] ?? null)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Carteira 4.3: a person validates how each integrated PII project relates to its anchor. The decision lives in
|
||||
* projects.metadata.anchor_relation (status, type, who, when, note) and the internal complementary_project_links
|
||||
* row follows it. Nothing is published here.
|
||||
*/
|
||||
class PiiAnchorRelations
|
||||
{
|
||||
public const TYPES = [
|
||||
'enabler' => 'Viabiliza o âncora (infra-estrutura, energia, água, formação, regulação)',
|
||||
'supplier' => 'Fornece o âncora ou integra a sua cadeia',
|
||||
'market' => 'É alimentado pelo âncora (procura, mercado)',
|
||||
'dependency' => 'O âncora depende dele para funcionar',
|
||||
];
|
||||
|
||||
public const STATUSES = ['por_validar' => 'Por validar', 'validada' => 'Validadas', 'rejeitada' => 'Sem relação directa'];
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
public function list(?string $status): array
|
||||
{
|
||||
$projects = DB::table('projects as p')->where('p.source_system', PiiIntegratedProjects::SOURCE_SYSTEM)->whereNull('p.deleted_at')
|
||||
->when($status, fn ($q) => $q->where('p.metadata->anchor_relation->status', $status))
|
||||
->orderBy('p.code')->get(['p.id', 'p.code', 'p.name', 'p.metadata', 'p.budget_amount', 'p.budget_currency']);
|
||||
$anchors = DB::table('projects')->whereNull('deleted_at')->whereIn('code', $projects->map(fn ($p) => json_decode($p->metadata, true)['anchor_code'] ?? null)->filter()->unique())
|
||||
->pluck('name', 'code');
|
||||
$users = DB::table('users')->whereIn('id', $projects->map(fn ($p) => json_decode($p->metadata, true)['anchor_relation']['decided_by'] ?? null)->filter()->unique())
|
||||
->pluck('name', 'id');
|
||||
|
||||
return array_values($projects->map(function ($p) use ($anchors, $users) {
|
||||
$meta = json_decode($p->metadata, true);
|
||||
$relation = $meta['anchor_relation'] ?? [];
|
||||
|
||||
return ['id' => $p->id, 'code' => $p->code, 'name' => $p->name, 'anchor_code' => $meta['anchor_code'] ?? null,
|
||||
'anchor_name' => $anchors[$meta['anchor_code'] ?? ''] ?? null, 'relation_literal' => $relation['literal'] ?? '',
|
||||
'suggested_type' => $relation['suggested_type'] ?? null, 'type' => $relation['type'] ?? null,
|
||||
'status' => $relation['status'] ?? 'por_validar', 'decided_by' => isset($relation['decided_by']) ? ($users[$relation['decided_by']] ?? null) : null,
|
||||
'decided_at' => $relation['decided_at'] ?? null, 'note' => $relation['note'] ?? null,
|
||||
'location_literal' => $meta['pii']['location_literal'] ?? null, 'cost_literal' => $meta['pii']['cost_literal'] ?? null,
|
||||
'currency_header_literal' => $meta['pii']['currency_header_literal'] ?? null,
|
||||
'source' => isset($meta['pii']) ? 'PII 2026–2030, tabela '.$meta['pii']['table'].', linha '.$meta['pii']['row'] : null,
|
||||
'possible_duplicate_of' => $meta['possible_duplicate_of'] ?? []];
|
||||
})->all());
|
||||
}
|
||||
|
||||
/**
|
||||
* validate (with a type) · reject (no direct relation) · reopen (back to the source suggestion).
|
||||
*
|
||||
* @param list<string> $ids
|
||||
*/
|
||||
public function decide(User $actor, array $ids, string $decision, ?string $type, ?string $note): int
|
||||
{
|
||||
abort_unless(in_array($decision, ['validate', 'reject', 'reopen'], true), 422, 'Decisão inválida.');
|
||||
abort_if($decision === 'validate' && $type !== null && ! array_key_exists($type, self::TYPES), 422, 'Tipo de relação inválido.');
|
||||
|
||||
return DB::transaction(function () use ($actor, $ids, $decision, $type, $note) {
|
||||
$changed = 0;
|
||||
$projects = DB::table('projects')->whereIn('id', $ids)->where('source_system', PiiIntegratedProjects::SOURCE_SYSTEM)
|
||||
->whereNull('deleted_at')->lockForUpdate()->get(['id', 'metadata', 'version_no']);
|
||||
foreach ($projects as $project) {
|
||||
$meta = json_decode($project->metadata, true);
|
||||
$relation = $meta['anchor_relation'];
|
||||
$anchor = DB::table('projects')->whereNull('deleted_at')->where('code', $meta['anchor_code'])->value('id');
|
||||
abort_unless($anchor !== null, 422, 'Projecto âncora inexistente: '.$meta['anchor_code']);
|
||||
$chosen = match ($decision) {
|
||||
'validate' => $type ?? $relation['suggested_type'],
|
||||
'reject' => null,
|
||||
'reopen' => $relation['suggested_type'],
|
||||
};
|
||||
if ($decision === 'validate' && $chosen === null) {
|
||||
continue; // no suggestion and no type chosen: nothing to validate
|
||||
}
|
||||
$previous = $relation;
|
||||
$this->link($anchor, $project->id, $chosen);
|
||||
$relation = ['literal' => $relation['literal'], 'suggested_type' => $relation['suggested_type'],
|
||||
...match ($decision) {
|
||||
'validate' => ['status' => 'validada', 'type' => $chosen],
|
||||
'reject' => ['status' => 'rejeitada', 'type' => null],
|
||||
'reopen' => ['status' => 'por_validar'],
|
||||
},
|
||||
...($decision === 'reopen' ? [] : ['decided_by' => $actor->id, 'decided_at' => now()->toIso8601String(), 'note' => $note])];
|
||||
$meta['anchor_relation'] = $relation;
|
||||
DB::table('projects')->where('id', $project->id)->update(['metadata' => json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
'version_no' => $project->version_no + 1, 'updated_at' => now()]);
|
||||
DB::table('audit_events')->insert(['source_system' => 'pii-anchor-relations', 'entity_type' => 'projects', 'entity_id' => $project->id,
|
||||
'actor_user_id' => $actor->id, 'action' => 'pii_anchor_relation_'.$decision,
|
||||
'before_data' => json_encode($previous, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||||
'after_data' => json_encode($relation, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
|
||||
$changed++;
|
||||
}
|
||||
|
||||
return $changed;
|
||||
});
|
||||
}
|
||||
|
||||
/** Keeps exactly one live internal link of the given type between anchor and project, or none. */
|
||||
private function link(string $anchor, string $project, ?string $type): void
|
||||
{
|
||||
$pair = ['anchor_project_id' => $anchor, 'complementary_project_id' => $project, 'source_system' => PiiIntegratedProjects::SOURCE_SYSTEM];
|
||||
$live = DB::table('complementary_project_links')->where($pair)->whereNull('deleted_at')->get(['id', 'relation_type', 'version_no']);
|
||||
foreach ($live as $link) {
|
||||
if ($link->relation_type !== $type) {
|
||||
DB::table('complementary_project_links')->where('id', $link->id)->update(['deleted_at' => now(), 'updated_at' => now(), 'version_no' => $link->version_no + 1]);
|
||||
}
|
||||
}
|
||||
if ($type !== null && ! $live->contains('relation_type', $type)) {
|
||||
DB::table('complementary_project_links')->insert([...$pair, 'id' => (string) Str::uuid(), 'data_classification' => 'internal', 'relation_type' => $type]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user