This commit is contained in:
2026-11-02 20:31:15 +02:00
parent 8ddfa93f45
commit 1da273f1f3
131 changed files with 14802 additions and 526 deletions
@@ -0,0 +1,454 @@
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);
function load(file, mocks) {
const output = ts.transpileModule(
fs
.readFileSync(
new URL(
'../../resources/js/components/' + file,
import.meta.url,
),
'utf8',
)
.replaceAll('import.meta.env.VITE_MAP_TILE_URL', 'undefined'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const polygon = (x, y) => ({
type: 'Polygon',
coordinates: [
[
[x, y],
[x + 1, y],
[x + 1, y + 1],
[x, y + 1],
[x, y],
],
],
});
const boundary = {
geometry: polygon(30, -20),
title: 'Província sintética',
purpose: 'administrative_boundary',
selected_territory: true,
location_type: 'province',
url: '/territorio',
source_reference: 'Fonte sintética',
source_date: '2026-01-01',
};
const point = {
geometry: { coordinates: [40, -10] },
properties: {
id: 1,
title: 'Investimento sintético',
url: '/oportunidades/1',
location: 'Local confirmado',
},
};
const flatten = (node) =>
!node || typeof node !== 'object'
? []
: [
node,
...React.Children.toArray(node.props.children).flatMap(flatten),
];
await test('catalogue composes one map with the same opportunity data and separate administrative context, including no selected territory', () => {
const Map = () => null,
Info = () => null;
const requests = [];
const Component = load('catalogue-investment-map.tsx', {
'./interactive-investment-map': { default: Map },
'./territory-geometry-preview': { TerritoryGeometryDetails: Info },
'./use-territory-geometry': {
useTerritoryGeometry: (id) => {
requests.push(id);
return { context: { areas: [boundary] }, error: '' };
},
},
}).default;
const points = [point],
areas = [];
const tree = Component({ points, areas, territoryId: 'province-1' });
assert.equal(tree.type, Map);
assert.equal(tree.props.points, points);
assert.equal(tree.props.areas, areas);
assert.deepEqual(tree.props.administrativeAreas, [boundary]);
assert.equal(tree.props.layerControls, true);
assert.equal(tree.props.administrativeInfo.type, Info);
assert.deepEqual(requests, ['province-1']);
assert.equal(
Component({ points: [], areas }).props.administrativeInfo,
undefined,
);
});
await test('territorial request changes discard old boundaries immediately and ignore late responses; clearing selection removes context', async () => {
const previousFetch = globalThis.fetch;
const pending = [],
memory = [];
let cursor = 0,
effect;
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in memory)) memory[index] = initial;
return [memory[index], (value) => (memory[index] = value)];
},
useEffect(fn) {
effect = fn;
},
};
globalThis.fetch = (url, options) =>
new Promise((resolve) => pending.push({ url, options, resolve }));
try {
const { useTerritoryGeometry } = load('use-territory-geometry.ts', {
react: hooks,
});
const render = (id) => {
cursor = 0;
return useTerritoryGeometry(id);
};
render('a');
const cleanup = effect();
cleanup();
render('b');
effect();
pending[0].resolve({
ok: true,
json: async () => ({ areas: [boundary] }),
});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(render('b').context, null);
pending[1].resolve({
ok: true,
json: async () => ({ areas: [{ ...boundary, title: 'B' }] }),
});
await new Promise((resolve) => setImmediate(resolve));
assert.equal(render('b').context.areas[0].title, 'B');
assert.equal(render('c').context, null);
assert.equal(render(undefined).context, null);
assert.equal(pending[0].options.signal.aborted, true);
assert.equal(pending.length, 2);
} finally {
globalThis.fetch = previousFetch;
}
});
await test('Leaflet uses one instance, independent layers and selected boundary bounds; restoring hidden points from the list never creates positions', async () => {
const previousDocument = globalThis.document,
previousObserver = globalThis.ResizeObserver;
let effect, overlayOptions, overlayEvents, fitted;
const refs = [],
instances = [],
groups = [];
globalThis.document = {
createElement: () => ({ append() {}, textContent: '', style: {} }),
};
globalThis.ResizeObserver = class {
observe() {}
disconnect() {}
};
const instance = {
setView() {
return this;
},
fitBounds(value) {
fitted = value;
},
on(_event, fn) {
overlayEvents = fn;
return this;
},
addLayer(group) {
group.visible = true;
return this;
},
invalidateSize() {},
remove() {},
};
const layer = () => ({
addTo(group) {
group.items.push(this);
return this;
},
bindPopup() {
return this;
},
on() {
return this;
},
getLatLng() {
return [
point.geometry.coordinates[1],
point.geometry.coordinates[0],
];
},
openPopup() {},
});
const L = {
map() {
instances.push(instance);
return instance;
},
tileLayer: () => ({
on() {
return this;
},
addTo() {},
}),
layerGroup() {
const group = {
items: [],
addTo() {
this.visible = true;
return this;
},
};
groups.push(group);
return group;
},
control: {
scale: () => ({ addTo() {} }),
layers(_base, overlays) {
overlayOptions = overlays;
return { addTo() {} };
},
},
geoJSON(geometry) {
const item = layer();
const coords = geometry.coordinates[0];
item.getBounds = () => ({
isValid: () => true,
getSouth: () => Math.min(...coords.map((c) => c[1])),
getNorth: () => Math.max(...coords.map((c) => c[1])),
getWest: () => Math.min(...coords.map((c) => c[0])),
getEast: () => Math.max(...coords.map((c) => c[0])),
});
return item;
},
divIcon: (value) => value,
marker: () => layer(),
};
const hooks = {
...React,
useMemo: (fn) => fn(),
useState: (initial) => [initial, () => {}],
useRef(initial) {
const ref = { current: refs.length === 0 ? {} : initial };
refs.push(ref);
return ref;
},
useEffect(fn) {
effect = fn;
},
};
try {
const Component = load('interactive-investment-map.tsx', {
react: hooks,
leaflet: L,
'leaflet/dist/leaflet.css': {},
}).default;
const area = {
...boundary,
title: 'Área sintética',
purpose: 'investment_area',
selected_territory: false,
};
const tree = Component({
points: [point],
areas: [area, boundary],
administrativeAreas: [boundary],
layerControls: true,
});
const cleanup = effect();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(instances.length, 1);
assert.equal(groups[0].items.length, 1);
assert.equal(groups[1].items.length, 1);
assert.equal(groups[2].items.length, 1); // Same boundary from both APIs is not doubled.
assert.deepEqual(fitted, [
[-20, 30],
[-19, 31],
]); // No national parent/outside point overrides the selection.
assert.equal(Object.keys(overlayOptions).length, 3);
overlayEvents({ layer: groups[0], type: 'overlayremove' });
assert.equal(refs[4].current.points, false);
const button = flatten(tree).find((n) => n.type === 'button');
button.props.onClick();
assert.equal(groups[0].visible, true);
assert.equal(refs[4].current.points, true);
assert(
flatten(tree).some(
(n) => n.type === 'a' && n.props.href === '/territorio',
),
);
assert(flatten(tree).some((n) => n.type === 'details'));
cleanup();
refs.length = 0;
groups.length = 0;
Component({
points: [],
areas: [],
administrativeAreas: [
{ ...boundary, selected_territory: false },
{
...boundary,
geometry: polygon(0, 0),
selected_territory: false,
location_type: 'country',
title: 'País sintético',
},
],
layerControls: true,
});
const cleanupEmpty = effect();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(groups[0].items.length, 0);
assert.deepEqual(fitted, [
[-20, 30],
[-19, 31],
]);
cleanupEmpty();
} finally {
globalThis.document = previousDocument;
globalThis.ResizeObserver = previousObserver;
}
});
await test('administrative failure does not remove investment results or add another map', () => {
const Map = () => null,
Info = () => null;
const Component = load('catalogue-investment-map.tsx', {
'./interactive-investment-map': { default: Map },
'./territory-geometry-preview': { TerritoryGeometryDetails: Info },
'./use-territory-geometry': {
useTerritoryGeometry: () => ({
context: null,
error: 'Limites indisponíveis',
}),
},
}).default;
const points = [point];
const tree = Component({ points, areas: [], territoryId: 'a' });
assert.equal(tree.type, Map);
assert.equal(tree.props.points, points);
assert.equal(tree.props.administrativeAreas, undefined);
assert(flatten(tree.props.notice).some((n) => n.props.role === 'alert'));
});
await test('declared parcels and documented source locations are never labelled as administrative boundaries or investments', () => {
const hooks = {
...React,
useMemo: (fn) => fn(),
useState: (value) => [value, () => {}],
useRef: (value) => ({ current: value }),
useEffect: () => {},
};
const Component = load('interactive-investment-map.tsx', {
react: hooks,
'leaflet/dist/leaflet.css': {},
}).default;
const parcel = renderToStaticMarkup(
Component({
points: [],
areas: [
{
...boundary,
purpose: 'declared_parcel',
title: 'Parcela sintética',
},
],
contextOnly: true,
mapKind: 'declared_parcel',
}),
);
assert.match(parcel, />Perímetro declarado pelo Promotor<\/h2>/);
assert.match(parcel, /não é limite administrativo/);
assert.doesNotMatch(
parcel,
/>Contexto administrativo<\/h2>|limites administrativos disponíveis/,
);
const documented = renderToStaticMarkup(
Component({
points: [],
areas: [],
mapKind: 'documented_locations',
layerControls: true,
}),
);
assert.match(documented, />Mapa dos locais documentados<\/h2>/);
assert.match(documented, /Local documentado com coordenadas/);
assert.doesNotMatch(documented, /Oportunidade com coordenadas confirmadas/);
const administrative = renderToStaticMarkup(
Component({ points: [], areas: [boundary], contextOnly: true }),
);
assert.match(administrative, />Contexto administrativo<\/h2>/);
});
await test('partnership catalogue has one contextual map and keeps the applied territory while filter edits are pending', () => {
let draft;
const hooks = {
...React,
useState(initial) {
draft ??= initial;
return [
draft,
(value) => {
draft = value;
},
];
},
};
const Map = () => null;
const Page = load('../pages/partnerships/catalogue.tsx', {
react: hooks,
'@inertiajs/react': { Link: 'a', router: { get() {} } },
'@/components/catalogue-investment-map': { default: Map },
'./shared': { Frame: 'main', Field: 'label', control: '', button: '' },
}).default;
const props = {
types: {},
sectors: [],
territories: [{ id: 'a', name: 'A', location_type: 'province' }],
filters: { territory_id: 'a' },
mapPoints: [point],
results: {
data: [],
total: 0,
prev_page_url: null,
next_page_url: null,
},
};
let tree = Page(props);
const maps = () => flatten(tree).filter((node) => node.type === Map);
assert.equal(maps().length, 1);
assert.equal(maps()[0].props.mapKind, 'documented_locations');
assert.equal(maps()[0].props.points, props.mapPoints);
flatten(tree)
.find((node) => node.type === 'select' && node.props.value === 'a')
.props.onChange({ target: { value: 'b' } });
tree = Page(props);
assert.equal(maps()[0].props.territoryId, 'a');
assert.equal(maps()[0].props.points, props.mapPoints);
});
@@ -0,0 +1,147 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import { createRequire } from 'node:module';
import ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url);
function source(name) {
return fs.readFileSync(
new URL('../../resources/js/pages/investment/' + name, import.meta.url),
'utf8',
);
}
function compile(source) {
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'])(
require,
module,
module.exports,
);
return module.exports;
}
const shared = ts.createSourceFile(
'shared.tsx',
source('shared.tsx'),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const apiNode = shared.statements.find(
(node) => ts.isFunctionDeclaration(node) && node.name?.text === 'api',
);
const { api } = compile(apiNode.getText(shared));
await test('API preserves JSON validation messages and handles empty and non-JSON responses', async () => {
const originalFetch = globalThis.fetch;
try {
globalThis.fetch = async () =>
new Response(JSON.stringify({ message: 'Campo obrigatorio' }), {
status: 422,
});
await assert.rejects(api('/synthetic'), /Campo obrigatorio/);
globalThis.fetch = async () =>
new Response('<html>proxy error</html>', { status: 502 });
await assert.rejects(api('/synthetic'), /concluir a opera/);
globalThis.fetch = async () =>
new Response('<html>expired</html>', { status: 419 });
await assert.rejects(api('/synthetic'), /sess.*expirou/);
globalThis.fetch = async () => new Response('', { status: 200 });
await assert.rejects(api('/synthetic'), /concluir a opera/);
globalThis.fetch = async () => new Response(null, { status: 204 });
assert.equal(await api('/synthetic'), null);
} finally {
globalThis.fetch = originalFetch;
}
});
await test('public GET ignores malformed CSRF cookie; writes preserve CSRF and multipart transport', async () => {
const originalFetch = globalThis.fetch;
const originalDocument = Object.getOwnPropertyDescriptor(
globalThis,
'document',
);
let request;
try {
Object.defineProperty(globalThis, 'document', {
value: { cookie: 'XSRF-TOKEN=%broken' },
configurable: true,
});
globalThis.fetch = async (url, options) => {
request = options;
return new Response('{"ok":true}');
};
assert.deepEqual(await api('/synthetic'), { ok: true });
await assert.rejects(api('/synthetic', {}), /validada/);
globalThis.document.cookie = 'XSRF-TOKEN=synthetic%3D';
const body = new FormData();
body.set('name', 'synthetic');
await api('/synthetic', body);
assert.equal(request.method, 'POST');
assert.equal(request.credentials, 'same-origin');
assert.equal(request.headers['X-XSRF-TOKEN'], 'synthetic=');
assert.equal(request.headers['Content-Type'], undefined);
assert.equal(request.body, body);
} finally {
globalThis.fetch = originalFetch;
if (originalDocument)
Object.defineProperty(globalThis, 'document', originalDocument);
else delete globalThis.document;
}
});
await test('catalogue pagination exposes applied links only after a successful search', () => {
const file = ts.createSourceFile(
'catalogue.tsx',
source('catalogue.tsx'),
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let nav;
function visit(node) {
if (
ts.isJsxElement(node) &&
node.openingElement.tagName.getText(file) === 'nav' &&
node.getText(file).includes('results.prev_page_url')
)
nav = node;
ts.forEachChild(node, visit);
}
visit(file);
assert.ok(nav);
const { Pagination } = compile(
`const Link='a'; export function Pagination({searchLoading,searchError,results,view}) {return (${nav.getText(file)});}`,
);
const props = {
view: 'list',
results: {
prev_page_url: '/previous?page=1',
next_page_url: '/previous?page=3',
},
};
for (const state of [
{ searchLoading: true, searchError: '' },
{ searchLoading: false, searchError: 'failure' },
]) {
const html = renderToStaticMarkup(
React.createElement(Pagination, { ...props, ...state }),
);
assert.doesNotMatch(html, /href=/);
}
const html = renderToStaticMarkup(
React.createElement(Pagination, {
...props,
searchLoading: false,
searchError: '',
}),
);
assert.match(html, /href="\/previous\?page=1"/);
assert.match(html, /href="\/previous\?page=3"/);
});
@@ -0,0 +1,129 @@
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 { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, overrides = {}) {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => overrides[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function render(payload) {
const empty = () => null;
const page = load('../../resources/js/pages/desk/request.tsx', {
'@inertiajs/react': {
Link: ({ href, children }) =>
createElement('a', { href }, children),
useForm: (data) => ({ data, errors: {}, processing: false }),
},
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
'@/lib/desk-field-visibility': load(
'../../resources/js/lib/desk-field-visibility.ts',
),
'@/components/dossier-prefill': { DossierPrefill: empty },
'@/components/country-select': { __esModule: true, default: empty },
'@/components/investment-territory': { TerritoryFields: empty },
'@/components/desk-internal-operations': {
DocumentReview: empty,
RequestOperations: empty,
},
'@/pages/investment/shared': {
Frame: ({ children }) => createElement('main', null, children),
card: '',
input: '',
button: '',
},
}).default;
return renderToStaticMarkup(
page({
request: {
id: 'synthetic-request',
version: 1,
status: 'draft',
payload,
protocol: null,
editable_fields: [],
analyst_id: null,
due_at: null,
},
case: { id: 'synthetic-case', title: 'Synthetic dossier' },
definition: {
title: 'Synthetic form',
result: 'Synthetic result',
fields: {
detail: {
label: 'Deep detail',
type: 'text',
required: true,
when: { field: 'branch', equals: '1' },
},
branch: {
label: 'Branch question',
type: 'select',
required: true,
options: { 0: 'No', 1: 'Yes' },
when: { field: 'root', equals: '1' },
},
root: {
label: 'Root question',
type: 'select',
required: true,
options: { 0: 'No', 1: 'Yes' },
},
},
},
owner: true,
manager: false,
analyst: false,
fieldsEditable: true,
states: { draft: 'Draft' },
transitions: [],
findings: [],
messages: [],
analysts: [],
territoryPaths: {},
events: [],
documents: [],
payments: [],
caseVersion: 1,
countries: [],
toolPrefill: null,
}),
);
}
await test('hidden parent answers never reveal nested questions, while reopening the branch restores their answers', () => {
const payload = { root: '0', branch: '1', detail: 'Preserved detail' };
const hidden = render(payload);
assert.ok(hidden.includes('Root question'));
assert.ok(!hidden.includes('Branch question'));
assert.ok(!hidden.includes('Deep detail'));
assert.ok(!hidden.includes('Preserved detail'));
const visible = render({ ...payload, root: '1' });
assert.ok(visible.includes('Branch question'));
assert.ok(visible.includes('Deep detail'));
assert.ok(visible.includes('Preserved detail'));
assert.deepEqual(payload, {
root: '0',
branch: '1',
detail: 'Preserved detail',
});
});
+117
View File
@@ -0,0 +1,117 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('service editor retains the source, invalidates confirmation after edits and compares old/new values before publishing a remembered draft', () => {
const service = {
code: 'project-change',
version: 1,
definition: {
title: 'Synthetic service',
theme: 'Synthetic',
profile: 'Investor',
entity: 'Internal team',
result: 'Preparation',
stage: 'E10',
fields: {
question: {
label: 'Original question',
type: 'text',
required: false,
},
},
},
};
const before = JSON.stringify(service);
let form, rememberedKey, sent;
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/pages/desk/service-editor.tsx',
import.meta.url,
),
'utf8',
) + '\nexport { Editor };',
{
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'
? { useState: (initial) => [initial, () => {}] }
: name === '@inertiajs/react'
? {
Link: 'a',
useForm(key, initial) {
rememberedKey = key;
form ??= {
data: initial,
errors: {},
processing: false,
setData(value, next) {
this.data =
typeof value === 'function'
? value(this.data)
: { ...this.data, [value]: next };
},
put(url) {
sent = {
url,
data: structuredClone(this.data),
};
},
};
return form;
},
}
: name === '@/pages/investment/shared'
? { Frame: 'main', card: '', button: '', input: '' }
: name === '@/components/desk-service-history'
? { default: () => null, __esModule: true }
: require(name),
module,
module.exports,
);
const render = () => module.exports.Editor({ service });
let tree = render();
assert.equal(rememberedKey, 'desk-service-editor:project-change:1');
form.data.confirm = true;
const question = nodes(tree).find(
(node) =>
node.type === 'input' && node.props.value === 'Original question',
);
question.props.onChange({ target: { value: 'Revised question' } });
assert.equal(form.data.confirm, false);
tree = render();
const html = renderToStaticMarkup(tree);
assert.match(html, /Versão anterior/);
assert.match(html, /Original question/);
assert.match(html, /Revised question/);
assert.match(html, /pedidos.*definição original/is);
assert.equal(JSON.stringify(service), before);
form.data.confirm = true;
tree.props.onSubmit({ preventDefault() {} });
assert.equal(sent.url, '/management/balcao/servicos/project-change');
assert.equal(sent.data.base_version, 1);
assert.equal(
sent.data.definition.fields.question.label,
'Revised question',
);
});
@@ -0,0 +1,186 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
function harness() {
const values = [],
requests = [];
let cursor = 0,
effect;
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in values)) values[index] = initial;
return [
values[index],
(value) => {
values[index] =
typeof value === 'function'
? value(values[index])
: value;
},
];
},
useEffect(callback) {
effect = callback;
},
};
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/desk-service-history.tsx',
import.meta.url,
),
'utf8',
),
{
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'
? hooks
: name === '@/lib/portal-api'
? {
portalRequest: (url, options) =>
new Promise((resolve, reject) =>
requests.push({
url,
options,
resolve,
reject,
}),
),
}
: require(name),
module,
module.exports,
);
return {
requests,
start: () => effect(),
render(code = 'project-change') {
cursor = 0;
return module.exports.default({
code,
formatField: (field) =>
field.label +
(field.required ? ' — Obrigatório' : ' — Opcional'),
});
},
};
}
const version = {
id: 'v1',
version: 1,
status: 'published',
author_id: 21,
published_by: 22,
published_at: null,
reason: 'Synthetic publication reason',
source: { identifier: 'Synthetic source', edition: 'Synthetic edition' },
definition: {
title: 'Old form',
theme: 'Theme',
profile: 'Investor',
entity: 'Internal team',
stage: 'E10',
result: 'Internal preparation',
fields: {
title: { label: 'Original question', type: 'text', required: true },
},
},
payload: 'PRIVATE-ANSWER',
};
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('history renders immutable definitions and provenance without applicant answers, then paginates using the same authorised endpoint', async () => {
const h = harness();
h.render();
h.start();
assert.equal(
h.requests[0].url,
'/management/balcao/servicos/project-change/versoes?page=1',
);
h.requests[0].resolve({ page: 1, pages: 2, total: 11, data: [version] });
await flush();
const tree = h.render(),
html = renderToStaticMarkup(tree);
assert.match(html, /Original question — Obrigatório/);
assert.match(html, /Synthetic publication reason/);
assert.match(html, /Synthetic source · Synthetic edition/);
assert.doesNotMatch(html, /PRIVATE-ANSWER|<input|<form|<textarea/);
nodes(tree)
.find(
(node) =>
node.type === 'button' && node.props.children === 'Seguinte',
)
.props.onClick();
assert.match(renderToStaticMarkup(h.render()), /A recuperar/);
h.start();
assert.equal(
h.requests[1].url,
'/management/balcao/servicos/project-change/versoes?page=2',
);
h.requests[1].resolve({
page: 2,
pages: 2,
total: 11,
data: [
{
...version,
id: 'older',
version: 0,
definition: { ...version.definition, title: 'Previous page' },
},
],
});
await flush();
assert.match(renderToStaticMarkup(h.render()), /Previous page/);
});
await test('failed history differs from an empty history and stale service responses never replace the selected service', async () => {
const h = harness();
h.render();
const cleanup = h.start();
cleanup();
h.render('project-follow-up');
h.start();
h.requests[0].resolve({ page: 1, pages: 1, total: 1, data: [version] });
await flush();
assert.doesNotMatch(
renderToStaticMarkup(h.render('project-follow-up')),
/Original question/,
);
h.requests[1].reject(new Error('Network unavailable'));
await flush();
const failed = h.render('project-follow-up');
assert.match(renderToStaticMarkup(failed), /Tentar novamente/);
assert.doesNotMatch(renderToStaticMarkup(failed), /Ainda não existem/);
nodes(failed)
.find((node) => node.type === 'button')
.props.onClick();
h.render('project-follow-up');
h.start();
h.requests[2].resolve({ page: 1, pages: 1, total: 0, data: [] });
await flush();
assert.match(
renderToStaticMarkup(h.render('project-follow-up')),
/Ainda não existem/,
);
});
@@ -0,0 +1,72 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
await test('blocked browser storage cannot prevent authentication or clearing a submitted interest', () => {
const source = fs.readFileSync(
new URL(
'../../resources/js/hooks/use-interest-draft.ts',
import.meta.url,
),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}).outputText;
const module = { exports: {} };
let destination;
const storage = {
getItem() {
throw new Error('blocked');
},
setItem() {
throw new Error('blocked');
},
removeItem() {
throw new Error('blocked');
},
};
compileFunction(output, [
'require',
'module',
'exports',
'sessionStorage',
'window',
'location',
])(
(name) =>
name === 'react'
? {
useState: (init) => [init(), () => {}],
useEffect: (effect) => effect(),
}
: { newSubmissionKey: () => 'synthetic-key' },
module,
module.exports,
storage,
{
location: {
assign: (url) => {
destination = url;
},
},
},
{ pathname: '/oportunidades/teste', search: '?sector=1' },
);
const draft = module.exports.useInterestDraft('synthetic', {
name: 'Synthetic',
email: 'synthetic@example.invalid',
});
assert.equal(draft.key, 'synthetic-key');
assert.doesNotThrow(() => draft.clear());
assert.doesNotThrow(() => draft.authenticate());
assert.equal(
destination,
'/participar/entrar?return=%2Foportunidades%2Fteste%3Fsector%3D1',
);
});
+20 -18
View File
@@ -110,7 +110,7 @@ void test('map coverage distinguishes returned counts, missing provenance and tr
assert.doesNotMatch(empty, /As fichas continuam disponíveis abaixo/);
assert.doesNotMatch(empty, /Resultados limitados/);
});
void test('map layer choices preserve received records, coverage, unlocated links and filters without another request', async () => {
void test('one layered map preserves records, coverage, unlocated links and applied filters without a duplicate map or nonadministrative inference', async () => {
const previousFetch = globalThis.fetch;
let resolve;
const requests = [];
@@ -149,7 +149,7 @@ void test('map layer choices preserve received records, coverage, unlocated link
{
react: hooks,
'@/components/search-state': { default: SearchState },
'./territory-geometry-preview': { default: () => null },
'./catalogue-investment-map': { default: MapView },
'./interactive-investment-map': { default: MapView },
'./investment-map-coverage': { default: Coverage },
},
@@ -180,34 +180,36 @@ void test('map layer choices preserve received records, coverage, unlocated link
const map = () => flat(tree).find((node) => node.type === MapView);
assert.equal(map().props.points.length, 2);
assert.equal(map().props.areas.length, 1);
flat(tree)
.filter((node) => node.type === 'input')[0]
.props.onChange({ target: { checked: false } });
tree = render();
assert.deepEqual(map().props.points, []);
assert.equal(map().props.areas.length, 1);
flat(tree)
.filter((node) => node.type === 'input')[1]
.props.onChange({ target: { checked: false } });
tree = render();
assert.deepEqual(map().props.areas, []);
assert.equal(
flat(tree).filter((node) => node.type === MapView).length,
1,
);
assert.equal(
flat(tree).filter((node) => node.type === 'input').length,
0,
);
assert.equal(map().props.territoryId, 'synthetic-province');
const html = renderToStaticMarkup(tree);
assert.match(html, /Camadas ocultas/);
assert.match(html, /incluindo camadas ocultas/);
assert.match(html, /href="\/synthetic\/3"/);
assert.match(
html,
/<th scope="row">Marcadores de investimento<\/th><td>2<\/td>/,
);
for (const checkbox of flat(tree).filter(
(node) => node.type === 'input',
))
checkbox.props.onChange({ target: { checked: true } });
tree = render();
assert.equal(map().props.points, data.features);
assert.equal(map().props.areas, data.areas);
assert.equal(requests.length, 1);
assert.match(requests[0].url, /province_id=synthetic-province/);
cursor = 0;
const changed = Panel({
filters: { geo_location_id: 'synthetic-park' },
});
const changedMap = flat(changed).find((node) => node.type === MapView);
assert.equal(changedMap.props.territoryId, undefined);
assert.equal(changedMap.props.points, null);
assert.deepEqual(changedMap.props.areas, []);
assert(!flat(changed).some((node) => node.type === Coverage));
} finally {
cleanup?.();
globalThis.fetch = previousFetch;
@@ -3,6 +3,32 @@ import assert from 'node:assert/strict';
import { contextApi } from '../../resources/js/lib/investor-context.ts';
const success = { ok: true, json: async () => ({ saved: true }) };
await test('context handles compact CSRF cookies and rejects malformed writes before transport', async () => {
let calls = 0;
await withTransport(
async (_url, options) => {
calls++;
if (options.method !== 'GET')
assert.equal(
options.headers['X-XSRF-TOKEN'],
'synthetic/token',
);
return success;
},
async () => {
globalThis.document.cookie = 'other=x;XSRF-TOKEN=synthetic%2Ftoken';
await contextApi('/synthetic', {});
globalThis.document.cookie = 'XSRF-TOKEN=%broken';
await assert.rejects(
contextApi('/synthetic', {}, 'POST', true),
/sessão/,
);
assert.equal(calls, 1);
await contextApi('/synthetic');
assert.equal(calls, 2);
},
);
});
async function withTransport(fetch, callback) {
const previousFetch = globalThis.fetch;
const previousDocument = globalThis.document;
@@ -134,3 +160,37 @@ void test('ordinary context writes and reads retain their existing method and er
},
);
});
void test('invalid successful context response remains a failure and releases keepalive budget', async () => {
let calls = 0;
await withTransport(
async (_url, options) => {
calls++;
assert.equal(options.keepalive, true);
return calls === 1
? new Response('<html>unexpected</html>', { status: 200 })
: success;
},
async () => {
await assert.rejects(
contextApi(
'/synthetic',
{ text: 'a'.repeat(40000) },
'POST',
true,
),
/HTTP 200/,
);
assert.equal(calls, 1);
assert.deepEqual(
await contextApi(
'/synthetic',
{ text: 'a'.repeat(40000) },
'POST',
true,
),
{ saved: true },
);
},
);
});
@@ -0,0 +1,454 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(path, mocks) {
const output = ts.transpileModule(
fs.readFileSync(new URL(path, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports.default;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('preferences submit their own version and chosen criteria, with explicit opt-in and an independent cancellation action', () => {
let form, sent;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
transform(fn) {
this.apply = fn;
},
put(url, options) {
sent = {
url,
options,
data: this.apply(this.data),
};
},
};
return form;
},
},
'@/components/opportunity-search-filters': {
modalityLabels: {
investment_project: 'Projecto de investimento',
},
},
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 7,
enabled: true,
frequency: 'daily',
channel: 'in_app',
next_run_at: null,
criteria: {
sector: 'qa',
province_id: 'province',
category: 'investment_project',
},
};
const render = () =>
Component({
preferences,
options: {
frequencies: { daily: 'Daily' },
sectors: [{ slug: 'qa', name: 'Synthetic sector' }],
provinces: [{ id: 'province', name: 'Synthetic province' }],
categories: ['investment_project'],
},
});
let tree = render();
assert.equal(form.data.consent, false);
assert.ok(
renderToStaticMarkup(tree).includes('Não são enviados emails ou SMS'),
);
const criteria = nodes(tree).find(
(node) => node.type === 'select' && node.props.value === 'qa',
);
criteria.props.onChange({ target: { value: '' } });
tree = render();
assert.equal(form.data.criteria.province_id, 'province');
nodes(tree)
.find(
(node) =>
node.type === 'input' && node.props.name === 'alert-consent',
)
.props.onChange({ target: { checked: true } });
tree = render();
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(sent.url, '/investidor/alert-preferences');
assert.equal(sent.data.version, 7);
assert.equal(sent.data.channel, 'in_app');
assert.equal(sent.data.enabled, true);
assert.equal(sent.data.consent, true);
assert.equal(sent.data.criteria.sector, '');
nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Cancelar estes alertas',
)
.props.onClick();
assert.equal(sent.data.enabled, false);
assert.equal(sent.data.consent, false);
assert.equal(preferences.enabled, true);
const unavailable = renderToStaticMarkup(
Component({
preferences: { ...preferences, criteria_available: false },
options: {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: [],
},
}),
);
assert.ok(
unavailable.includes(
'O acompanhamento das selecções indisponíveis fica suspenso',
),
);
assert.ok(unavailable.includes('Província anterior indisponível'));
assert.ok(unavailable.includes('Cancelar estes alertas'));
assert.equal(form.data.criteria.province_id, 'province');
});
await test('opportunity notifications preserve the legacy manifestation action and link to the public fiche', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 2,
notifications: {
data: [
{
id: 'alert',
opportunity_id: 12,
submission_id: null,
kind: 'opportunity_match',
payload: {
title: 'Synthetic public opportunity',
slug: 'synthetic-fiche',
source: 'Synthetic catalogue',
preference_version: 7,
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
{
id: 'legacy',
submission_id: 'synthetic-submission',
kind: 'received',
payload: { reference: 'SYNTHETIC-REF' },
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/oportunidades/synthetic-fiche'));
assert.ok(html.includes('/investidor/manifestacoes/synthetic-submission'));
assert.ok(html.includes('versão 7'));
assert.ok(html.includes('Manifestação recebida'));
assert.ok(!html.includes('/manifestacoes/null'));
});
await test('tender alerts require an explicit source choice and show only their applicable form controls', () => {
let form, sent;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
transform(fn) {
this.apply = fn;
},
put(url) {
sent = { url, data: this.apply(this.data) };
},
};
return form;
},
},
'@/components/opportunity-search-filters': {
modalityLabels: {
investment_project: 'Projecto de investimento',
},
},
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 3,
enabled: true,
frequency: 'daily',
channel: 'in_app',
next_run_at: null,
criteria: { category: 'investment_project' },
};
const options = {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: ['investment_project'],
tendersAvailable: true,
tenderRegimes: { private: 'Concurso privado' },
};
const render = (currentOptions = options) =>
Component({ preferences, options: currentOptions });
let tree = render();
assert.deepEqual(form.data.sources, ['opportunities']);
assert.equal(
nodes(tree).find((node) => node.props?.name === 'source-tenders').props
.checked,
false,
);
form.setData('consent', true);
nodes(tree)
.find((node) => node.props?.name === 'source-tenders')
.props.onChange({ target: { checked: true } });
assert.equal(form.data.consent, false);
tree = render();
nodes(tree)
.find((node) => node.props?.name === 'source-opportunities')
.props.onChange({ target: { checked: false } });
tree = render();
const html = renderToStaticMarkup(tree);
assert.ok(html.includes('Regime do concurso'));
assert.ok(!html.includes('Todas as modalidades'));
assert.ok(html.includes('Concurso privado'));
form.setData('consent', true);
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.deepEqual(sent.data.sources, ['tenders']);
tree = render({ ...options, tendersAvailable: false });
const unavailable = nodes(tree).find(
(node) => node.props?.name === 'source-tenders',
);
assert.equal(
unavailable.props.disabled,
false,
'An unavailable selected source must remain removable.',
);
unavailable.props.onChange({ target: { checked: false } });
assert.deepEqual(form.data.sources, []);
});
await test('published tender acts retain their identity and use the tender action rather than a manifestation URL', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 1,
alertOptions: { tenderActs: { extension: 'Prorrogação' } },
notifications: {
data: [
{
id: 'synthetic-alert',
submission_id: null,
tender_version_id: 'synthetic-version',
kind: 'tender_match',
payload: {
title: 'Synthetic public tender',
tender_id: 'synthetic-tender',
act: 'extension',
publication_version: 4,
source: 'Synthetic catalogue',
preference_version: 3,
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/concursos/synthetic-tender'));
assert.ok(html.includes('Consultar concurso'));
assert.ok(html.includes('Prorrogação'));
assert.ok(html.includes('versão 4'));
assert.ok(html.includes('não apresenta uma proposta'));
assert.ok(!html.includes('/manifestacoes/null'));
});
await test('funding preferences require opt-in and expose scope and window choices only for that source', () => {
let form;
const Component = load(
'../../resources/js/components/opportunity-alert-preferences.tsx',
{
'@inertiajs/react': {
useForm(initial) {
form ??= {
data: initial,
processing: false,
errors: {},
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
};
return form;
},
},
'@/components/opportunity-search-filters': { modalityLabels: {} },
'@/pages/investment/shared': { card: '', button: '', input: '' },
},
);
const preferences = {
version: 1,
enabled: true,
frequency: 'daily',
criteria: {},
channel: 'in_app',
next_run_at: null,
};
const options = {
frequencies: { daily: 'Daily' },
sectors: [],
provinces: [],
categories: [],
fundingAvailable: true,
};
let tree = Component({ preferences, options });
assert.deepEqual(form.data.sources, ['opportunities']);
assert.equal(
renderToStaticMarkup(tree).includes('Estado de uma janela'),
false,
);
form.setData('consent', true);
nodes(tree)
.find((node) => node.props?.name === 'source-funding')
.props.onChange({ target: { checked: true } });
assert.equal(form.data.consent, false);
tree = Component({ preferences, options });
assert.ok(
renderToStaticMarkup(tree).includes(
'Incluir e assinalar informação por confirmar',
),
);
assert.ok(renderToStaticMarkup(tree).includes('Estado de uma janela'));
assert.equal(form.data.criteria.funding_certainty, 'documented');
const unavailable = nodes(
Component({
preferences,
options: { ...options, fundingAvailable: false },
}),
).find((node) => node.props?.name === 'source-funding');
assert.equal(unavailable.props.disabled, false);
unavailable.props.onChange({ target: { checked: false } });
assert.deepEqual(form.data.sources, ['opportunities']);
});
await test('funding notice links to its programme and qualifies historical window states', () => {
const Page = load('../../resources/js/pages/investment/notifications.tsx', {
'@inertiajs/react': { Link: 'a', router: { post() {} } },
'./shared': { Frame: 'main', card: '', button: '' },
'@/components/opportunity-alert-preferences': {
__esModule: true,
default: () => null,
},
});
const html = renderToStaticMarkup(
Page({
unread: 1,
notifications: {
data: [
{
id: 'qa',
submission_id: null,
kind: 'funding_match',
payload: {
title: 'Synthetic fund',
programme_id: 'qa-fund',
source_url:
'https://example.invalid/funding-source',
source_reference: 'Synthetic source edition',
source_checked_on: '2026-11-02',
publication_version: 2,
scope_explanation: {
sector: 'Âmbito por confirmar',
},
window_states: [
{
title: 'Synthetic historical window',
state: 'closed',
end_on: '2025-10-20',
},
],
},
created_at: '2026-11-02T12:00:00Z',
read_at: null,
},
],
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(html.includes('/fundos/qa-fund'));
assert.ok(html.includes('https://example.invalid/funding-source'));
assert.ok(html.includes('Synthetic source edition'));
assert.ok(html.includes('não confirma uma candidatura aberta'));
assert.ok(html.includes('estado na data do aviso'));
assert.ok(html.includes('encerrada'));
assert.ok(html.includes('Âmbito por confirmar'));
assert.ok(!html.includes('/manifestacoes/null'));
});
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
readOpportunitySelection,
persistOpportunitySelection,
} from '../../resources/js/lib/opportunity-selection.ts';
await test('selection accepts only unique positive safe integer identifiers', () => {
const old = globalThis.sessionStorage;
try {
for (const value of ['null', '{}', '"123"', 'invalid', 'false']) {
globalThis.sessionStorage = { getItem: () => value };
assert.deepEqual(readOpportunitySelection(), []);
}
globalThis.sessionStorage = {
getItem: () => '[1,2,1,"3",null,-1,0,1.5,9007199254740992]',
};
assert.deepEqual(readOpportunitySelection(), [1, 2]);
} finally {
globalThis.sessionStorage = old;
}
});
await test('blocked storage never prevents reading, selecting or clearing and reports persistence failure', () => {
const old = globalThis.sessionStorage;
try {
globalThis.sessionStorage = {
getItem() {
throw Error('blocked');
},
setItem() {
throw Error('quota');
},
removeItem() {
throw Error('blocked');
},
};
assert.deepEqual(readOpportunitySelection(), []);
assert.equal(persistOpportunitySelection([1]), false);
assert.equal(persistOpportunitySelection([]), false);
} finally {
globalThis.sessionStorage = old;
}
});
await test('selection persists and clears the existing key without altering other browser data', () => {
const old = globalThis.sessionStorage;
const memory = new Map([['unrelated', 'preserved']]);
try {
globalThis.sessionStorage = {
getItem: (k) => memory.get(k) ?? null,
setItem: (k, v) => memory.set(k, v),
removeItem: (k) => memory.delete(k),
};
assert.equal(persistOpportunitySelection([12, 4]), true);
assert.deepEqual(readOpportunitySelection(), [12, 4]);
assert.equal(persistOpportunitySelection([]), true);
assert.deepEqual(readOpportunitySelection(), []);
assert.equal(memory.get('unrelated'), 'preserved');
} finally {
globalThis.sessionStorage = old;
}
});
+39 -1
View File
@@ -148,7 +148,7 @@ await test('browser writes preserve the CSRF cookie header', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: { cookie: 'other=x; XSRF-TOKEN=qa%2Ftoken' },
value: { cookie: 'other=x;XSRF-TOKEN=qa%2Ftoken' },
});
try {
t.mock.method(globalThis, 'fetch', async (_url, options) => {
@@ -201,3 +201,41 @@ await test('invalid JSON and network errors remain failures', async (t) => {
});
await assert.rejects(portalRequest('/api/v1/home'), TypeError);
});
await test('malformed CSRF cookie prevents writes with a readable session error but permits reads', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: { cookie: 'XSRF-TOKEN=%broken' },
});
let calls = 0;
t.mock.method(globalThis, 'fetch', async () => {
calls++;
return new Response('{"success":true}');
});
try {
await assert.rejects(
portalRequest('/synthetic', { method: 'POST' }),
(error) =>
error instanceof PortalApiError && /sessão/.test(error.message),
);
assert.equal(calls, 0);
await portalRequest('/synthetic');
assert.equal(calls, 1);
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
});
await test('nullable validation errors never crash field rendering', async (t) => {
t.mock.method(
globalThis,
'fetch',
async () => new Response('{"errors":null}', { status: 422 }),
);
await assert.rejects(portalRequest('/synthetic'), (error) => {
assert.deepEqual(fieldErrors(error), {});
return error instanceof PortalApiError;
});
});
+76
View File
@@ -325,3 +325,79 @@ void test('direct analysis and ordinary creation preserve distinct selection sta
'new-my-opportunity',
);
});
void test('investment entry belongs to realization exactly once', () => {
const groups = portalNavigation({ authenticated: false, manager: false });
const realization = groups.find((g) => g.id === 'realization');
assert.ok(
realization.children.some(
(i) => i.id === 'start' && i.href === '/investimentos/iniciar',
),
);
assert.equal(
destinations(groups).filter((href) => href === '/investimentos/iniciar')
.length,
1,
);
assert.equal(
currentNavigationGroup(groups, '/investimentos/iniciar'),
'realization',
);
});
void test('portfolio and zone fiche return keeps the applied catalogue page and filters', () => {
for (const base of [
'/carteira',
'/zonas',
'/management/portfolio',
'/management/investment/zones',
]) {
const href = catalogueDetailHref(
base + '/synthetic',
'q=energia&province_id=p',
base + '?q=energia&province_id=p&page=3&unrelated=private',
);
const returned = new URL(
catalogueReturnHref(base, href),
'https://portal.invalid',
);
assert.equal(returned.searchParams.get('page'), '3');
assert.equal(returned.searchParams.get('q'), 'energia');
assert.equal(returned.searchParams.get('province_id'), 'p');
assert.equal(returned.searchParams.has('unrelated'), false);
}
});
void test('catalogue pagination inheritance rejects invalid page values', () => {
for (const page of ['0', '-1', '1.5', 'invalid', '9007199254740992']) {
const href = catalogueDetailHref(
'/carteira/synthetic',
'kind=project',
'/carteira?page=' + page,
);
const query = new URLSearchParams(
new URL(href, 'https://portal.invalid').searchParams.get(
'catalogue_query',
),
);
assert.equal(query.has('page'), false);
}
});
void test('funding links require installation and saved list requires authentication', () => {
const base = { authenticated: false, manager: false };
assert.equal(
JSON.stringify(portalNavigation(base)).includes('/fundos'),
false,
);
const publicMenu = JSON.stringify(
portalNavigation({ ...base, funding: true }),
);
assert.equal(publicMenu.includes('/fundos'), true);
assert.equal(publicMenu.includes('/fundos/guardados'), false);
assert.equal(
JSON.stringify(
portalNavigation({ ...base, funding: true, authenticated: true }),
).includes('/fundos/guardados'),
true,
);
});
+140
View File
@@ -0,0 +1,140 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import { compileFunction } from 'node:vm';
const source = fs.readFileSync(
new URL('../../resources/js/lib/profile-json.ts', import.meta.url),
'utf8',
);
const output = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}).outputText;
const module = { exports: {} };
compileFunction(output, ['exports'])(module.exports);
const { profileJson, ProfileValidationError } = module.exports;
async function transport(response, run) {
const fetch = globalThis.fetch,
document = globalThis.document;
let count = 0;
globalThis.document = { cookie: 'XSRF-TOKEN=synthetic' };
globalThis.fetch = async () => {
count++;
return response;
};
try {
await run();
assert.equal(count, 1);
} finally {
globalThis.fetch = fetch;
globalThis.document = document;
}
}
await test('profile HTML failures retain reauthentication without JSON parser errors or automatic retry', async () => {
await transport(
new Response('<html>authentication required</html>', {
status: 403,
headers: { 'X-Portal-Reauthentication': 'required' },
}),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
e.reauthenticate &&
Object.keys(e.fields).length === 0,
);
},
);
});
await test('profile validation preserves field errors and server message', async () => {
await transport(
new Response(
JSON.stringify({
message: 'Invalid synthetic field',
errors: { name: ['Required', 'Too short'] },
}),
{ status: 422 },
),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
e.message === 'Invalid synthetic field' &&
e.fields.name === 'Required Too short',
);
},
);
});
await test('profile rejects invalid successful response and explains expired sessions', async () => {
for (const status of [200, 419])
await transport(
new Response('<html>unexpected</html>', { status }),
async () => {
await assert.rejects(
profileJson('/synthetic'),
(e) =>
e instanceof ProfileValidationError &&
(status !== 419 || /expirou/.test(e.message)),
);
},
);
});
await test('profile accepts no-content success', async () => {
await transport(new Response(null, { status: 204 }), async () =>
assert.equal(await profileJson('/synthetic'), null),
);
});
await test('profile reads ignore malformed CSRF while writes fail before transport with a useful error', async () => {
const oldFetch = globalThis.fetch,
oldDocument = globalThis.document;
let calls = 0;
try {
globalThis.document = { cookie: 'other=1;XSRF-TOKEN=%broken' };
globalThis.fetch = async (_url, options) => {
calls++;
assert.equal(options.method, 'GET');
assert.equal(options.headers['X-XSRF-TOKEN'], undefined);
assert.equal(options.credentials, 'same-origin');
return new Response('{"ok":true}');
};
assert.deepEqual(await profileJson('/synthetic', {}, 'GET'), {
ok: true,
});
await assert.rejects(
profileJson('/synthetic', {}),
(e) =>
e instanceof ProfileValidationError &&
/validada/.test(e.message),
);
assert.equal(calls, 1);
} finally {
globalThis.fetch = oldFetch;
globalThis.document = oldDocument;
}
});
await test('profile writes decode CSRF cookies regardless of separator spacing', async () => {
const oldFetch = globalThis.fetch,
oldDocument = globalThis.document;
try {
globalThis.document = { cookie: 'other=1;XSRF-TOKEN=synthetic%3D' };
globalThis.fetch = async (_url, options) => {
assert.equal(options.headers['X-XSRF-TOKEN'], 'synthetic=');
assert.equal(options.credentials, 'same-origin');
assert.equal(options.body, JSON.stringify({ name: 'synthetic' }));
return new Response('{"saved":true}');
};
assert.deepEqual(
await profileJson('/synthetic', { name: 'synthetic' }),
{ saved: true },
);
} finally {
globalThis.fetch = oldFetch;
globalThis.document = oldDocument;
}
});
@@ -0,0 +1,127 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
publicBusinessOfflineHtml,
downloadPublicBusinessOffline,
} from '../../resources/js/lib/public-business-offline.ts';
const savedAt = new Date('2026-11-02T15:00:00.000Z');
const record = {
slug: 'synthetic',
title: 'Negócio sintético',
modality: 'company_sale',
amount_min: '9007199254740993.25',
currency: 'MZN',
province: 'Província sintética',
payload: { private: 'RESERVED' },
owner_user_id: 73,
};
await test('offline fiche is self-contained, preserves exact public values and identifies capture versus publication', () => {
const html = publicBusinessOfflineHtml(
record,
'Venda da empresa',
'https://portal.example.invalid',
savedAt,
);
assert.match(html, /9007199254740993\.25 MZN/);
assert.match(html, /2026-11-02T15:00:00\.000Z/);
assert.match(html, /Publicação no portal<\/dt><dd>Não indicado/);
assert.match(html, /Província sintética/);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/negocios\/synthetic"/,
);
assert.doesNotMatch(
html,
/RESERVED|owner_user_id|<script|<link|<img|<iframe|<form|src=/,
);
assert.match(html, /default-src 'none'/);
assert.match(html, /<html lang="pt-MZ">/);
});
await test('untrusted text and slugs cannot create executable markup or an external source link', () => {
const html = publicBusinessOfflineHtml(
{
...record,
slug: '//external.invalid/"',
title: '<script>alert(1)</script>',
objective: '<img src=x onerror=alert(1)> & "value"',
},
'"malicious"',
'https://portal.example.invalid',
savedAt,
);
assert.doesNotMatch(html, /<script|<img/);
assert.match(html, /&lt;script&gt;/);
assert.match(
html,
/&lt;img src=x onerror=alert\(1\)&gt; &amp; &quot;value&quot;/,
);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/negocios\/%2F%2Fexternal/,
);
assert.throws(
() =>
publicBusinessOfflineHtml(
record,
'Venda',
'javascript:alert(1)',
savedAt,
),
/inválida/,
);
});
await test('download creates a standalone HTML file and releases its temporary URL', () => {
const previousWindow = globalThis.window,
previousDocument = globalThis.document;
const previousCreate = URL.createObjectURL.bind(URL),
previousRevoke = URL.revokeObjectURL.bind(URL);
let clicked = false,
removed = false,
revoked,
blob,
release;
const link = {
click() {
clicked = true;
},
remove() {
removed = true;
},
};
try {
globalThis.window = {
location: { origin: 'https://portal.example.invalid' },
setTimeout(fn) {
release = fn;
},
};
globalThis.document = {
createElement: () => link,
body: { appendChild() {} },
};
URL.createObjectURL = (value) => {
blob = value;
return 'blob:synthetic';
};
URL.revokeObjectURL = (value) => {
revoked = value;
};
downloadPublicBusinessOffline(record, 'Venda da empresa');
assert.equal(clicked, true);
assert.equal(removed, true);
assert.equal(link.download, 'negocio-synthetic.html');
assert.equal(blob.type, 'text/html;charset=utf-8');
assert.equal(revoked, undefined);
release();
assert.equal(revoked, 'blob:synthetic');
} finally {
globalThis.window = previousWindow;
globalThis.document = previousDocument;
URL.createObjectURL = previousCreate;
URL.revokeObjectURL = previousRevoke;
}
});
@@ -0,0 +1,75 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { publicOpportunityOfflineHtml } from '../../resources/js/lib/public-opportunity-offline.ts';
import { publicRecordOfflineHtml } from '../../resources/js/lib/public-record-offline.ts';
await test('opportunity offline projection keeps public content, precise values and source while excluding private context and attachments', () => {
const html = publicOpportunityOfflineHtml(
{
title: 'Synthetic opportunity',
slug: 'synthetic',
reference: 'SYN-1',
summary: 'Summary',
description: '<img src=x onerror=alert(1)>',
expected_impact: 'Expected jobs, not measured results',
estimated_investment_amount: '9007199254740993.25',
estimated_investment_currency: 'MZN',
district: 'Synthetic district',
province: 'Synthetic province',
last_validated_at: '2026-10-01',
payload: 'PRIVATE-PAYLOAD',
context: 'PRIVATE-CONTEXT',
documents: ['PRIVATE-FILE'],
},
'https://portal.example.invalid',
new Date('2026-11-02T12:00:00Z'),
);
assert.match(html, /9007199254740993\.25 MZN/);
assert.match(html, /SYN-1/);
assert.match(html, /2026-10-01/);
assert.match(html, /Synthetic district, Synthetic province/);
assert.match(html, /Contexto territorial/);
assert.match(
html,
/href="https:\/\/portal\.example\.invalid\/oportunidades\/synthetic"/,
);
assert.doesNotMatch(html, /PRIVATE-|<(?:img|script|iframe|link)\b/);
assert.match(html, /&lt;img/);
assert.match(html, /não confirma a implantação/);
});
await test('shared offline renderer rejects source paths outside the portal and preserves unknown fields as unknown', () => {
const content = {
title: 'Synthetic',
kind: 'Ficha',
sourcePath: '//external.invalid',
rows: [],
sections: [],
notice: '',
};
assert.throws(
() =>
publicRecordOfflineHtml(
content,
'https://portal.example.invalid',
new Date(),
),
/inválida/,
);
assert.throws(
() =>
publicRecordOfflineHtml(
{ ...content, sourcePath: '/\\external.invalid' },
'https://portal.example.invalid',
new Date(),
),
/inválida/,
);
const html = publicOpportunityOfflineHtml(
{ title: 'Unknown', slug: 'unknown', reference: 'SYN-2' },
'https://portal.example.invalid',
new Date(),
);
assert.match(html, /Investimento estimado<\/dt><dd>Não indicado/);
assert.doesNotMatch(html, /<dd>0/);
});
@@ -0,0 +1,133 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks) {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports.default;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
await test('the quick search has a native GET destination and submits the actual input value even after browser autofill', () => {
let sent, edited;
const Hero = load('../../resources/js/components/portal-hero.tsx', {
react: { useState: (initial) => [initial, () => {}], useEffect() {} },
'@inertiajs/react': {
Link: 'a',
router: {
get: (url, data) => {
sent = { url, data };
},
},
},
'lucide-react': { ArrowRight: () => null, Search: () => null },
});
const tree = Hero({
query: 'stale rendered value',
setQuery: (value) => {
edited = value;
},
});
const form = nodes(tree).find((node) => node.type === 'form');
const input = nodes(tree).find(
(node) => node.type === 'input' && node.props.name === 'q',
);
assert.equal(form.props.action, '/oportunidades');
assert.equal(form.props.method, 'get');
assert.equal(input.props.maxLength, 120);
input.props.onChange({ target: { value: 'plantio de algodao' } });
assert.equal(edited, 'plantio de algodao');
const original = globalThis.FormData;
try {
globalThis.FormData = class {
constructor(element) {
this.element = element;
}
get(key) {
assert.equal(key, 'q');
return this.element.value;
}
};
let prevented = false;
form.props.onSubmit({
preventDefault() {
prevented = true;
},
currentTarget: { value: ' plantio de algodao ' },
});
assert.equal(prevented, true);
assert.deepEqual(sent, {
url: '/oportunidades',
data: { q: 'plantio de algodao' },
});
} finally {
globalThis.FormData = original;
}
const html = renderToStaticMarkup(tree);
assert.ok(html.includes('Pesquisa rápida de oportunidades'));
assert.ok(html.includes('action="/oportunidades"'));
assert.ok(html.includes('Pesquisar'));
});
await test('related processing fiches are explicitly distinct from the requested cultivation and disappear during pending or failed searches', () => {
const Related = load(
'../../resources/js/components/opportunity-related-results.tsx',
{ '@inertiajs/react': { Link: 'a' } },
);
const related = {
query: 'plantio de algodao',
subject: 'algodao',
href: '/oportunidades?sector=qa&q=algodao',
items: [
{
id: 1,
slug: 'synthetic-processing',
title: 'Synthetic processing',
summary: 'Descaroçamento e transformação de algodão.',
},
],
};
const props = { related, loading: false, error: '', total: 0 };
const html = renderToStaticMarkup(Related(props));
assert.ok(
html.includes('não correspond') ||
html.includes(
'Não encontrámos fichas que correspondam a todos os termos',
),
);
assert.ok(html.includes('outras etapas da cadeia'));
assert.ok(html.includes('Descaroçamento e transformação de algodão'));
assert.ok(html.includes('q=plantio+de+algodao'));
assert.ok(html.includes('Ver a pesquisa relacionada'));
for (const state of [
{ loading: true },
{ error: 'failure' },
{ total: 1 },
{ related: null },
]) {
assert.equal(Related({ ...props, ...state }), null);
}
});
+225
View File
@@ -0,0 +1,225 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function harness() {
let cursor = 0,
effect;
const state = [],
requests = [];
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in state)) state[index] = initial;
return [
state[index],
(value) => {
state[index] =
typeof value === 'function'
? value(state[index])
: value;
},
];
},
useEffect(fn) {
effect = fn;
},
};
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/similar-businesses.tsx',
import.meta.url,
),
'utf8',
),
{
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'
? hooks
: name === '@inertiajs/react'
? { Link: 'a' }
: name === '@/lib/portal-api'
? {
portalRequest: (url, options) =>
new Promise((resolve, reject) =>
requests.push({
url,
options,
resolve,
reject,
}),
),
}
: require(name),
module,
module.exports,
);
const render = (props) => {
cursor = 0;
return module.exports.default(props);
};
return { render, start: () => effect(), requests };
}
const props = {
currentId: 'current',
catalogueUrl: '/negocios?sector=4&modality=company_sale',
criteria: ['Venda da empresa', 'Agricultura'],
};
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('explicit public classification changes matching criteria and is cleared when the source record changes', async () => {
const h = harness();
const row = {
target_type: 'chain',
target_id: 'synthetic-chain',
purpose: 'coverage',
purpose_label: 'Abrangencia documentada',
label: 'Cadeia sintética',
source_reference: 'Fonte sintética divulgada',
};
const scoped = {
...props,
classifications: [
row,
row,
{ ...row, purpose: 'location', purpose_label: 'Localização' },
],
};
let tree = h.render(scoped);
const chooser = tree.props.children.find((child) => child?.type === 'label')
.props.children[1];
chooser.props.onChange({
target: { value: 'chain:synthetic-chain:coverage' },
});
tree = h.render(scoped);
h.start();
const url = new URL(h.requests[0].url, 'https://portal.invalid');
assert.equal(url.searchParams.get('association_type'), 'chain');
assert.equal(url.searchParams.get('association_target'), 'synthetic-chain');
assert.equal(url.searchParams.get('association_purpose'), 'coverage');
assert.match(renderToStaticMarkup(tree), /Fonte sintética divulgada/);
assert.match(
renderToStaticMarkup(tree),
/value="chain:synthetic-chain:location"/,
);
assert.equal(
(
renderToStaticMarkup(tree).match(
/value="chain:synthetic-chain:coverage"/g,
) ?? []
).length,
1,
);
h.requests[0].resolve({ data: [] });
await flush();
const changed = { ...scoped, currentId: 'other-record' };
const next = renderToStaticMarkup(h.render(changed));
assert.doesNotMatch(next, /Fonte sintética divulgada/);
assert.match(next, /A consultar/);
h.start();
assert.equal(
new URL(h.requests[1].url, 'https://portal.invalid').searchParams.has(
'association_target',
),
false,
);
});
await test('similar businesses reuse public criteria, exclude self and duplicates, bound the preview and preserve filters in detail links', async () => {
const h = harness();
assert.match(renderToStaticMarkup(h.render(props)), /A consultar/);
h.start();
assert.equal(
h.requests[0].url,
'/api/v1/business-opportunities?sector=4&modality=company_sale&per_page=7&page=1',
);
h.requests[0].resolve({
data: [
{ id: 'current', slug: 'self', title: 'Self' },
{
id: 'a',
slug: 'a',
title: 'A',
published_at: '2026-11-01T12:00:00Z',
},
{ id: 'a', slug: 'duplicate', title: 'Duplicate' },
...Array.from({ length: 8 }, (_, i) => ({
id: `b${i}`,
slug: `b${i}`,
title: `Business ${i}`,
})),
],
});
await flush();
const html = renderToStaticMarkup(h.render(props));
assert.doesNotMatch(html, />Self<|>Duplicate<|Business 7/);
assert.equal((html.match(/<li>/g) ?? []).length, 6);
assert.match(html, /\/negocios\/a\?sector=4&amp;modality=company_sale/);
assert.match(html, /Agricultura/);
assert.match(html, /proximidade geográfica/);
assert.match(html, /Fonte: catálogo público/);
assert.match(html, /datetime="2026-11-01T12:00:00Z"/i);
assert.match(html, /Data de publicação não indicada/);
});
await test('malformed catalogue records are a recoverable error, never proof of no matching businesses', async () => {
const h = harness();
h.render(props);
h.start();
h.requests[0].resolve({
data: [{ id: 'a', slug: null, title: 'Malformed' }],
});
await flush();
const html = renderToStaticMarkup(h.render(props));
assert.match(html, /Tentar novamente/);
assert.doesNotMatch(html, /Não foram encontrados/);
});
await test('empty catalogue differs from failed lookup; changing context hides old rows and ignores late responses', async () => {
const h = harness();
h.render(props);
const cleanup = h.start();
cleanup();
const next = { ...props, catalogueUrl: '/negocios?modality=real_estate' };
assert.match(renderToStaticMarkup(h.render(next)), /A consultar/);
h.start();
h.requests[0].resolve({
data: [{ id: 'old', slug: 'old', title: 'Old response' }],
});
await flush();
assert.doesNotMatch(renderToStaticMarkup(h.render(next)), /Old response/);
h.requests[1].resolve({ data: [] });
await flush();
assert.match(
renderToStaticMarkup(h.render(next)),
/não demonstra ausência/,
);
h.render(props);
h.start();
h.requests[2].reject(new Error('network'));
await flush();
const tree = h.render(props);
const html = renderToStaticMarkup(tree);
assert.match(html, /Tentar novamente/);
assert.doesNotMatch(html, /não demonstra ausência/);
const button = tree.props.children[2].props.children[1];
button.props.onClick();
assert.match(renderToStaticMarkup(h.render(props)), /A consultar/);
h.start();
assert.equal(h.requests.length, 4);
});