feat: add public resource and infrastructure evidence layers to catalogue map

This commit is contained in:
2026-11-04 11:16:01 +02:00
parent bbc05f1df6
commit 21ebad73e7
10 changed files with 860 additions and 5 deletions
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace Tests\Feature;
use App\Models\Opportunity;
use App\Models\User;
use App\Services\InvestmentGeography;
use App\Support\IsolatedQaDatabase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class InvestmentThematicMapTest extends TestCase
{
use DatabaseTransactions;
protected function setUp(): void
{
parent::setUp();
$this->assertTrue(IsolatedQaDatabase::allowsSchemaChanges());
$this->withoutVite();
$this->withoutMiddleware(ThrottleRequests::class);
}
private function proof(string $category = 'resource', string $purpose = 'local'): array
{
return ['id' => (string) Str::uuid(), 'category' => $category, 'purpose' => $purpose,
'statement' => 'SYNTHETIC QA documented observation', 'source' => 'Synthetic public source',
'locator' => 'Table QA', 'period' => '2026', 'scope' => 'Synthetic district',
'coverage' => 'Partial observation; no availability confirmed', 'verified_on' => '2026-10-01'];
}
private function record(string $prefix, array $proofs, ?string $territory = null): Opportunity
{
$record = Opportunity::create(['sector_id' => 1, 'reference' => 'QA-'.Str::uuid(), 'slug' => 'qa-'.Str::uuid(),
'title' => $prefix.' synthetic thematic map', 'status' => 'published', 'published_at' => now()->subMinute(),
'primary_territory_id' => $territory]);
$record->forceFill(['workflow_context' => ['promotional_summary' => ['projection' => ['proactive' => [
'evidence' => $proofs, 'state' => 'hypothesis', 'limitations' => 'SYNTHETIC QA scope only']]],
'private_evidence' => 'PRIVATE-DRAFT-MUST-NOT-LEAK']])->save();
return $record;
}
private function url(string $prefix, array $filters = []): string
{
return '/api/v1/investment/map?'.http_build_query(['q' => $prefix, ...$filters]);
}
public function test_only_selected_public_local_thematic_evidence_is_exposed_with_its_sources_and_limits(): void
{
$prefix = 'THEME-'.Str::uuid();
$record = $this->record($prefix, [$this->proof(), $this->proof('infrastructure'), $this->proof('resource', 'methodology'), $this->proof('demand')]);
$before = $record->fresh()->getRawOriginal('workflow_context');
$response = $this->getJson($this->url($prefix))->assertOk()->assertJsonPath('matched_count', 1)
->assertJsonPath('thematic_records.0.id', $record->id)->assertJsonCount(2, 'thematic_records.0.evidence')
->assertJsonPath('thematic_records.0.evidence.0.source', 'Synthetic public source')
->assertJsonPath('thematic_records.0.evidence.0.period', '2026')
->assertJsonPath('thematic_records.0.evidence.0.scope', 'Synthetic district')
->assertJsonPath('thematic_records.0.state', 'hypothesis')->assertJsonCount(0, 'features')->assertJsonCount(1, 'unlocated');
$this->assertStringNotContainsString('PRIVATE-DRAFT-MUST-NOT-LEAK', $response->getContent());
$this->assertSame($before, $record->fresh()->getRawOriginal('workflow_context'));
}
public function test_unpublished_future_restricted_and_unselected_private_evidence_are_not_disclosed(): void
{
$prefix = 'THEME-'.Str::uuid();
$draft = $this->record($prefix, [$this->proof()]);
$draft->update(['status' => 'draft']);
$future = $this->record($prefix, [$this->proof()]);
$future->update(['published_at' => now()->addDay()]);
$restricted = $this->record($prefix, [$this->proof()]);
$restricted->forceFill(['owner_user_id' => User::factory()->create()->id])->save();
$private = $this->record($prefix, []);
$private->forceFill(['workflow_context' => ['private_evidence' => [$this->proof()]]])->save();
$this->getJson($this->url($prefix))->assertOk()->assertJsonPath('matched_count', 1)->assertJsonCount(0, 'thematic_records');
}
public function test_thematic_records_follow_the_same_province_and_district_filters_without_inventing_coordinates(): void
{
$prefix = 'THEME-'.Str::uuid();
$geo = app(InvestmentGeography::class);
$districts = $geo->publicReferences()->where('location_type', 'district')->get(['id', 'parent_id']);
$district = $districts->first();
$other = $districts->first(fn ($row) => $row->parent_id !== $district->parent_id);
$this->assertNotNull($other);
$record = $this->record($prefix, [$this->proof()], $district->id);
$this->record($prefix, [$this->proof('infrastructure')], $other->id);
foreach ([['province_id' => $district->parent_id], ['province_id' => $district->parent_id, 'district_id' => $district->id]] as $filters) {
$this->getJson($this->url($prefix, $filters))->assertOk()->assertJsonPath('matched_count', 1)
->assertJsonCount(1, 'thematic_records')->assertJsonPath('thematic_records.0.id', $record->id)
->assertJsonCount(0, 'features')->assertJsonCount(1, 'unlocated');
}
$this->assertNull($record->fresh()->district);
}
public function test_thematic_evidence_reuses_existing_site_coordinates_without_relocating_the_resource(): void
{
$prefix = 'THEME-'.Str::uuid();
$record = $this->record($prefix, [$this->proof()]);
$site = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $site, 'name' => 'Synthetic opportunity site', 'code' => $site,
'location_type' => 'site', 'data_classification' => 'public', 'source_system' => 'investment-site-editor']);
DB::insert("INSERT INTO geo_geometries(id,geo_location_id,geometry_type,geom,properties,data_classification) VALUES (?,?,'point',ST_SetSRID(ST_MakePoint(32.5,-25.9),4326),'{}'::jsonb,'public')", [(string) Str::uuid(), $site]);
$record->update(['primary_territory_id' => $site]);
$this->getJson($this->url($prefix))->assertOk()->assertJsonCount(1, 'features')
->assertJsonPath('features.0.geometry.coordinates', [32.5, -25.9])
->assertJsonPath('features.0.properties.id', $record->id)->assertJsonPath('thematic_records.0.id', $record->id);
$this->assertSame($site, $record->fresh()->primary_territory_id);
}
}
@@ -0,0 +1,278 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const Map = () => React.createElement('div', { 'data-test-map': true });
function setup() {
let theme;
let mounted = false;
const source = fs.readFileSync(
new URL(
'../../resources/js/components/thematic-investment-map.tsx',
import.meta.url,
),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === 'react'
? {
...React,
useEffect: (effect) => {
if (!mounted) {
mounted = true;
effect();
}
},
useState: (initial) => {
if (theme === undefined)
theme =
typeof initial === 'function'
? initial()
: initial;
return [
theme,
(next) => {
theme = next;
},
];
},
}
: name === './catalogue-investment-map'
? { default: Map }
: require(name),
module,
module.exports,
);
return (...args) => {
module.exports.default(...args);
return module.exports.default(...args);
};
}
const flat = (node) =>
!node || typeof node !== 'object'
? []
: [node, ...React.Children.toArray(node.props.children).flatMap(flat)];
const proof = (category) => ({
id: category,
category,
statement: '<script>synthetic</script>',
source: 'Synthetic source',
locator: 'Table 4',
period: '2024',
scope: 'District A',
coverage: 'Partial coverage',
verified_on: '2026-10-01',
});
const records = [
{
id: 1,
title: 'Resource fixture',
url: '/fixture/1',
location: 'District A',
state: 'hypothesis',
limitations: 'No availability confirmed',
evidence: [proof('resource')],
},
{
id: 2,
title: 'Infrastructure fixture',
url: '/fixture/2',
location: 'Province B',
state: 'hypothesis',
limitations: null,
evidence: [proof('infrastructure')],
},
];
const points = [1, 3].map((id) => ({
geometry: { coordinates: [32, -25] },
properties: {
id,
title: 'Site ' + id,
url: '/fixture/' + id,
location: 'Confirmed opportunity site',
},
}));
const areas = [1, 2, 3].map((id) => ({
opportunity_id: id,
title: 'Area ' + id,
geometry: { type: 'Polygon', coordinates: [] },
}));
const props = {
points,
areas,
records,
territoryId: 'province-a',
truncated: false,
};
test('default preserves every opportunity and one map, with sourced thematic evidence and no new location claims', () => {
const Component = setup(),
tree = Component(props),
nodes = flat(tree);
const map = nodes.find((node) => node.type === Map);
assert.equal(nodes.filter((node) => node.type === Map).length, 1);
assert.equal(map.props.points, points);
assert.equal(map.props.areas, areas);
assert.equal(map.props.territoryId, 'province-a');
const html = renderToStaticMarkup(tree);
for (const text of [
'Synthetic source',
'Table 4',
'2024',
'District A',
'Partial coverage',
'2026-10-01',
'não representam a posição exacta',
'não são inferidos',
])
assert.ok(html.includes(text), text);
assert.match(html, /2 fichas com evidência temática pública/);
assert.match(html, /1 sem ponto público utilizável/);
assert.doesNotMatch(html, /<script>/);
});
test('choosing resources filters existing points and opportunity areas, retaining administrative identity and source context', () => {
const Component = setup();
flat(Component(props))
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'resource' } });
const tree = Component(props),
map = flat(tree).find((node) => node.type === Map);
assert.deepEqual(map.props.points, [points[0]]);
assert.deepEqual(map.props.areas, [areas[0]]);
assert.equal(map.props.territoryId, 'province-a');
const html = renderToStaticMarkup(tree);
assert.match(html, /Resource fixture/);
assert.doesNotMatch(html, /Infrastructure fixture/);
flat(tree)
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'all' } });
assert.equal(
flat(Component(props)).find((node) => node.type === Map).props.points,
points,
);
});
test('infrastructure without confirmed coordinates remains consultable without borrowing another opportunity point', () => {
const Component = setup();
flat(Component(props))
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'infrastructure' } });
const tree = Component(props),
map = flat(tree).find((node) => node.type === Map);
assert.deepEqual(map.props.points, []);
assert.deepEqual(map.props.areas, [areas[1]]);
assert.match(renderToStaticMarkup(tree), /Infrastructure fixture/);
assert.match(renderToStaticMarkup(tree), /Sem ponto público utilizável/);
assert.ok(
flat(tree).some(
(node) => node.type === 'a' && node.props.href === '/fixture/2',
),
);
});
test('changing query data never retains previous evidence; loading and incomplete coverage are explicit', () => {
const Component = setup();
flat(Component(props))
.find((node) => node.type === 'select')
.props.onChange({ target: { value: 'resource' } });
const loading = Component({
...props,
records: [],
points: null,
areas: [],
});
assert.equal(
flat(loading).find((node) => node.type === Map).props.points,
null,
);
assert.equal(
flat(loading).find((node) => node.type === 'select').props.disabled,
true,
);
assert.doesNotMatch(renderToStaticMarkup(loading), /Resource fixture/);
const html = renderToStaticMarkup(
Component({
...props,
points: [],
records: [],
areas: [],
truncated: true,
}),
);
assert.match(html, /Sem evidência pública local/);
assert.match(html, /A resposta está limitada/);
assert.match(html, /não significa ausência do recurso/);
});
test('theme selection survives reload in the tab and unavailable or invalid storage does not break the map', () => {
const previous = globalThis.window;
let saved = 'resource';
globalThis.window = {
sessionStorage: {
getItem: () => saved,
setItem: (key, value) => {
assert.equal(key, 'investmoz-map-theme-v1');
saved = value;
},
},
};
try {
const Component = setup();
let select = flat(Component(props)).find(
(node) => node.type === 'select',
);
assert.equal(select.props.value, 'resource');
select.props.onChange({ target: { value: 'infrastructure' } });
assert.equal(saved, 'infrastructure');
assert.equal(
flat(setup()(props)).find((node) => node.type === 'select').props
.value,
'infrastructure',
);
saved = 'invalid';
assert.equal(
flat(setup()(props)).find((node) => node.type === 'select').props
.value,
'all',
);
globalThis.window = {
sessionStorage: {
getItem: () => {
throw new Error('Storage unavailable');
},
setItem: () => {
throw new Error('Storage unavailable');
},
},
};
const WithoutStorage = setup();
select = flat(WithoutStorage(props)).find(
(node) => node.type === 'select',
);
assert.equal(select.props.value, 'all');
select.props.onChange({ target: { value: 'resource' } });
assert.equal(
flat(WithoutStorage(props)).find((node) => node.type === 'select')
.props.value,
'resource',
);
} finally {
if (previous === undefined) delete globalThis.window;
else globalThis.window = previous;
}
});