diff --git a/app/Http/Controllers/InformationGapController.php b/app/Http/Controllers/InformationGapController.php new file mode 100644 index 00000000..8942d89b --- /dev/null +++ b/app/Http/Controllers/InformationGapController.php @@ -0,0 +1,31 @@ +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]); + } +} diff --git a/app/Http/Controllers/InvestmentPortfolioController.php b/app/Http/Controllers/InvestmentPortfolioController.php index 2e2f7569..4be9da80 100644 --- a/app/Http/Controllers/InvestmentPortfolioController.php +++ b/app/Http/Controllers/InvestmentPortfolioController.php @@ -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]); } diff --git a/app/Services/InformationGaps.php b/app/Services/InformationGaps.php new file mode 100644 index 00000000..8fa1ea1e --- /dev/null +++ b/app/Services/InformationGaps.php @@ -0,0 +1,138 @@ + '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> 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 $geography + * @return array + */ + 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 $location + * @return list + */ + 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> */ + 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 $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)]); + }); + } +} diff --git a/database/migrations/2026_12_05_100000_create_information_gaps.php b/database/migrations/2026_12_05_100000_create_information_gaps.php new file mode 100644 index 00000000..1d4234b0 --- /dev/null +++ b/database/migrations/2026_12_05_100000_create_information_gaps.php @@ -0,0 +1,37 @@ +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'); + } +}; diff --git a/resources/js/components/structure-geography.tsx b/resources/js/components/structure-geography.tsx index 3f908a02..f771fc82 100644 --- a/resources/js/components/structure-geography.tsx +++ b/resources/js/components/structure-geography.tsx @@ -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; }; 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 = { + 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 = { opportunity: 'Localização declarada da oportunidade', primary: 'Localização principal', @@ -93,7 +113,7 @@ export function LocationList({
{location.path.find( (node) => node.location_type === type, - )?.name ?? 'Não documentado'} + )?.name ?? gapLabel(location, type)}
))} @@ -145,7 +165,7 @@ export function LocationList({

))} {!location.coordinates.length && ( -

Coordenadas não documentadas.

+

Coordenadas: {gapLabel(location, 'coordinates')}.

)} {publicReference(location.source_reference) && (

@@ -161,7 +181,8 @@ export function LocationList({ )}

Data da fonte:{' '} - {location.source_date?.trim() || 'Não documentada'} + {location.source_date?.trim() || + gapLabel(location, 'source_date')}

{uniquePresentation(location.boundaries ?? [], (b) => JSON.stringify([ @@ -194,7 +215,7 @@ export function LocationList({

))} {!location.boundaries?.length && ( -

Polígono não documentado.

+

Polígono: {gapLabel(location, 'polygon')}.

)} ; + installed: boolean; +}) { + return ( + +

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

+ {!installed && ( +

+ O registo de lacunas ainda não está instalado neste ambiente + (migração por executar). +

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

Sem lacunas neste estado.

+ ) : ( +
    + {items.map((item) => ( + + ))} +
+ )} +
+ ); +} + +function GapRow({ + item, + statuses, +}: { + item: Item; + statuses: Record; +}) { + const [value, setValue] = useState(item.status); + const [note, setNote] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + return ( +
  • +

    + + {item.dossier} + {' '} + · {item.location} · {item.field_label} +

    +
    + + + +
    + {error &&

    {error}

    } +
  • + ); +} diff --git a/resources/js/pages/management/shared.tsx b/resources/js/pages/management/shared.tsx index a30fc3a0..0901a0ad 100644 --- a/resources/js/pages/management/shared.tsx +++ b/resources/js/pages/management/shared.tsx @@ -78,6 +78,7 @@ export function Management({ Revisão da origem das oportunidades Histórico + Lacunas nas fichas Demografia INE CRM Investidores diff --git a/routes/web.php b/routes/web.php index a722dce1..b3ce589a 100644 --- a/routes/web.php +++ b/routes/web.php @@ -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']); diff --git a/tests/Feature/InformationGapsTest.php b/tests/Feature/InformationGapsTest.php new file mode 100644 index 00000000..bd959990 --- /dev/null +++ b/tests/Feature/InformationGapsTest.php @@ -0,0 +1,60 @@ +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(); + } +} diff --git a/tests/frontend/territorial-unknown-fields.test.mjs b/tests/frontend/territorial-unknown-fields.test.mjs index 4b3bb9f5..6f65144f 100644 --- a/tests/frontend/territorial-unknown-fields.test.mjs +++ b/tests/frontend/territorial-unknown-fields.test.mjs @@ -65,9 +65,18 @@ void test('P16 shows every required unknown field without inventing territorial ); assert.match(html, /Posto administrativo<\/dt>
    N\u00e3o documentado/); assert.match(html, /Localidade<\/dt>
    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); } });