diff --git a/app/Http/Controllers/PiiAnchorRelationController.php b/app/Http/Controllers/PiiAnchorRelationController.php new file mode 100644 index 00000000..94160c29 --- /dev/null +++ b/app/Http/Controllers/PiiAnchorRelationController.php @@ -0,0 +1,32 @@ +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)]); + } +} diff --git a/app/Services/PiiAnchorRelations.php b/app/Services/PiiAnchorRelations.php new file mode 100644 index 00000000..1d7f2c9f --- /dev/null +++ b/app/Services/PiiAnchorRelations.php @@ -0,0 +1,116 @@ + '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> */ + 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 $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]); + } + } +} diff --git a/resources/js/pages/management/pii-anchor-relations.tsx b/resources/js/pages/management/pii-anchor-relations.tsx new file mode 100644 index 00000000..a1d272cc --- /dev/null +++ b/resources/js/pages/management/pii-anchor-relations.tsx @@ -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; + types: Record; +}) { + const groups = new Map(); + for (const item of items) { + const key = `${item.anchor_code ?? '?'} — ${item.anchor_name ?? 'âncora por identificar'}`; + groups.set(key, [...(groups.get(key) ?? []), item]); + } + return ( + +

+ 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. +

+ + {items.length === 0 ? ( +

Sem projectos neste estado.

+ ) : ( + [...groups.entries()].map(([group, rows]) => ( + + )) + )} +
+ ); +} + +function Group({ + title, + rows, + types, +}: { + title: string; + rows: Item[]; + types: Record; +}) { + const suggested = rows.filter( + (row) => row.status === 'por_validar' && row.suggested_type, + ); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + return ( +
+
+

+ {title} ({rows.length}) +

+ {suggested.length > 1 && ( + + )} +
+ {error &&

{error}

} +
    + {rows.map((row) => ( + + ))} +
+
+ ); +} + +function Row({ item, types }: { item: Item; types: Record }) { + 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 ( +
  • +

    + {item.code} · {item.name} +

    +

    + Relação no relatório: «{item.relation_literal || 'sem texto'}» +

    +

    + {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} +

    + {item.possible_duplicate_of.length > 0 && ( +

    + Possível duplicado de:{' '} + {item.possible_duplicate_of.join('; ')} +

    + )} +

    + Estado:{' '} + + {item.status === 'validada' + ? `Validada — ${types[item.type ?? ''] ?? item.type}` + : item.status === 'rejeitada' + ? 'Sem relação directa' + : 'Por validar'} + + {item.decided_at && + ` · ${item.decided_by ?? 'utilizador'} em ${new Date(item.decided_at).toLocaleString('pt-PT')}`} + {item.note && ` · «${item.note}»`} +

    + {item.status === 'por_validar' ? ( +
    + + + + +
    + ) : ( + + )} + {error &&

    {error}

    } +
  • + ); +} diff --git a/resources/js/pages/management/shared.tsx b/resources/js/pages/management/shared.tsx index 93f23301..5f223b5d 100644 --- a/resources/js/pages/management/shared.tsx +++ b/resources/js/pages/management/shared.tsx @@ -82,6 +82,9 @@ export function Management({ Ligações da carteira + + Relações dos projectos do PII + Demografia INE CRM Investidores diff --git a/routes/web.php b/routes/web.php index 7233e790..a6df75be 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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 () { diff --git a/tests/Feature/PiiAnchorRelationsTest.php b/tests/Feature/PiiAnchorRelationsTest.php new file mode 100644 index 00000000..37ad6ea4 --- /dev/null +++ b/tests/Feature/PiiAnchorRelationsTest.php @@ -0,0 +1,56 @@ +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()); + } +}