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:
Claude
2026-12-05 13:10:24 +02:00
committed by nala
parent 21ad2e998c
commit 02517741f4
6 changed files with 480 additions and 0 deletions
@@ -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)]);
}
}
+116
View File
@@ -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]);
}
}
}
@@ -0,0 +1,269 @@
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { Management, button, control } from './shared';
import { api } from '@/pages/investment/shared';
type Item = {
id: string;
code: string;
name: string;
anchor_code: string | null;
anchor_name: string | null;
relation_literal: string;
suggested_type: string | null;
type: string | null;
status: 'por_validar' | 'validada' | 'rejeitada';
decided_by: string | null;
decided_at: string | null;
note: string | null;
location_literal: string | null;
cost_literal: string | null;
currency_header_literal: string | null;
source: string | null;
possible_duplicate_of: string[];
};
type Decision = 'validate' | 'reject' | 'reopen';
async function decide(
ids: string[],
decision: Decision,
type: string | null,
note: string,
) {
await api('/management/relacoes-pii', { ids, decision, type, note });
router.reload();
}
/** Carteira 4.3: how each integrated PII project relates to its anchor, decided by a person. Nothing is published here. */
export default function PiiAnchorRelations({
items,
status,
statuses,
types,
}: {
items: Item[];
status: string;
statuses: Record<string, string>;
types: Record<string, string>;
}) {
const groups = new Map<string, Item[]>();
for (const item of items) {
const key = `${item.anchor_code ?? '?'} — ${item.anchor_name ?? 'âncora por identificar'}`;
groups.set(key, [...(groups.get(key) ?? []), item]);
}
return (
<Management title="Relações dos projectos do PII com o âncora">
<p>
Os projectos integrados do PII 2026–2030 são investimentos
planeados, internos e por confirmar com a entidade competente;
não são oportunidades nem estão publicados. Aqui confirma como
cada um se relaciona com o seu projecto âncora. O tipo sugerido
vem do texto do relatório; pode aceitá-lo, escolher outro ou
indicar que não há relação directa.
</p>
<nav className="my-3 flex flex-wrap gap-3" aria-label="Estado">
{[...Object.entries(statuses), ['all', 'Todas']].map(
([key, label]) => (
<Link
key={key}
className={
key === status ? 'font-bold' : 'underline'
}
href={`/management/relacoes-pii?status=${key}`}
>
{label}
</Link>
),
)}
</nav>
{items.length === 0 ? (
<p>Sem projectos neste estado.</p>
) : (
[...groups.entries()].map(([group, rows]) => (
<Group
key={group}
title={group}
rows={rows}
types={types}
/>
))
)}
</Management>
);
}
function Group({
title,
rows,
types,
}: {
title: string;
rows: Item[];
types: Record<string, string>;
}) {
const suggested = rows.filter(
(row) => row.status === 'por_validar' && row.suggested_type,
);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
return (
<section className="mt-6" aria-label={title}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold">
{title} ({rows.length})
</h2>
{suggested.length > 1 && (
<button
type="button"
className={button}
disabled={busy}
onClick={async () => {
setBusy(true);
setError('');
try {
await decide(
suggested.map((row) => row.id),
'validate',
null,
'Tipo sugerido aceite para o grupo',
);
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: 'Não foi possível guardar.',
);
} finally {
setBusy(false);
}
}}
>
Aceitar as {suggested.length} sugestões
</button>
)}
</div>
{error && <p role="alert">{error}</p>}
<ul className="mt-2 space-y-3">
{rows.map((row) => (
<Row key={row.id} item={row} types={types} />
))}
</ul>
</section>
);
}
function Row({ item, types }: { item: Item; types: Record<string, string> }) {
const [type, setType] = useState(item.type ?? item.suggested_type ?? '');
const [note, setNote] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const act = async (decision: Decision) => {
setBusy(true);
setError('');
try {
await decide([item.id], decision, type || null, note);
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: 'Não foi possível guardar.',
);
} finally {
setBusy(false);
}
};
return (
<li className="rounded border p-3">
<p>
<strong>{item.code}</strong> · {item.name}
</p>
<p className="text-sm">
Relação no relatório: «{item.relation_literal || 'sem texto'}»
</p>
<p className="text-muted-foreground text-xs">
{item.location_literal &&
`Local na fonte: ${item.location_literal} · `}
{item.cost_literal &&
`Custo na fonte: ${item.cost_literal} (${item.currency_header_literal ?? 'moeda por indicar'}) · `}
{item.source}
</p>
{item.possible_duplicate_of.length > 0 && (
<p className="text-sm">
Possível duplicado de:{' '}
{item.possible_duplicate_of.join('; ')}
</p>
)}
<p className="text-sm">
Estado:{' '}
<strong>
{item.status === 'validada'
? `Validada — ${types[item.type ?? ''] ?? item.type}`
: item.status === 'rejeitada'
? 'Sem relação directa'
: 'Por validar'}
</strong>
{item.decided_at &&
` · ${item.decided_by ?? 'utilizador'} em ${new Date(item.decided_at).toLocaleString('pt-PT')}`}
{item.note && ` · «${item.note}»`}
</p>
{item.status === 'por_validar' ? (
<div className="mt-2 flex flex-wrap items-end gap-2">
<label className="grid gap-1 text-sm">
Tipo de relação
<select
className={control}
value={type}
onChange={(e) => setType(e.target.value)}
>
<option value="">Escolher…</option>
{Object.entries(types).map(([key, label]) => (
<option key={key} value={key}>
{label}
{key === item.suggested_type
? ' (sugerido)'
: ''}
</option>
))}
</select>
</label>
<label className="grid min-w-64 flex-1 gap-1 text-sm">
Nota (opcional)
<input
className={control}
value={note}
maxLength={2000}
onChange={(e) => setNote(e.target.value)}
/>
</label>
<button
type="button"
className={button}
disabled={busy || !type}
onClick={() => act('validate')}
>
Validar
</button>
<button
type="button"
className={button}
disabled={busy}
onClick={() => act('reject')}
>
Sem relação directa
</button>
</div>
) : (
<button
type="button"
className={`${button} mt-2`}
disabled={busy}
onClick={() => act('reopen')}
>
Voltar a «por validar»
</button>
)}
{error && <p role="alert">{error}</p>}
</li>
);
}
+3
View File
@@ -82,6 +82,9 @@ export function Management({
<Link href="/management/ligacoes-carteira">
Ligações da carteira
</Link>
<Link href="/management/relacoes-pii">
Relações dos projectos do PII
</Link>
<Link href="/management/demography">Demografia INE</Link>
<Link href="/management/crm/leads">CRM</Link>
<Link href="/management/crm/investors">Investidores</Link>
+4
View File
@@ -40,6 +40,7 @@ use App\Http\Controllers\OpportunityManagementController;
use App\Http\Controllers\OpportunityOriginReviewController;
use App\Http\Controllers\OpportunityPromotionController;
use App\Http\Controllers\OpportunityResourceController;
use App\Http\Controllers\PiiAnchorRelationController;
use App\Http\Controllers\PortalEditorialWorkflowController;
use App\Http\Controllers\PortalManagementController;
use App\Http\Controllers\PortalProfileController;
@@ -179,6 +180,9 @@ Route::middleware(['auth', 'verified', 'can:manage-portal', PrivateInvestmentRes
// Carteira 4.3: proposed opportunity ↔ project/corridor/cluster links, decided one by one or by group.
Route::get('/management/ligacoes-carteira', [PortfolioLinkReviewController::class, 'index'])->name('management.portfolio-link-reviews');
Route::post('/management/ligacoes-carteira', [PortfolioLinkReviewController::class, 'store']);
// Carteira 4.3: relation of each integrated PII project to its anchor, validated by a person.
Route::get('/management/relacoes-pii', [PiiAnchorRelationController::class, 'index'])->name('management.pii-anchor-relations');
Route::post('/management/relacoes-pii', [PiiAnchorRelationController::class, 'store']);
});
Route::get('/management/product-usage', [ProductUsageMetricsController::class, 'index'])->middleware(['auth', 'verified', 'can:manage-portal', PrivateInvestmentResponse::class, 'throttle:30,1']);
Route::middleware(['auth', 'verified', 'can:manage-portal', PrivateInvestmentResponse::class, 'throttle:30,1'])->prefix('management/product-experiments')->group(function () {
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use App\Services\PiiIntegratedProjects;
use Database\Seeders\InvestmentPortfolioSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class PiiAnchorRelationsTest extends TestCase
{
use AuthenticatesQaActors;
use RefreshDatabase;
public function test_manager_validates_changes_rejects_and_reopens_anchor_relations(): void
{
$this->seed(InvestmentPortfolioSeeder::class);
app(PiiIntegratedProjects::class)->run(true);
$project = fn (string $code) => DB::table('projects')->where('code', $code)->first();
$links = fn (string $code) => DB::table('complementary_project_links')->where('complementary_project_id', $project($code)->id)->whereNull('deleted_at')->pluck('relation_type')->all();
$relation = fn (string $code) => json_decode($project($code)->metadata, true)['anchor_relation'];
$this->actingAs(User::factory()->create())->getJson('/management/relacoes-pii')->assertForbidden();
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAsWithMfa($manager);
$this->getJson('/management/relacoes-pii')->assertOk()->assertJsonCount(161, 'items')->assertJsonPath('items.0.anchor_code', 'A03');
// A03-C01 «Parque Industrial de Nacala»: suggestion from «alimentada pelo PDEC» is market.
$this->assertSame(['market'], $links('A03-C01'));
$this->postJson('/management/relacoes-pii', ['ids' => [$project('A03-C01')->id], 'decision' => 'validate'])->assertOk()->assertJsonPath('changed', 1);
$this->assertSame(['validada', 'market', $manager->id], [$relation('A03-C01')['status'], $relation('A03-C01')['type'], $relation('A03-C01')['decided_by']]);
// Another type replaces the internal link; rejecting removes it; reopening restores the suggestion.
$this->postJson('/management/relacoes-pii', ['ids' => [$project('A03-C02')->id], 'decision' => 'validate', 'type' => 'enabler', 'note' => 'Infra-estrutura'])->assertOk();
$this->assertSame(['enabler'], $links('A03-C02'));
$this->postJson('/management/relacoes-pii', ['ids' => [$project('A03-C03')->id], 'decision' => 'reject'])->assertOk();
$this->assertSame([], $links('A03-C03'));
$this->postJson('/management/relacoes-pii', ['ids' => [$project('A03-C03')->id], 'decision' => 'reopen'])->assertOk();
$this->assertSame('por_validar', $relation('A03-C03')['status']);
$this->assertSame([$relation('A03-C03')['suggested_type']], $links('A03-C03'));
// A project without suggestion needs an explicit type.
$bare = DB::table('projects')->where('source_system', PiiIntegratedProjects::SOURCE_SYSTEM)->whereNull('metadata->anchor_relation->suggested_type')->orderBy('code')->first();
$this->postJson('/management/relacoes-pii', ['ids' => [$bare->id], 'decision' => 'validate'])->assertOk()->assertJsonPath('changed', 0);
$this->postJson('/management/relacoes-pii', ['ids' => [$bare->id], 'decision' => 'validate', 'type' => 'supplier'])->assertOk()->assertJsonPath('changed', 1);
$this->assertSame(['supplier'], $links($bare->code));
$this->getJson('/management/relacoes-pii?status=validada')->assertOk()->assertJsonCount(3, 'items');
$this->assertSame(5, DB::table('audit_events')->where('source_system', 'pii-anchor-relations')->count());
$this->assertSame(0, DB::table('complementary_project_links')->where('source_system', PiiIntegratedProjects::SOURCE_SYSTEM)->where('data_classification', '!=', 'internal')->count());
}
}