Files
Investidor-V2/tests/frontend/funding-journey-coherence.test.mjs
T

406 lines
13 KiB
JavaScript

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, ...nodes(tree.props?.children)]
: [];
const text = (tree) =>
Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string'
? tree
: '';
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
function harness(filters, errors = {}, items = []) {
const memory = [];
let cursor = 0;
const state = (initial) => {
const id = cursor++;
if (!(id in memory)) memory[id] = initial;
return [
memory[id],
(next) => {
memory[id] =
typeof next === 'function' ? next(memory[id]) : next;
},
];
};
let submitted;
let form;
const TerritoryFields = () => null;
const module = { exports: {} };
const source = fs.readFileSync(
'resources/js/pages/funding/index.tsx',
'utf8',
);
compileFunction(
ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText,
['require', 'module', 'exports'],
)(
(id) => {
if (id === 'react')
return {
...React,
useState: state,
useRef(initial) {
const [value] = state({ current: initial });
return value;
},
};
if (id === '@inertiajs/react')
return {
Link: 'a',
useForm(initial) {
const [data, set] = state(initial);
form = {
data,
errors: {},
processing: false,
setData(key, value) {
set(
typeof key === 'string'
? { ...data, [key]: value }
: key,
);
},
get(url) {
submitted = { url, data };
},
};
return form;
},
};
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',
},
financialTypes: {
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: {} };
return require(id);
},
module,
module.exports,
);
const props = {
filters,
criteriaErrors: errors,
items: { data: items, links: [] },
options: { sectors: [], territories: [] },
kinds: { institution: 'Instituição', fund: 'Fundo' },
management: false,
categoryTypes: {
banking: ['commercial_bank'],
insurance_intermediation: ['broker'],
},
};
let tree;
function render() {
cursor = 0;
const wrapper = module.exports.default(props);
tree = wrapper.type(wrapper.props);
return tree;
}
const select = (label) =>
nodes(
nodes(tree).find(
(n) => n.type === 'label' && text(n).startsWith(label),
),
).find((n) => n.type === 'select');
render();
return {
render,
select,
form: () => form,
tree: () => tree,
submitted: () => submitted,
territory: () => nodes(tree).find((n) => n.type === TerritoryFields),
};
}
test('B03 broad coverage remains explicit and physical choice requests documented presence', () => {
const h = harness({
need: 'investment',
territory: '7d908cf8-6e52-5141-8832-b1193985e39f',
});
assert.equal(h.select('Localização a pesquisar').props.value, 'coverage');
h.select('Localização a pesquisar').props.onChange({
target: { value: 'physical' },
});
h.render();
assert.equal(h.form().data.location_mode, 'physical');
assert.equal(h.form().data.certainty, 'documented');
assert.match(
text(h.tree()),
/a cobertura indica onde o financiamento se aplica/,
);
});
test('B06 empty results omit institution alternatives and real result links keep exact identities', () => {
const filters = {
need: 'investment',
territory: '4aa31470-997e-5c63-8fe0-ff2f62586f56',
location_mode: 'physical',
};
const empty = harness(filters);
assert.match(text(empty.tree()), /Não foram encontradas instituições/);
assert.equal(
nodes(empty.tree()).filter(
(n) =>
n.props?.href?.startsWith('/fundos/') &&
n.props.href !== '/fundos/guardados',
).length,
0,
);
const fixture = JSON.parse(
fs.readFileSync(
'outputs/funding-b03-b06-20261120/fixture.json',
'utf8',
),
);
const originals = JSON.parse(
fs.readFileSync(
'database/data/funding-institutions-nov2026.json',
'utf8',
),
).references;
const items = Object.entries(fixture.records).map(([key, r]) => ({
id: r.id,
payload: originals[key].draft,
}));
const h = harness(filters, {}, items);
for (const item of items) {
const link = nodes(h.tree()).find(
(n) =>
text(n) === item.payload.title &&
n.props?.href?.startsWith('/fundos/'),
);
assert.ok(link, item.payload.title);
assert.ok(link.props.href.startsWith('/fundos/' + item.id + '?'));
assert.match(link.props.href, /location_mode=physical/);
}
});
void test('searching another province resets only the search location and preserves the investment scope', () => {
const filters = {
category: 'banking',
institution_type: 'commercial_bank',
need: 'investment',
context: 'case-qa',
opportunity: 'opportunity-qa',
province_id: 'province-qa',
district_id: 'district-qa',
territory: 'district-qa',
location_mode: 'physical',
certainty: 'documented',
};
const h = harness(filters);
const action = nodes(h.tree()).find(
(n) =>
n.type === 'button' &&
text(n) === 'Procurar instituição noutra província',
);
assert.ok(action);
action.props.onClick();
h.render();
for (const key of [
'territory',
'province_id',
'district_id',
'admin_post_id',
'locality_id',
])
assert.equal(h.form().data[key], '');
for (const key of [
'category',
'institution_type',
'need',
'context',
'opportunity',
'location_mode',
'certainty',
])
assert.equal(h.form().data[key], filters[key]);
assert.deepEqual(h.territory().props.initial, []);
assert.equal(h.submitted(), undefined);
assert.match(
text(h.tree()),
/a localização do investimento no dossier mantém-se/,
);
});
void 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',
});
h.select('Categoria da instituição').props.onChange({
target: { value: 'banking' },
});
h.render();
assert.equal(h.form().data.institution_type, '');
for (const [key, value] of Object.entries({
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')
.map((n) => n.props.value),
['', 'commercial_bank', 'other'],
);
assert.match(text(h.tree()), /tipo anterior não pertence/);
const results = nodes(h.tree()).find((n) => n.type === 'details');
assert.equal(results.props.open, false);
assert.match(text(results), /pesquisa anterior/);
});
void 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',
need: 'investment',
},
{ kind: ['Combinação incompatível.'] },
);
assert.match(text(h.tree()), /A pesquisa não foi executada/);
assert.equal(h.form().data.kind, 'fund');
const action = nodes(h.tree()).find(
(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');
for (const [key, value] of Object.entries({
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')
.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',
);
});
void test('search needs both location and purpose; Enter and missing criteria cannot submit', () => {
for (const filters of [
{},
{ need: 'investment' },
{ province_id: 'province-qa' },
]) {
const h = harness(filters);
const submit = nodes(h.tree()).find(
(n) => n.type === 'button' && text(n) === 'Pesquisar',
);
assert.equal(submit.props.disabled, true);
nodes(h.tree())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted(), undefined);
assert.match(
text(h.tree()),
/Escolha a localização a pesquisar e a necessidade/,
);
}
for (const location of [
{ province_id: 'province-qa' },
{ territory: 'district-qa' },
]) {
const h = harness({
...location,
need: 'investment',
context: 'dossier-qa',
opportunity: 'opportunity-qa',
});
assert.equal(
nodes(h.tree()).find(
(n) => n.type === 'button' && text(n) === 'Pesquisar',
).props.disabled,
false,
);
nodes(h.tree())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted().data.need, 'investment');
assert.equal(h.submitted().data.context, 'dossier-qa');
assert.equal(h.submitted().data.opportunity, 'opportunity-qa');
}
});
void 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',
);
});