Fichas: cada campo vazio mostra se já foi verificado na fonte, e a gestão regista a verificação

Mapa de erros 4.9, decisão do proprietário: os campos «Não documentado»
das fichas (posto administrativo, localidade, coordenadas, polígono, data
da fonte) continuam a ser mostrados e o portal distingue omissão de falta
de informação. Cada campo vazio passa a dizer o seu estado: «Não
documentado — por verificar na fonte», «Não consta da fonte» ou «Consta da
fonte; em carregamento no portal».

O estado é decidido por uma pessoa, nunca pelo portal: a nova página de
gestão «Lacunas nas fichas» (/management/lacunas) lista os campos vazios
das fichas publicadas, filtra por estado e regista a verificação com nota
e evento de auditoria. Só se pode registar um campo que esteja de facto
vazio nessa localização. Nova tabela information_gaps (migração).

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 08:02:00 +02:00
committed by nala
parent 9e8ca986ae
commit a2b1ce35e1
10 changed files with 472 additions and 10 deletions
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use App\Services\InformationGaps;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
final class InformationGapController extends Controller
{
public function index(Request $request, InformationGaps $gaps): Response|JsonResponse
{
$data = $request->validate(['status' => ['nullable', Rule::in([...array_keys(InformationGaps::STATUSES), 'all'])]]);
$status = ($data['status'] ?? 'to_verify') === 'all' ? null : ($data['status'] ?? 'to_verify');
$payload = ['items' => $gaps->installed() ? $gaps->pending($status) : [], 'status' => $data['status'] ?? 'to_verify',
'statuses' => InformationGaps::STATUSES, 'installed' => $gaps->installed()];
return $request->expectsJson() ? response()->json($payload) : Inertia::render('management/information-gaps', $payload);
}
public function store(Request $request, InformationGaps $gaps): JsonResponse
{
abort_unless($gaps->installed(), 503, 'O registo de lacunas ainda não está instalado.');
$gaps->record($request->user(), $request->all());
return response()->json(['saved' => true]);
}
}
@@ -8,6 +8,7 @@ use App\Models\Opportunity;
use App\Models\Project;
use App\Services\ClusterCompetitiveness;
use App\Services\CorridorAgribusinessOpportunities;
use App\Services\InformationGaps;
use App\Services\InvestmentCatalogue;
use App\Services\InvestmentComplements;
use App\Services\InvestmentGeography;
@@ -186,7 +187,7 @@ class InvestmentPortfolioController extends Controller
return Inertia::render('portfolio/show', ['publicReferenceNames' => $management ? [] : $this->publicReferenceNames(), 'editorialEnabled' => $editorial, 'complements' => $management ? [] : app(InvestmentComplements::class)->options('portfolio:'.$record->id), 'record' => $record, 'related' => $related, 'management' => $management, 'zones' => $zones,
'anchorProject' => $anchorProject, 'existingSubmissions' => $existingSubmissions,
'competitiveness' => $record->cluster_id ? app(ClusterCompetitiveness::class)->publicData($record->cluster_id) : null,
'geography' => app(InvestmentRelations::class)->dossier($record, $management),
'geography' => app(InformationGaps::class)->annotate($record->id, app(InvestmentRelations::class)->dossier($record, $management)),
'origin' => $origin ? ['id' => $origin->id, 'title' => $origin->title] : null, 'opportunities' => $opportunities, 'chains' => $chains]);
}
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Services;
use App\Http\Controllers\InvestmentPortfolioController;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
/**
* Empty fields of the published project and cluster records (mapa de erros 4.9). Every empty field is shown; its
* state says whether it was checked against the source: «por verificar» (no review yet), «não consta da fonte» or
* «consta da fonte e falta carregar». The portal never decides that by itself: a person compares with the source.
*/
final class InformationGaps
{
public const FIELDS = ['admin_post' => 'Posto administrativo', 'locality' => 'Localidade', 'coordinates' => 'Coordenadas',
'polygon' => 'Polígono', 'source_date' => 'Data da fonte'];
public const STATUSES = ['to_verify' => 'Por verificar', 'not_in_source' => 'Não consta da fonte',
'missing_in_portal' => 'Consta da fonte; falta carregar no portal'];
public function installed(): bool
{
return Schema::hasTable('information_gaps');
}
/** @return array<string, array<string, string>> location id => field => status */
public function statuses(string $dossierId): array
{
if (! $this->installed()) {
return [];
}
$result = [];
foreach (DB::table('information_gaps')->where('dossier_id', $dossierId)->get(['geo_location_id', 'field', 'status']) as $row) {
$result[$row->geo_location_id][$row->field] = $row->status;
}
return $result;
}
/**
* Adds the state of each empty field to the locations of a dossier geography.
*
* @param array<string,mixed> $geography
* @return array<string,mixed>
*/
public function annotate(string $dossierId, array $geography): array
{
$statuses = $this->statuses($dossierId);
$mark = fn (array $locations) => array_map(function (array $location) use ($statuses) {
$location['gaps'] = [];
foreach ($this->empty($location) as $field) {
$location['gaps'][$field] = $statuses[$location['id']][$field] ?? 'to_verify';
}
return $location;
}, $locations);
$geography['locations'] = $mark($geography['locations'] ?? []);
return $geography;
}
/**
* @param array<string,mixed> $location
* @return list<string>
*/
public function empty(array $location): array
{
$types = array_column(array_map(fn ($node) => (array) $node, $location['path'] ?? []), 'location_type');
$empty = [];
foreach (['admin_post', 'locality'] as $type) {
if (! in_array($type, $types, true)) {
$empty[] = $type;
}
}
if (empty($location['coordinates'])) {
$empty[] = 'coordinates';
}
if (empty($location['boundaries'])) {
$empty[] = 'polygon';
}
if (trim((string) ($location['source_date'] ?? '')) === '') {
$empty[] = 'source_date';
}
return $empty;
}
/** @return list<array<string,mixed>> */
public function pending(?string $status = 'to_verify'): array
{
$items = [];
foreach (InvestmentPortfolioController::visible()->orderBy('title')->get() as $dossier) {
$geography = $this->annotate($dossier->id, app(InvestmentRelations::class)->dossier($dossier, true));
foreach ($geography['locations'] as $location) {
foreach ($location['gaps'] as $field => $state) {
if ($status === null || $state === $status) {
$items[] = ['dossier_id' => $dossier->id, 'dossier' => $dossier->title, 'location_id' => $location['id'],
'location' => $location['name'], 'field' => $field, 'field_label' => self::FIELDS[$field], 'status' => $state,
'source_reference' => $location['source_reference'] ?? null];
}
}
}
}
return $items;
}
/** @param array<string,mixed> $input */
public function record(User $actor, array $input): void
{
$data = Validator::make($input, ['dossier_id' => 'required|uuid', 'location_id' => 'required|uuid',
'field' => ['required', Rule::in(array_keys(self::FIELDS))], 'status' => ['required', Rule::in(array_keys(self::STATUSES))],
'note' => 'nullable|string|max:2000'])->validate();
$dossier = InvestmentPortfolioController::visible()->whereKey($data['dossier_id'])->firstOrFail();
$location = collect(app(InvestmentRelations::class)->dossier($dossier, true)['locations'])->firstWhere('id', $data['location_id']);
abort_unless($location !== null && in_array($data['field'], $this->empty($location), true), 422,
'Este campo já está preenchido nesta ficha ou não pertence a esta localização.');
DB::transaction(function () use ($actor, $data) {
$key = ['dossier_id' => $data['dossier_id'], 'geo_location_id' => $data['location_id'], 'field' => $data['field']];
if ($data['status'] === 'to_verify') {
DB::table('information_gaps')->where($key)->delete();
} else {
$existing = DB::table('information_gaps')->where($key)->value('id');
DB::table('information_gaps')->updateOrInsert($key, ['id' => $existing ?? (string) Str::uuid(), 'status' => $data['status'],
'note' => $data['note'] ?? null, 'reviewer_id' => $actor->id, 'reviewed_at' => now(), 'updated_at' => now(),
...($existing ? [] : ['created_at' => now()])]);
}
DB::table('audit_events')->insert(['source_system' => 'information-gaps', 'entity_type' => 'investment_dossiers',
'entity_id' => $data['dossier_id'], 'actor_user_id' => $actor->id, 'action' => 'information_gap_reviewed',
'after_data' => json_encode($data, JSON_THROW_ON_ERROR)]);
});
}
}
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Mapa de erros 4.9, decisão do proprietário: campos vazios das fichas são mostrados e verificados. A falta de
* registo significa «por verificar»; a equipa compara com a fonte e indica se a informação não consta dela ou se
* consta e falta carregá-la no portal.
*/
public function up(): void
{
Schema::create('information_gaps', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->foreignUuid('dossier_id')->constrained('investment_dossiers')->restrictOnDelete();
$t->foreignUuid('geo_location_id')->constrained('geo_locations')->restrictOnDelete();
$t->string('field', 40);
$t->string('status', 40);
$t->text('note')->nullable();
$t->foreignId('reviewer_id')->constrained('users')->restrictOnDelete();
$t->timestampTz('reviewed_at');
$t->timestampsTz();
$t->unique(['dossier_id', 'geo_location_id', 'field']);
});
DB::statement("ALTER TABLE information_gaps ADD CONSTRAINT information_gaps_field_check CHECK (field IN ('admin_post','locality','coordinates','polygon','source_date')),
ADD CONSTRAINT information_gaps_status_check CHECK (status IN ('not_in_source','missing_in_portal'))");
}
public function down(): void
{
Schema::dropIfExists('information_gaps');
}
};
@@ -28,6 +28,8 @@ export type DocumentedLocation = {
source_date?: string | null;
geometry: { coordinates: [number, number] };
}[];
/** State of each empty field, checked against the source (mapa de erros 4.9). */
gaps?: Record<string, string>;
};
export type StructureGeography = {
source_evidence?: TerritorialSourceEvidence[];
@@ -59,6 +61,24 @@ export type StructureGeography = {
chains?: { id: string; code: string; name: string; stage: string }[];
};
const gapLabels: Record<string, string> = {
to_verify: 'Não documentado — por verificar na fonte',
not_in_source: 'Não consta da fonte',
missing_in_portal: 'Consta da fonte; em carregamento no portal',
};
/** What an empty field says: never a bare «Não documentado» without its verification state. */
const gapFields = [
'admin_post',
'locality',
'coordinates',
'polygon',
'source_date',
];
const gapLabel = (location: DocumentedLocation, field: string) =>
gapFields.includes(field)
? gapLabels[location.gaps?.[field] ?? 'to_verify']
: 'Não documentado';
const roles: Record<string, string> = {
opportunity: 'Localização declarada da oportunidade',
primary: 'Localização principal',
@@ -93,7 +113,7 @@ export function LocationList({
<dd>
{location.path.find(
(node) => node.location_type === type,
)?.name ?? 'Não documentado'}
)?.name ?? gapLabel(location, type)}
</dd>
</div>
))}
@@ -145,7 +165,7 @@ export function LocationList({
</p>
))}
{!location.coordinates.length && (
<p>Coordenadas não documentadas.</p>
<p>Coordenadas: {gapLabel(location, 'coordinates')}.</p>
)}
{publicReference(location.source_reference) && (
<p className="text-sm">
@@ -161,7 +181,8 @@ export function LocationList({
)}
<p className="text-sm">
Data da fonte:{' '}
{location.source_date?.trim() || 'Não documentada'}
{location.source_date?.trim() ||
gapLabel(location, 'source_date')}
</p>
{uniquePresentation(location.boundaries ?? [], (b) =>
JSON.stringify([
@@ -194,7 +215,7 @@ export function LocationList({
</p>
))}
{!location.boundaries?.length && (
<p>Polígono não documentado.</p>
<p>Polígono: {gapLabel(location, 'polygon')}.</p>
)}
<Link
className="underline"
@@ -0,0 +1,154 @@
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { Management, button, control } from './shared';
import { api } from '@/pages/investment/shared';
type Item = {
dossier_id: string;
dossier: string;
location_id: string;
location: string;
field: string;
field_label: string;
status: string;
source_reference: string | null;
};
/** Mapa de erros 4.9: each empty field of a published record is checked against its source by a person. */
export default function InformationGaps({
items,
status,
statuses,
installed,
}: {
items: Item[];
status: string;
statuses: Record<string, string>;
installed: boolean;
}) {
return (
<Management title="Lacunas de informação nas fichas">
<p>
Cada campo vazio das fichas publicadas é mostrado ao investidor
com o estado indicado aqui. Compare com o documento de origem e
indique se a informação não consta da fonte ou se consta e falta
carregá-la no portal. O portal não decide isto sozinho.
</p>
{!installed && (
<p role="status">
O registo de lacunas ainda não está instalado neste ambiente
(migração por executar).
</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/lacunas?status=${key}`}
>
{label}
</Link>
),
)}
</nav>
{items.length === 0 ? (
<p>Sem lacunas neste estado.</p>
) : (
<ul className="space-y-3">
{items.map((item) => (
<GapRow
key={`${item.dossier_id}:${item.location_id}:${item.field}`}
item={item}
statuses={statuses}
/>
))}
</ul>
)}
</Management>
);
}
function GapRow({
item,
statuses,
}: {
item: Item;
statuses: Record<string, string>;
}) {
const [value, setValue] = useState(item.status);
const [note, setNote] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
return (
<li className="rounded border p-3">
<p>
<Link
className="font-semibold underline"
href={`/carteira/${item.dossier_id}`}
>
{item.dossier}
</Link>{' '}
· {item.location} · <strong>{item.field_label}</strong>
</p>
<div className="mt-2 flex flex-wrap items-end gap-2">
<label className="grid gap-1 text-sm">
Estado
<select
className={control}
value={value}
onChange={(e) => setValue(e.target.value)}
>
{Object.entries(statuses).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</label>
<label className="grid min-w-64 flex-1 gap-1 text-sm">
Nota (o que foi consultado)
<input
className={control}
value={note}
maxLength={2000}
onChange={(e) => setNote(e.target.value)}
/>
</label>
<button
type="button"
className={button}
disabled={busy || value === item.status}
onClick={async () => {
setBusy(true);
setError('');
try {
await api('/management/lacunas', {
dossier_id: item.dossier_id,
location_id: item.location_id,
field: item.field,
status: value,
note,
});
router.reload();
} catch (cause) {
setError(
cause instanceof Error
? cause.message
: 'Não foi possível guardar.',
);
} finally {
setBusy(false);
}
}}
>
{busy ? 'A guardar…' : 'Guardar'}
</button>
</div>
{error && <p role="alert">{error}</p>}
</li>
);
}
+1
View File
@@ -78,6 +78,7 @@ export function Management({
Revisão da origem das oportunidades
</Link>
<Link href="/management/history">Histórico</Link>
<Link href="/management/lacunas">Lacunas nas fichas</Link>
<Link href="/management/demography">Demografia INE</Link>
<Link href="/management/crm/leads">CRM</Link>
<Link href="/management/crm/investors">Investidores</Link>
+6
View File
@@ -23,6 +23,7 @@ use App\Http\Controllers\EducationController;
use App\Http\Controllers\EducationDeclarationDraftController;
use App\Http\Controllers\EducationInvestmentController;
use App\Http\Controllers\GlobalSearchController;
use App\Http\Controllers\InformationGapController;
use App\Http\Controllers\InvestmentCoordinatesController;
use App\Http\Controllers\InvestmentDiscoveryController;
use App\Http\Controllers\InvestmentPortfolioController;
@@ -170,6 +171,11 @@ Route::middleware(['auth', 'verified'])->group(function () {
require __DIR__.'/settings.php';
require __DIR__.'/investment.php';
require __DIR__.'/land-assistance.php';
Route::middleware(['auth', 'verified', 'can:manage-portal', PrivateInvestmentResponse::class, 'throttle:60,1'])->group(function () {
// Mapa de erros 4.9: empty fields of published records, checked against their sources.
Route::get('/management/lacunas', [InformationGapController::class, 'index'])->name('management.information-gaps');
Route::post('/management/lacunas', [InformationGapController::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 () {
Route::get('/', [ProductExperimentController::class, 'index']);
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace Tests\Feature;
use App\Models\InvestmentDossier;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\Support\AuthenticatesQaActors;
use Tests\TestCase;
final class InformationGapsTest extends TestCase
{
use AuthenticatesQaActors;
use RefreshDatabase;
public function test_empty_record_fields_are_shown_with_their_verification_state_and_reviewed_by_the_team(): void
{
// Mapa de erros 4.9, decisão do proprietário: mostrar os campos vazios e verificar se é omissão ou falta de informação.
$this->withoutVite();
$ids = [];
$parent = null;
foreach (['country' => 'SYNTHETIC Moçambique', 'province' => 'SYNTHETIC Zambézia', 'district' => 'SYNTHETIC Mocuba'] as $type => $name) {
$id = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $id, 'parent_id' => $parent, 'name' => $name, 'code' => $id, 'location_type' => $type,
'source_system' => 'cartografia-workbook', 'data_classification' => 'public',
'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:QA:'.$id]);
$ids[$type] = $parent = $id;
}
[$province, $district] = [$ids['province'], $ids['district']];
$project = (string) Str::uuid();
DB::table('projects')->insert(['id' => $project, 'code' => 'SYNTHETIC-MOCUBA', 'name' => 'Projecto fictício', 'status' => 'draft',
'primary_territory_id' => $district, 'metadata' => '{}', 'data_classification' => 'public']);
$dossier = InvestmentDossier::create(['project_id' => $project, 'title' => 'SYNTHETIC Cidadela', 'source' => 'Synthetic fixture only', 'content' => [],
'publication_status' => 'published', 'published_at' => now()->subMinute(), 'data_classification' => 'public',
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA fixture only']);
$gaps = fn () => collect($this->get('/carteira/'.$dossier->id)->assertOk()->viewData('page')['props']['geography']['locations'])->firstWhere('id', $district)['gaps'];
$this->assertSame(['admin_post' => 'to_verify', 'locality' => 'to_verify', 'coordinates' => 'to_verify', 'polygon' => 'to_verify', 'source_date' => 'to_verify'], $gaps());
$manager = User::factory()->create();
config(['portal.managers' => [$manager->email]]);
$this->actingAsWithMfa($manager);
$this->actingAs($manager)->getJson('/management/lacunas')->assertOk()->assertJsonCount(5, 'items')->assertJsonPath('items.0.dossier', 'SYNTHETIC Cidadela');
$this->postJson('/management/lacunas', ['dossier_id' => $dossier->id, 'location_id' => $district, 'field' => 'admin_post', 'status' => 'not_in_source',
'note' => 'Documento de origem consultado: não indica o posto administrativo.'])->assertOk();
$this->postJson('/management/lacunas', ['dossier_id' => $dossier->id, 'location_id' => $district, 'field' => 'coordinates', 'status' => 'missing_in_portal'])->assertOk();
$this->postJson('/management/lacunas', ['dossier_id' => $dossier->id, 'location_id' => $province, 'field' => 'admin_post', 'status' => 'not_in_source'])->assertUnprocessable();
$this->getJson('/management/lacunas')->assertOk()->assertJsonCount(3, 'items');
$this->getJson('/management/lacunas?status=not_in_source')->assertOk()->assertJsonCount(1, 'items');
$this->assertSame(1, DB::table('audit_events')->where('action', 'information_gap_reviewed')->where('entity_id', $dossier->id)->where('after_data->field', 'admin_post')->count());
$this->assertSame(['admin_post' => 'not_in_source', 'locality' => 'to_verify', 'coordinates' => 'missing_in_portal', 'polygon' => 'to_verify', 'source_date' => 'to_verify'], $gaps());
$this->postJson('/management/lacunas', ['dossier_id' => $dossier->id, 'location_id' => $district, 'field' => 'admin_post', 'status' => 'to_verify'])->assertOk();
$this->assertSame('to_verify', $gaps()['admin_post']);
$this->actingAs(User::factory()->create())->getJson('/management/lacunas')->assertForbidden();
}
}
@@ -65,9 +65,18 @@ void test('P16 shows every required unknown field without inventing territorial
);
assert.match(html, /Posto administrativo<\/dt><dd>N\u00e3o documentado/);
assert.match(html, /Localidade<\/dt><dd>N\u00e3o documentado/);
assert.match(html, /Coordenadas n\u00e3o documentadas/);
assert.match(html, /Pol\u00edgono n\u00e3o documentado/);
assert.match(html, /Data da fonte: N\u00e3o documentada/);
assert.match(
html,
/Coordenadas: N\u00e3o documentado — por verificar na fonte/,
);
assert.match(
html,
/Pol\u00edgono: N\u00e3o documentado — por verificar na fonte/,
);
assert.match(
html,
/Data da fonte: N\u00e3o documentado — por verificar na fonte/,
);
assert.ok(!html.includes('programacao.docx'));
assert.equal(JSON.stringify(row), before);
});
@@ -83,8 +92,12 @@ void test('P16 shows a confirmed source date once and treats empty dates as undo
);
if (value.trim()) {
assert.equal((html.match(/2026-11-01/g) || []).length, 1);
assert.ok(!html.includes('Data da fonte: N\u00e3o documentada'));
} else assert.match(html, /Data da fonte: N\u00e3o documentada/);
assert.ok(!html.includes('Data da fonte: N\u00e3o documentado'));
} else
assert.match(
html,
/Data da fonte: N\u00e3o documentado — por verificar na fonte/,
);
assert.equal(row.source_date, value);
}
});