merge: retain installed funding correction alongside isolated sector QA

This commit is contained in:
2026-11-15 20:32:04 +02:00
13 changed files with 858 additions and 764 deletions
@@ -68,6 +68,17 @@ final class FundingCriteriaCoherenceTest extends TestCase
$this->getJson('/api/v1/investment/territory-options?type=district&parent_id='.$this->geo['province'])->assertOk()->assertJsonCount(1, 'data');
}
public function test_physical_search_defaults_to_documented_presence_but_preserves_explicit_unknown_choice(): void
{
$local = $this->publish('qa-local');
$this->publish('qa-unlocated', overrides: ['locations' => []]);
$filters = ['q' => 'SYNTHETIC qa-', 'location_mode' => 'physical', 'territory' => $this->geo['province']];
$this->get('/fundos?'.http_build_query($filters))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'documented')->has('items.data', 1)->where('items.data.0.id', $local));
$this->get('/fundos?'.http_build_query([...$filters, 'certainty' => 'include_unknown']))->assertOk()->assertInertia(fn ($page) => $page
->where('filters.certainty', 'include_unknown')->has('items.data', 2));
}
public function test_contradictory_type_or_record_kind_and_incomplete_hierarchy_are_rejected(): void
{
foreach ([['category' => 'banking', 'institution_type' => 'broker'], ['category' => 'banking', 'institution_type' => 'commercial_bank', 'kind' => 'fund', 'location_mode' => 'physical'], ['district_id' => $this->geo['district']]] as $filters) {
@@ -1,26 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import React from 'react';
import ts from 'typescript';
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import { createRequire } from "node:module";
import { compileFunction } from "node:vm";
import React from "react";
import ts from "typescript";
const require = createRequire(import.meta.url);
const nodes = (tree) =>
Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
: tree && typeof tree === "object"
? [tree, ...nodes(tree.props?.children)]
: [];
const text = (tree) =>
Array.isArray(tree)
? tree.map(text).join('')
? tree.map(text).join("")
: tree?.props
? text(tree.props.children)
: typeof tree === 'string'
: typeof tree === "string"
? tree
: '';
: "";
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
function harness(filters, errors = {}) {
@@ -32,8 +32,7 @@ function harness(filters, errors = {}) {
return [
memory[id],
(next) => {
memory[id] =
typeof next === 'function' ? next(memory[id]) : next;
memory[id] = typeof next === "function" ? next(memory[id]) : next;
},
];
};
@@ -41,10 +40,7 @@ function harness(filters, errors = {}) {
let form;
const TerritoryFields = () => null;
const module = { exports: {} };
const source = fs.readFileSync(
'resources/js/pages/funding/index.tsx',
'utf8',
);
const source = fs.readFileSync("resources/js/pages/funding/index.tsx", "utf8");
compileFunction(
ts.transpileModule(source, {
compilerOptions: {
@@ -52,10 +48,10 @@ function harness(filters, errors = {}) {
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText,
['require', 'module', 'exports'],
["require", "module", "exports"],
)(
(id) => {
if (id === 'react')
if (id === "react")
return {
...React,
useState: state,
@@ -64,9 +60,9 @@ function harness(filters, errors = {}) {
return value;
},
};
if (id === '@inertiajs/react')
if (id === "@inertiajs/react")
return {
Link: 'a',
Link: "a",
useForm(initial) {
const [data, set] = state(initial);
form = {
@@ -74,11 +70,7 @@ function harness(filters, errors = {}) {
errors: {},
processing: false,
setData(key, value) {
set(
typeof key === 'string'
? { ...data, [key]: value }
: key,
);
set(typeof key === "string" ? { ...data, [key]: value } : key);
},
get(url) {
submitted = { url, data };
@@ -87,25 +79,22 @@ function harness(filters, errors = {}) {
return form;
},
};
if (id === '@/pages/investment/shared')
return { Frame: 'main', card: '', button: '' };
if (id === '@/components/funding-classification')
if (id === "@/pages/investment/shared") return { Frame: "main", card: "", button: "" };
if (id === "@/components/funding-classification")
return {
financialCategories: {
banking: 'Banca',
insurance_intermediation: 'Mediação de seguros',
banking: "Banca",
insurance_intermediation: "Mediação de seguros",
},
financialTypes: {
commercial_bank: 'Banco comercial',
broker: 'Corretora',
other: 'Outro',
commercial_bank: "Banco comercial",
broker: "Corretora",
other: "Outro",
},
};
if (id === '@/components/investment-territory')
return { TerritoryFields };
if (id === '@/components/funding-institution')
return { InstitutionView: 'article' };
if (id === './shared') return { windowLabels: {} };
if (id === "@/components/investment-territory") return { TerritoryFields };
if (id === "@/components/funding-institution") return { InstitutionView: "article" };
if (id === "./shared") return { windowLabels: {} };
return require(id);
},
module,
@@ -116,11 +105,11 @@ function harness(filters, errors = {}) {
criteriaErrors: errors,
items: { data: [], links: [] },
options: { sectors: [], territories: [] },
kinds: { institution: 'Instituição', fund: 'Fundo' },
kinds: { institution: "Instituição", fund: "Fundo" },
management: false,
categoryTypes: {
banking: ['commercial_bank'],
insurance_intermediation: ['broker'],
banking: ["commercial_bank"],
insurance_intermediation: ["broker"],
},
};
let tree;
@@ -131,11 +120,9 @@ function harness(filters, errors = {}) {
return tree;
}
const select = (label) =>
nodes(
nodes(tree).find(
(n) => n.type === 'label' && text(n).startsWith(label),
),
).find((n) => n.type === 'select');
nodes(nodes(tree).find((n) => n.type === "label" && text(n).startsWith(label))).find(
(n) => n.type === "select",
);
render();
return {
render,
@@ -147,76 +134,92 @@ function harness(filters, errors = {}) {
};
}
test('institution category restricts types and removes only an incompatible dependent choice', () => {
test("institution category restricts types and removes only an incompatible dependent choice", () => {
const h = harness({
category: 'insurance_intermediation',
institution_type: 'broker',
sector: '7',
need: 'investment',
territory: 'district-qa',
category: "insurance_intermediation",
institution_type: "broker",
sector: "7",
need: "investment",
territory: "district-qa",
});
h.select('Categoria da instituição').props.onChange({
target: { value: 'banking' },
h.select("Categoria da instituição").props.onChange({
target: { value: "banking" },
});
h.render();
assert.equal(h.form().data.institution_type, '');
assert.equal(h.form().data.institution_type, "");
for (const [key, value] of Object.entries({
sector: '7',
need: 'investment',
territory: 'district-qa',
sector: "7",
need: "investment",
territory: "district-qa",
}))
assert.equal(h.form().data[key], value);
assert.deepEqual(
nodes(h.select('Tipo de instituição'))
.filter((n) => n.type === 'option')
nodes(h.select("Tipo de instituição"))
.filter((n) => n.type === "option")
.map((n) => n.props.value),
['', 'commercial_bank', 'other'],
["", "commercial_bank", "other"],
);
assert.match(text(h.tree()), /tipo anterior não pertence/);
const results = nodes(h.tree()).find((n) => n.type === 'details');
const results = nodes(h.tree()).find((n) => n.type === "details");
assert.equal(results.props.open, false);
assert.match(text(results), /pesquisa anterior/);
});
test('contradictory record criteria remain explicit until the user chooses a correction', () => {
test("contradictory record criteria remain explicit until the user chooses a correction", () => {
const h = harness(
{
kind: 'fund',
category: 'banking',
institution_type: 'commercial_bank',
location_mode: 'physical',
province_id: 'province-qa',
sector: '8',
state: 'closed',
certainty: 'documented',
kind: "fund",
category: "banking",
institution_type: "commercial_bank",
location_mode: "physical",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
},
{ kind: ['Combinação incompatível.'] },
{ kind: ["Combinação incompatível."] },
);
assert.match(text(h.tree()), /A pesquisa não foi executada/);
assert.equal(h.form().data.kind, 'fund');
assert.equal(h.form().data.kind, "fund");
const action = nodes(h.tree()).find(
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)),
(n) => n.type === "button" && /Manter o fundo/.test(text(n)),
);
action.props.onClick();
h.render();
assert.equal(h.form().data.category, '');
assert.equal(h.form().data.institution_type, '');
assert.equal(h.form().data.location_mode, 'coverage');
assert.equal(h.form().data.category, "");
assert.equal(h.form().data.institution_type, "");
assert.equal(h.form().data.location_mode, "coverage");
for (const [key, value] of Object.entries({
kind: 'fund',
province_id: 'province-qa',
sector: '8',
state: 'closed',
certainty: 'documented',
kind: "fund",
province_id: "province-qa",
sector: "8",
state: "closed",
certainty: "documented",
}))
assert.equal(h.form().data[key], value);
nodes(h.tree())
.find((n) => n.type === 'form')
.find((n) => n.type === "form")
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted().url, '/fundos');
assert.equal(h.submitted().data.province_id, 'province-qa');
assert.ok(
h.territory(),
'the catalogue consumes the common hierarchical location control',
);
assert.equal(h.submitted().url, "/fundos");
assert.equal(h.submitted().data.province_id, "province-qa");
assert.ok(h.territory(), "the catalogue consumes the common hierarchical location control");
});
test("local search defaults to documented presence and keeps the explicit unknown option and chosen territory", () => {
const h = harness({ territory: "district-qa", sector: "7" });
h.select("Localização a pesquisar").props.onChange({ target: { value: "physical" } });
h.render();
assert.equal(h.form().data.certainty, "documented");
assert.equal(h.form().data.territory, "district-qa");
assert.equal(h.form().data.sector, "7");
h.select("Informação por confirmar").props.onChange({ target: { value: "include_unknown" } });
h.render();
assert.equal(h.form().data.certainty, "include_unknown");
const resumed = harness({
location_mode: "physical",
territory: "district-qa",
certainty: "include_unknown",
});
assert.equal(resumed.form().data.certainty, "include_unknown");
assert.equal(harness({ location_mode: "physical" }).form().data.certainty, "documented");
});
@@ -1,32 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
import * as presentation from '../../resources/js/lib/funding-public-presentation.ts';
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { compileFunction } from "node:vm";
import { createRequire } from "node:module";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import ts from "typescript";
import * as presentation from "../../resources/js/lib/funding-public-presentation.ts";
const require = createRequire(import.meta.url),
records = Object.values(
JSON.parse(
fs.readFileSync(
new URL(
'../../database/data/funding-institutions-nov2026.json',
import.meta.url,
),
'utf8',
new URL("../../database/data/funding-institutions-nov2026.json", import.meta.url),
"utf8",
),
).references,
).map((x) => x.draft);
function load(file) {
const module = { exports: {} };
const output = ts.transpileModule(
fs.readFileSync(
new URL('../../resources/js/' + file, import.meta.url),
'utf8',
),
fs.readFileSync(new URL("../../resources/js/" + file, import.meta.url), "utf8"),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
@@ -35,98 +29,89 @@ function load(file) {
},
},
).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
compileFunction(output, ["require", "module", "exports"])(
(name) =>
name === '@/lib/funding-public-presentation'
name === "@/lib/funding-public-presentation"
? presentation
: name === '@/pages/investment/shared'
: name === "@/pages/investment/shared"
? {
Frame: ({ title, children }) =>
React.createElement(
'main',
"main",
null,
React.createElement('h1', null, title),
React.createElement("h1", null, title),
children,
),
card: 'card',
button: 'button',
input: 'input',
card: "card",
button: "button",
input: "input",
}
: name === '@inertiajs/react'
: name === "@inertiajs/react"
? {
Link: ({ children, href }) =>
React.createElement('a', { href }, children),
React.createElement("a", { href }, children),
router: {},
useForm: (data) => ({ data, errors: {}, setData() {}, get() {} }),
}
: name === './shared'
: name === "./shared"
? { windowLabels: {} }
: name === '@/lib/portal-api'
: name === "@/lib/portal-api"
? {
portalRequest: () => {
throw Error(
'Read-only rendering must not send requests',
);
throw Error("Read-only rendering must not send requests");
},
}
: name === '@/components/funding-classification'
? load('components/funding-classification.tsx')
: name === '@/components/funding-institution'
? load('components/funding-institution.tsx')
: name === '@/components/funding-dossier-choice'
: name === "@/components/funding-classification"
? load("components/funding-classification.tsx")
: name === "@/components/funding-institution"
? load("components/funding-institution.tsx")
: name === "@/components/funding-dossier-choice"
? { FundingDossierChoice: () => null }
: name ===
'@/components/funding-criteria-assessment'
? load(
'components/funding-criteria-assessment.tsx',
)
: name === "@/components/funding-criteria-assessment"
? load("components/funding-criteria-assessment.tsx")
: resolveLocal(name, file),
module,
module.exports,
);
return module.exports;
}
test('all270 imported institutions get readable descriptions and evidenced services without changing the published payload', () => {
test("all270 imported institutions get readable descriptions and evidenced services without changing the published payload", () => {
assert.equal(records.length, 270);
for (const p of records) {
const original = JSON.stringify(p),
m = presentation.fundingPublicPresentation(p);
assert.ok(m.description);
assert.doesNotMatch(
m.description,
/documento fornecido|ficha|SHA-256|Público\/finalidade/,
);
assert.doesNotMatch(m.description, /documento fornecido|ficha|SHA-256|Público\/finalidade/);
assert.equal(JSON.stringify(p), original);
assert.equal(
m.products.length,
(p.products ?? []).filter((x) => x.availability !== 'closed')
.length,
(p.products ?? []).filter((x) => x.availability !== "closed").length,
);
}
});
test('deliberate editorial descriptions survive and missing products are never fabricated', () => {
test("deliberate editorial descriptions survive and missing products are never fabricated", () => {
const m = presentation.fundingPublicPresentation({
title: 'Example',
kind: 'institution',
summary: 'Apoio especializado ao investimento rural.',
title: "Example",
kind: "institution",
summary: "Apoio especializado ao investimento rural.",
products: [],
institution_types: ['insurer'],
institution_types: ["insurer"],
});
assert.equal(m.description, 'Apoio especializado ao investimento rural.');
assert.equal(m.description, "Apoio especializado ao investimento rural.");
assert.deepEqual(m.products, []);
assert.deepEqual(m.services, []);
});
test('actual public cards and detail lead with description/products and keep import metadata out of the visitor text', () => {
const Index = load('pages/funding/index.tsx').default,
Show = load('pages/funding/show.tsx').default;
test("actual public cards and detail lead with description/products and keep import metadata out of the visitor text", () => {
const Index = load("pages/funding/index.tsx").default,
Show = load("pages/funding/show.tsx").default;
for (const raw of [
records[0],
records.find((p) => p.institution_types.includes('investment_manager')),
records.find((p) => p.institution_types.includes("investment_manager")),
]) {
const p = { ...raw, windows: [], documents: [] },
item = {
id: 'synthetic',
version_id: 'synthetic-version',
id: "synthetic",
version_id: "synthetic-version",
version: 1,
payload: p,
};
@@ -152,23 +137,15 @@ test('actual public cards and detail lead with description/products and keep imp
/ficha|documento fornecido|SHA-256|linha de origem|Instituições financeiras em Moçambique\.docx/i,
);
assert.match(html, /Produtos e serviços/);
assert.match(
html,
new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
);
assert.match(html, new RegExp(raw.title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
}
const out = new URL(
'../../outputs/funding-public-editorial-20261111/',
import.meta.url,
);
const out = new URL("../../outputs/funding-public-editorial-20261111/", import.meta.url);
fs.mkdirSync(out, { recursive: true });
const name = p.products.length
? 'bank-with-products'
: 'investment-manager';
fs.writeFileSync(new URL(name + '-index.html', out), index);
fs.writeFileSync(new URL(name + '-detail.html', out), detail);
const name = p.products.length ? "bank-with-products" : "investment-manager";
fs.writeFileSync(new URL(name + "-index.html", out), index);
fs.writeFileSync(new URL(name + "-detail.html", out), detail);
fs.writeFileSync(
new URL('verification.json', out),
new URL("verification.json", out),
JSON.stringify(
{
publishedSourceRecords: 270,
@@ -189,21 +166,18 @@ test('actual public cards and detail lead with description/products and keep imp
}
});
test('Quorus and Moza use one shared clean profile in both list and detail', () => {
const Index = load('pages/funding/index.tsx').default,
Show = load('pages/funding/show.tsx').default;
const out = new URL(
'../../outputs/funding-uniform-menu-20261111/',
import.meta.url,
);
test("Quorus and Moza use one shared clean profile in both list and detail", () => {
const Index = load("pages/funding/index.tsx").default,
Show = load("pages/funding/show.tsx").default;
const out = new URL("../../outputs/funding-uniform-menu-20261111/", import.meta.url);
fs.mkdirSync(out, { recursive: true });
for (const title of ['Quorus', 'Moza Banco']) {
for (const title of ["Quorus", "Moza Banco"]) {
const raw = records.find((p) => p.title === title);
assert.ok(raw, title);
const p = { ...raw, windows: [], documents: [] },
item = {
id: 'synthetic',
version_id: 'synthetic-version',
id: "synthetic",
version_id: "synthetic-version",
version: 1,
payload: p,
};
@@ -224,8 +198,7 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
}),
);
for (const html of [
index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ??
index,
index.match(/<article class="card">([\s\S]*?)<\/article>/)?.[0] ?? index,
detail,
]) {
assert.doesNotMatch(
@@ -235,62 +208,38 @@ test('Quorus and Moza use one shared clean profile in both list and detail', ()
assert.equal((html.match(/Produtos e serviços/g) || []).length, 1);
assert.equal((html.match(/Descrição/g) || []).length, 1);
}
if (title === 'Quorus') {
assert.equal(
(detail.match(/Entidade de corretagem de seguros/g) || [])
.length,
1,
);
assert.doesNotMatch(
detail,
/<h3[^>]*>Contactos|<h3[^>]*>Localização/,
);
if (title === "Quorus") {
assert.equal((detail.match(/Entidade de corretagem de seguros/g) || []).length, 1);
assert.doesNotMatch(detail, /<h3[^>]*>Contactos|<h3[^>]*>Localização/);
} else {
assert.equal((detail.match(/21 342 000/g) || []).length, 1);
assert.equal((detail.match(/Rua dos Desportistas/g) || []).length, 1);
assert.equal(
(detail.match(/Rua dos Desportistas/g) || []).length,
1,
);
assert.equal(
(
detail.match(
/Tesouraria, investimento, construção e equipamento/g,
) || []
).length,
(detail.match(/Tesouraria, investimento, construção e equipamento/g) || []).length,
1,
);
assert.doesNotMatch(detail, /500\.000|30\.000\.000|Prime|spread/);
}
fs.writeFileSync(
new URL(title.replaceAll(' ', '-') + '-index.html', out),
index,
);
fs.writeFileSync(
new URL(title.replaceAll(' ', '-') + '-detail.html', out),
detail,
);
fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-index.html", out), index);
fs.writeFileSync(new URL(title.replaceAll(" ", "-") + "-detail.html", out), detail);
}
});
test('contact and location deduplication preserves different branches and original records', () => {
const moza = records.find((p) => p.title === 'Moza Banco'),
test("contact and location deduplication preserves different branches and original records", () => {
const moza = records.find((p) => p.title === "Moza Banco"),
original = JSON.stringify(moza);
assert.equal(
presentation
.publicInstitutionContacts(moza.contacts)
.filter((c) => c.kind === 'phone').length,
1,
);
assert.equal(
presentation.publicInstitutionLocations(moza.locations).length,
presentation.publicInstitutionContacts(moza.contacts).filter((c) => c.kind === "phone")
.length,
1,
);
assert.equal(presentation.publicInstitutionLocations(moza.locations).length, 1);
assert.equal(
presentation.publicInstitutionLocations([
...moza.locations,
{
...moza.locations[0],
role: 'branch',
address: 'Rua dos Desportistas, número 714',
role: "branch",
address: "Rua dos Desportistas, número 714",
},
]).length,
2,
@@ -299,10 +248,68 @@ test('contact and location deduplication preserves different branches and origin
});
function resolveLocal(name, parent) {
if (name === './territory-geometry-preview') return { default: () => null };
const relative = name.startsWith('@/') ? name.slice(2) : name.startsWith('.') ? path.posix.join(path.posix.dirname(parent), name) : null;
if (relative) for (const candidate of [relative, relative + '.tsx', relative + '.ts']) {
if (fs.existsSync(new URL('../../resources/js/' + candidate, import.meta.url))) return load(candidate);
}
if (name === "./territory-geometry-preview") return { default: () => null };
const relative = name.startsWith("@/")
? name.slice(2)
: name.startsWith(".")
? path.posix.join(path.posix.dirname(parent), name)
: null;
if (relative)
for (const candidate of [relative, relative + ".tsx", relative + ".ts"]) {
if (fs.existsSync(new URL("../../resources/js/" + candidate, import.meta.url)))
return load(candidate);
}
return require(name);
}
test("physical presence matches descendants, not a broader province or unknown locations", () => {
const points = [
{
territory_id: "district-a",
territory_path: [
{ id: "province", name: "Province" },
{ id: "district-a", name: "A" },
],
evidence_status: "reported",
},
{
territory_id: "province",
territory_path: [{ id: "province", name: "Province" }],
evidence_status: "reported",
},
{ territory_id: "district-a", evidence_status: "to_confirm" },
{ territory_id: "district-a", evidence_status: "historical" },
{ territory_id: "" },
];
assert.deepEqual(presentation.matchingInstitutionLocations(points, "district-a"), [points[0]]);
assert.deepEqual(
presentation.matchingInstitutionLocations(points, "province"),
points.slice(0, 2),
);
assert.deepEqual(presentation.matchingInstitutionLocations(points, "elsewhere"), []);
});
test("compact institutions show local address and explicitly identify unconfirmed physical presence", () => {
const { InstitutionView } = load("components/funding-institution.tsx");
const value = {
...records[0],
locations: [
{
role: "branch",
address: "Balcão de Tete",
territory_id: "tete",
territory_path: [{ id: "tete", name: "Tete" }],
},
{ role: "headquarters", address: "Sede Maputo", territory_id: "maputo" },
],
};
const render = (territory, compact = true) =>
renderToStaticMarkup(
React.createElement(InstitutionView, { value, compact, physicalTerritory: territory }),
);
assert.match(render("tete"), /Balcão de Tete/);
assert.doesNotMatch(render("tete"), /Sede Maputo|Presença física por confirmar/);
assert.match(render("niassa"), /Presença física por confirmar no local escolhido/);
assert.doesNotMatch(render("niassa"), /Balcão de Tete|Sede Maputo/);
assert.match(render("tete", false), /Sede Maputo/);
assert.match(render("tete", false), /Balcão de Tete/);
});