feat: consolidar desenvolvimentos do portal InvestMoz

This commit is contained in:
2026-11-03 23:32:32 +02:00
parent 1da273f1f3
commit 36c8cadb49
345 changed files with 110714 additions and 2799 deletions
@@ -0,0 +1,426 @@
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, 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;
}
const locations = load('../../resources/js/lib/business-locations.ts');
const summaryModule = load(
'../../resources/js/components/business-point-summary.tsx',
{ '@/lib/business-locations': locations },
);
const Summary = summaryModule.default;
const sourceModule = load(
'../../resources/js/components/similar-businesses.tsx',
{ '@inertiajs/react': { Link: 'a' }, '@/lib/portal-api': {} },
);
const paths = [
{
province_id: 'qa-province',
district_id: 'qa-one',
admin_post_id: '',
locality_id: '',
},
{
province_id: 'qa-province',
district_id: 'qa-two',
admin_post_id: '',
locality_id: '',
},
];
const payload = {
title: 'QA private preparation',
wizard_version: '2',
wizard_step: '5',
geography_scope: 'multiple',
locations_json: JSON.stringify(paths),
location_unknown: 'no',
disclosure_precision: 'exact',
location_point_enabled: 'yes',
location_latitude: '-26.0001',
location_longitude: '32.0001',
location_point_source_mode: 'listing',
source_reference: '<QA source>',
source_date: '2026-10-02',
location_point_source_reference: 'Other private source',
location_point_source_date: '',
location_point_share_source: 'no',
};
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(initial = payload) {
let cursor = 0;
const state = [],
requests = [];
const hooks = {
useState(initial) {
const index = cursor++;
if (!(index in state))
state[index] =
typeof initial === 'function' ? initial() : initial;
return [
state[index],
(value) => {
state[index] =
typeof value === 'function'
? value(state[index])
: value;
},
];
},
useRef(initial) {
const index = cursor++;
if (!(index in state)) state[index] = { current: initial };
return state[index];
},
useEffect() {},
useCallback(fn) {
return fn;
},
};
const active = {
geography_scope: ['specific', 'multiple'],
disclosure_precision: ['exact'],
location_unknown: ['no'],
location_point_enabled: ['yes'],
};
const schema = {
geography_scope: {
step: 5,
pt: 'Geographic scope',
en: 'Scope',
type: 'select',
max: 30,
options: {
multiple: 'Multiple',
specific: 'Specific',
national: 'National',
digital: 'Digital',
},
},
location_point_territory: {
step: 5,
pt: 'Primary site',
en: 'Primary site',
type: 'point_territory',
max: 150,
when: { ...active, geography_scope: ['multiple'] },
},
location_latitude: {
step: 5,
pt: 'Latitude',
en: 'Latitude',
type: 'decimal',
max: 16,
when: active,
},
location_longitude: {
step: 5,
pt: 'Longitude',
en: 'Longitude',
type: 'decimal',
max: 16,
when: active,
},
location_point_source_mode: {
step: 5,
pt: 'Coordinate source',
en: 'Coordinate source',
type: 'select',
max: 20,
options: { listing: 'Existing source', custom: 'Different source' },
when: active,
},
location_point_source_reference: {
step: 5,
pt: 'Point source',
en: 'Point source',
type: 'textarea',
max: 2000,
when: { ...active, location_point_source_mode: ['custom'] },
},
};
const record = {
id: 'qa-listing',
code: 'MNE-QA',
modality: 'company_sale',
classification: 'restricted',
version_no: 1,
payload: initial,
territory_paths: [
['QA province', 'QA one'],
['QA province', 'QA two'],
],
};
const Wizard = load(
'../../resources/js/pages/investment/business-wizard.tsx',
{
react: hooks,
'@inertiajs/react': { router: { visit() {}, reload() {} } },
'@/components/country-select': { default: () => null },
'@/components/business-point-summary': summaryModule,
'./shared': {
Frame: 'div',
Field: ({ label, children }) =>
createElement('label', null, label, children),
input: 'input',
button: 'button',
card: 'card',
api: async (url, body) => {
requests.push({ url, body });
return { ...record, payload: body.payload, version_no: 2 };
},
},
'./business-types': {
businessModalities: { company_sale: 'Sale' },
},
'./business-objects': { default: () => null },
'../../lib/business-locations': locations,
},
).default;
return {
render() {
cursor = 0;
return Wizard({
countries: [],
record,
formSchema: schema,
modalityFormType: 'company_sale',
modalities: ['company_sale'],
objects: [],
objectKinds: [],
sectors: [],
});
},
requests,
};
}
await test('the existing wizard requires an explicit primary path and keeps the selected path distinct from the first site', async () => {
const h = harness();
let tree = h.render();
const chooser = nodes(tree).find(
(node) =>
node.type === 'select' &&
nodes(node).some(
(child) =>
child.type === 'option' &&
child.props.value ===
locations.businessPointTerritoryKey(paths[1]),
),
);
assert.equal(chooser.props.value, '');
chooser.props.onChange({
target: { value: locations.businessPointTerritoryKey(paths[1]) },
});
tree = h.render();
const html = renderToStaticMarkup(tree);
assert.match(html, /QA two/);
assert.match(html, /Latitude \*/);
assert.match(html, /não publica o ponto/);
assert.match(html, /mantida no processo reservado/);
const save = nodes(tree).find(
(node) =>
node.type === 'button' && node.props.children === 'Guardar e sair',
);
await save.props.onClick();
assert.equal(
h.requests[0].url,
'/api/v1/existing-business/listings/qa-listing',
);
assert.equal(
h.requests[0].body.payload.location_point_territory,
locations.businessPointTerritoryKey(paths[1]),
);
assert.equal(h.requests[0].body.version_no, 1);
assert.equal(h.requests[0].body.payload.location_latitude, '-26.0001');
});
await test('switching source reuses existing fields and switching to national hides the supplement while preserving the private draft', async () => {
const h = harness();
let tree = h.render();
assert.equal(
nodes(tree).some((node) => node.type === 'textarea'),
false,
);
const source = nodes(tree).find(
(node) => node.type === 'select' && node.props.value === 'listing',
);
source.props.onChange({ target: { value: 'custom' } });
tree = h.render();
assert.equal(
nodes(tree).find((node) => node.type === 'textarea').props.value,
'Other private source',
);
const scope = nodes(tree).find(
(node) => node.type === 'select' && node.props.value === 'multiple',
);
scope.props.onChange({ target: { value: 'national' } });
tree = h.render();
assert.doesNotMatch(
renderToStaticMarkup(tree),
/Ponto em preparação|Other private source|Latitude WGS84/,
);
assert.equal(
nodes(tree).some((node) => node.type === 'textarea'),
false,
);
await nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Guardar e sair',
)
.props.onClick();
assert.equal(h.requests[0].body.payload.location_latitude, '-26.0001');
assert.equal(
h.requests[0].body.payload.location_point_source_reference,
'Other private source',
);
assert.equal(
h.requests[0].body.payload.location_point_source_mode,
'custom',
);
assert.equal(h.requests[0].body.payload.geography_scope, 'national');
});
await test('stale point path stays visible for reconciliation instead of selecting another site', () => {
const h = harness({
...payload,
location_point_territory: 'qa-removed-site',
});
const html = renderToStaticMarkup(h.render());
assert.match(html, /Selecção guardada fora das localizações actuais/);
assert.match(html, /value="qa-removed-site" selected/);
});
await test('an incomplete earlier location does not change the index or name of a later selectable site', () => {
const h = harness({
...payload,
locations_json: JSON.stringify([
locations.emptyBusinessLocation(),
paths[1],
]),
});
const option = nodes(h.render()).find(
(node) =>
node.type === 'option' &&
node.props.value === locations.businessPointTerritoryKey(paths[1]),
);
const html = renderToStaticMarkup(option);
assert.match(html, /Localização 2/);
assert.match(html, /QA two/);
assert.doesNotMatch(html, /QA one/);
assert.equal(
locations.businessPointTerritoryLabel(
{
...payload,
location_point_territory: locations.businessPointTerritoryKey(
paths[1],
),
},
[['QA one'], ['QA two']],
),
'QA two',
);
});
await test('summary distinguishes registered, prepared and published data, escapes the reused source and reports an unavailable supplement', () => {
const registered = {
id: 'qa-existing',
is_public: false,
precision_level: 'exact',
has_geometry: true,
latitude: -27,
longitude: 33,
};
let html = renderToStaticMarkup(
Summary({ payload, registered, available: false }),
);
assert.match(html, /Latitude -27; longitude/);
assert.match(html, /Ponto em preparação/);
assert.match(html, /&lt;QA source&gt;/);
assert.match(html, /ainda não está instalado/);
assert.match(html, /substitui o primário cadastrado/);
html = renderToStaticMarkup(
Summary({ payload, registered, published: true }),
);
assert.match(html, /Ponto declarado na publicação/);
assert.match(html, /não reescreve o histórico/);
assert.equal(
Summary({ payload: { ...payload, location_unknown: 'yes' } }),
null,
);
html = renderToStaticMarkup(
Summary({
payload: { ...payload, location_point_enabled: 'no' },
registered,
}),
);
assert.match(
html,
/cadastro existente é conservado|cadastro\s+existente é conservado/,
);
assert.doesNotMatch(html, /-26.0001|&lt;QA source&gt;/);
});
await test('public source dates remain calendar dates in a western timezone and unknown dates are not replaced by the registration time', () => {
const previous = process.env.TZ;
try {
process.env.TZ = 'Pacific/Honolulu';
const html = renderToStaticMarkup(
sourceModule.BusinessLocationSource({
record: {
location_source_reference: '<Public source>',
location_source_date: '2026-10-02',
location_recorded_at: '2026-11-02T10:00:00Z',
},
showRecorded: true,
}),
);
assert.match(html, /&lt;Public source&gt;/);
assert.ok(
html.includes(
new Date('2026-10-02T00:00:00Z').toLocaleDateString('pt-MZ', {
timeZone: 'UTC',
}),
),
);
const unknown = renderToStaticMarkup(
sourceModule.BusinessLocationSource({
record: { location_recorded_at: '2026-11-02T10:00:00Z' },
}),
);
assert.match(unknown, /Data da fonte: desconhecida/);
assert.doesNotMatch(unknown, /2026/);
} finally {
if (previous === undefined) delete process.env.TZ;
else process.env.TZ = previous;
}
});
@@ -0,0 +1,177 @@
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;
}
const proximity = load('../../resources/js/components/similar-businesses.tsx', {
'@inertiajs/react': { Link: 'a' },
'@/lib/portal-api': {},
});
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const coverage = {
origin_id: 'qa-public-reference',
origin_title: '<Public reference>',
radius_km: 25,
origin_recorded_at: null,
with_public_point: 1,
without_public_point: 3,
source: 'Published register',
method: 'Geodesic, not road',
};
await test('catalogue preserves applied radius in detail links while edits affect only the next search, and clearing removes both proximity fields', () => {
let cursor = 0,
sent;
const state = [];
const Page = load(
'../../resources/js/pages/investment/business-marketplace.tsx',
{
react: {
useState(initial) {
const index = cursor++;
if (!(index in state))
state[index] =
typeof initial === 'function' ? initial() : initial;
return [
state[index],
(value) => {
state[index] =
typeof value === 'function'
? value(state[index])
: value;
},
];
},
},
'@inertiajs/react': {
Link: 'a',
router: {
get: (...args) => {
sent = args;
},
},
},
'./shared': {
Frame: 'div',
button: 'button',
card: 'card',
input: 'input',
},
'./business-types': {
businessModalities: { company_sale: 'Company sale' },
},
'@/components/investment-territory': {
TerritoryFields: () => null,
},
'@/components/opportunity-classification': {
ClassificationSummary: () => null,
},
'@/components/similar-businesses': proximity,
},
).default;
const props = {
filters: {
near_business: 'qa-public-reference',
radius_km: '25',
sector: '4',
},
geographicCoverage: coverage,
results: {
data: [
{
id: 'qa-near',
slug: 'qa-near',
title: 'Nearby',
modality: 'company_sale',
distance_km: 1.2,
location_recorded_at: '2026-10-02T10:00:00Z',
},
],
},
};
const render = () => {
cursor = 0;
return Page(props);
};
let tree = render();
let html = renderToStaticMarkup(tree);
assert.match(html, /1 com ponto utilizável; 3 sem ponto público/);
assert.match(html, /&lt;Public reference&gt;/);
assert.match(html, /data não indicada/);
assert.match(html, /Distância aproximada em linha recta/);
nodes(tree)
.find((node) => node.type === 'input' && node.props.type === 'number')
.props.onChange({ target: { value: '10.5' } });
nodes(tree)
.find(
(node) =>
node.type === 'input' && node.props.id === 'business-search',
)
.props.onChange({ target: { value: 'next search' } });
tree = render();
html = renderToStaticMarkup(tree);
assert.match(
html,
/\/negocios\/qa-near\?near_business=qa-public-reference&amp;radius_km=25&amp;sector=4/,
);
assert.doesNotMatch(html, /qa-near\?[^"]*radius_km=10/);
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(sent[1].radius_km, '10.5');
assert.equal(sent[1].near_business, 'qa-public-reference');
assert.equal(sent[1].sector, '4');
assert.equal(sent[1].q, 'next search');
nodes(tree)
.find((node) => node.type === 'input' && node.props.type === 'number')
.props.onChange({ target: { value: '' } });
tree = render();
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal('radius_km' in sent[1], false);
assert.equal('near_business' in sent[1], false);
assert.equal(sent[1].sector, '4');
});
await test('distance rendering rejects unknown or malformed values and keeps unknown source dates explicit', () => {
for (const distance of [null, undefined, -1, Infinity, NaN, '2'])
assert.equal(
proximity.BusinessDistance({ record: { distance_km: distance } }),
null,
);
const html = renderToStaticMarkup(
proximity.BusinessDistance({
record: { distance_km: 0, location_recorded_at: 'not-a-date' },
}),
);
assert.match(html, /0 km/);
assert.match(html, /data não indicada/);
});
+296
View File
@@ -0,0 +1,296 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { execFileSync } from 'node:child_process';
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
// Pure config export: no application bootstrap, connection or active database access.
const guide = JSON.parse(
execFileSync(
'php',
[
'-r',
"echo json_encode(require 'config/bvm-admission-guide.php', JSON_THROW_ON_ERROR);",
],
{ cwd: new URL('../..', import.meta.url), encoding: 'utf8' },
),
);
guide.sha256 = 'b'.repeat(64);
const lib = load('../../resources/js/lib/investment-guides.ts');
const props = {
guide,
instruments: [],
note: '',
case: null,
saved: null,
canWrite: false,
historical: false,
olderEdition: false,
currentAvailable: true,
workingCopy: false,
contextChanged: false,
unavailableInstruments: [],
history: [],
historyNext: null,
};
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() {
let cursor = 0;
const values = [],
requests = [];
class ValidationError extends Error {}
const component = load('../../resources/js/pages/investment/guide.tsx', {
react: {
useState(initial) {
const i = cursor++;
if (!(i in values)) values[i] = structuredClone(initial);
return [
values[i],
(value) => {
values[i] =
typeof value === 'function'
? value(values[i])
: value;
},
];
},
useRef(initial) {
const i = cursor++;
if (!(i in values)) values[i] = { current: initial };
return values[i];
},
},
'@inertiajs/react': { Link: 'a', router: { visit() {} } },
'./shared': { Frame: 'main', card: '', input: '', button: '' },
'@/lib/investment-guides': lib,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
},
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
profileJson: async (...args) => {
requests.push(args);
return { saved: true };
},
},
});
return {
render(extra = {}) {
cursor = 0;
const outer = component.default({ ...props, ...extra });
return outer.type(outer.props);
},
requests,
};
}
function headingCount(tree, label) {
return nodes(tree).filter(
(n) =>
['h2', 'h3', 'h4'].includes(n.type) && n.props.children === label,
).length;
}
await test('actual source guide renders five paths, scoped gaps and article/page links with explicit historical minimums', () => {
const tree = harness().render(),
html = renderToStaticMarkup(tree);
assert.equal(
nodes(tree).filter(
(n) => n.type === 'input' && n.props.name === 'instruments[]',
).length,
5,
);
assert.match(html, /Que segmento e tipo de valor pretende preparar/);
assert.match(html, /Requisitos por segmento e tipo de valor/);
assert.match(html, /Período indicado até 2025-03-31/);
assert.match(html, /fonte histórica, sem aplicação como mínimo actual/);
assert.match(html, /Por esclarecer/);
assert.match(html, /Regra com dispensa ou condição específica/);
assert.match(html, /Regulamento 04\/2021/);
assert.ok(
nodes(tree).some(
(n) =>
n.type === 'a' &&
n.props.href ===
'https://www.bvm.co.mz/documentos/regulamentos/RegulamentoTerceiroMercado.pdf#page=2',
),
);
assert.match(html, /Art. 2\(1\)\(c\) e art. 8/);
assert.equal(headingCount(tree, 'Preparar para discussão'), 0);
assert.doesNotMatch(html, /name="(note|nuit|email|amount|capital)"/);
});
await test('third-market selection hides the entry audit document while keeping OCAM, declaration and conditional waiver explanations', () => {
const h = harness();
nodes(h.render())
.find((n) => n.props?.value === 'third_shares')
.props.onChange({ target: { checked: true } });
const tree = h.render(),
html = renderToStaticMarkup(tree);
assert.equal(headingCount(tree, 'Auditoria ou certificação aplicável'), 0);
assert.equal(
headingCount(
tree,
'Demonstrações financeiras assinadas por contabilista certificado',
),
1,
);
assert.equal(
headingCount(tree, 'Declaração de actualidade das informações'),
1,
);
assert.equal(
headingCount(tree, 'Detentores do capital e participações'),
1,
);
assert.match(html, /sem extensão automática/);
assert.match(html, /demonstrações e relatório de evolução semestrais/);
assert.doesNotMatch(html, /Existência jurídica de um ano, não derrogável/);
assert.doesNotMatch(
html,
/Relatórios de gestão e contas anuais dos dois exercícios anteriores/,
);
});
await test('multiple paths share common documents once while retaining their different accounts and prospectus conditions', () => {
const h = harness();
for (const code of ['official_shares', 'second_shares'])
nodes(h.render())
.find((n) => n.props?.value === code)
.props.onChange({ target: { checked: true } });
const tree = h.render(),
html = renderToStaticMarkup(tree);
for (const title of [
'Deliberações, estatutos e certidão',
'Relatórios, contas, fiscalização e publicações',
'Auditoria ou certificação aplicável',
'Projecto de prospecto conforme o segmento',
])
assert.equal(headingCount(tree, title), 1);
assert.equal(
headingCount(
tree,
'Demonstrações financeiras assinadas por contabilista certificado',
),
0,
);
assert.match(html, /dois exercícios anteriores/);
assert.match(html, /pelo menos nove meses/);
assert.match(html, /Anexo A do Regulamento do Segundo Mercado/);
assert.doesNotMatch(
html,
/Documentos específicos do empréstimo obrigacionista/,
);
});
await test('bonds use their own document path and external handoffs never receive private note or dossier parameters', () => {
const dossier = {
id: 'SYNTHETIC-private-dossier',
title: 'SYNTHETIC private context',
version: 1,
};
const tree = harness().render({
case: dossier,
canWrite: true,
instruments: ['second_bonds'],
note: 'SYNTHETIC PRIVATE NOTE',
});
assert.equal(
headingCount(
tree,
'Documentos específicos do empréstimo obrigacionista',
),
1,
);
assert.equal(
headingCount(tree, 'Detentores do capital e participações'),
0,
);
assert.ok(
nodes(tree).some(
(n) =>
n.props?.href ===
'/balcao-virtual/dossiers/SYNTHETIC-private-dossier',
),
);
const external = nodes(tree).filter(
(n) => n.type === 'a' && n.props.href?.startsWith('https://'),
);
assert.ok(external.length > 10);
for (const link of external) {
assert.doesNotMatch(
link.props.href,
/SYNTHETIC|note=|context=|dossier=/,
);
assert.equal(new URL(link.props.href).search, '');
assert.equal(link.props.rel, 'noopener noreferrer');
}
assert.ok(
external.some(
(n) => n.props.href === 'https://www.bvm.co.mz/empresas/0/0',
),
);
});
await test('historical BVM references render frozen sources and conditions without reopening a write or mixing guide history', async () => {
const h = harness();
const oldGuide = { ...guide, version: 'SYNTHETIC-old-BVM-edition' };
const tree = h.render({
guide: oldGuide,
instruments: ['third_shares'],
case: { id: 'SYNTHETIC-case', title: 'SYNTHETIC', version: 3 },
saved: { revision: 1, at: 'SYNTHETIC-date', context: { revision: 0 } },
canWrite: true,
historical: true,
history: [
{
id: 'SYNTHETIC-event',
revision: 1,
edition: 'SYNTHETIC-old-BVM-edition',
at: 'SYNTHETIC-date',
},
],
});
assert.equal(
nodes(tree).find((n) => n.type === 'fieldset').props.disabled,
true,
);
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await new Promise((resolve) => setImmediate(resolve));
assert.equal(h.requests.length, 0);
assert.match(renderToStaticMarkup(tree), /SYNTHETIC-old-BVM-edition/);
assert.ok(
nodes(tree).some(
(n) =>
n.props?.href ===
'/investimentos/SYNTHETIC-case/guias/bolsa?revision=SYNTHETIC-event',
),
);
});
+335
View File
@@ -0,0 +1,335 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const urls = load('../../resources/js/lib/company-comparison.ts');
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const questions = {
purpose: {
label: 'Finalidade',
options: {
new: 'Nova',
representation: 'Representação',
unknown: 'Por definir',
},
},
participants: {
label: 'Participantes',
options: { one: 'Um', several: 'Vários', unknown: 'Por definir' },
},
regulated: {
label: 'Regras específicas',
options: { unknown: 'Por conferir' },
},
preferred: {
label: 'Preferência',
options: { quotas: 'Quotas', unknown: 'Por definir' },
},
};
const props = {
definition: { version: 'v1', questions },
answers: {
purpose: 'new',
participants: 'one',
regulated: 'unknown',
preferred: 'quotas',
},
result: {
engine_version: 'v1',
questions,
active: Object.keys(questions),
pending: ['regulated'],
route: 'Compare alternativas.',
preparation: ['Preparar contrato.'],
scope: 'Edição indicada.',
source: {
title: 'Código Comercial',
edition: 'Edição consultada',
issued_on: '2022-05-25',
consulted_on: '2026-11-02',
url: 'https://tsrm.gov.mz/source.pdf',
},
forms: [
{
code: 'quotas',
title: 'Sociedade <SYNTHETIC>',
description: 'Capital em quotas',
articles: 'Artigo 281',
source_href: 'https://tsrm.gov.mz/source.pdf#page=42',
selected: true,
constraints: ['SYNTHETIC incompatibility'],
notes: ['Conferir modalidade.'],
},
],
},
case: null,
saved: null,
history: [],
historyNext: null,
historical: false,
workingCopy: false,
canWrite: false,
};
function harness() {
let cursor = 0;
const values = [],
refs = [],
visits = [],
requests = [];
let rejectSave = false;
const hooks = {
useState(initial) {
const i = cursor++;
if (!(i in values))
values[i] = typeof initial === 'function' ? initial() : initial;
return [
values[i],
(v) => {
values[i] = v;
},
];
},
useRef(initial) {
const i = cursor++;
if (!(i in values)) {
values[i] = { current: initial };
refs.push(values[i]);
}
return values[i];
},
};
const module = load(
'../../resources/js/pages/investment/company-comparison.tsx',
{
react: hooks,
'@inertiajs/react': {
Link: 'a',
router: { visit: (...args) => visits.push(args) },
},
'./shared': { Frame: 'main', card: '', input: '', button: '' },
'@/lib/company-comparison': urls,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
},
'@/lib/profile-json': {
profileJson: async (...args) => {
requests.push(args);
if (rejectSave)
throw new Error('SYNTHETIC conflict; keep edits');
return { saved: true };
},
},
},
);
return {
render(extra = {}) {
cursor = 0;
const outer = module.default({ ...props, ...extra });
return outer.type(outer.props);
},
refs,
visits,
requests,
fail() {
rejectSave = true;
},
};
}
const find = (tree, name) =>
nodes(tree).find((node) => node.props?.name === `answers[${name}]`);
const button = (tree, text) =>
nodes(tree).find(
(node) => node.type === 'button' && node.props.children === text,
);
await test('public comparison is a real GET form, safely renders sources and constraints, and asks no identity data', () => {
const h = harness(),
tree = h.render(),
html = renderToStaticMarkup(tree);
const form = nodes(tree).find((node) => node.type === 'form');
assert.equal(form.props.method, 'get');
assert.equal(form.props.action, '/formas-juridicas');
assert.match(html, /Sociedade &lt;SYNTHETIC&gt;/);
assert.match(html, /Incompatibilidade a resolver/);
assert.match(html, /Preferência para aprofundar/);
assert.match(html, /2022-05-25/);
assert.doesNotMatch(html, /name="(email|nuit|name|registration)"/);
});
await test('changing to representation hides inapplicable questions while keeping their answers for later recovery', () => {
const h = harness();
find(h.render(), 'purpose').props.onChange({
target: { value: 'representation' },
});
const tree = h.render();
assert.equal(find(tree, 'participants').type, 'input');
assert.equal(find(tree, 'participants').props.type, 'hidden');
assert.equal(find(tree, 'participants').props.value, 'one');
assert.equal(find(tree, 'preferred').props.value, 'quotas');
find(tree, 'purpose').props.onChange({ target: { value: 'new' } });
assert.equal(find(h.render(), 'participants').props.value, 'one');
});
await test('dossier choice uses current browser values and transports only answer codes through normal authentication', () => {
const h = harness(),
tree = h.render();
h.refs[0].current = {};
const old = globalThis.FormData;
globalThis.FormData = class {
get(key) {
return key === 'answers[participants]' ? 'several' : null;
}
};
try {
button(tree, 'Escolher dossier para guardar').props.onClick();
} finally {
globalThis.FormData = old;
}
const target = new URL(h.visits[0][0], 'https://portal.test');
assert.equal(target.pathname, '/investimentos');
assert.equal(
target.searchParams.get('company_comparison[participants]'),
'several',
);
assert.equal(
target.searchParams.get('company_comparison[preferred]'),
'quotas',
);
});
await test('a failed save keeps actual field values and context, and never navigates as though the comparison was saved', async () => {
const h = harness();
h.fail();
const extra = {
case: { id: 'dossier-a', title: 'SYNTHETIC dossier', version: 7 },
canWrite: true,
};
let tree = h.render(extra);
h.refs[0].current = {};
find(tree, 'participants').props.onChange({ target: { value: 'several' } });
tree = h.render(extra);
const old = globalThis.FormData;
globalThis.FormData = class {
get(key) {
return key === 'answers[participants]' ? 'several' : null;
}
};
try {
await button(tree, 'Guardar no dossier').props.onClick();
} finally {
globalThis.FormData = old;
}
assert.equal(h.requests[0][0], '/investimentos/dossier-a/forma-juridica');
assert.equal(h.requests[0][1].version, 7);
assert.equal(h.requests[0][1].answers.participants, 'several');
assert.equal(h.visits.length, 0);
const after = h.render(extra);
assert.equal(find(after, 'participants').props.value, 'several');
assert.match(renderToStaticMarkup(after), /SYNTHETIC conflict; keep edits/);
assert.equal(
button(after, 'Reabrir com estas respostas').props.type,
'submit',
);
assert.equal(
nodes(after).find((node) => node.type === 'form').props.method,
'get',
);
});
await test('historical and superseded results retain their own question labels and source and require explicit current preparation', () => {
const h = harness();
const historicalResult = {
...props.result,
engine_version: 'older',
questions: {
...questions,
participants: {
...questions.participants,
label: 'SYNTHETIC historical wording',
},
},
};
const tree = h.render({
case: { id: 'dossier-a', title: 'Dossier', version: 3 },
canWrite: true,
historical: true,
saved: { revision: 1, at: '2026-11-01', result: historicalResult },
result: historicalResult,
});
const html = renderToStaticMarkup(tree);
assert.match(html, /SYNTHETIC historical wording/);
assert.equal(nodes(tree).filter((node) => node.type === 'form').length, 0);
const link = nodes(tree).find(
(node) =>
node.props?.children ===
'Preparar nova comparação com estas respostas',
);
assert.equal(
new URL(link.props.href, 'https://portal.test').searchParams.get(
'answers[participants]',
),
'one',
);
assert.equal(
new URL(link.props.href, 'https://portal.test').searchParams.has(
'revision',
),
false,
);
});
await test('successful save recovers the saved dossier edition and history links retain the exact dossier scope', async () => {
const h = harness(),
extra = {
case: { id: 'dossier-a', title: 'Dossier', version: 5 },
canWrite: true,
history: [
{
id: 'event-a',
revision: 2,
at: '2026-11-02',
engine_version: 'v1',
},
],
historyNext: 100,
};
const tree = h.render(extra);
h.refs[0].current = {};
const old = globalThis.FormData;
globalThis.FormData = class {
get() {
return null;
}
};
try {
await button(tree, 'Guardar no dossier').props.onClick();
} finally {
globalThis.FormData = old;
}
assert.equal(h.visits[0][0], '/investimentos/dossier-a/forma-juridica');
assert.equal(h.visits[0][1].preserveState, false);
const html = renderToStaticMarkup(tree);
assert.match(html, /dossier-a\/forma-juridica\?revision=event-a/);
assert.match(html, /dossier-a\/forma-juridica\?history_before=100/);
});
+389
View File
@@ -0,0 +1,389 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/company-preparation.ts');
const party = {
id: 'SYNTHETIC-party',
name: '<SYNTHETIC>',
kind: 'person',
source: null,
roles: ['subscriber'],
represented_id: null,
cash: '10',
in_kind: '0',
paid: '2',
share_count: '5',
work: null,
commitment: null,
};
const facts = {
form: 'quotas',
proposed_name: null,
seat: null,
activities: null,
regulated: 'unknown',
currency: 'MZN',
capital: '10',
nominal_value: '2',
management: null,
binding: null,
notes: null,
parties: [party],
};
const props = {
case: { id: 'SYNTHETIC-case', title: 'SYNTHETIC dossier', version: 1 },
canWrite: true,
historical: false,
definition: {
version: 'v1',
forms: {
individual: { title: 'Individual' },
quotas: { title: 'Quotas' },
anonymous: { title: 'Anónima' },
},
roles: {
subscriber: 'Sócio',
administrator: 'Administração',
representative: 'Representante',
beneficial_owner: 'Beneficiário',
},
template_notice: 'Exemplares pendentes; ficha de preparação.',
source: {
title: 'SYNTHETIC source',
edition: '2022',
url: 'https://source.test/code.pdf',
},
},
facts,
review: {
issues: ['SYNTHETIC pending'],
totals: { subscribed: '10', unpaid: '8' },
note: 'SYNTHETIC declared',
},
saved: null,
sources: {
case_proponent: {
name: 'SYNTHETIC reused',
kind: 'person',
origin: 'Proponente do dossier',
},
},
history: [],
historyNext: null,
};
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const named = (tree, name) => nodes(tree).find((n) => n.props?.name === name);
const button = (tree, label) =>
nodes(tree).find((n) => n.type === 'button' && n.props.children === label);
const tick = () => new Promise((resolve) => setImmediate(resolve));
function harness() {
let cursor = 0,
reject = false;
const values = [],
refs = [],
visits = [],
requests = [];
class ValidationError extends Error {
constructor(message) {
super(message);
this.fields = { 'facts.capital': 'SYNTHETIC amount error' };
}
}
const component = load(
'../../resources/js/pages/investment/company-preparation.tsx',
{
react: {
useState(initial) {
const i = cursor++;
if (!(i in values)) values[i] = structuredClone(initial);
return [
values[i],
(next) => {
values[i] =
typeof next === 'function'
? next(values[i])
: next;
},
];
},
useRef(initial) {
const i = cursor++;
if (!(i in values)) {
values[i] = { current: initial };
refs.push(values[i]);
}
return values[i];
},
},
'@inertiajs/react': {
Link: 'a',
router: { visit: (...args) => visits.push(args) },
},
'./shared': { Frame: 'main', card: '', input: '', button: '' },
'@/lib/company-preparation': lib,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
},
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
profileJson: async (...args) => {
requests.push(args);
if (args[2] === 'GET')
return {
...props,
case: { ...props.case, version: 4 },
facts: {
...facts,
notes: 'SYNTHETIC concurrent edit',
},
};
if (reject) throw new ValidationError('SYNTHETIC conflict');
return { saved: true };
},
},
},
);
return {
render(extra = {}) {
cursor = 0;
const outer = component.default({ ...props, ...extra });
return outer.type(outer.props);
},
refs,
visits,
requests,
fail() {
reject = true;
},
};
}
async function withData(data, fn) {
const original = globalThis.FormData;
globalThis.FormData = class {
get(key) {
return Object.hasOwn(data, key) ? data[key] : null;
}
};
try {
return await fn();
} finally {
globalThis.FormData = original;
}
}
await test('preparation renders seven sections, escaped private names, source and explicit incomplete state', () => {
const tree = harness().render(),
html = renderToStaticMarkup(tree);
assert.equal(
nodes(tree).filter(
(n) => n.type === 'h2' && /^[1-7]\./.test(n.props.children),
).length,
7,
);
assert.match(html, /&lt;SYNTHETIC&gt;/);
assert.match(html, /Exemplares pendentes/);
assert.match(html, /SYNTHETIC pending/);
assert.match(html, /https:\/\/source.test\/code.pdf/);
assert.doesNotMatch(html, /name="(email|nuit|password)"/);
});
await test('changing form hides only inapplicable capital and preserves amounts for later recovery', () => {
const h = harness();
named(h.render(), 'form').props.onChange({
target: { value: 'individual' },
});
assert.equal(named(h.render(), 'capital'), undefined);
named(h.render(), 'form').props.onChange({
target: { value: 'anonymous' },
});
assert.equal(named(h.render(), 'capital').props.value, '10');
assert.equal(named(h.render(), 'nominal_value').props.value, '2');
assert.equal(named(h.render(), `${party.id}.share_count`).props.value, '5');
});
await test('explicit reuse fills source identity while roles remain independently selectable', () => {
const h = harness();
const source = nodes(h.render()).find(
(n) =>
n.type === 'select' &&
n.props.children?.[0]?.props?.children ===
'Informação nova desta preparação',
);
source.props.onChange({ target: { value: 'case_proponent' } });
assert.equal(
named(h.render(), `${party.id}.name`).props.value,
'SYNTHETIC reused',
);
assert.equal(named(h.render(), `${party.id}.name`).props.readOnly, true);
const checkboxes = nodes(h.render()).filter(
(n) => n.type === 'input' && n.props.type === 'checkbox',
);
assert.deepEqual(
checkboxes.map((n) => n.props.checked),
[true, false, false, false],
);
checkboxes[1].props.onChange({ target: { checked: true } });
assert.deepEqual(
nodes(h.render())
.filter((n) => n.type === 'input' && n.props.type === 'checkbox')
.map((n) => n.props.checked),
[true, true, false, false],
);
});
await test('actual browser values are sent privately and hidden values survive without forged source snapshots', async () => {
await withData(
{
proposed_name: 'SYNTHETIC autofill',
[`${party.id}.cash`]: '7,25',
capital: '',
},
() => {
const values = lib.preparationValues(
{},
{
...facts,
form: 'individual',
parties: [
{
...party,
source_snapshot: { reference: 'DO NOT POST' },
},
],
},
);
assert.equal(values.proposed_name, 'SYNTHETIC autofill');
assert.equal(values.capital, null);
assert.equal(values.parties[0].cash, '7,25');
assert.equal(values.parties[0].share_count, '5');
assert.equal('source_snapshot' in values.parties[0], false);
},
);
const h = harness();
h.render();
h.refs[0].current = {};
await withData({ notes: 'SYNTHETIC autofill' }, async () => {
nodes(h.render())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
});
assert.equal(
h.requests[0][0],
'/investimentos/SYNTHETIC-case/preparar-empresa',
);
assert.equal(h.requests[0][1].facts.notes, 'SYNTHETIC autofill');
assert.deepEqual(h.visits, [
[
'/investimentos/SYNTHETIC-case/preparar-empresa',
{ preserveState: false },
],
]);
});
await test('failed save retains private edits, consults current version without URL data and requires explicit reconciliation', async () => {
const h = harness();
h.render();
h.refs[0].current = {};
h.fail();
await withData({ notes: 'SYNTHETIC unsaved' }, async () => {
nodes(h.render())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
});
assert.equal(h.visits.length, 0);
assert.equal(named(h.render(), 'notes').props.value, 'SYNTHETIC unsaved');
assert.match(renderToStaticMarkup(h.render()), /SYNTHETIC amount error/);
await button(
h.render(),
'Conferir edição actual sem perder estes dados',
).props.onClick();
assert.equal(h.requests[1][2], 'GET');
assert.equal(named(h.render(), 'notes').props.value, 'SYNTHETIC unsaved');
const recoveryHtml = renderToStaticMarkup(h.render());
assert.match(recoveryHtml, /SYNTHETIC concurrent edit/);
assert.match(recoveryHtml, /Denominação proposta/);
const recoverySection = nodes(h.render()).find(
(n) =>
n.type === 'section' &&
nodes(n).some(
(child) =>
child.type === 'h2' &&
child.props.children ===
'Edição actualmente guardada no dossier',
),
);
assert.doesNotMatch(
renderToStaticMarkup(recoverySection),
/source_snapshot|proposed_name|SYNTHETIC-party/,
);
button(
h.render(),
'Conferi: manter os meus dados para uma nova revisão',
).props.onClick();
assert.equal(named(h.render(), 'notes').props.value, 'SYNTHETIC unsaved');
await withData({}, async () => {
nodes(h.render())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
});
assert.equal(h.requests[2][1].version, 4);
});
await test('history and consultation keep all fields read-only and cannot submit a write', async () => {
const h = harness();
const tree = h.render({
historical: true,
saved: { revision: 1, at: 'SYNTHETIC-date' },
history: [{ id: 'old', revision: 1, at: 'SYNTHETIC-date' }],
historyNext: 7,
});
assert.equal(
nodes(tree).find((n) => n.type === 'fieldset').props.disabled,
true,
);
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
assert.equal(h.requests.length, 0);
assert.match(renderToStaticMarkup(tree), /preparar-empresa\?revision=old/);
assert.match(renderToStaticMarkup(tree), /history_before=7/);
const viewer = harness();
assert.equal(
nodes(viewer.render({ canWrite: false })).find(
(n) => n.type === 'fieldset',
).props.disabled,
true,
);
});
+171
View File
@@ -0,0 +1,171 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url);
const Link = ({ children, href }) =>
React.createElement('a', { href }, children);
const Empty = () => null;
const mocks = {
'@inertiajs/react': {
Link,
useForm: (data) => ({ data, processing: false, errors: {} }),
},
'@/lib/crm-record-edit': {
useCrmRecordEdit: ({ values }) => ({
form: { processing: false },
values,
blocked: false,
error: () => undefined,
}),
},
'@/components/crm-edit-comparison': { default: Empty },
'../management/shared': {
Management: ({ children }) =>
React.createElement('main', null, children),
Field: ({ label, children }) =>
React.createElement('label', null, label, children),
button: '',
control: '',
},
'./types': {
leadStates: {
new: 'Novo',
qualified: 'Qualificado',
disqualified: 'Desqualificado',
converted: 'Convertido',
},
taskStates: { open: 'Aberta', done: 'Concluída' },
},
};
function load(path) {
const code = ts.transpileModule(
fs.readFileSync(new URL('../../' + path, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/pages/management/shared'] = mocks['../management/shared'];
mocks['./operation-key'] = {
createOperationKey: () => '00000000-0000-4000-8000-000000000001',
};
mocks['./profile-json'] = load('resources/js/lib/profile-json.ts');
mocks['./crm-task-preparation'] = load(
'resources/js/lib/crm-task-preparation.ts',
);
mocks['@/lib/crm-task-creation'] = load(
'resources/js/lib/crm-task-creation.ts',
);
mocks['@/components/crm-task-creation'] = load(
'resources/js/components/crm-task-creation.tsx',
);
const Detail = load('resources/js/pages/crm/lead.tsx').default;
function render(patch = {}) {
return renderToStaticMarkup(
React.createElement(Detail, {
lead: {
id: 'one',
version_no: 1,
title: 'SYNTHETIC lead',
status: 'new',
owner_user_id: 1,
tasks: [],
},
taskCreation: { lead_id: 'one', actor_id: 1, commands: [] },
contacts: [],
owners: [{ id: 1, name: 'SYNTHETIC manager' }],
nextAction: { future_tasks: 0 },
...patch,
}),
);
}
test('an active lead without an available future task explains the existing requirement and links to its creation form', () => {
const html = render();
assert.match(html, /0 tarefas disponíveis com prazo futuro/);
assert.match(html, /role="status"/);
assert.match(html, /dossier encerrado ficam no histórico/);
assert.match(html, /href="#new-crm-task"/);
assert.match(html, /id="new-crm-task"/);
assert.doesNotMatch(html, /disabled=""/); // Disqualification and creation remain available; the server checks the chosen operation.
});
test('a future action count does not claim that qualification or completion has already occurred', () => {
const singular = render({ nextAction: { future_tasks: 1 } });
assert.match(singular, /1 tarefa disponível com prazo futuro/);
assert.doesNotMatch(singular, /1 tarefas/);
const html = render({ nextAction: { future_tasks: 2 } });
assert.match(html, /2 tarefas disponíveis com prazo futuro/);
assert.doesNotMatch(
html,
/role="status"|acompanhamento qualificado|licença aprovada/,
);
});
test('a suspended task retains its title, deadline and history without a response button', () => {
const html = render({
lead: {
id: 'one',
version_no: 1,
title: 'SYNTHETIC lead',
status: 'qualified',
owner_user_id: 1,
tasks: [
{
id: 'paused',
version_no: 1,
title: 'SYNTHETIC preserved task',
status: 'open',
due_at: '2026-11-05T10:00:00Z',
assignee_user_id: 1,
can_update: false,
},
],
},
});
assert.match(html, /SYNTHETIC preserved task/);
assert.match(html, /Dossier associado encerrado/);
assert.match(html, /Maputo/);
assert.match(html, /id="crm-task-paused"/);
assert.doesNotMatch(html, /Actualizar tarefa<\/button>/);
});
test('an older response without availability metadata does not invent a zero', () => {
const html = render({ nextAction: undefined });
assert.doesNotMatch(
html,
/tarefas disponíveis com prazo futuro|role="status"/,
);
assert.match(html, /Registar próxima acção/);
});
test('disqualified leads retain their form without the active-lead requirement notice', () => {
const html = render({
lead: {
id: 'one',
version_no: 1,
title: 'SYNTHETIC disqualified lead',
status: 'disqualified',
owner_user_id: 1,
tasks: [],
},
});
assert.match(html, /0 tarefas disponíveis com prazo futuro/);
assert.doesNotMatch(html, /role="status"|disabled=""/);
});
+463
View File
@@ -0,0 +1,463 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}, suffix = '') {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function harness(initial = {}, component = null) {
const cells = [],
sent = [],
reloads = [];
let cursor,
result,
props = {
id: 'one',
kind: 'investor',
version: 1,
values: { name: 'original', status: 'prospect' },
...initial,
};
const form = {
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
},
setDefaults(value) {
this.defaults = value;
},
clearErrors(key) {
if (key) delete this.errors[key];
else this.errors = {};
},
transform(callback) {
this.transformer = callback;
},
patch(url, options) {
sent.push({
url,
options,
data: structuredClone(this.transformer(this.data)),
});
},
};
const mocks = {
react: {
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) => {
cells[i] =
typeof value === 'function'
? value(cells[i])
: value;
},
];
},
},
'@inertiajs/react': {
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
},
useForm(initial) {
form.data ??= structuredClone(initial);
return form;
},
},
'../management/shared': {
Management: 'main',
Field: 'label',
control: '',
button: '',
},
'./types': {
leadStates: { new: 'Novo', qualified: 'Qualificado' },
taskStates: { open: 'Aberta', in_progress: 'Em curso' },
},
};
const hook = load('../../resources/js/lib/crm-record-edit.ts', mocks);
mocks['@/lib/crm-record-edit'] = hook;
mocks['@/components/crm-edit-comparison'] = { default: () => null };
mocks['@/components/crm-task-creation'] = { default: () => null };
const renderComponent = component
? load(component.file, mocks, component.suffix ?? '')[
component.name ?? 'default'
]
: hook.useCrmRecordEdit;
function render(patch = {}) {
props = { ...props, ...patch };
cursor = 0;
result = renderComponent(props);
return result;
}
render();
return {
form,
sent,
reloads,
render,
get edit() {
return result;
},
};
}
function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
const text = (tree) =>
typeof tree === 'string'
? tree
: Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: '';
test('different fields merge only after explicit adoption, retaining batched deliberate edits', () => {
const h = harness();
h.edit.change('name', 'my name');
h.edit.change('extra', 'ignored');
h.render({ version: 2, values: { name: 'original', status: 'active' } });
assert.deepEqual(h.edit.changed, ['status']);
assert.deepEqual(h.edit.unresolved, []);
h.edit.submit('/synthetic');
assert.equal(h.sent.length, 0);
h.edit.adopt();
h.render();
assert.deepEqual(h.edit.values, { name: 'my name', status: 'active' });
h.edit.submit('/synthetic');
assert.deepEqual(h.sent[0].data, {
name: 'my name',
status: 'active',
version: 2,
});
});
test('same-field conflicts require a choice and deliberate return to the initial value is retained', () => {
const h = harness();
h.edit.change('name', 'temporary');
h.edit.change('name', 'original');
h.render({
version: 2,
values: { name: 'other operator', status: 'prospect' },
});
assert.deepEqual(h.edit.unresolved, ['name']);
h.edit.adopt();
h.render();
assert.equal(h.edit.baseVersion, 1);
h.edit.choose('name', 'mine');
h.render();
h.edit.adopt();
h.render();
assert.equal(h.edit.values.name, 'original');
assert.equal(h.edit.baseVersion, 2);
});
test('choosing the current value changes only that field and another update requires a fresh choice', () => {
const h = harness();
h.edit.change('name', 'mine');
h.edit.change('status', 'inactive');
h.render({ version: 2, values: { name: 'remote', status: 'prospect' } });
h.edit.choose('name', 'current');
h.render();
h.edit.adopt();
h.render();
assert.deepEqual(h.edit.values, { name: 'remote', status: 'inactive' });
h.render({
version: 3,
values: { name: 'new remote', status: 'prospect' },
});
assert.deepEqual(h.edit.unresolved, ['name']);
});
test('refresh keeps the draft and version error until the current revision is compared', () => {
const h = harness();
h.edit.change('name', 'draft');
h.form.errors.version = 'Stale';
h.render();
h.edit.submit('/synthetic');
assert.equal(h.sent.length, 0);
h.edit.refresh();
h.render();
assert.deepEqual(h.reloads[0].only, ['investor', 'contacts']);
assert.equal(h.edit.values.name, 'draft');
assert.equal(h.edit.blocked, true);
h.reloads[0].onFinish();
h.render({ version: 2, values: { name: 'original', status: 'active' } });
h.edit.adopt();
h.render();
assert.equal(h.form.errors.version, undefined);
assert.equal(h.edit.values.name, 'draft');
});
test('success uses the actual returned record and keeps edits made while saving', () => {
const h = harness({
kind: 'contact',
values: { email: 'UPPER@EXAMPLE.INVALID', phone: '111' },
});
h.edit.submit('/synthetic');
h.edit.change('email', 'temporary');
h.edit.change('email', 'UPPER@EXAMPLE.INVALID');
h.edit.change('phone', '222');
assert.equal(h.sent[0].data.phone, '111');
h.sent[0].options.onSuccess({
props: {
contacts: [
{ id: 'different', version_no: 900 },
{
id: 'one',
version_no: 2,
email: 'upper@example.invalid',
phone: '111',
},
],
},
});
h.render({
version: 2,
values: { email: 'upper@example.invalid', phone: '111' },
});
assert.deepEqual(h.edit.values, {
email: 'UPPER@EXAMPLE.INVALID',
phone: '222',
});
assert.deepEqual(h.form.defaults, {
version: 2,
values: { email: 'upper@example.invalid', phone: '111' },
});
h.edit.submit('/synthetic');
assert.equal(h.sent[1].data.version, 2);
});
test('lead success clears the previous event reason while keeping a newly typed reason', () => {
for (const duringSave of [false, true]) {
const h = harness({
kind: 'lead',
values: { status: 'new', qualification_reason: '' },
blankAfterSave: ['qualification_reason'],
});
h.edit.change('qualification_reason', 'first event');
h.render();
h.edit.submit('/synthetic');
if (duringSave) h.edit.change('qualification_reason', 'new event');
h.sent[0].options.onSuccess({
props: {
taskCreation: { lead_id: 'one', actor_id: 1, commands: [] },
lead: {
id: 'one',
version_no: 2,
status: 'qualified',
qualification_reason: 'first event',
},
},
});
h.render({
version: 2,
values: { status: 'qualified', qualification_reason: '' },
});
assert.equal(
h.edit.values.qualification_reason,
duringSave ? 'new event' : '',
);
}
});
test('task success resolves the exact task; invalid responses and another record cannot reset a draft', () => {
const h = harness({ kind: 'task', values: { status: 'open' } });
h.edit.change('status', 'in_progress');
h.render();
h.edit.submit('/synthetic');
for (const props of [
{ lead: { tasks: [{ id: 'other', version_no: 2, status: 'done' }] } },
{ lead: { tasks: [{ id: 'one', version_no: '2', status: 'done' }] } },
]) {
h.sent[0].options.onSuccess({ props });
assert.equal(h.form.data.values.status, 'in_progress');
}
h.sent[0].options.onSuccess({
props: {
lead: {
tasks: [{ id: 'one', version_no: 2, status: 'in_progress' }],
},
},
});
h.render({ version: 2 });
assert.equal(h.edit.baseVersion, 2);
h.edit.submit('/synthetic');
h.render({ id: 'two' });
h.sent[1].options.onSuccess({
props: {
lead: { tasks: [{ id: 'one', version_no: 3, status: 'done' }] },
},
});
assert.equal(h.form.data.values.status, 'in_progress');
assert.equal(h.edit.blocked, true);
});
test('invalid version blocks a command and transformed field errors remain accessible', () => {
const h = harness({ version: 0 });
h.edit.submit('/synthetic');
assert.equal(h.sent.length, 0);
h.form.errors.email = 'Invalid email';
assert.equal(h.edit.error('email'), 'Invalid email');
});
test('comparison offers explicit non-submit choices and blocks adoption while conflicts remain', () => {
const h = harness();
h.edit.change('name', 'mine');
h.render({ version: 2, values: { name: 'remote', status: 'prospect' } });
const Panel = load(
'../../resources/js/components/crm-edit-comparison.tsx',
).default;
const tree = Panel({ editor: h.edit, labels: { name: 'Nome' } });
const buttons = nodes(tree).filter((node) => node.type === 'button');
assert.ok(buttons.every((button) => button.props.type === 'button'));
assert.match(text(tree), /Actualmente guardado/);
assert.match(text(tree), /mine/);
assert.match(text(tree), /remote/);
assert.equal(buttons.at(-1).props.disabled, true);
buttons
.find((button) => text(button).includes('Manter minha'))
.props.onClick();
h.render();
assert.equal(h.edit.unresolved.length, 0);
});
test('all four CRM forms send their real revisions without asking the user to enter one', () => {
const cases = [
{
file: '../../resources/js/pages/crm/investor.tsx',
props: {
investor: {
id: 'one',
version_no: 6,
legal_name: 'Synthetic investor',
investor_type: 'domestic',
status: 'prospect',
},
contacts: [],
leads: [],
},
expected: {
legal_name: 'Synthetic investor',
investor_type: 'domestic',
status: 'prospect',
version: 6,
},
},
{
file: '../../resources/js/pages/crm/investor.tsx',
suffix: '\nexport { ContactForm };',
name: 'ContactForm',
props: {
investorId: 'i',
contact: {
id: 'one',
version_no: 7,
full_name: 'Synthetic',
email: 'a@example.invalid',
phone: '',
},
},
expected: {
full_name: 'Synthetic',
email: 'a@example.invalid',
phone: '',
version: 7,
},
},
{
file: '../../resources/js/pages/crm/lead.tsx',
props: {
taskCreation: { lead_id: 'one', actor_id: 1, commands: [] },
lead: {
id: 'one',
version_no: 9,
title: 'Synthetic lead',
status: 'new',
owner_user_id: 1,
tasks: [],
},
contacts: [],
owners: [{ id: 1, name: 'Synthetic owner' }],
},
expected: {
status: 'new',
owner_user_id: '1',
qualification_reason: '',
version: 9,
},
},
{
file: '../../resources/js/pages/crm/lead.tsx',
suffix: '\nexport { TaskRow };',
name: 'TaskRow',
props: {
leadId: 'l',
task: {
id: 'one',
version_no: 8,
title: 'Synthetic',
status: 'open',
due_at: null,
assignee_user_id: 1,
can_update: true,
},
},
expected: { status: 'open', version: 8 },
},
];
for (const item of cases) {
const h = harness(item.props, item);
nodes(h.edit)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.deepEqual(h.sent[0].data, item.expected);
assert.equal(
nodes(h.edit).filter(
(node) =>
node.type === 'input' && node.props.name === 'version',
).length,
0,
);
}
});
+207
View File
@@ -0,0 +1,207 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text, leadId } from './helpers/crm-task-creation.mjs';
const form = 'new-crm-task';
function fill(h, title = 'SYNTHETIC first') {
h.change(form, 'Tarefa', title);
h.change(form, 'Prazo (hora local)', '2027-11-04T10:30');
}
function saved(h, request, patch = {}) {
return {
...h.props,
lead: {
...h.props.lead,
tasks: [
{
id: '20000000-0000-4000-8000-000000000001',
title: request.data.title,
due_at: request.data.due_at,
assignee_user_id: Number(request.data.assignee_user_id),
version_no: 1,
status: 'open',
},
],
},
taskCreation: {
lead_id: leadId,
actor_id: 1,
commands: [
{
key: request.data.client_key,
task_id: '20000000-0000-4000-8000-000000000001',
version: 1,
},
],
},
...patch,
};
}
test('confirmation preserves title and deadline edited after the request was sent', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.change(form, 'Tarefa', 'SYNTHETIC later');
h.change(form, 'Prazo (hora local)', '2027-11-05T11:00');
h.success(saved(h, request), request);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC later');
assert.equal(
h.field(form, 'Prazo (hora local)').props.value,
'2027-11-05T11:00',
);
});
test('a lost response retries exactly the frozen request, preserving later edits', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.change(form, 'Tarefa', 'SYNTHETIC next task');
h.change(form, 'Responsável pela tarefa', '2');
h.fail(request);
const retry = h.submit(form);
assert.deepEqual(retry.data, request.data);
h.success(saved(h, retry), retry);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC next task');
assert.equal(h.field(form, 'Responsável pela tarefa').props.value, '2');
const next = h.submit(form);
assert.notEqual(next.data.client_key, request.data.client_key);
assert.equal(next.data.title, 'SYNTHETIC next task');
});
test('a fresh read acknowledges the committed creation without posting again', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.fail(request, 500);
h.click('Actualizar tarefas');
assert.deepEqual(h.reloads.at(-1).only, [
'lead',
'owners',
'taskCreation',
'nextAction',
]);
h.refreshed(saved(h, request));
assert.equal(h.sent.length, 1);
assert.equal(h.field(form, 'Tarefa').props.value, '');
assert.match(text(h.tree), /Tarefa registada/);
});
test('unconfirmed reads keep the original command and later edits', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.fail(request);
h.change(form, 'Tarefa', 'SYNTHETIC later');
h.click('Actualizar tarefas');
h.refreshed(h.props);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC later');
assert.deepEqual(h.submit(form).data, request.data);
});
test('another account or lead cannot acknowledge or clear a pending command', () => {
for (const context of [
{ lead_id: leadId, actor_id: 2 },
{ lead_id: 'other', actor_id: 1 },
]) {
const h = harness();
fill(h);
const request = h.submit(form);
const next = saved(h, request);
next.taskCreation = { ...next.taskCreation, ...context };
request.options.onSuccess({ props: next });
request.form.processing = false;
h.render();
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC first');
assert.doesNotMatch(text(h.tree), /Tarefa registada/);
}
});
test('a same-version task mismatch does not count as confirmation', () => {
const h = harness();
fill(h);
const request = h.submit(form);
const next = saved(h, request);
next.lead.tasks[0].title = 'SYNTHETIC different';
h.success(next, request);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC first');
assert.match(text(h.tree), /não permitiu confirmar/);
});
test('later task changes and a removed task are acknowledged without restoration', () => {
for (const removed of [false, true]) {
const h = harness();
fill(h);
const request = h.submit(form);
const next = saved(h, request);
if (removed) next.lead.tasks = [];
else
Object.assign(next.lead.tasks[0], {
version_no: 2,
status: 'done',
title: 'SYNTHETIC updated',
});
request.options.onSuccess({ props: next });
request.form.processing = false;
h.render();
assert.equal(h.field(form, 'Tarefa').props.value, '');
assert.equal(h.sent.length, 1);
if (removed) assert.match(text(h.tree), /já não está disponível/);
}
});
test('validation retains the draft and allows a corrected fresh command', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.validation({ due_at: 'SYNTHETIC validation' }, request);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC first');
h.change(form, 'Prazo (hora local)', '2027-11-06T12:00');
const next = h.submit(form);
assert.notEqual(next.data.client_key, request.data.client_key);
assert.equal(next.data.due_at, new Date('2027-11-06T12:00').toISOString());
});
test('an untouched assignee follows a refreshed owner while an explicit choice is retained', () => {
const h = harness();
h.render({ ...h.props, lead: { ...h.props.lead, owner_user_id: 2 } });
assert.equal(h.field(form, 'Responsável pela tarefa').props.value, '2');
h.change(form, 'Responsável pela tarefa', '1');
h.render({
...h.props,
lead: { ...h.props.lead, owner_user_id: null },
owners: [],
});
assert.equal(h.field(form, 'Responsável pela tarefa').props.value, '1');
assert.match(text(h.form(form)), /Responsável anterior indisponível/);
});
test('draft and unknown results have one navigation guard; confirmed unchanged values clear it', () => {
const h = harness();
assert.equal(h.leave(), false);
fill(h);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.unload(), true);
const request = h.submit(form);
h.fail(request);
assert.equal(h.leave(true), false);
h.success(saved(h, request), request);
assert.equal(h.leave(), false);
assert.equal(h.unload(), false);
});
test('an obsolete callback cannot erase the draft of a different lead or actor', () => {
const h = harness();
fill(h);
const request = h.submit(form);
const other = props({
lead: { ...h.props.lead, id: 'other' },
taskCreation: { lead_id: 'other', actor_id: 2, commands: [] },
});
h.render(other);
h.change(form, 'Tarefa', 'SYNTHETIC other draft');
request.options.onSuccess({ props: saved(h, request) });
request.form.processing = false;
h.render();
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC other draft');
});
test('access and conflict responses keep the command blocked until a scoped refresh', () => {
const h = harness();
fill(h);
const request = h.submit(form);
h.fail(request, 403);
assert.equal(h.button('Recuperar a mesma criação').props.disabled, true);
h.click('Actualizar tarefas');
h.refreshed(h.props);
assert.equal(h.button('Recuperar a mesma criação').props.disabled, false);
assert.deepEqual(h.submit(form).data, request.data);
});
@@ -0,0 +1,326 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/crm-task-preparation.mjs';
const form = 'new-crm-task';
const taskId = '20000000-0000-4000-8000-000000000001';
function fill(h, title = 'SYNTHETIC prepared task') {
h.change(form, 'Tarefa', title);
h.change(form, 'Prazo (hora local)', '2027-11-04T10:30');
}
function savedContext(h, call = h.draftRequests.at(-1)) {
return {
...h.props.taskCreation,
preparation: {
installed: true,
version: call.data.version + 1,
operation_key: call.data.operation_key,
snapshot: call.data.snapshot,
unavailable: false,
updated_at: '2026-11-03T12:00:00Z',
},
};
}
function pageWith(context, patch = {}) {
return props({ taskCreation: context, ...patch });
}
test('automatic preparation survives a new page instance and adoption is explicit', async () => {
const first = harness();
fill(first);
await first.tick();
assert.equal(first.sent.length, 0);
assert.equal(first.draftRequests.length, 1);
const context = savedContext(first);
await first.respond(context);
const next = harness(pageWith(context));
assert.equal(next.field(form, 'Tarefa').props.value, '');
assert.ok(next.button('Comparar preparação guardada'));
next.click('Comparar preparação guardada');
next.click('Aplicar escolhas e retomar');
assert.equal(
next.field(form, 'Tarefa').props.value,
'SYNTHETIC prepared task',
);
assert.equal(
new Date(
next.field(form, 'Prazo (hora local)').props.value,
).toISOString(),
context.preparation.snapshot.values.due_at,
);
assert.equal(next.sent.length, 0);
});
test('creation waits until its frozen command has been checkpointed', async () => {
const h = harness();
fill(h);
h.submit(form);
assert.equal(h.sent.length, 0);
assert.equal(h.draftRequests.length, 1);
const context = savedContext(h);
await h.respond(context);
assert.equal(h.sent.length, 1);
assert.deepEqual(
h.sent[0].data,
context.preparation.snapshot.pending.values,
);
});
test('an uncertain preparation write retries exactly its key and preserves later edits', async () => {
const h = harness();
fill(h);
h.submit(form);
const first = h.draftRequests[0];
h.change(form, 'Tarefa', 'SYNTHETIC later');
await h.rejectDraft(first);
h.click('Voltar a guardar preparação');
const retry = h.draftRequests.at(-1);
assert.deepEqual(retry.data, first.data);
await h.respond(savedContext(h, retry), retry);
assert.equal(h.sent.length, 0);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC later');
h.submit(form);
await h.flush();
assert.equal(h.sent.length, 1);
assert.equal(h.sent[0].data.title, 'SYNTHETIC prepared task');
});
test('a new page recovers an uncertain business command with its original key', async () => {
const h = harness();
fill(h);
h.submit(form);
const context = savedContext(h);
await h.respond(context);
const request = h.sent[0];
h.fail(request, 500);
const next = harness(pageWith(context));
next.click('Comparar preparação guardada');
next.click('Aplicar escolhas e retomar');
assert.equal(next.sent.length, 0);
next.submit(form);
assert.deepEqual(next.sent[0].data, request.data);
});
test('a committed creation is acknowledged after reopening without another business request', async () => {
const h = harness();
fill(h);
h.submit(form);
const context = savedContext(h);
await h.respond(context);
const request = h.sent[0];
const stored = structuredClone(context);
stored.preparation.snapshot.values.title = 'SYNTHETIC later';
stored.preparation.snapshot.generation.title++;
stored.commands = [
{ key: request.data.client_key, task_id: taskId, version: 1 },
];
const next = harness(
pageWith(stored, {
lead: {
...h.props.lead,
tasks: [
{
id: taskId,
title: request.data.title,
due_at: request.data.due_at,
assignee_user_id: 1,
version_no: 1,
status: 'open',
},
],
},
}),
);
next.click('Comparar preparação guardada');
next.click('Aplicar escolhas e retomar');
assert.equal(next.sent.length, 0);
assert.equal(next.field(form, 'Tarefa').props.value, 'SYNTHETIC later');
assert.equal(next.field(form, 'Prazo (hora local)').props.value, '');
assert.match(text(next.tree), /Tarefa registada/);
});
test('changes made during the business request are checkpointed with its immutable command', async () => {
const h = harness();
fill(h);
h.submit(form);
await h.respond(savedContext(h));
const request = h.sent[0];
h.change(form, 'Tarefa', 'SYNTHETIC later');
await h.tick();
const latest = h.draftRequests.at(-1).data;
assert.equal(latest.snapshot.values.title, 'SYNTHETIC later');
assert.deepEqual(latest.snapshot.pending.values, request.data);
});
test('comparison preserves local edits and requires a new choice after further changes', async () => {
const h = harness();
fill(h);
await h.tick();
const context = savedContext(h);
const next = harness(pageWith(context));
next.change(form, 'Tarefa', 'SYNTHETIC local');
next.click('Comparar preparação guardada');
next.change(form, 'Valor a retomar: Tarefa', 'saved');
next.change(form, 'Tarefa', 'SYNTHETIC after choice');
assert.equal(
next.button('Aplicar escolhas e retomar').props.disabled,
true,
);
next.change(form, 'Valor a retomar: Tarefa', 'page');
next.click('Aplicar escolhas e retomar');
assert.equal(
next.field(form, 'Tarefa').props.value,
'SYNTHETIC after choice',
);
});
test('a response for a different account cannot authorise a business send or clear the draft', async () => {
const h = harness();
fill(h);
h.submit(form);
await h.respond({ ...savedContext(h), actor_id: 2 });
assert.equal(h.sent.length, 0);
assert.equal(
h.field(form, 'Tarefa').props.value,
'SYNTHETIC prepared task',
);
assert.match(text(h.tree), /Não foi possível confirmar a preparação/);
});
test('a callback from the previous account cannot send a task after navigation', async () => {
const h = harness();
fill(h);
h.submit(form);
const call = h.draftRequests[0],
context = savedContext(h, call);
h.render(props({ taskCreation: { ...props().taskCreation, actor_id: 2 } }));
h.change(form, 'Tarefa', 'SYNTHETIC next account');
await h.respond(context, call);
assert.equal(h.sent.length, 0);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC next account');
});
test('an unavailable installation retains the existing manual creation path', () => {
const initial = props();
initial.taskCreation.preparation.installed = false;
const h = harness(initial);
fill(h);
const request = h.submit(form);
assert.equal(h.draftRequests.length, 0);
assert.equal(request.data.title, 'SYNTHETIC prepared task');
assert.match(text(h.tree), /criação manual continua disponível/);
});
test('another saved preparation cannot replace a locally sent unknown command', async () => {
const h = harness();
fill(h);
h.submit(form);
await h.respond(savedContext(h));
const request = h.sent[0];
h.fail(request);
const newer = savedContext(h);
newer.preparation.version = 3;
newer.preparation.operation_key = '00000000-0000-4000-8000-999999999999';
newer.preparation.snapshot = structuredClone(newer.preparation.snapshot);
newer.preparation.snapshot.pending.values.client_key =
'00000000-0000-4000-8000-888888888888';
h.render({ ...h.props, taskCreation: newer });
h.click('Comparar preparação guardada');
h.click('Aplicar escolhas e retomar');
assert.match(text(h.tree), /outro envio sem confirmação/);
const retry = h.submit(form);
assert.deepEqual(retry.data, request.data);
});
test('a confirmed durable preparation does not repeat the leave warning but new edits do', async () => {
const h = harness();
fill(h);
assert.equal(h.leave(), true);
await h.tick();
await h.respond(savedContext(h));
assert.equal(h.leave(), false);
assert.equal(h.unload(), false);
h.change(form, 'Tarefa', 'SYNTHETIC unsaved change');
assert.equal(h.leave(), true);
assert.equal(h.unload(), true);
});
test('validation allows a corrected preparation with a fresh save key without discarding its fields', async () => {
const h = harness();
fill(h, 'S'.repeat(201));
await h.tick();
const first = h.draftRequests[0];
await h.validationDraft(
{ 'snapshot.values.title': 'SYNTHETIC validation' },
first,
);
h.change(form, 'Tarefa', 'SYNTHETIC corrected');
h.click('Voltar a guardar preparação');
const corrected = h.draftRequests.at(-1);
assert.notEqual(corrected.data.operation_key, first.data.operation_key);
assert.equal(corrected.data.snapshot.values.title, 'SYNTHETIC corrected');
await h.respond(savedContext(h, corrected), corrected);
assert.equal(h.field(form, 'Tarefa').props.value, 'SYNTHETIC corrected');
});
test('unreadable saved data is explained and the explicit manual path preserves the server preparation', () => {
const initial = props();
initial.taskCreation.preparation = {
...initial.taskCreation.preparation,
version: 1,
unavailable: true,
};
const h = harness(initial);
assert.match(text(h.tree), /não pôde ser lida/);
h.click('Continuar só nesta página');
fill(h);
h.submit(form);
assert.equal(h.sent.length, 1);
assert.equal(h.draftRequests.length, 0);
assert.match(text(h.tree), /guardada no servidor foi preservada/);
});
test('cross-time-zone recovery keeps the saved instant including repeated local time and seconds', async () => {
const previous = process.env.TZ;
process.env.TZ = 'America/New_York';
try {
const initial = props(),
instant = '2027-11-07T06:30:12.345Z';
initial.taskCreation.preparation = {
installed: true,
version: 1,
operation_key: '00000000-0000-4000-8000-111111111111',
unavailable: false,
updated_at: '2026-11-03T12:00:00Z',
snapshot: {
values: {
title: 'SYNTHETIC saved instant',
due_at: instant,
assignee_user_id: '1',
},
generation: { title: 1, due_at: 1, assignee_user_id: 0 },
pending: null,
},
};
const h = harness(initial);
h.click('Comparar preparação guardada');
h.click('Aplicar escolhas e retomar');
h.submit(form);
assert.equal(
h.draftRequests[0].data.snapshot.pending.values.due_at,
instant,
);
await h.respond(savedContext(h));
assert.equal(h.sent[0].data.due_at, instant);
} finally {
if (previous === undefined) delete process.env.TZ;
else process.env.TZ = previous;
}
});
test('an empty completed preparation matching the page does not ask the user to compare it again', () => {
const initial = props();
initial.taskCreation.preparation = {
installed: true,
version: 2,
operation_key: '00000000-0000-4000-8000-111111111111',
unavailable: false,
updated_at: '2026-11-03T12:00:00Z',
snapshot: {
values: { title: '', due_at: '', assignee_user_id: '1' },
generation: { title: 2, due_at: 1, assignee_user_id: 0 },
pending: null,
},
};
const h = harness(initial);
assert.equal(h.button('Comparar preparação guardada'), undefined);
assert.equal(h.button('Criar tarefa').props.disabled, false);
assert.equal(h.leave(), false);
assert.equal(h.draftRequests.length, 0);
});
@@ -0,0 +1,274 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url);
function load(file, mocks = {}, suffix = '') {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const Link = ({ children, href, className }) =>
React.createElement('a', { href, className }, children);
const Empty = () => null;
const mocks = {
'@inertiajs/react': { Link, Head: Empty },
'@/pages/management/shared': { states: { received: 'Recebido existente' } },
'@/pages/crm/types': { taskStates: { open: 'Aberta existente' } },
};
const Queue = load(
'../../resources/js/components/dashboard-work-queue.tsx',
mocks,
).default;
const Dashboard = load('../../resources/js/pages/dashboard.tsx', {
...mocks,
'@/components/dashboard-work-queue': { default: Queue },
'@/components/profile-navigation': { default: Empty },
'@/components/content-management-entry': { default: Empty },
'@/routes': { dashboard: () => '/dashboard' },
}).default;
const item = (patch = {}) => ({
id: 'synthetic-one',
title: 'SYNTHETIC next action',
reference: 'SYNTHETIC-REF',
status: 'received',
due_at: '2026-11-03T10:00:00.000000Z',
overdue: true,
href: '/management/interests/1',
...patch,
});
const group = (patch = {}) => ({
total: 1,
overdue: 1,
items: [item()],
page: 1,
last_page: 1,
previous: null,
next: null,
...patch,
});
const queue = (groups) => ({
as_of: '2026-11-03T11:00:00.000000Z',
desk_states: { accepted: 'Aceite internamente — edição configurada' },
groups,
});
const render = (Component, props) =>
renderToStaticMarkup(React.createElement(Component, props));
function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
test('investor dashboard retains its investment context without an irrelevant operational panel', () => {
const html = render(Dashboard, {
summary: null,
workQueue: null,
investorPath: {
contexts: [{ id: 'own-case', title: 'SYNTHETIC own investment' }],
current: {
id: 'own-case',
next: { code: 'S01', title: 'SYNTHETIC next investment step' },
pending: 2,
documents: 3,
results: 1,
tasks: 4,
},
},
});
assert.match(html, /SYNTHETIC own investment/);
assert.match(html, /href="\/investimentos\/own-case#S01"/);
assert.doesNotMatch(
html,
/O meu acompanhamento|Manifestações atribuídas a mim|Gestão de Oportunidades/,
);
});
test('the three collections keep separate totals and labels from their existing domains', () => {
const html = render(Queue, {
queue: queue({
interests: group({ total: 7, overdue: 2 }),
desk: group({
total: 8,
overdue: 3,
items: [
item({
status: 'accepted',
href: '/balcao-virtual/pedidos/one',
}),
],
}),
crm_tasks: group({
total: 9,
overdue: 4,
items: [
item({
status: 'open',
href: '/management/crm/leads/one#crm-task-one',
}),
],
}),
}),
});
for (const label of [
'Manifestações atribuídas a mim',
'Pedidos do Balcão atribuídos a mim',
'Tarefas do CRM atribuídas a mim',
'Recebido existente',
'Aceite internamente — edição configurada',
'Aberta existente',
])
assert.ok(html.includes(label));
for (const n of [7, 8, 9]) assert.ok(html.includes(`${n} por acompanhar`));
assert.doesNotMatch(html, /24 por acompanhar|Aprovado|Licença concedida/);
assert.ok(html.includes('href="/management/crm/leads/one#crm-task-one"'));
});
test('missing groups stay absent and an accessible empty collection shows its real zero', () => {
const html = render(Queue, {
queue: queue({ desk: group({ total: 0, overdue: 0, items: [] }) }),
});
assert.match(html, /0 por acompanhar/);
assert.match(html, /Não tem registos activos atribuídos/);
assert.doesNotMatch(
html,
/Manifestações atribuídas|Tarefas do CRM atribuídas|Página/,
);
assert.equal(render(Queue, { queue: undefined }), '');
});
test('deadlines use Maputo time with explicit overdue and unknown-deadline information', () => {
const html = render(Queue, {
queue: queue({
interests: group({
items: [
item(),
item({ id: 'no-date', due_at: null, overdue: false }),
],
}),
}),
});
assert.ok(html.includes('dateTime="2026-11-03T10:00:00.000000Z"'));
assert.match(html, /12:00.*?Maputo/);
assert.match(html, /Prazo ultrapassado/);
assert.match(html, /Sem prazo definido/);
});
test('each collection paginates through supplied destinations without losing scroll position', () => {
const tree = Queue({
queue: queue({
interests: group({
total: 13,
page: 2,
last_page: 3,
previous: '/dashboard?interests_page=1&desk_page=2',
next: '/dashboard?interests_page=3&desk_page=2',
}),
}),
});
const pagination = nodes(tree).find((node) => node.type === 'nav');
assert.equal(
pagination.props['aria-label'],
'Páginas: Manifestações atribuídas a mim',
);
const links = nodes(pagination).filter((node) => node.type === Link);
assert.deepEqual(
links.map((link) => link.props.href),
[
'/dashboard?interests_page=1&desk_page=2',
'/dashboard?interests_page=3&desk_page=2',
],
);
assert.ok(links.every((link) => link.props.preserveScroll === true));
assert.match(
render(Queue, {
queue: queue({
interests: group({ total: 13, page: 2, last_page: 3 }),
}),
}),
/Página 2 de 3/,
);
});
test('work queue and existing management indicators coexist, escaping record text', () => {
const html = render(Dashboard, {
summary: {
requestsByStatus: { received: 4 },
publishedOpportunities: 3,
draftOpportunities: 2,
activeSectors: 1,
recentRequests: [],
canCreateOpportunity: false,
},
workQueue: queue({
interests: group({
items: [item({ title: '<img src=x onerror=alert(1)>' })],
}),
}),
});
assert.match(html, /O meu acompanhamento/);
assert.match(html, /Indicadores de utilização e cobertura/);
assert.match(html, /Oportunidades publicadas/);
assert.ok(html.includes('&lt;img src=x onerror=alert(1)&gt;'));
assert.doesNotMatch(html, /<img/);
});
test('a queue task points to the actual existing CRM form anchor', () => {
const TaskRow = load(
'../../resources/js/pages/crm/lead.tsx',
{
'@inertiajs/react': { Link, useForm() {} },
'@/lib/crm-record-edit': {
useCrmRecordEdit: () => ({
form: { processing: false },
values: { status: 'open' },
error: () => undefined,
blocked: false,
}),
},
'@/components/crm-edit-comparison': { default: Empty },
'@/components/crm-task-creation': { default: Empty },
'../management/shared': {
Management: Empty,
Field: Empty,
button: '',
control: '',
},
'./types': { leadStates: {}, taskStates: { open: 'Aberta' } },
},
'\nexport { TaskRow };',
).TaskRow;
const form = TaskRow({
task: {
id: 'one',
title: 'SYNTHETIC task',
status: 'open',
due_at: null,
assignee_user_id: 1,
version_no: 1,
},
leadId: 'lead-one',
});
const href = '/management/crm/leads/lead-one#crm-task-one';
assert.equal(form.props.id, href.split('#')[1]);
});
+569
View File
@@ -0,0 +1,569 @@
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 { File } from 'node:buffer';
import { renderToStaticMarkup } from 'react-dom/server';
import ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}, globals = {}, suffix = '') {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(output, [
'require',
'module',
'exports',
...Object.keys(globals),
])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
...Object.values(globals),
);
return module.exports;
}
const values = load('../../resources/js/lib/desk-field-values.ts');
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const field = {
type: 'attachment',
label: 'SYNTHETIC support',
required: true,
mime_types: ['text/plain'],
max_size_kb: 2,
max_files: 1,
};
const document = {
id: 'link-one',
document_id: 'document-one',
file_name: 'SYNTHETIC proof.txt',
category: 'SYNTHETIC',
source_reference: 'SYNTHETIC source',
status: 'quarantined',
malware_scan_status: 'pending',
media_type: 'text/plain',
size_bytes: 100,
version_no: 1,
};
function fieldHarness(
handler = async () => ({
documents: [document],
case_version: 2,
link_id: document.id,
}),
) {
const cells = [],
calls = [],
inventory = [],
busy = [],
changes = [];
let cursor = 0,
props,
tree;
const react = {
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) =>
(cells[i] =
typeof value === 'function' ? value(cells[i]) : value),
];
},
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
};
class ValidationError extends Error {}
const Component = load(
'../../resources/js/components/desk-attachment-field.tsx',
{
react,
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
async profileJson(url, body = {}, method = 'POST') {
calls.push({ url, body, method });
return handler(url, body, method);
},
},
'@/lib/desk-field-values': values,
'./desk-document-picker': { default: () => null },
},
).default;
props = {
caseId: 'synthetic-case',
requestId: 'synthetic-request',
caseVersion: 1,
fieldKey: 'support',
field,
value: [],
documents: [document],
disabled: false,
uploading: false,
onChange: (ids) => changes.push(ids),
onBusy: (value) => busy.push(value),
onInventory: (data, select) => inventory.push({ data, select }),
};
const render = (patch = {}) => {
props = { ...props, ...patch };
cursor = 0;
tree = Component(props);
return tree;
};
render();
return {
render,
calls,
inventory,
busy,
changes,
async settle() {
for (let i = 0; i < 8; i++) await Promise.resolve();
render();
},
get tree() {
return tree;
},
button(label) {
return nodes(tree).find(
(node) =>
node.type === 'button' && node.props.children === label,
);
},
prepare(
file = new File(['SYNTHETIC bytes'], 'synthetic-proof.txt', {
type: 'text/plain',
}),
) {
nodes(tree)
.find(
(node) =>
node.type === 'input' && node.props.type === 'file',
)
.props.onChange({ target: { files: [file] } });
render();
nodes(tree)
.find(
(node) =>
node.type === 'input' && node.props.maxLength === 3000,
)
.props.onChange({
target: { value: 'SYNTHETIC submitted source' },
});
render();
nodes(tree)
.filter(
(node) =>
node.type === 'input' && node.props.type === 'checkbox',
)
.at(-1)
.props.onChange({ target: { checked: true } });
render();
},
};
}
await test('cross-dossier picker uses the selected origin identity and does not re-enter existing provenance', async () => {
const h = fieldHarness();
const picker = nodes(h.tree).find(
(node) => typeof node.type === 'function' && 'onSelect' in node.props,
);
picker.props.onSelect({
...document,
id: 'other-dossier-link',
document_id: 'other-original',
origin_label: 'SYNTHETIC previous dossier',
});
h.render();
assert.ok(
!nodes(h.tree).some(
(node) => node.type === 'input' && node.props.type === 'file',
),
);
assert.ok(
!nodes(h.tree).some(
(node) => node.type === 'input' && node.props.maxLength === 3000,
),
);
nodes(h.tree)
.filter(
(node) => node.type === 'input' && node.props.type === 'checkbox',
)
.at(-1)
.props.onChange({ target: { checked: true } });
h.render();
h.button('Reutilizar documento nesta pergunta').props.onClick();
await h.settle();
assert.equal(h.calls[0].body.get('document_id'), 'other-original');
assert.equal(h.calls[0].body.get('reuse_link_id'), 'other-dossier-link');
assert.equal(h.calls[0].body.has('source_reference'), false);
assert.equal(h.calls[0].body.has('file'), false);
assert.equal(h.inventory[0].select, true);
});
await test('attachment question reuses labelled documents, preserves pending drafts and enforces configured choice/format limits', () => {
const h = fieldHarness();
let tree = h.tree;
assert.equal(
nodes(tree).filter(
(node) => node.type === 'input' && node.props.type === 'checkbox',
)[0].props.disabled,
false,
);
nodes(tree)
.filter(
(node) => node.type === 'input' && node.props.type === 'checkbox',
)[0]
.props.onChange({ target: { checked: true } });
assert.deepEqual(h.changes[0], ['link-one']);
const html = renderToStaticMarkup(tree);
assert.match(html, /SYNTHETIC proof.txt/);
assert.match(html, /Análise ou disponibilidade pendente/);
assert.match(html, /2 KB por ficheiro/);
assert.ok(
!nodes(tree).some(
(node) =>
node.type === 'input' && node.props.name === 'document_id',
),
);
tree = h.render({
value: ['link-one'],
documents: [
document,
{
...document,
id: 'link-two',
document_id: 'document-two',
file_name: 'SYNTHETIC other.txt',
},
],
});
assert.equal(
nodes(tree).filter(
(node) => node.type === 'input' && node.props.type === 'checkbox',
)[1].props.disabled,
true,
);
tree = h.render({
value: [],
documents: [{ ...document, media_type: 'application/pdf' }],
});
assert.equal(
nodes(tree).find(
(node) => node.type === 'input' && node.props.type === 'checkbox',
).props.disabled,
true,
);
tree = h.render({
value: [],
documents: [{ ...document, media_type: null, size_bytes: null }],
});
assert.equal(
nodes(tree).find(
(node) => node.type === 'input' && node.props.type === 'checkbox',
).props.disabled,
false,
);
assert.match(renderToStaticMarkup(tree), /Formato ou tamanho por conferir/);
assert.equal(h.render({ disabled: true }).props.disabled, true);
});
await test('document aliases render once and removing a choice removes duplicate aliases without changing another question', () => {
const h = fieldHarness();
const tree = h.render({
value: ['link-one', 'link-alias'],
documents: [document, { ...document, id: 'link-alias' }],
});
const checkboxes = nodes(tree).filter(
(node) => node.type === 'input' && node.props.type === 'checkbox',
);
assert.equal(checkboxes.length, 2); // One document and upload consent.
checkboxes[0].props.onChange({ target: { checked: false } });
assert.deepEqual(h.changes[0], []);
const inherited = values.mergeDeskPrefill(
{ support: [] },
{ support: ['link-one'] },
{ support: field },
true,
);
assert.deepEqual(inherited.support, []);
});
await test('new support uses multipart with request, question and case version and never submits the request', async () => {
const h = fieldHarness();
h.prepare();
const fileInput = nodes(h.tree).find(
(node) => node.type === 'input' && node.props.type === 'file',
);
fileInput.props.ref.current = { value: 'selected' };
await h.button('Associar ficheiro a esta pergunta').props.onClick();
await h.settle();
assert.equal(h.calls.length, 1);
const data = h.calls[0].body;
assert.ok(data instanceof FormData);
assert.equal(data.get('field_key'), 'support');
assert.equal(data.get('request_id'), 'synthetic-request');
assert.equal(data.get('version'), '1');
assert.equal(data.get('source_reference'), 'SYNTHETIC submitted source');
assert.equal(data.get('submit'), null);
assert.equal(data.get('context_reviewed'), null);
assert.equal(h.inventory[0].select, true);
assert.deepEqual(h.busy, [true, false]);
assert.equal(fileInput.props.ref.current.value, '');
assert.equal(
h.button('Associar ficheiro a esta pergunta').props.disabled,
true,
);
});
await test('oversized file stays selected without a write and a failed upload can be retried with the original data', async () => {
const oversized = fieldHarness();
oversized.prepare(
new File(['X'.repeat(2049)], 'oversized.txt', { type: 'text/plain' }),
);
await oversized.button('Associar ficheiro a esta pergunta').props.onClick();
oversized.render();
assert.equal(oversized.calls.length, 0);
assert.match(
renderToStaticMarkup(oversized.tree),
/excede o tamanho máximo/,
);
let failed = true;
const h = fieldHarness(async () => {
if (failed) throw Error('SYNTHETIC network failure');
return {
documents: [document],
case_version: 2,
link_id: document.id,
reused_link: true,
};
});
h.prepare();
await h.button('Associar ficheiro a esta pergunta').props.onClick();
await h.settle();
assert.equal(
h.button('Associar ficheiro a esta pergunta').props.disabled,
false,
);
failed = false;
await h.button('Associar ficheiro a esta pergunta').props.onClick();
await h.settle();
assert.equal(h.calls.length, 2);
assert.equal(
h.calls[0].body.get('file').size,
h.calls[1].body.get('file').size,
);
assert.match(
renderToStaticMarkup(h.tree),
/Conservou-se a referência registada/,
);
});
await test('document refresh keeps answers on the page and a stale upload response is not treated as a confirmed selection', async () => {
const h = fieldHarness(async (url, body, method) =>
method === 'GET'
? { documents: [document], caseVersion: 8 }
: { ok: true },
);
await h.button('Actualizar documentos disponíveis').props.onClick();
await h.settle();
assert.equal(h.inventory[0].select, false);
assert.equal(h.inventory[0].data.case_version, 8);
assert.equal(h.changes.length, 0);
h.prepare();
await h.button('Associar ficheiro a esta pergunta').props.onClick();
await h.settle();
assert.equal(h.inventory.length, 1);
assert.match(renderToStaticMarkup(h.tree), /não confirmou o documento/);
assert.equal(
h.button('Associar ficheiro a esta pergunta').props.disabled,
false,
);
});
await test('the common transport keeps multipart boundaries with the browser and preserves existing JSON and CSRF behaviour', async () => {
const sent = [];
const api = load(
'../../resources/js/lib/profile-json.ts',
{},
{
document: { cookie: 'XSRF-TOKEN=synthetic%3Dtoken' },
fetch: async (url, options) => {
sent.push(options);
return new Response(JSON.stringify({ ok: true }), {
status: 200,
});
},
},
);
const data = new FormData();
data.set(
'file',
new File(['SYNTHETIC'], 'proof.txt', { type: 'text/plain' }),
);
await api.profileJson('/synthetic-upload', data);
assert.equal(sent[0].body, data);
assert.equal(sent[0].headers['Content-Type'], undefined);
assert.equal(sent[0].headers['X-XSRF-TOKEN'], 'synthetic=token');
assert.equal(sent[0].credentials, 'same-origin');
await api.profileJson('/synthetic-json', { answer: 0 });
assert.equal(sent[1].body, '{"answer":0}');
assert.equal(sent[1].headers['Content-Type'], 'application/json');
});
await test('owner reuse chooses the precise registered source without asking for its reference again or sending another file', async () => {
const sourceB = {
...document,
id: 'source-b',
document_id: 'shared-original',
source_reference: 'SYNTHETIC ref B',
stage: 'E1',
valid_until: '2027-01-02',
};
const sourceC = {
...sourceB,
id: 'source-c',
source_reference: 'SYNTHETIC ref C',
stage: 'E2',
};
const target = { ...sourceB, id: 'new-use' };
const h = fieldHarness(async () => ({
documents: [target],
case_version: 4,
link_id: target.id,
reusable_documents: [sourceB, sourceC, target],
}));
h.render({ documents: [], reusableDocuments: [sourceB, sourceC] });
let select = nodes(h.tree).find((node) => node.type === 'select');
assert.equal(
nodes(select).filter((node) => node.type === 'option').length,
3,
);
select.props.onChange({ target: { value: 'source-b' } });
h.render();
assert.ok(
!nodes(h.tree).some(
(node) => node.type === 'input' && node.props.type === 'file',
),
);
assert.ok(
!nodes(h.tree).some(
(node) => node.type === 'input' && node.props.maxLength === 3000,
),
);
assert.match(
renderToStaticMarkup(h.tree),
/Referência já registada: SYNTHETIC ref B/,
);
nodes(h.tree)
.find((node) => node.type === 'input' && node.props.type === 'checkbox')
.props.onChange({ target: { checked: true } });
h.render();
await h.button('Reutilizar documento nesta pergunta').props.onClick();
await h.settle();
const data = h.calls[0].body;
assert.equal(data.get('document_id'), 'shared-original');
assert.equal(data.get('reuse_link_id'), 'source-b');
assert.equal(data.get('source_reference'), null);
assert.equal(data.get('file'), null);
assert.equal(h.inventory[0].select, true);
});
await test('editor publishes explicit attachment limits in the proposed version and clears unrelated metadata when type changes', () => {
let form;
const Editor = load(
'../../resources/js/pages/desk/service-editor.tsx',
{
react: { useState: (value) => [value, () => {}] },
'@inertiajs/react': {
Link: 'a',
useForm(key, initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(value) {
this.data = value(this.data);
},
};
return form;
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/desk-service-history': { default: () => null },
},
{},
'\nexport { Editor };',
).Editor;
const service = {
code: 'synthetic',
version: 1,
definition: {
title: 'SYNTHETIC',
theme: 'Synthetic',
profile: 'Investor',
entity: 'Internal',
result: 'Internal preparation',
stage: 'E10',
fields: {
question: {
label: 'SYNTHETIC support',
type: 'text',
required: false,
},
},
},
};
const render = () => Editor({ service });
let tree = render();
const type = () =>
nodes(tree).find(
(node) =>
node.type === 'select' &&
nodes(node).some(
(child) =>
child.type === 'option' &&
child.props.value === 'attachment',
),
);
type().props.onChange({ target: { value: 'attachment' } });
tree = render();
assert.equal(form.data.definition.fields.question.max_files, 1);
assert.equal(form.data.definition.fields.question.max_size_kb, 10240);
assert.equal(form.data.definition.fields.question.mime_types.length, 4);
assert.equal(form.data.definition.fields.question.required, false);
const size = nodes(tree).find(
(node) => node.type === 'input' && node.props.max === 10240,
);
size.props.onChange({ target: { value: '256' } });
tree = render();
assert.equal(form.data.definition.fields.question.max_size_kb, 256);
assert.equal(form.data.confirm, false);
assert.match(renderToStaticMarkup(tree), /Tamanho por ficheiro: 256 KiB/);
type().props.onChange({ target: { value: 'text' } });
assert.equal(form.data.definition.fields.question.mime_types, undefined);
assert.equal(form.data.definition.fields.question.max_files, undefined);
assert.equal(service.definition.fields.question.type, 'text');
});
+278
View File
@@ -0,0 +1,278 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks) {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports.default;
}
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const text = (tree) =>
typeof tree === 'string'
? tree
: Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'number'
? String(tree)
: '';
function harness(file, initial, extra = {}) {
const forms = [],
cells = [],
calls = [];
let formCursor = 0,
cursor = 0,
serial = 0,
tree,
props = initial;
const Empty = () => null;
const Component = load(file, {
react: {
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) => {
cells[i] = value;
},
];
},
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
},
'@inertiajs/react': {
Link: 'a',
router: { reload() {} },
usePage: () => ({
url: '/synthetic',
props: { auth: { user: { id: 1 } } },
}),
useForm(initial) {
const i = formCursor++;
forms[i] ??= {
data: { ...initial },
errors: {},
processing: false,
setData(key, value) {
this.data[key] = value;
},
reset(...keys) {
for (const key of keys) this.data[key] = initial[key];
},
put(url, options) {
calls.push({ url, options, data: { ...this.data } });
},
};
return forms[i];
},
},
'@/lib/operation-key': {
createOperationKey: () => `SYNTHETIC-${++serial}`,
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/investor-guidance': { InvestorGuidance: Empty },
'@/components/desk-internal-operations': { DocumentReview: Empty },
'@/components/desk-document-picker': { default: Empty },
...extra,
});
function render(patch = {}) {
props = { ...props, ...patch };
cursor = 0;
formCursor = 0;
tree = Component(props);
}
render();
return {
forms,
calls,
render,
all: () => nodes(tree),
text: () => text(tree),
find: (type, label) =>
nodes(tree).find(
(n) => n.type === type && (!label || text(n).includes(label)),
),
submit() {
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
},
};
}
const dossier = { id: 'case-one', version: 1, closed_at: null };
const activity = { open_requests: 2, open_tasks: 1, pending_payments: 3 };
const state = (extra) =>
harness('../../resources/js/components/desk-case-state-form.tsx', {
dossier,
activity,
...extra,
});
test('owner can explicitly close with recorded pending items and sends only state decision data', () => {
const h = state();
h.find('textarea').props.onChange({
target: { value: 'SYNTHETIC owner reason' },
});
h.render();
h.submit();
assert.match(h.calls[0].url, /dossiers\/case-one\/estado$/);
assert.deepEqual(
Object.keys(h.calls[0].data).sort(),
['version', 'state', 'reason', 'client_key'].sort(),
);
assert.equal(h.calls[0].data.state, 'closed');
assert.equal(h.calls[0].data.version, 1);
assert.match(
h.text(),
/Pedidos em curso: 2.*tarefas em curso: 1.*comprovativos por conferir: 3/,
);
});
test('success adopts actual server state and version for reopening and calls parent cleanup only for the same dossier', () => {
let changed = 0;
const h = state({
onChanged() {
changed++;
},
});
h.find('textarea').props.onChange({
target: { value: 'SYNTHETIC close reason' },
});
h.render();
h.submit();
const key = h.forms[0].data.client_key;
h.calls[0].options.onSuccess({
props: { case: { ...dossier, version: 2, closed_at: '2026-11-03' } },
});
h.render({ dossier: { ...dossier, version: 2, closed_at: '2026-11-03' } });
assert.equal(h.forms[0].data.state, 'open');
assert.equal(h.forms[0].data.version, 2);
assert.equal(h.forms[0].data.reason, '');
assert.notEqual(h.forms[0].data.client_key, key);
assert.equal(changed, 1);
h.calls[0].options.onSuccess({
props: { case: { id: 'other-case', version: 9 } },
});
assert.equal(changed, 1);
assert.ok(h.find('button', 'Confirmar reabertura'));
});
test('failed retry keeps operation identity and reason while editing or explicitly adopting new state starts a new intent', () => {
const h = state();
h.find('textarea').props.onChange({
target: { value: 'SYNTHETIC deliberate reason' },
});
h.render();
h.submit();
h.submit();
assert.deepEqual(h.calls[0].data, h.calls[1].data);
const key = h.forms[0].data.client_key;
h.render({ dossier: { ...dossier, version: 3, closed_at: '2026-11-03' } });
assert.equal(h.find('button', 'Confirmar reabertura').props.disabled, true);
h.submit();
assert.equal(h.calls.length, 2);
h.find('button', 'Usar estado actual').props.onClick();
h.render();
assert.equal(h.forms[0].data.version, 3);
assert.equal(h.forms[0].data.state, 'open');
assert.equal(h.forms[0].data.reason, 'SYNTHETIC deliberate reason');
assert.notEqual(h.forms[0].data.client_key, key);
});
test('unknown optional counts remain unknown and in-flight business work disables the decision', () => {
const h = state({
activity: {
open_requests: 0,
open_tasks: null,
pending_payments: null,
},
disabled: true,
});
assert.match(
h.text(),
/Pedidos em curso: 0.*tarefas em curso: por confirmar.*comprovativos por conferir: por confirmar/,
);
assert.equal(
h.find('button', 'Confirmar encerramento').props.disabled,
true,
);
h.submit();
assert.equal(h.calls.length, 0);
});
test('case exposes owner control separately from ordinary writing and clears unassociated file consent after success', () => {
const State = () => null;
const base = {
case: {
...dossier,
closed_at: '2026-11-03',
title: 'SYNTHETIC owner dossier',
workflow: {},
},
canWrite: false,
canChangeState: true,
activity,
manager: false,
requests: [],
services: [],
documents: [],
workflow: {},
stepStates: {},
states: {},
guidance: null,
events: [],
links: [],
legacyRequest: null,
};
const h = harness('../../resources/js/pages/desk/case.tsx', base, {
'@/components/desk-case-state-form': { default: State },
});
let widget = h.all().find((n) => n.type === State);
assert.ok(widget);
h.forms[2].setData('file', { name: 'SYNTHETIC unsent file' });
h.forms[2].setData('consent', true);
widget.props.onChanged();
assert.equal(h.forms[2].data.file, null);
assert.equal(h.forms[2].data.consent, false);
h.forms[2].processing = true;
h.render();
widget = h.all().find((n) => n.type === State);
assert.equal(widget.props.disabled, true);
h.render({ canChangeState: false, canWrite: true, manager: true });
assert.equal(
h.all().some((n) => n.type === State),
false,
);
});
+778
View File
@@ -0,0 +1,778 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}, globals = {}) {
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',
...Object.keys(globals),
])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
...Object.values(globals),
);
return module.exports;
}
const lib = load('../../resources/js/lib/desk-checkpoints.ts');
class ValidationError extends Error {
constructor(message, fields = {}) {
super(message);
this.fields = fields;
}
}
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const request = {
id: 'synthetic-request',
version: 1,
status: 'draft',
payload: { title: 'Original', choices: ['0'], declaration: null },
editable_fields: [],
can_edit: true,
protocol: null,
analyst_id: null,
due_at: null,
};
const initialView = () => ({
installed: true,
request: structuredClone(request),
checkpoint: null,
});
function serverCheckpoint(body) {
return {
version: body.version + 1,
request_version: body.request_version,
updated_at: '2026-11-03T03:00:00Z',
payload: structuredClone(body.payload),
reason: body.reason,
base_payload: structuredClone(request.payload),
edited_keys: [...body.edited_keys],
};
}
function harness(handler) {
const cells = [],
timers = new Map(),
listeners = new Map(),
before = [];
let cursor = 0,
dirty = true,
tree,
props,
sequence = 0,
clock = 0;
const effects = [],
calls = [],
recovered = [],
blocked = [],
busy = [];
const react = {
useState(initial) {
const i = cursor++;
if (!cells[i])
cells[i] = {
value: typeof initial === 'function' ? initial() : initial,
};
return [
cells[i].value,
(value) => {
const next =
typeof value === 'function'
? value(cells[i].value)
: value;
if (!Object.is(next, cells[i].value)) {
cells[i].value = next;
dirty = true;
}
},
];
},
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
useEffect(effect, deps) {
const i = cursor++,
old = cells[i];
if (!old || deps.some((v, j) => !Object.is(v, old.deps[j]))) {
cells[i] = { deps, cleanup: old?.cleanup };
effects.push(() => {
cells[i].cleanup?.();
cells[i].cleanup = effect();
});
}
},
};
const Component = load(
'../../resources/js/components/desk-draft-recovery.tsx',
{
react,
'@inertiajs/react': {
router: {
on(name, callback) {
before.push(callback);
return () => {
before.splice(before.indexOf(callback), 1);
};
},
},
},
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
async profileJson(url, body = {}, method = 'POST') {
calls.push({ url, body: structuredClone(body), method });
return handler(url, body, method);
},
},
'@/lib/operation-key': {
createOperationKey: () => `synthetic-operation-${++sequence}`,
},
'@/lib/desk-checkpoints': lib,
},
{
window: {
addEventListener: (name, fn) => listeners.set(name, fn),
removeEventListener: (name) => listeners.delete(name),
confirm: () => false,
},
setTimeout: (fn) => {
const id = ++clock;
timers.set(id, fn);
return id;
},
clearTimeout: (id) => timers.delete(id),
},
).default;
props = {
id: request.id,
version: 1,
initial: structuredClone(request.payload),
payload: structuredClone(request.payload),
reason: '',
fields: {
title: { label: 'Title' },
choices: { label: 'Choices' },
declaration: { label: 'Declaration' },
},
paused: false,
onBusy: (value) => busy.push(value),
onBlocked: (value) => blocked.push(value),
onRecover: (payload, reason, current) => {
recovered.push({ payload, reason, current });
props = { ...props, payload, reason, version: current.version };
dirty = true;
},
};
function render(patch = {}) {
props = { ...props, ...patch };
dirty = true;
flush();
return tree;
}
function flush() {
let loops = 0;
while (dirty || effects.length) {
if (++loops > 25) throw Error('Effect loop');
if (dirty) {
dirty = false;
cursor = 0;
tree = Component(props);
}
while (effects.length) effects.shift()();
}
return tree;
}
async function settle() {
for (let i = 0; i < 10; i++) {
await Promise.resolve();
flush();
}
return tree;
}
return {
render,
settle,
calls,
recovered,
blocked,
busy,
listeners,
before,
timers,
get tree() {
return tree;
},
get props() {
return props;
},
async advance() {
for (const [id, fn] of timers) {
timers.delete(id);
fn();
}
await settle();
},
button(label) {
const node = nodes(tree).find(
(n) => n.type === 'button' && n.props.children === label,
);
assert.ok(node, `Button missing: ${label}`);
return node;
},
unmount() {
for (const cell of cells) cell?.cleanup?.();
},
};
}
await test('recovery preserves typed choices, explicit zero and deliberate reverts; concurrent answers require a choice', () => {
const base = {
title: 'Original',
amount: 0,
choices: ['0'],
declaration: 'declined',
};
const saved = {
base_payload: base,
payload: { ...base, title: 'Saved', choices: ['cotton', '0'] },
edited_keys: ['title', 'choices', 'declaration'],
};
const current = { ...base, title: 'External', declaration: 'accepted' };
const result = lib.checkpointRecovery(
base,
base,
[],
current,
saved,
Object.keys(base),
);
assert.deepEqual(result.conflicts, ['title', 'declaration']);
const chosen = lib.checkpointRecovery(
base,
base,
[],
current,
saved,
Object.keys(base),
{ title: 'current', declaration: 'saved' },
);
assert.deepEqual(chosen.conflicts, []);
assert.equal(chosen.payload.title, 'External');
assert.equal(chosen.payload.declaration, 'declined');
assert.equal(chosen.payload.amount, 0);
assert.deepEqual(chosen.payload.choices, ['cotton', '0']);
const returned = lib.checkpointRecovery(
base,
{ ...base, title: 'Forbidden' },
['title'],
current,
saved,
['amount'],
);
assert.equal(returned.payload.title, 'External');
assert.equal(
lib.checkpointSignature({ choices: ['0', 'cotton'] }),
lib.checkpointSignature({ choices: ['cotton', '0'] }),
);
});
await test('opportunity and its preserved context are recovered as one choice without displaying technical snapshots', () => {
const base = {
context_opportunity: 'old',
context_opportunity_snapshot: JSON.stringify({
choice: { opportunity: { title: 'Old opportunity' } },
revision: 1,
}),
context_reuse: 'old metadata',
};
const page = {
context_opportunity: 'local',
context_opportunity_snapshot: JSON.stringify({
choice: { opportunity: { title: 'Local opportunity' } },
revision: 2,
}),
context_reuse: 'local metadata',
};
const current = {
context_opportunity: 'remote',
context_opportunity_snapshot: JSON.stringify({
choice: { opportunity: { title: 'Remote opportunity' } },
revision: 3,
}),
context_reuse: 'remote metadata',
};
const result = lib.checkpointRecovery(
base,
page,
Object.keys(page),
current,
null,
Object.keys(page),
{ context_opportunity: 'page' },
);
assert.deepEqual(result.payload, page);
assert.equal(result.rows.length, 1);
assert.equal(result.rows[0].page, 'Local opportunity · revisão 2');
assert.deepEqual(result.intent, Object.keys(page));
assert.ok(!JSON.stringify(result.rows).includes('local metadata'));
});
await test('autosave is debounced, captures edits during a pending write and never sends submission or consent flags', async () => {
let view = initialView(),
resolveFirst;
const h = harness(async (url, body, method) => {
if (method === 'GET') return structuredClone(view);
if (!resolveFirst)
return new Promise((resolve) => {
resolveFirst = () => {
view.checkpoint = serverCheckpoint(body);
resolve(structuredClone(view));
};
});
view.checkpoint = serverCheckpoint(body);
return structuredClone(view);
});
h.render();
await h.settle();
assert.equal(h.timers.size, 0);
h.render({ payload: { ...request.payload, title: 'First' } });
assert.equal(h.timers.size, 1);
await h.advance();
assert.equal(h.calls.filter((c) => c.method === 'POST').length, 1);
h.render({ payload: { ...request.payload, title: 'Newer while saving' } });
assert.equal(h.timers.size, 0);
resolveFirst();
await h.settle();
assert.equal(h.timers.size, 1);
await h.advance();
const posts = h.calls.filter((c) => c.method === 'POST');
assert.equal(posts.length, 2);
assert.equal(posts[1].body.version, 1);
assert.equal(posts[1].body.payload.title, 'Newer while saving');
assert.equal(Object.hasOwn(posts[0].body, 'submit'), false);
assert.equal(Object.hasOwn(posts[0].body, 'consent'), false);
assert.equal(Object.hasOwn(posts[0].body, 'context_reviewed'), false);
assert.equal(h.timers.size, 0);
assert.deepEqual(h.busy, [true, false, true, false]);
h.unmount();
});
await test('ambiguous network failure repeats the exact attempt before saving newer local answers', async () => {
let view = initialView(),
failed = false;
const h = harness(async (url, body, method) => {
if (method === 'GET') return structuredClone(view);
if (!failed) {
failed = true;
view.checkpoint = serverCheckpoint(body);
throw Error('SYNTHETIC connection lost after commit');
}
if (body.version === 0) return structuredClone(view);
view.checkpoint = serverCheckpoint(body);
return structuredClone(view);
});
h.render();
await h.settle();
h.render({
payload: { ...request.payload, title: 'Committed but unacknowledged' },
});
await h.advance();
h.render({ payload: { ...request.payload, title: 'Newer' } });
assert.equal(h.timers.size, 0);
h.button('Tentar novamente a mesma gravação').props.onClick();
await h.settle();
let posts = h.calls.filter((c) => c.method === 'POST');
assert.deepEqual(posts[0].body, posts[1].body);
assert.equal(h.props.payload.title, 'Newer');
await h.advance();
posts = h.calls.filter((c) => c.method === 'POST');
assert.equal(posts[2].body.version, 1);
assert.notEqual(posts[2].body.operation_key, posts[1].body.operation_key);
h.unmount();
});
await test('server normalization does not cause autosave loops and validation failures wait for an actual edit', async () => {
let view = initialView(),
invalid = true;
const h = harness(async (url, body, method) => {
if (method === 'GET') return structuredClone(view);
if (invalid)
throw new ValidationError('SYNTHETIC invalid type', {
'checkpoint.payload.title': 'Invalid',
});
view.checkpoint = serverCheckpoint(body);
view.checkpoint.payload.title = body.payload.title.trim() || null;
return structuredClone(view);
});
h.render();
await h.settle();
h.render({ payload: { ...request.payload, title: ' text ' } });
await h.advance();
await h.settle();
assert.equal(h.timers.size, 0);
invalid = false;
h.render({ payload: { ...request.payload, title: ' corrected ' } });
await h.settle();
assert.equal(h.timers.size, 1);
await h.advance();
assert.equal(h.timers.size, 0);
assert.equal(h.calls.filter((c) => c.method === 'POST').length, 2);
h.unmount();
});
await test('stored drafts are compared before adoption and a failed recovery is retried without changing its chosen answers', async () => {
let view = initialView(),
failed = false;
view.request.version = 2;
view.request.payload.title = 'External';
view.checkpoint = {
...serverCheckpoint({
version: 0,
request_version: 1,
payload: {
...request.payload,
title: 'Saved',
declaration: 'declined',
},
reason: 'Saved reason',
edited_keys: ['title', 'declaration'],
}),
base_payload: structuredClone(request.payload),
};
const h = harness(async (url, body, method) => {
if (method === 'GET') return structuredClone(view);
view.checkpoint = serverCheckpoint(body);
if (!failed) {
failed = true;
throw Error('SYNTHETIC recovery response lost');
}
return structuredClone(view);
});
h.render();
await h.settle();
assert.equal(h.recovered.length, 0);
assert.equal(
h.button('Recuperar as respostas escolhidas').props.disabled,
true,
);
const select = nodes(h.tree).find(
(n) => n.type === 'select' && n.props.value === '',
);
select.props.onChange({ target: { value: 'saved' } });
await h.settle();
assert.equal(
h.button('Recuperar as respostas escolhidas').props.disabled,
false,
);
h.button('Recuperar as respostas escolhidas').props.onClick();
await h.settle();
assert.equal(h.recovered.length, 0);
h.button('Recuperar as respostas escolhidas').props.onClick();
await h.settle();
assert.equal(h.recovered.length, 1);
assert.equal(h.recovered[0].current.version, 2);
assert.equal(h.recovered[0].payload.title, 'Saved');
assert.equal(h.recovered[0].payload.declaration, 'declined');
const posts = h.calls.filter((c) => c.method === 'POST');
assert.deepEqual(posts[0].body, posts[1].body);
assert.equal(h.blocked.at(-1), false);
h.unmount();
});
await test('manual operations pause autosave, unavailable installation leaves manual access, and unsaved navigation can be cancelled', async () => {
let view = initialView();
const h = harness(async (url, body, method) => {
if (method === 'GET') return structuredClone(view);
view.checkpoint = serverCheckpoint(body);
return structuredClone(view);
});
h.render();
await h.settle();
h.render({
payload: { ...request.payload, title: 'Unsaved' },
paused: true,
});
assert.equal(h.timers.size, 0);
let prevented = false;
h.before[0]({
detail: { visit: { method: 'get' } },
preventDefault() {
prevented = true;
},
});
assert.equal(prevented, true);
h.render({ paused: false });
await h.advance();
assert.equal(h.timers.size, 0);
h.unmount();
assert.equal(h.before.length, 0);
assert.equal(h.listeners.size, 0);
view.installed = false;
const fallback = harness(async () => structuredClone(view));
fallback.render();
await fallback.settle();
fallback.render({ payload: { title: 'Manual still available' } });
assert.equal(fallback.timers.size, 0);
assert.ok(!fallback.blocked.includes(true));
fallback.unmount();
});
await test('request recovery adopts the actual server version and returned scope while clearing submission and context approvals', () => {
const cells = [],
forms = [],
sent = [];
let stateCursor = 0,
formCursor = 0;
const Empty = () => null,
Recovery = () => null,
Attachment = () => null;
const Page = load('../../resources/js/pages/desk/request.tsx', {
react: {
useState(initial) {
const i = stateCursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) =>
(cells[i] =
typeof value === 'function'
? value(cells[i])
: value),
];
},
},
'@inertiajs/react': {
Link: 'a',
useForm(initial) {
const i = formCursor++;
forms[i] ??= {
data: structuredClone(initial),
errors: {},
processing: false,
setData(value, next) {
this.data =
typeof value === 'function'
? value(this.data)
: { ...this.data, [value]: next };
},
transform(fn) {
this.mapping = fn;
},
put(url) {
sent.push({
url,
data: this.mapping
? this.mapping(this.data)
: this.data,
});
},
};
return forms[i];
},
},
'@/components/desk-draft-recovery': {
__esModule: true,
default: Recovery,
},
'@/components/dossier-prefill': { DossierPrefill: Empty },
'@/components/country-select': { default: Empty },
'@/components/investment-territory': { TerritoryFields: Empty },
'@/components/desk-internal-operations': {
DocumentReview: Empty,
RequestOperations: Empty,
},
'@/components/desk-typed-choice': { default: Empty },
'@/components/desk-attachment-field': { default: Attachment },
'@/lib/operation-key': { createOperationKey: () => 'synthetic' },
'@/lib/desk-field-visibility': load(
'../../resources/js/lib/desk-field-visibility.ts',
),
'@/lib/desk-field-values': load(
'../../resources/js/lib/desk-field-values.ts',
),
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
}).default;
const props = {
request: { ...request, analyst_id: null, due_at: null },
case: { id: 'synthetic-case', title: 'Synthetic' },
definition: {
title: 'Synthetic',
result: 'Internal',
fields: {
title: { type: 'text', label: 'Title', required: true },
support: {
type: 'attachment',
label: 'Support',
required: false,
max_files: 2,
max_size_kb: 2,
mime_types: ['text/plain'],
},
choices: {
type: 'multiselect',
label: 'Choices',
required: false,
options: { 0: 'Zero' },
},
declaration: {
type: 'consent',
label: 'Declaration',
required: false,
statement: 'Synthetic',
},
},
},
owner: true,
manager: false,
analyst: false,
fieldsEditable: true,
states: { draft: 'Draft', returned: 'Returned' },
transitions: [],
findings: [],
messages: [],
analysts: [],
territoryPaths: {},
events: [],
documents: [],
payments: [],
caseVersion: 1,
countries: [],
toolPrefill: null,
};
const render = () => {
stateCursor = 0;
formCursor = 0;
return Page(props);
};
let tree = render();
forms[0].data.payload.title = 'Deliberate edit during upload';
nodes(tree)
.find((n) => n.type === Attachment)
.props.onBusy(true);
tree = render();
assert.equal(
nodes(tree).find((n) => n.type === Recovery).props.pendingWork,
true,
);
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(sent.length, 0);
const uploaded = {
id: 'link-first',
document_id: 'binary-one',
file_name: 'Synthetic original',
status: 'quarantined',
malware_scan_status: 'pending',
};
nodes(tree)
.find((n) => n.type === Attachment)
.props.onInventory(
{ documents: [uploaded], case_version: 2, link_id: uploaded.id },
true,
);
nodes(tree)
.find((n) => n.type === Attachment)
.props.onBusy(false);
tree = render();
assert.equal(forms[0].data.payload.title, 'Deliberate edit during upload');
assert.deepEqual(forms[0].data.payload.support, ['link-first']);
const alias = { ...uploaded, id: 'link-alias' };
nodes(tree)
.find((n) => n.type === Attachment)
.props.onInventory(
{
documents: [uploaded, alias],
case_version: 2,
link_id: alias.id,
},
true,
);
tree = render();
assert.deepEqual(forms[0].data.payload.support, ['link-first']);
props.caseVersion = 2;
props.documents = [
{ ...uploaded, status: 'active', malware_scan_status: 'clean' },
];
tree = render();
assert.equal(
nodes(tree).find((n) => n.type === Attachment).props.documents[0]
.malware_scan_status,
'clean',
);
const refreshed = {
...uploaded,
malware_scan_status: 'synthetic-new-status',
};
nodes(tree)
.find((n) => n.type === Attachment)
.props.onInventory({ documents: [refreshed], case_version: 2 }, false);
tree = render();
assert.equal(
nodes(tree).find((n) => n.type === Attachment).props.documents[0]
.malware_scan_status,
'synthetic-new-status',
);
forms[0].data.consent = true;
forms[0].data.context_reviewed = true;
forms[0].data.context_revision = 8;
const restore = nodes(tree).find((n) => n.type === Recovery);
restore.props.onRecover(
{
title: 'Current official draft',
choices: ['0'],
declaration: 'declined',
},
'Recovered reason',
{
...request,
version: 3,
status: 'returned',
editable_fields: ['choices'],
},
);
tree = render();
assert.equal(forms[0].data.version, 3);
assert.equal(forms[0].data.consent, false);
assert.equal(forms[0].data.context_reviewed, false);
assert.equal(forms[0].data.context_revision, 0);
assert.equal(forms[0].data.payload.declaration, 'declined');
const form = nodes(tree).find((n) => n.type === 'form');
form.props.onSubmit({ preventDefault() {} });
assert.equal(sent[0].data.version, 3);
assert.equal(sent[0].data.submit, false);
nodes(tree)
.find((n) => n.type === Recovery)
.props.onBusy(true);
tree = render();
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(sent.length, 1);
});
@@ -0,0 +1,453 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}, suffix = '') {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const text = (tree) =>
typeof tree === 'string'
? tree
: Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'number'
? String(tree)
: '';
const Empty = () => null;
function harness(file, initial, extra = {}, suffix = '') {
const cells = [],
forms = [],
sent = [];
let cursor = 0,
formCursor = 0,
props = initial,
tree;
const mocks = {
react: {
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) => {
cells[i] =
typeof value === 'function'
? value(cells[i])
: value;
},
];
},
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
},
'@inertiajs/react': {
Link: 'a',
router: { reload() {}, post() {} },
usePage: () => ({
url: '/synthetic',
props: { auth: { user: { id: 1 } } },
}),
useForm(initial) {
const i = formCursor++;
forms[i] ??= {
data: structuredClone(initial),
errors: {},
processing: false,
setData(key, value) {
if (typeof key === 'function')
this.data = key(this.data);
else if (typeof key === 'object') this.data = key;
else this.data[key] = value;
},
clearErrors() {},
setDefaults() {},
transform(callback) {
this.transformer = callback;
},
post(url, options) {
sent.push({
url,
options,
data: this.transformer
? this.transformer(this.data)
: this.data,
});
},
patch(url, options) {
sent.push({ url, options, data: this.data });
},
};
return forms[i];
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/lib/operation-key': {
createOperationKey: () => 'synthetic-operation',
},
'@/lib/desk-field-values': load(
'../../resources/js/lib/desk-field-values.ts',
),
'@/lib/desk-field-visibility': load(
'../../resources/js/lib/desk-field-visibility.ts',
),
'@/components/dossier-prefill': { DossierPrefill: Empty },
'@/components/desk-typed-choice': { default: Empty },
'@/components/desk-draft-recovery': { default: Empty },
'@/components/desk-attachment-field': { default: Empty },
'@/components/country-select': { default: Empty },
'@/components/investment-territory': { TerritoryFields: Empty },
'@/components/desk-internal-operations': {
DocumentReview: Empty,
RequestOperations: Empty,
},
'@/components/investor-guidance': { InvestorGuidance: Empty },
'@/components/desk-case-state-form': { default: Empty },
'@/components/desk-document-picker': { default: Empty },
...extra,
};
mocks['@/lib/crm-record-edit'] = load(
'../../resources/js/lib/crm-record-edit.ts',
mocks,
);
mocks['@/components/crm-edit-comparison'] = { default: Empty };
mocks['@/components/crm-task-creation'] = { default: Empty };
const exports = load(file, mocks, suffix);
const Component =
exports.TaskRow ?? exports.default ?? exports.InvestorGuidance;
function render(patch = {}) {
props = { ...props, ...patch };
cursor = 0;
formCursor = 0;
tree = Component(props);
}
render();
return {
forms,
sent,
render,
all: () => nodes(tree),
text: () => text(tree),
find: (type, label) =>
nodes(tree).find(
(n) => n.type === type && (!label || text(n).includes(label)),
),
};
}
const request = {
id: 'request-one',
version: 1,
status: 'draft',
payload: { title: 'SYNTHETIC saved title' },
protocol: null,
editable_fields: [],
analyst_id: null,
due_at: null,
};
const props = {
request,
case: { id: 'case-one', title: 'SYNTHETIC dossier' },
definition: {
title: 'SYNTHETIC service',
fields: {
title: { label: 'Project title', type: 'text', required: true },
},
result: 'SYNTHETIC',
},
owner: true,
manager: false,
analyst: false,
fieldsEditable: true,
operationsEditable: true,
states: {
draft: 'Rascunho',
submitted: 'Submetido',
reviewing: 'Em análise',
},
transitions: [],
findings: [],
messages: [],
analysts: [],
territoryPaths: {},
events: [],
documents: [],
payments: [],
caseVersion: 1,
countries: [],
toolPrefill: null,
};
const page = (patch) =>
harness('../../resources/js/pages/desk/request.tsx', {
...props,
...patch,
});
test('owner cancellation uses the existing transition and restores saved server payload only after success', () => {
const h = page();
h.forms[0].setData('payload', { title: 'SYNTHETIC unsaved edit' });
h.forms[1].setData('reason', 'SYNTHETIC deliberate cancellation');
h.find('form', 'Cancelar este pedido').props.onSubmit({
preventDefault() {},
});
assert.equal(h.sent[0].data.status, 'cancelled');
assert.equal(h.sent[0].data.version, 1);
assert.equal(h.sent[0].data.reason, 'SYNTHETIC deliberate cancellation');
assert.equal(h.forms[0].data.payload.title, 'SYNTHETIC unsaved edit');
h.sent[0].options.onSuccess({
props: { request: { ...request, status: 'cancelled', version: 2 } },
});
h.render({
request: { ...request, status: 'cancelled', version: 2 },
fieldsEditable: false,
operationsEditable: false,
});
assert.equal(h.forms[0].data.payload.title, 'SYNTHETIC saved title');
assert.equal(h.forms[0].data.consent, false);
assert.equal(h.find('form', 'Cancelar este pedido'), undefined);
});
test('cancellation waits for recovery work and is unavailable to submitted requests, reviewers and closed dossiers', () => {
const Recovery = () => null;
const h = harness('../../resources/js/pages/desk/request.tsx', props, {
'@/components/desk-draft-recovery': { default: Recovery },
});
h.all()
.find((n) => n.type === Recovery)
.props.onBusy(true);
h.render();
assert.equal(
h.find('button', 'Confirmar cancelamento').props.disabled,
true,
);
h.find('form', 'Cancelar este pedido').props.onSubmit({
preventDefault() {},
});
assert.equal(h.sent.length, 0);
for (const patch of [
{ request: { ...request, status: 'submitted' } },
{ owner: false, manager: true },
{ operationsEditable: false },
])
assert.equal(
page(patch).find('form', 'Cancelar este pedido'),
undefined,
);
});
test('closed dossier request hides response, assignment and message actions while keeping previous messages visible', () => {
const open = {
request: { ...request, status: 'submitted' },
owner: false,
manager: true,
fieldsEditable: false,
transitions: ['reviewing'],
analysts: [{ id: 2, name: 'SYNTHETIC analyst' }],
messages: [
{
id: 'message-one',
body: 'SYNTHETIC historical message',
name: 'SYNTHETIC author',
kind: 'responsible_response',
created_at: '2026-11-03',
},
],
};
const h = page({ ...open, operationsEditable: false });
assert.match(h.text(), /SYNTHETIC historical message/);
assert.equal(h.find('button', 'Atribuir acompanhamento'), undefined);
assert.equal(
h.find('form', 'Resposta / análise do responsável'),
undefined,
);
assert.equal(h.find('form', 'Mensagem privada'), undefined);
assert.ok(page(open).find('form', 'Resposta / análise do responsável'));
assert.ok(page(open).find('form', 'Mensagem privada'));
});
test('correction explanation applies to returned requests and does not ask draft authors an inapplicable question', () => {
assert.doesNotMatch(page().text(), /Justificação de correcção/);
assert.match(
page({
request: {
...request,
status: 'returned',
editable_fields: ['title'],
},
}).text(),
/Justificação de correcção/,
);
});
test('closed case keeps workflow and documentary context without stage or review operations', () => {
const Review = () => null;
const base = {
case: {
id: 'case-one',
title: 'SYNTHETIC dossier',
version: 1,
closed_at: '2026-11-03',
workflow: {},
},
canWrite: false,
manager: true,
requests: [],
services: [],
documents: [],
workflow: {},
stepStates: {},
states: {},
guidance: null,
events: [],
links: [],
legacyRequest: null,
};
const h = harness('../../resources/js/pages/desk/case.tsx', base, {
'@/components/desk-internal-operations': { DocumentReview: Review },
});
assert.match(h.text(), /Dossier encerrado/);
assert.equal(h.find('button', 'Registar etapa'), undefined);
assert.equal(
h.all().some((n) => n.type === Review),
false,
);
h.render({ case: { ...base.case, closed_at: null } });
assert.ok(h.find('button', 'Registar etapa'));
assert.equal(
h.all().some((n) => n.type === Review),
true,
);
});
test('CRM linked task preserves its title, status and deadline without an update action when dossier is closed', () => {
const task = {
id: 'task-one',
title: 'SYNTHETIC linked task',
status: 'open',
due_at: '2026-11-05T12:00:00Z',
assignee_user_id: 1,
version_no: 1,
can_update: false,
};
const h = harness(
'../../resources/js/pages/crm/lead.tsx',
{ task, leadId: 'lead-one' },
{
'../management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'./types': {
taskStates: { open: 'Aberta', done: 'Concluída' },
leadStates: {},
},
},
'\nexport { TaskRow };',
);
assert.match(h.text(), /SYNTHETIC linked task/);
assert.equal(h.find('select').props.disabled, true);
assert.equal(h.find('button', 'Actualizar tarefa'), undefined);
h.find('form').props.onSubmit({ preventDefault() {} });
assert.equal(h.sent.length, 0);
h.render({ task: { ...task, can_update: true } });
assert.ok(h.find('button', 'Actualizar tarefa'));
});
test('guidance hides task changes on a closed dossier but keeps task history and consulted sources', () => {
const guidance = {
version: 1,
fingerprint: 'x'.repeat(64),
rules_version: 'SYNTHETIC',
computed_at: '2026-11-03',
can_write: false,
can_update_tasks: false,
facts: {},
financial_draft: null,
consulted: [],
unavailable: [],
catalogue_checks: [],
phases: [
{
id: 'one',
objective: 'SYNTHETIC phase',
known: [],
questions: [],
evidence: [],
recommendations: [],
risks: [],
},
],
tasks: [
{
id: 'task-one',
title: 'SYNTHETIC saved task',
status: 'open',
due_at: '2026-11-05',
assignee_user_id: 1,
assignee_name: 'SYNTHETIC actor',
version_no: 1,
accepted_at: '2026-11-03',
desk_request_id: null,
},
],
calculator_versions: {},
crm: { reason: 'SYNTHETIC internal context' },
};
const h = harness(
'../../resources/js/components/investor-guidance.tsx',
{
caseId: 'case-one',
guidance,
manager: true,
actorId: 1,
requests: [],
},
{
'@/lib/investor-guidance-finance': {
guidanceFinance: () => ({
reason: 'SYNTHETIC no financial draft',
result: null,
}),
guidanceFinancialTools: () => null,
},
},
);
assert.match(h.text(), /SYNTHETIC saved task/);
assert.doesNotMatch(h.text(), /Resultado ou motivo/);
h.render({ guidance: { ...guidance, can_update_tasks: true } });
assert.match(h.text(), /Resultado ou motivo/);
});
@@ -0,0 +1,495 @@
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 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 (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const text = (node) =>
typeof node === 'string'
? node
: Array.isArray(node)
? node.map(text).join('')
: node?.props
? text(node.props.children)
: typeof node === 'number'
? String(node)
: '';
const document = {
id: 'source-one',
document_id: 'original-one',
file_name: 'SYNTHETIC source.txt',
version_no: 3,
source_reference: 'SYNTHETIC exact source',
category: 'project_evidence',
stage: 'E2',
valid_until: '2028-01-02',
origin_label: 'SYNTHETIC previous dossier',
status: 'active',
malware_scan_status: 'clean',
media_type: 'text/plain',
size_bytes: 100,
};
function harness(handler) {
const cells = [],
calls = [],
selections = [];
let cursor = 0,
props,
tree;
const Component = load(
'../../resources/js/components/desk-document-picker.tsx',
{
react: {
useId: () => 'synthetic-picker',
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) => {
cells[i] =
typeof value === 'function'
? value(cells[i])
: value;
},
];
},
},
'@/lib/profile-json': {
async profileJson(url, body, method) {
calls.push({ url, body, method });
return handler(url);
},
},
},
);
props = {
caseId: 'synthetic-case',
disabled: false,
selected: null,
onSelect: (doc) => {
selections.push(doc);
props.selected = doc;
},
};
const render = (updates) => {
props = { ...props, ...updates };
cursor = 0;
tree = Component(props);
return tree;
};
const find = (type, label) =>
nodes(tree).find(
(n) => n.type === type && (!label || text(n).includes(label)),
);
render();
return {
render,
find,
all: () => nodes(tree),
calls,
selections,
text: () => text(tree),
};
}
const settle = async () => {
await new Promise((resolve) => setImmediate(resolve));
};
test('search encodes literal input, returns names/provenance and never associates on search or selection', async () => {
const h = harness(async () => ({
documents: [document],
next_offset: null,
}));
h.find('input').props.onChange({
target: { value: '%_ source & dossier' },
});
h.render();
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
assert.equal(h.calls.length, 1);
assert.equal(h.calls[0].method, 'GET');
const params = new URL(h.calls[0].url, 'http://localhost').searchParams;
assert.equal(params.get('q'), '%_ source & dossier');
assert.equal(params.get('offset'), '0');
assert.match(
h.text(),
/SYNTHETIC source\.txt.*versão 3.*SYNTHETIC previous dossier.*exact source.*2028-01-02/,
);
h.all()
.find((n) => n.type === 'input' && n.props.type === 'radio')
.props.onChange();
h.render();
assert.deepEqual(h.selections, [document]);
assert.equal(h.calls.length, 1);
assert.match(h.text(), /Origem seleccionada/);
h.find('button', 'Retirar origem seleccionada').props.onClick();
assert.equal(h.selections.at(-1), null);
});
test('pagination does not erase a selected source and new searches start at zero', async () => {
const h = harness(async (url) => ({
documents: [document],
next_offset: url.includes('offset=0') ? 25 : null,
}));
h.render({ selected: document });
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
h.find('button', 'Próxima página').props.onClick();
await settle();
h.render();
assert.equal(
new URL(h.calls.at(-1).url, 'http://localhost').searchParams.get(
'offset',
),
'25',
);
assert.match(h.text(), /Origem seleccionada/);
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
assert.equal(
new URL(h.calls.at(-1).url, 'http://localhost').searchParams.get(
'offset',
),
'0',
);
assert.equal(h.selections.length, 0);
});
test('failed or malformed responses retain selected source and do not expose partial replacements', async () => {
let failed = true;
const h = harness(async () => {
if (failed) throw Error('SYNTHETIC denied');
return { documents: {}, next_offset: null };
});
h.render({ selected: document });
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
assert.match(h.text(), /SYNTHETIC denied/);
assert.match(h.text(), /Origem seleccionada/);
failed = false;
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
assert.match(h.text(), /selecção anterior foi conservada/);
assert.equal(h.selections.length, 0);
});
test('editing the search removes the old page cursor while retaining a deliberate document selection', async () => {
const h = harness(async () => ({ documents: [document], next_offset: 25 }));
h.render({ selected: document });
h.find('button', 'Pesquisar documentos').props.onClick();
await settle();
h.render();
assert.ok(h.find('button', 'Próxima página'));
h.find('input').props.onChange({ target: { value: 'different source' } });
h.render();
assert.equal(h.find('button', 'Próxima página'), undefined);
assert.match(h.text(), /Pesquisa alterada/);
assert.match(h.text(), /Origem seleccionada/);
assert.equal(h.selections.length, 0);
});
test('search pending prevents duplicate requests and stale dossier responses are ignored', async () => {
let resolve;
const h = harness(
() =>
new Promise((r) => {
resolve = r;
}),
);
h.find('button', 'Pesquisar documentos').props.onClick();
h.render();
assert.equal(h.find('button', 'Pesquisar documentos').props.disabled, true);
h.find('button', 'Pesquisar documentos').props.onClick();
assert.equal(h.calls.length, 1);
h.render({ caseId: 'different-case' });
resolve({ documents: [document], next_offset: null });
await settle();
h.render();
assert.equal(
h.all().filter((n) => n.type === 'input' && n.props.type === 'radio')
.length,
0,
);
h.render({ disabled: true });
h.find('button', 'Pesquisar documentos').props.onClick();
assert.equal(h.calls.length, 1);
});
test('Enter searches without submitting the surrounding form and an unlinked upload remains selectable', async () => {
const h = harness(async () => ({
documents: [
{
...document,
id: null,
origin_label: null,
source_reference: null,
},
],
next_offset: null,
}));
let prevented = false;
h.find('input').props.onKeyDown({
key: 'Enter',
preventDefault() {
prevented = true;
},
});
await settle();
h.render();
assert.equal(prevented, true);
assert.match(h.text(), /Ficheiro enviado por si.*Referência por completar/);
h.all()
.find((n) => n.type === 'input' && n.props.type === 'radio')
.props.onChange();
assert.equal(h.selections[0].id, null);
assert.equal(h.selections[0].document_id, document.document_id);
assert.ok(
h
.all()
.filter((n) => n.type === 'button')
.every((n) => n.props.type === 'button'),
);
});
test('general and question consumers send chosen source identity without asking for UUIDs or rewriting known source', () => {
const general = fs.readFileSync(
new URL('../../resources/js/pages/desk/case.tsx', import.meta.url),
'utf8',
);
const field = fs.readFileSync(
new URL(
'../../resources/js/components/desk-attachment-field.tsx',
import.meta.url,
),
'utf8',
);
assert.match(general, /<DeskDocumentPicker/);
assert.doesNotMatch(
general,
/Ou identificador de documento|Identificador do documento de suporte/,
);
assert.match(general, /document_link_id/);
assert.match(general, /reuse_link_id: documentOrigin\?\.id/);
assert.match(
general,
/source_reference:\s*documentOrigin\?\.source_reference\?\.trim\(\)/,
);
assert.match(field, /<DeskDocumentPicker/);
assert.match(
field,
/if \(origin.id\) data.set\('reuse_link_id', origin.id\)/,
);
});
function generalHarness() {
const cells = [],
forms = [],
posts = [];
let cursor = 0,
formCursor = 0,
tree;
const Picker = () => null;
const Component = load('../../resources/js/pages/desk/case.tsx', {
react: {
useRef(initial) {
const i = cursor++;
cells[i] ??= { current: initial };
return cells[i];
},
useState(initial) {
const i = cursor++;
if (!(i in cells)) cells[i] = initial;
return [
cells[i],
(value) => {
cells[i] =
typeof value === 'function'
? value(cells[i])
: value;
},
];
},
},
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
'@inertiajs/react': {
Link: 'a',
router: { reload() {} },
usePage: () => ({
props: { auth: { user: { id: 1 } } },
url: '/balcao-virtual/dossiers/synthetic-case',
}),
useForm(initial) {
const i = formCursor++;
forms[i] ??= {
data: { ...initial },
errors: {},
processing: false,
setData(key, value) {
this.data[key] = value;
},
transform(callback) {
this.transformer = callback;
},
post(url, options) {
posts.push({
url,
data: this.transformer
? this.transformer(this.data)
: this.data,
options,
});
},
reset(...keys) {
for (const key of keys) this.data[key] = initial[key];
},
};
return forms[i];
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/investor-guidance': { InvestorGuidance: () => null },
'@/components/desk-case-state-form': { default: () => null },
'@/components/desk-internal-operations': { DocumentReview: () => null },
'@/components/desk-document-picker': { default: Picker },
});
const props = {
case: {
id: 'synthetic-case',
title: 'SYNTHETIC dossier',
version: 7,
workflow: {},
payload: {},
},
canWrite: true,
manager: false,
requests: [],
services: [],
documents: [],
workflow: {},
stepStates: {},
states: {},
guidance: null,
events: [],
links: [],
legacyRequest: null,
};
function render() {
cursor = 0;
formCursor = 0;
tree = Component(props);
}
render();
return {
render,
forms,
posts,
picker: () => nodes(tree).find((n) => n.type === Picker),
all: () => nodes(tree),
submit() {
nodes(tree)
.find(
(n) =>
n.type === 'form' &&
nodes(n).some((child) => child.type === Picker),
)
.props.onSubmit({ preventDefault() {} });
},
};
}
test('general association sends the selected link, original version context and consent, preserving selection on failure', () => {
const h = generalHarness();
h.forms[2].setData('file', { name: 'SYNTHETIC old local choice' });
h.forms[2].setData('consent', true);
h.picker().props.onSelect(document);
h.render();
assert.equal(h.forms[2].data.file, null);
assert.equal(h.forms[2].data.consent, false);
h.forms[2].setData('consent', true);
h.submit();
const posted = h.posts[0];
assert.equal(posted.data.version, 7);
assert.equal(posted.data.document_id, document.document_id);
assert.equal(posted.data.reuse_link_id, document.id);
assert.equal(posted.data.file, null);
assert.equal(posted.data.source_reference, undefined);
h.render();
assert.equal(h.picker().props.selected.id, document.id);
posted.options.onSuccess();
h.render();
assert.equal(h.picker().props.selected, null);
assert.equal(h.forms[2].data.consent, false);
});
test('general association asks only for missing provenance on unlinked uploads and preserves entered text until success', () => {
const h = generalHarness();
h.picker().props.onSelect({
...document,
id: null,
source_reference: null,
});
h.render();
const source = h.all().find((n) => n.type === 'input' && n.props.required);
assert.ok(source);
source.props.onChange({
target: { value: 'SYNTHETIC missing provenance supplied' },
});
h.render();
h.forms[2].setData('consent', true);
h.submit();
assert.equal(h.posts[0].data.document_id, document.document_id);
assert.equal(h.posts[0].data.reuse_link_id, '');
assert.equal(
h.posts[0].data.source_reference,
'SYNTHETIC missing provenance supplied',
);
h.render();
assert.equal(
h.forms[2].data.source_reference,
'SYNTHETIC missing provenance supplied',
);
h.posts[0].options.onSuccess();
assert.equal(h.forms[2].data.source_reference, '');
});
@@ -0,0 +1,349 @@
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, suffix = '') {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
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;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
function form(initial) {
return {
data: initial,
errors: {},
processing: false,
setData(value, next) {
this.data =
typeof value === 'function'
? value(this.data)
: { ...this.data, [value]: next };
},
};
}
const service = {
code: 'project-change',
version: 2,
effective_from: '2026-11-12',
activeVersion: 1,
definition: {
title: 'SYNTHETIC scheduled form',
theme: 'QA',
profile: 'Investor',
entity: 'Internal',
result: 'Internal preparation',
stage: 'E10',
fields: {
question: {
label: 'Synthetic question',
type: 'text',
required: false,
},
},
},
};
function editorHarness() {
let saved, sent;
const Editor = load(
'../../resources/js/pages/desk/service-editor.tsx',
{
react: { useState: (initial) => [initial, () => {}] },
'@inertiajs/react': {
Link: 'a',
useForm(key, initial) {
saved ??= {
...form(initial),
put(url) {
sent = { url, data: structuredClone(this.data) };
},
};
return saved;
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/desk-service-history': { default: () => null },
},
'\nexport { Editor };',
).Editor;
return {
render: (props = {}) =>
Editor({
service,
schedulingAvailable: true,
today: '2026-11-02',
calendarTimezone: 'UTC',
...props,
}),
data: () => saved,
sent: () => sent,
};
}
await test('editing a scheduled edition keeps its future date until changed deliberately and date-only changes require fresh confirmation', () => {
const before = JSON.stringify(service);
const h = editorHarness();
let tree = h.render();
assert.equal(h.data().data.effective_from, '2026-11-12');
const date = nodes(tree).find(
(node) => node.type === 'input' && node.props.type === 'date',
);
assert.equal(date.props.min, '2026-11-02');
h.data().data.confirm = true;
date.props.onChange({ target: { value: '2026-11-02' } });
assert.equal(h.data().data.confirm, false);
tree = h.render();
let html = renderToStaticMarkup(tree);
assert.match(html, /Versão actualmente disponível para novos pedidos: 1/);
assert.match(html, /Entrada em vigor proposta: 2026-11-02/);
assert.match(html, /não cancela uma edição já agendada/);
assert.match(html, /Calendário do portal: UTC/);
h.data().data.confirm = true;
tree = h.render();
const publish = nodes(tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Publicar nova versão',
);
assert.equal(publish.props.disabled, false);
tree.props.onSubmit({ preventDefault() {} });
assert.equal(h.sent().data.effective_from, '2026-11-02');
assert.equal(h.sent().data.base_version, 2);
assert.equal(JSON.stringify(service), before);
date.props.onChange({ target: { value: '' } });
html = renderToStaticMarkup(h.render());
assert.match(html, /Entrada em vigor proposta: 2026-11-02/);
});
await test('destinations without the migration retain immediate publication and cannot silently present a scheduling control', () => {
const h = editorHarness();
const tree = h.render({ schedulingAvailable: false });
assert.equal(h.data().data.effective_from, '');
assert.equal(
nodes(tree).some(
(node) => node.type === 'input' && node.props.type === 'date',
),
false,
);
assert.match(
renderToStaticMarkup(tree),
/agendamento requer a actualização/,
);
});
await test('advancing the calendar does not silently propose an unchanged edition, and upcoming editions remain visible', () => {
const h = editorHarness();
const props = {
service: {
...service,
effective_from: '2026-11-01',
activeVersion: 2,
upcoming: [{ version: 1, effective_from: '2026-11-12' }],
},
};
let tree = h.render(props);
h.data().data.confirm = true;
tree = h.render(props);
let publish = nodes(tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Publicar nova versão',
);
assert.equal(publish.props.disabled, true);
const html = renderToStaticMarkup(tree);
assert.match(html, /Edições já agendadas/);
assert.match(html, /Versão 1: 2026-11-12/);
nodes(tree)
.find((node) => node.type === 'input' && node.props.type === 'date')
.props.onChange({ target: { value: '2026-11-02' } });
h.data().data.confirm = true;
tree = h.render(props);
publish = nodes(tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Publicar nova versão',
);
assert.equal(publish.props.disabled, false);
});
await test('refreshing services retains other case forms and requires an explicit choice when the selected edition is no longer listed', () => {
let cursor = 0,
stateCursor = 0,
refreshed,
submitted;
const forms = [],
states = [];
const Case = load('../../resources/js/pages/desk/case.tsx', {
react: {
useState(initial) {
const index = stateCursor++;
if (!(index in states)) states[index] = initial;
return [
states[index],
(value) => {
states[index] =
typeof value === 'function'
? value(states[index])
: value;
},
];
},
useRef(initial) {
const index = stateCursor++;
states[index] ??= { current: initial };
return states[index];
},
},
'@/lib/operation-key': { createOperationKey: () => 'qa-operation' },
'@inertiajs/react': {
Link: 'a',
usePage: () => ({
props: { auth: { user: { id: 3 } } },
url: '/balcao-virtual/dossiers/qa',
}),
router: {
reload(options) {
refreshed = options;
},
},
useForm(initial) {
const index = cursor++;
forms[index] ??= {
...form(initial),
post(url) {
submitted = { url, data: this.data };
},
};
return forms[index];
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/investor-guidance': { InvestorGuidance: () => null },
'@/components/desk-case-state-form': { default: () => null },
'@/components/desk-document-picker': { default: () => null },
'@/components/desk-internal-operations': { DocumentReview: () => null },
}).default;
const props = {
case: { id: 'qa', title: 'Synthetic case', version: 1, workflow: {} },
canWrite: true,
manager: false,
requests: [],
services: [{ id: 'v1', title: 'Current', version: 1 }],
documents: [],
workflow: {},
stepStates: {},
states: {},
guidance: null,
events: [],
links: [],
legacyRequest: null,
};
const render = (services) => {
cursor = 0;
stateCursor = 0;
return Case({ ...props, services });
};
let tree = render(props.services);
forms[1].data.reason = 'Unsaved stage evidence';
tree = render([
{
id: 'v2',
title: 'New current',
version: 2,
effective_from: '2026-11-03',
},
]);
const html = renderToStaticMarkup(tree);
assert.match(html, /versão seleccionada já não está na lista/);
assert.match(html, /desde 2026-11-03/);
const create = nodes(tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Preparar rascunho de pedido',
);
assert.equal(create.props.disabled, true);
const requestForm = nodes(tree).find(
(node) => node.type === 'form' && nodes(node).includes(create),
);
requestForm.props.onSubmit({ preventDefault() {} });
assert.equal(submitted, undefined);
nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Actualizar versões disponíveis',
)
.props.onClick();
assert.deepEqual(refreshed.only, ['services']);
assert.equal(forms[1].data.reason, 'Unsaved stage evidence');
const select = nodes(tree).find(
(node) => node.type === 'select' && node.props.value === 'v1',
);
select.props.onChange({ target: { value: 'v2' } });
tree = render([{ id: 'v2', title: 'New current', version: 2 }]);
const ready = nodes(tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Preparar rascunho de pedido',
);
assert.equal(ready.props.disabled, false);
});
await test('catalogue shows the selected calendar date with the distinction between new and existing requests', () => {
const Catalogue = load('../../resources/js/pages/desk/catalogue.tsx', {
'@inertiajs/react': { Link: 'a' },
'@/pages/investment/shared': { Frame: 'main', card: '' },
}).default;
const html = renderToStaticMarkup(
Catalogue({
installed: true,
services: [
{
id: 'v2',
version: 2,
effective_from: '2026-11-03',
definition: {
title: '<Synthetic public form>',
result: 'Internal preparation',
},
},
],
prepared: {},
}),
);
assert.match(html, /novos pedidos desde 2026-11-03/);
assert.match(html, /Pedidos anteriores mantêm/);
assert.match(html, /&lt;Synthetic public form&gt;/);
});
@@ -0,0 +1,310 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks) {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const text = (tree) =>
typeof tree === 'string'
? tree
: Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'number'
? String(tree)
: '';
const document = {
id: 'link-one',
document_id: 'original-one',
file_name: 'SYNTHETIC proof.txt',
version_no: 3,
source_reference: 'SYNTHETIC document source',
status: 'active',
malware_scan_status: 'clean',
};
const payment = {
id: 'payment-one',
reference: 'SYNTHETIC reference',
amount: '25.50',
currency: 'MZN',
source_reference: 'SYNTHETIC amount purpose',
document_id: null,
version: 1,
status: 'pending',
verified_by: null,
reason: null,
};
const shared = { card: '', input: '', button: '' };
function formsHarness(file, defaults, pickerMock = {}) {
const forms = [],
calls = [];
let cursor = 0,
serial = 0,
tree,
props = defaults;
const loaded = load(file, {
'@inertiajs/react': {
useForm(initial) {
const i = cursor++;
forms[i] ??= {
data: { ...initial },
errors: {},
processing: false,
setData(key, value) {
this.data[key] = value;
},
transform(callback) {
this.transformer = callback;
},
reset(...keys) {
for (const key of keys) this.data[key] = initial[key];
},
put(url, options) {
calls.push({
url,
method: 'PUT',
data: { ...this.data },
options,
});
},
post(url, options) {
calls.push({
url,
method: 'POST',
data: this.transformer
? this.transformer(this.data)
: { ...this.data },
options,
});
},
};
return forms[i];
},
},
'@/lib/operation-key': {
createOperationKey: () => `synthetic-key-${++serial}`,
},
'@/pages/investment/shared': shared,
'./desk-payment-document-form': pickerMock,
});
const Component = loaded.default ?? loaded.RequestOperations;
function render(patch = {}) {
props = { ...props, ...patch };
cursor = 0;
tree = Component(props);
}
render();
return {
forms,
calls,
render,
all: () => nodes(tree),
text: () => text(tree),
find: (type, label) =>
nodes(tree).find(
(n) => n.type === type && (!label || text(n).includes(label)),
),
submit() {
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
},
};
}
const proofHarness = () =>
formsHarness(
'../../resources/js/components/desk-payment-document-form.tsx',
{ requestId: 'request-one', payment, documents: [document] },
);
test('adding proof to a pending payment sends only new documentary facts and conserves financial declaration', () => {
const h = proofHarness();
h.find('select').props.onChange({ target: { value: document.id } });
h.render();
h.find('textarea').props.onChange({
target: { value: 'SYNTHETIC reason' },
});
h.render();
h.find('input').props.onChange({ target: { checked: true } });
h.render();
h.submit();
assert.match(h.calls[0].url, /pagamentos\/payment-one\/comprovativo$/);
assert.equal(h.calls[0].method, 'PUT');
assert.deepEqual(
Object.keys(h.calls[0].data).sort(),
[
'version',
'document_link_id',
'reason',
'consent',
'client_key',
].sort(),
);
assert.equal(h.calls[0].data.document_link_id, document.id);
assert.equal(h.calls[0].data.version, 1);
assert.equal(h.calls[0].data.consent, true);
assert.match(
h.text(),
/referência, o valor e a moeda já registados são conservados/,
);
assert.equal(h.all().filter((n) => n.type === 'input').length, 1);
});
test('failed retry keeps payload and operation key while editing deliberately starts a new operation', () => {
const h = proofHarness();
h.forms[0].setData('document_link_id', document.id);
h.forms[0].setData('reason', 'SYNTHETIC original reason');
h.forms[0].setData('consent', true);
h.submit();
h.submit();
assert.deepEqual(h.calls[0].data, h.calls[1].data);
const original = h.forms[0].data.client_key;
h.find('textarea').props.onChange({
target: { value: 'SYNTHETIC edited reason' },
});
h.render();
assert.notEqual(h.forms[0].data.client_key, original);
assert.equal(h.forms[0].data.consent, false);
assert.equal(h.forms[0].data.document_link_id, document.id);
h.forms[0].setData('consent', true);
h.submit();
const key = h.forms[0].data.client_key;
h.calls.at(-1).options.onSuccess();
h.render({ payment: { ...payment, version: 2 } });
assert.equal(h.forms[0].data.version, 2);
assert.equal(h.forms[0].data.reason, '');
assert.equal(h.forms[0].data.document_link_id, '');
assert.notEqual(h.forms[0].data.client_key, key);
});
test('new server version requires deliberate adoption and does not erase reason or selected proof', () => {
const h = proofHarness();
h.forms[0].setData('document_link_id', document.id);
h.forms[0].setData('reason', 'SYNTHETIC unsaved reason');
h.forms[0].setData('consent', true);
h.render({ payment: { ...payment, version: 3 } });
assert.equal(h.find('button', 'Guardar comprovativo').props.disabled, true);
h.submit();
assert.equal(h.calls.length, 0);
h.find('button', 'Usar versão actual').props.onClick();
h.render();
assert.equal(h.forms[0].data.version, 3);
assert.equal(h.forms[0].data.document_link_id, document.id);
assert.equal(h.forms[0].data.reason, 'SYNTHETIC unsaved reason');
assert.equal(h.forms[0].data.consent, false);
});
test('read-only operations preserve payment history without offering manual business forms', () => {
const Proof = () => null;
const h = formsHarness(
'../../resources/js/components/desk-internal-operations.tsx',
{
requestId: 'request-one',
owner: false,
reviewer: false,
documents: [document],
payments: [payment],
},
{ default: Proof },
);
assert.match(h.text(), /SYNTHETIC reference/);
assert.match(h.text(), /Comprovativo ainda não associado/);
assert.equal(h.all().filter((n) => n.type === 'form').length, 0);
assert.equal(h.all().filter((n) => n.type === Proof).length, 0);
h.render({ payments: [{ ...payment, document_id: document.document_id }] });
assert.match(h.text(), /metadados da associação não capturados à época/);
});
test('only pending or disputed payment offers proof correction and creation uses exact link without copying amount provenance', () => {
const Proof = () => null;
const h = formsHarness(
'../../resources/js/components/desk-internal-operations.tsx',
{
requestId: 'request-one',
owner: true,
reviewer: false,
documents: [document],
payments: [
payment,
{ ...payment, id: 'verified', status: 'internal_verified' },
{ ...payment, id: 'issue', status: 'internal_issue' },
],
},
{ default: Proof },
);
assert.equal(h.all().filter((n) => n.type === Proof).length, 2);
const selector = h
.all()
.find(
(n) =>
n.type === 'select' &&
n.props.value === h.forms[0].data.document_link_id,
);
assert.ok(
nodes(selector).some(
(n) => n.type === 'option' && n.props.value === document.id,
),
);
selector.props.onChange({ target: { value: document.id } });
h.render();
assert.equal(h.forms[0].data.document_link_id, document.id);
assert.equal(h.forms[0].data.source_reference, '');
assert.equal(h.forms[0].data.amount, '');
});
test('historical evidence shows the frozen file version and separates documentary reference from amount purpose', () => {
const h = formsHarness(
'../../resources/js/components/desk-internal-operations.tsx',
{
requestId: 'request-one',
owner: false,
reviewer: false,
documents: [],
payments: [
{
...payment,
document_id: document.document_id,
document_evidence: {
link_id: document.id,
file_name: document.file_name,
document_version: 3,
source_reference: document.source_reference,
valid_until: '2028-01-02',
},
},
],
},
{ default: () => null },
);
assert.match(h.text(), /Fonte do valor: SYNTHETIC amount purpose/);
assert.match(
h.text(),
/SYNTHETIC proof.txt.*versão 3.*SYNTHETIC document source.*2028-01-02/,
);
});
@@ -27,7 +27,7 @@ function load(file, overrides = {}) {
);
return module.exports;
}
function render(payload) {
function render(payload, extra = {}) {
const empty = () => null;
const page = load('../../resources/js/pages/desk/request.tsx', {
'@inertiajs/react': {
@@ -39,12 +39,39 @@ function render(payload) {
'@/lib/desk-field-visibility': load(
'../../resources/js/lib/desk-field-visibility.ts',
),
'@/lib/desk-field-values': load(
'../../resources/js/lib/desk-field-values.ts',
),
'@/components/desk-typed-choice': load(
'../../resources/js/components/desk-typed-choice.tsx',
{
'@/lib/desk-field-values': load(
'../../resources/js/lib/desk-field-values.ts',
),
},
),
'@/components/dossier-prefill': { DossierPrefill: empty },
'@/components/desk-draft-recovery': {
__esModule: true,
default: empty,
},
'@/components/country-select': { __esModule: true, default: empty },
'@/components/desk-attachment-field': {
__esModule: true,
default: empty,
},
'@/components/investment-territory': { TerritoryFields: empty },
'@/components/desk-internal-operations': {
DocumentReview: empty,
RequestOperations: empty,
RequestOperations: ({ owner, reviewer, payments }) =>
createElement(
'section',
{
'data-test': 'manual-operations',
'data-writable': owner || reviewer ? 'yes' : 'no',
},
payments.map((payment) => payment.reference).join(', '),
),
},
'@/pages/investment/shared': {
Frame: ({ children }) => createElement('main', null, children),
@@ -54,7 +81,7 @@ function render(payload) {
},
}).default;
return renderToStaticMarkup(
page({
createElement(page, {
request: {
id: 'synthetic-request',
version: 1,
@@ -107,9 +134,28 @@ function render(payload) {
caseVersion: 1,
countries: [],
toolPrefill: null,
...extra,
}),
);
}
await test('manual payment history remains visible with operations disabled and legacy draft props still render', () => {
const readonly = render(
{},
{
operationsEditable: false,
payments: [{ reference: 'SYNTHETIC historical payment' }],
},
);
assert.match(readonly, /SYNTHETIC historical payment/);
assert.match(readonly, /data-writable="no"/);
const legacy = render(
{},
{ payments: [{ reference: 'SYNTHETIC legacy draft' }] },
);
assert.match(legacy, /SYNTHETIC legacy draft/);
assert.match(legacy, /data-writable="yes"/);
});
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);
@@ -127,3 +173,36 @@ await test('hidden parent answers never reveal nested questions, while reopening
detail: 'Preserved detail',
});
});
await test('return category is optional and comes from the server, while historical labels retain their snapshot', () => {
const props = {
owner: false,
manager: true,
fieldsEditable: false,
transitions: ['returned'],
returnReasons: {
unspecified: 'SYNTHETIC unclassified',
missing_documents: 'SYNTHETIC configured category',
},
events: [
{
id: 'event',
action: 'request_returned',
name: 'SYNTHETIC actor',
created_at: '2026-11-02T10:00:00Z',
payload: { return_reason_label: 'SYNTHETIC historical label' },
},
],
};
const returned = render({}, props);
assert.match(
returned,
/Categoria do motivo \(opcional, para indicadores\)/,
);
assert.match(returned, /SYNTHETIC configured category/);
assert.match(returned, /Categoria:.*SYNTHETIC historical label/);
assert.doesNotMatch(returned, /<select[^>]*required/);
const other = render({}, { ...props, transitions: ['reviewing'] });
assert.doesNotMatch(other, /SYNTHETIC configured category/);
assert.match(other, /SYNTHETIC historical label/);
});
+400
View File
@@ -0,0 +1,400 @@
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 = {}, suffix = '') {
const output = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8') + suffix,
{
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 values = load('../../resources/js/lib/desk-field-values.ts');
const { deskFieldApplies } = load(
'../../resources/js/lib/desk-field-visibility.ts',
);
const Choice = load('../../resources/js/components/desk-typed-choice.tsx', {
'@/lib/desk-field-values': values,
}).default;
function nodes(tree) {
if (Array.isArray(tree)) return tree.flatMap(nodes);
if (!tree || typeof tree !== 'object') return [];
return [tree, ...nodes(tree.props?.children)];
}
const fields = {
root: {
type: 'select',
label: 'SYNTHETIC root',
required: false,
options: { on: 'Open', off: 'Closed' },
},
activities: {
type: 'multiselect',
label: 'SYNTHETIC activities',
required: true,
options: { 0: 'Zero', cotton: 'Cotton' },
when: { field: 'root', equals: 'on' },
},
declaration: {
type: 'consent',
label: 'SYNTHETIC declaration',
statement: 'SYNTHETIC <script>fictional</script> declaration.',
required: true,
when: { field: 'activities', operator: 'contains', equals: 'cotton' },
},
explanation: {
type: 'textarea',
label: 'SYNTHETIC explanation',
required: true,
when: { field: 'declaration', equals: 'declined' },
},
amount: { type: 'number' },
};
await test('typed prefill preserves arrays, zero, refusal and deliberate answers; declarations cannot be inherited even with replacement', () => {
const before = {
activities: ['0'],
declaration: 'declined',
amount: 0,
detail: 'Edited',
};
const patch = {
activities: ['cotton'],
declaration: 'accepted',
amount: 300,
detail: 'Profile',
missing: 'New',
};
assert.deepEqual(values.mergeDeskPrefill(before, patch, fields), {
...before,
missing: 'New',
});
assert.deepEqual(values.mergeDeskPrefill(before, patch, fields, true), {
activities: ['cotton'],
declaration: 'declined',
amount: 300,
detail: 'Profile',
missing: 'New',
});
assert.deepEqual(before.activities, ['0']);
assert.equal(
values.mergeDeskPrefill({}, patch, fields).declaration,
undefined,
);
assert.deepEqual(
values.mergeDeskPrefill(
{ activities: [] },
{ activities: ['0'] },
fields,
).activities,
['0'],
);
assert.equal(
values.mergeDeskPrefill({}, { activities: ['absent'] }, fields)
.activities,
undefined,
);
assert.equal(
values.mergeDeskPrefill({}, { activities: 'cotton' }, fields)
.activities,
undefined,
);
assert.equal(values.deskScalar(0), '0');
assert.equal(values.deskScalar(['cotton']), '');
});
await test('multiple choice controls retain code zero and toggle individual answers without checking an empty answer', () => {
let answer;
const initial = ['0'];
const tree = Choice({
fieldKey: 'activities',
field: fields.activities,
value: initial,
disabled: false,
onChange: (v) => (answer = v),
});
const inputs = nodes(tree).filter((n) => n.type === 'input');
assert.deepEqual(
inputs.map((n) => n.props.checked),
[true, false],
);
inputs[1].props.onChange({ target: { checked: true } });
assert.deepEqual(answer, ['0', 'cotton']);
inputs[0].props.onChange({ target: { checked: false } });
assert.deepEqual(answer, []);
assert.deepEqual(initial, ['0']);
assert.ok(inputs.every((n) => !n.props.required)); // Saving a partial draft remains possible.
const blank = Choice({
fieldKey: 'activities',
field: fields.activities,
value: [],
disabled: false,
onChange() {},
});
assert.ok(
nodes(blank)
.filter((n) => n.type === 'input')
.every((n) => !n.props.checked),
);
});
await test('consent has explicit acceptance and refusal, starts unanswered, can be cleared and renders statement safely', () => {
let answer;
const render = (value) =>
Choice({
fieldKey: 'declaration',
field: fields.declaration,
value,
disabled: false,
onChange: (v) => (answer = v),
});
let tree = render('');
const inputs = nodes(tree).filter((n) => n.type === 'input');
assert.deepEqual(
inputs.map((n) => n.props.checked),
[false, false],
);
inputs[1].props.onChange();
assert.equal(answer, 'declined');
tree = render(answer);
assert.deepEqual(
nodes(tree)
.filter((n) => n.type === 'input')
.map((n) => n.props.checked),
[false, true],
);
nodes(tree)
.find((n) => n.type === 'button')
.props.onClick();
assert.equal(answer, '');
const html = renderToStaticMarkup(tree);
assert.ok(html.includes('&lt;script&gt;fictional&lt;/script&gt;'));
assert.ok(!html.includes('<script>fictional</script>'));
assert.match(html, /não exige aceitar/);
assert.equal(
Choice({
fieldKey: 'declaration',
field: fields.declaration,
value: 'accepted',
disabled: true,
onChange() {},
}).props.disabled,
true,
);
});
await test('contains conditions require string membership and active ancestors; reopening restores prior refusal and detail', () => {
const payload = {
root: 'off',
activities: ['cotton', '0'],
declaration: 'declined',
explanation: 'Preserved',
};
assert.equal(deskFieldApplies('declaration', fields, payload), false);
assert.equal(deskFieldApplies('explanation', fields, payload), false);
assert.equal(
deskFieldApplies('explanation', fields, { ...payload, root: 'on' }),
true,
);
assert.equal(
deskFieldApplies('declaration', fields, {
...payload,
root: 'on',
activities: 'cotton',
}),
false,
);
assert.equal(
deskFieldApplies('declaration', fields, {
...payload,
root: 'on',
activities: ['0'],
}),
false,
);
assert.equal(
deskFieldApplies('explanation', fields, {
...payload,
root: 'on',
declaration: 'accepted',
}),
false,
);
assert.equal(
deskFieldApplies('explanation', fields, {
...payload,
root: 'on',
declaration: '',
}),
false,
);
assert.deepEqual(payload.activities, ['cotton', '0']);
});
function editorHarness() {
let form;
const Editor = load(
'../../resources/js/pages/desk/service-editor.tsx',
{
react: { useState: (value) => [value, () => {}] },
'@inertiajs/react': {
Link: 'a',
useForm(key, initial) {
form ??= {
data: initial,
errors: {},
processing: false,
setData(value) {
this.data = value(this.data);
},
};
return form;
},
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/components/desk-service-history': { default: () => null },
},
'\nexport { Editor };',
).Editor;
const service = {
code: 'project-change',
version: 1,
definition: {
title: 'SYNTHETIC form',
theme: 'QA',
profile: 'Investor',
entity: 'Internal',
result: 'Preparation',
stage: 'E10',
fields: structuredClone(fields),
},
};
return {
render: () => Editor({ service }),
data: () => form.data,
section(key) {
return nodes(this.render()).find(
(n) =>
n.type === 'section' &&
nodes(n).some(
(v) =>
v.type === 'input' &&
v.props.value === fields[key].label,
),
);
},
};
}
await test('editor configures multiple-choice membership and consent refusal conditions without losing the operator', () => {
const h = editorHarness();
let section = h.section('explanation');
const conditionSource = nodes(section).find(
(n) =>
n.type === 'select' &&
nodes(n).some(
(o) => o.type === 'option' && o.props.children === 'Sempre',
),
);
conditionSource.props.onChange({ target: { value: 'activities' } });
assert.deepEqual(h.data().definition.fields.explanation.when, {
field: 'activities',
equals: '',
operator: 'contains',
});
section = h.section('explanation');
const operand = nodes(section).find(
(n) =>
n.type === 'select' &&
nodes(n).some(
(o) => o.type === 'option' && o.props.value === 'cotton',
),
);
operand.props.onChange({ target: { value: 'cotton' } });
assert.equal(
h.data().definition.fields.explanation.when.operator,
'contains',
);
assert.equal(h.data().definition.fields.explanation.when.equals, 'cotton');
section = h.section('explanation');
nodes(section)
.find(
(n) =>
n.type === 'select' &&
nodes(n).some(
(o) => o.type === 'option' && o.props.children === 'Sempre',
),
)
.props.onChange({ target: { value: 'declaration' } });
section = h.section('explanation');
const refusal = nodes(section).find(
(n) =>
n.type === 'select' &&
nodes(n).some(
(o) => o.type === 'option' && o.props.value === 'declined',
),
);
refusal.props.onChange({ target: { value: 'declined' } });
assert.deepEqual(h.data().definition.fields.explanation.when, {
field: 'declaration',
equals: 'declined',
});
assert.equal(h.data().confirm, false);
});
await test('changing simple and multiple choice types preserves codes and adjusts dependent conditions in the draft only', () => {
const h = editorHarness();
const typeControl = (section) =>
nodes(section).find(
(n) =>
n.type === 'select' &&
nodes(n).some(
(o) =>
o.type === 'option' && o.props.value === 'multiselect',
),
);
typeControl(h.section('activities')).props.onChange({
target: { value: 'select' },
});
assert.deepEqual(
h.data().definition.fields.activities.options,
fields.activities.options,
);
assert.deepEqual(h.data().definition.fields.declaration.when, {
field: 'activities',
equals: 'cotton',
});
typeControl(h.section('activities')).props.onChange({
target: { value: 'multiselect' },
});
assert.deepEqual(h.data().definition.fields.declaration.when, {
field: 'activities',
equals: 'cotton',
operator: 'contains',
});
assert.equal(h.data().confirm, false);
assert.equal(fields.declaration.when.operator, 'contains');
assert.match(renderToStaticMarkup(h.render()), /inclui cotton/);
});
+143
View File
@@ -0,0 +1,143 @@
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, mocks) {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../resources/js/' + file, import.meta.url),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const Empty = () => null;
function management(flash) {
return load('pages/management/shared.tsx', {
'@inertiajs/react': {
Head: Empty,
Link: 'a',
usePage: () => ({ props: { flash, basePath: '/management' } }),
},
'@/components/profile-navigation': { default: Empty },
'@/components/content-management-entry': { default: Empty },
}).Management;
}
test('the actual management shell exposes retry warnings as an alert alongside preserved page content', () => {
const html = renderToStaticMarkup(
createElement(
management({ warning: 'SYNTHETIC dispatch unconfirmed' }),
{ title: 'Documents' },
'SYNTHETIC unchanged editor',
),
);
assert.match(html, /role="alert"[^>]*>SYNTHETIC dispatch unconfirmed/);
assert.match(html, /SYNTHETIC unchanged editor/);
assert.doesNotMatch(html, /role="status"/);
});
test('the actual management shell still renders a confirmed retry as a status', () => {
const html = renderToStaticMarkup(
createElement(management({ success: 'SYNTHETIC accepted' }), {
title: 'Documents',
}),
);
assert.match(html, /role="status"[^>]*>SYNTHETIC accepted/);
assert.doesNotMatch(html, /role="alert"/);
});
function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree?.props
? [tree, ...nodes(tree.props.children)]
: [];
}
function zone(management) {
const sent = [],
setters = [];
const Page = load('pages/investment/zone-attachments.tsx', {
react: { useState: (value) => [value, (next) => setters.push(next)] },
'@inertiajs/react': { router: { post: (...args) => sent.push(args) } },
'./shared': {
api: () => {
throw new Error('Retry must use the redirect-aware transport');
},
button: '',
card: '',
input: '',
Field: 'label',
},
}).default;
const tree = Page({
zoneId: 'SYNTHETIC-zone',
management,
zonePublished: false,
attachments: [
{
id: 'SYNTHETIC-link',
document_id: 'SYNTHETIC-document',
kind: 'photo',
caption: 'SYNTHETIC attachment',
source_reference: '',
source_date: null,
media_type: 'image/png',
size_bytes: 12,
download_url: '/private-document',
malware_scan_status: 'failed',
},
],
});
return { tree, sent, setters };
}
test('the actual zone retry follows the flash response through Inertia and keeps the page scroll', () => {
const h = zone(true),
button = nodes(h.tree).find(
(node) =>
node.type === 'button' &&
node.props.children === 'Tentar análise novamente',
);
assert.ok(button);
button.props.onClick();
assert.equal(h.sent.length, 1);
assert.equal(
h.sent[0][0],
'/management/documents/SYNTHETIC-document/malware/retry',
);
assert.deepEqual(h.sent[0][1], {});
assert.equal(h.sent[0][2].preserveScroll, true);
assert.deepEqual(h.setters, [true, '']);
h.sent[0][2].onError();
assert.match(h.setters.at(-1), /Actualize o estado/);
h.sent[0][2].onFinish();
assert.equal(h.setters.at(-1), false);
});
test('public zone attachments expose no retry command', () => {
const h = zone(false);
assert.equal(
nodes(h.tree).filter(
(node) =>
node.type === 'button' &&
node.props.children === 'Tentar análise novamente',
).length,
0,
);
assert.equal(h.sent.length, 0);
});
+367
View File
@@ -0,0 +1,367 @@
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;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const emptyProps = {
today: '2026-11-02',
territories: [],
projects: [],
courses: [],
occupations: [],
skills: [],
draftsAvailable: true,
};
class ApiError extends Error {
constructor(status) {
super('Synthetic error');
this.status = status;
this.errors = {};
}
}
function setup(request, props = emptyProps, renderPage = false) {
const states = [];
let cursor = 0,
form;
const Snapshot = () => null;
const saved = [],
dirty = [];
const module = load('../../resources/js/pages/education/index.tsx', {
react: {
useState(initial) {
const index = cursor++;
if (!(index in states))
states[index] =
typeof initial === 'function' ? initial() : initial;
return [
states[index],
(value) => {
states[index] =
typeof value === 'function'
? value(states[index])
: value;
},
];
},
useEffect(fn) {
if (!renderPage) fn();
},
useCallback(fn) {
return fn;
},
},
'@inertiajs/react': {
Link: 'a',
router: {},
useForm(initial) {
if (renderPage)
return {
data: initial,
errors: {},
processing: false,
isDirty: false,
};
form ??= {
data: { ...initial },
defaults: { ...initial },
errors: {},
processing: false,
get isDirty() {
return (
JSON.stringify(this.data) !==
JSON.stringify(this.defaults)
);
},
setData(key, value) {
this.data = { ...this.data, [key]: value };
},
setDefaults(value) {
this.defaults = { ...value };
},
clearErrors() {
this.errors = {};
},
setError(errors) {
this.errors = errors;
},
post() {
throw new Error('Draft must not use legacy create');
},
};
return form;
},
},
'@/lib/portal-api': {
portalRequest: request,
PortalApiError: ApiError,
newSubmissionKey: () => 'synthetic-stable-key',
},
'@/components/education-submitted-snapshot': {
__esModule: true,
default: Snapshot,
},
'../management/shared': {
Management: 'main',
Field: 'label',
control: '',
button: '',
Pagination: () => null,
},
'@/components/investment-territory': {
TerritoryFields: 'territory-fields',
},
});
return {
page() {
cursor = 0;
return module.default(props);
},
render() {
cursor = 0;
return module.Intake({
kind: 'demands',
props,
onSaved: (item) => saved.push(item),
onDirty: (kind, value) => dirty.push([kind, value]),
});
},
get form() {
return form;
},
saved,
dirty,
Snapshot,
};
}
const saveButton = (tree) =>
nodes(tree).find(
(node) => node.type === 'button' && node.props.type === 'button',
);
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('the full education page renders the private draft list and both intake forms', () => {
const component = setup(
async () => {},
{
...emptyProps,
filters: {},
providers: [],
demands: { data: [] },
capacities: { data: [] },
indicators: {
demand_records: 0,
capacity_records: 0,
expired_demands: 0,
pending_demands: 0,
},
ownDrafts: {
data: [
{
id: 'qa-draft',
kind: 'demands',
state: 'draft',
version_no: 1,
label: 'Synthetic qualification',
updated_at: '2026-11-02T12:00:00Z',
},
],
},
},
true,
);
const html = renderToStaticMarkup(component.page());
assert.ok(html.includes('Os meus rascunhos e submissões'));
assert.ok(html.includes('/management/education?draft=qa-draft'));
assert.ok(html.includes('Synthetic qualification'));
assert.ok(html.includes('Declarar procura de trabalhadores'));
assert.ok(html.includes('Declarar vagas de formação'));
});
await test('incomplete save bypasses native required fields, keeps edits, and submits the saved identity with current values', async () => {
const requests = [];
const component = setup(async (url, options) => {
const data = JSON.parse(options.body);
requests.push({ url, method: options.method, data });
return {
id: 'qa-draft',
kind: 'demands',
version_no: data.version_no + 1,
state: url.endsWith('/submit') ? 'submitted' : 'draft',
payload: data.payload,
references: {},
record_id: null,
updated_at: '2026-11-02T12:00:00Z',
};
});
let tree = component.render();
component.form.setData('employer', 'Synthetic incomplete employer');
tree = component.render();
assert.equal(saveButton(tree).props.type, 'button');
saveButton(tree).props.onClick();
await flush();
assert.equal(requests[0].method, 'POST');
assert.equal(requests[0].data.payload.qualification, '');
assert.equal(component.form.data.employer, 'Synthetic incomplete employer');
assert.equal(component.form.isDirty, false);
tree = component.render();
component.form.setData('quantity', '12');
tree = component.render();
saveButton(tree).props.onClick();
await flush();
assert.equal(requests[1].method, 'PUT');
assert.equal(requests[1].data.version_no, 1);
assert.equal(requests[1].data.client_key, requests[0].data.client_key);
tree = component.render();
nodes(tree)
.find((node) => node.type === 'form')
.props.onSubmit({ preventDefault() {} });
await flush();
assert.equal(
requests[2].url,
'/management/education/drafts/demands/qa-draft/submit',
);
assert.equal(requests[2].data.version_no, 2);
assert.equal(requests[2].data.payload.quantity, '12');
tree = component.render();
assert.equal(tree.type, component.Snapshot);
assert.equal(tree.props.draft.state, 'submitted');
assert.equal(component.saved.length, 3);
});
await test('recovery preserves blank dates and reference IDs, and a conflict does not overwrite current edits', async () => {
const component = setup(
async () => {
throw new ApiError(409);
},
{
...emptyProps,
selectedDraft: {
id: 'recovered',
kind: 'demands',
version_no: 4,
state: 'draft',
payload: {
employer: 'Old',
reference_date: null,
geo_location_id: 'retired-location',
},
references: null,
},
},
);
let tree = component.render();
assert.equal(component.form.data.reference_date, '');
assert.equal(component.form.data.geo_location_id, 'retired-location');
component.form.setData('employer', 'Deliberate current edit');
tree = component.render();
saveButton(tree).props.onClick();
await flush();
tree = component.render();
assert.equal(component.form.data.employer, 'Deliberate current edit');
assert.equal(component.form.isDirty, true);
assert.ok(
nodes(tree).some(
(node) =>
node.props?.role === 'alert' &&
String(node.props.children).includes('noutra sessão'),
),
);
assert.equal(component.saved.length, 0);
});
await test('recovered territorial path remains stable while unrelated fields are edited', () => {
const territories = [
{
id: 'p',
name: 'Province',
parent_id: null,
location_type: 'province',
},
{
id: 'd',
name: 'District',
parent_id: 'p',
location_type: 'district',
},
];
const component = setup(async () => {}, {
...emptyProps,
territories,
selectedDraft: {
id: 'qa',
kind: 'demands',
version_no: 1,
state: 'draft',
payload: { geo_location_id: 'd' },
},
});
let tree = component.render();
const initial = nodes(tree).find((node) => node.type === 'territory-fields')
.props.initial;
assert.deepEqual(
initial.map((item) => item.id),
['p', 'd'],
);
component.form.setData('employer', 'New text');
tree = component.render();
assert.equal(
nodes(tree).find((node) => node.type === 'territory-fields').props
.initial,
initial,
);
});
await test('submitted view uses preserved reference names and escapes source text without another submission form', () => {
const Snapshot = load(
'../../resources/js/components/education-submitted-snapshot.tsx',
{ '@inertiajs/react': { Link: 'a' } },
).default;
const html = renderToStaticMarkup(
Snapshot({
draft: {
kind: 'demands',
record_id: 'qa-record',
payload: { quantity: 20, source: '<script>synthetic</script>' },
references: {
project_id: { name: 'Original project name' },
territory_path: [{ name: 'Original district' }],
},
},
}),
);
assert.ok(html.includes('Original project name'));
assert.ok(html.includes('Original district'));
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(!html.includes('<form'));
assert.ok(
html.includes('/management/education/demands/qa-record/analysis'),
);
});
+255
View File
@@ -0,0 +1,255 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/education-review.mjs';
const form = 'education-review';
test('the private detail renders preserved reasons, unavailable entries and contextual history pagination', () => {
const h = harness(
props({
history: {
data: [
{
id: 'one',
version: 3,
actor: 'SYNTHETIC reviewer',
occurred_at: '2026-11-03',
available: true,
status: 'rejected',
reason: 'SYNTHETIC preserved reason',
previous_reason: 'SYNTHETIC older reason',
},
{
id: 'two',
version: 2,
actor: null,
occurred_at: '2026-11-02',
available: false,
status: null,
reason: null,
previous_reason: null,
},
],
total: 12,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/management/education/demands/one?scope=mine&history_page=2',
},
}),
);
assert.match(text(h.tree), /Registos de revisão disponíveis/);
assert.match(text(h.tree), /SYNTHETIC preserved reason/);
assert.match(
text(h.tree),
/Fundamento anterior capturado: SYNTHETIC older reason/,
);
assert.match(text(h.tree), /Fundamento indisponível para leitura/);
assert.ok(h.tree);
});
test('the submitter sees the declaration without being asked to review it', () => {
const initial = props();
initial.declaration.can_review = false;
initial.declaration.review_unavailable = 'self';
const h = harness(initial);
assert.equal(h.button('Guardar decisão'), undefined);
assert.match(text(h.tree), /outro gestor/);
});
test('a newer declaration cannot silently replace the version on which the review was prepared', () => {
const h = harness();
h.change(
form,
'Justificação e evidência da revisão',
'SYNTHETIC prepared reason with evidence.',
);
h.render({
...h.props,
declaration: { ...h.props.declaration, version_no: 2, quantity: 30 },
});
h.submit(form);
assert.equal(h.sent.length, 0);
});
const reason = 'Justificação e evidência da revisão';
function prepared(h) {
h.change(form, reason, 'SYNTHETIC independent review with evidence.');
return h.submit(form);
}
function accepted(h, request = h.sent.at(-1), patch = {}) {
return {
...h.props,
declaration: {
...h.props.declaration,
version_no: request.data.version_no + 1,
status: request.data.status,
review_reason: request.data.review_reason,
review_context: {
actor_id: h.props.actorId,
commands: [
{
key: request.data.client_key,
version: request.data.version_no + 1,
},
],
},
},
...patch,
};
}
test('explicit comparison adopts the current version without discarding the prepared decision', () => {
const h = harness();
h.change(form, reason, 'SYNTHETIC prepared reason with evidence.');
h.render({
...h.props,
declaration: { ...h.props.declaration, version_no: 2, quantity: 30 },
});
assert.match(text(h.tree), /Analisada: 5.*Actual: 30/);
h.click('Confirmar a leitura desta versão');
const request = h.submit(form);
assert.equal(request.data.version_no, 2);
assert.equal(
request.data.review_reason,
'SYNTHETIC prepared reason with evidence.',
);
});
test('confirmation clears only sent event values and preserves later edits', () => {
const h = harness(),
request = prepared(h);
h.change(form, reason, 'SYNTHETIC later reason with evidence.');
h.change(form, 'Decisão interna', 'rejected');
h.success(accepted(h, request), request);
assert.equal(
h.field(form, reason).props.value,
'SYNTHETIC later reason with evidence.',
);
assert.equal(h.field(form, 'Decisão interna').props.value, 'rejected');
const next = h.submit(form);
assert.equal(next.data.version_no, 2);
assert.notEqual(next.data.client_key, request.data.client_key);
});
test('an uncertain result retries exactly the original version, decision and key', () => {
const h = harness(),
request = prepared(h);
h.fail(request);
h.change(form, reason, 'SYNTHETIC later reason with evidence.');
const retry = h.submit(form);
assert.deepEqual(retry.data, request.data);
h.success(accepted(h, retry), retry);
assert.equal(
h.field(form, reason).props.value,
'SYNTHETIC later reason with evidence.',
);
});
test('a fresh authorised read confirms the receipt without sending another decision', () => {
const h = harness(),
request = prepared(h);
h.fail(request, 500);
h.click('Actualizar dados da declaração');
assert.deepEqual(h.reloads[0].only, [
'declaration',
'references',
'today',
'actorId',
'kind',
'history',
]);
h.refreshed(accepted(h, request));
assert.equal(h.sent.length, 1);
assert.equal(h.field(form, reason).props.value, '');
assert.equal(h.leave(), false);
assert.match(text(h.tree), /Revisão registada/);
});
test('another actor cannot acknowledge or erase a local pending review', () => {
const h = harness(),
request = prepared(h);
request.options.onSuccess({ props: accepted(h, request, { actorId: 3 }) });
request.form.processing = false;
h.render();
assert.equal(
h.field(form, reason).props.value,
'SYNTHETIC independent review with evidence.',
);
assert.deepEqual(h.submit(form).data, request.data);
});
test('an obsolete callback cannot alter the draft of the next account', () => {
const h = harness(),
request = prepared(h);
h.render({
...h.props,
actorId: 3,
declaration: {
...h.props.declaration,
review_context: { actor_id: 3, commands: [] },
},
});
h.change(form, reason, 'SYNTHETIC next account review.');
request.options.onSuccess({ props: accepted(h, request, { actorId: 1 }) });
request.form.processing = false;
h.render();
assert.equal(
h.field(form, reason).props.value,
'SYNTHETIC next account review.',
);
});
test('a later decision remains current when an earlier receipt is acknowledged', () => {
const h = harness(),
request = prepared(h);
h.fail(request);
const next = accepted(h, request);
next.declaration.version_no = 3;
next.declaration.status = 'rejected';
h.render(next);
assert.match(text(h.tree), /A declaração mudou/);
assert.equal(h.sent.length, 1);
h.submit(form);
assert.equal(h.sent.length, 1);
h.click('Confirmar a leitura desta versão');
const fresh = h.submit(form);
assert.equal(fresh.data.version_no, 3);
assert.notEqual(fresh.data.client_key, request.data.client_key);
});
test('a competing newer version without the receipt requires explicit adoption before a new decision', () => {
const h = harness(),
request = prepared(h);
h.fail(request, 409);
h.click('Actualizar declaração');
h.refreshed({
...h.props,
declaration: { ...h.props.declaration, version_no: 2, quantity: 20 },
});
h.click('Confirmar a leitura desta versão');
const next = h.submit(form);
assert.equal(next.data.version_no, 2);
assert.notEqual(next.data.client_key, request.data.client_key);
});
test('expired declarations retain prepared text without a new decision form', () => {
const h = harness(),
request = prepared(h);
h.fail(request, 422);
h.render({
...h.props,
declaration: {
...h.props.declaration,
can_review: false,
review_unavailable: 'expired',
},
});
assert.equal(h.button('Guardar decisão'), undefined);
assert.equal(h.button('Recuperar a mesma revisão'), undefined);
assert.match(text(h.tree), /Fundamento preparado nesta página/);
assert.match(text(h.tree), /SYNTHETIC independent review/);
});
test('validation preserves the draft and a decision-only change has one leave guard', () => {
const h = harness();
h.change(form, 'Decisão interna', 'rejected');
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
const request = prepared(h);
h.validation({ review_reason: 'SYNTHETIC validation' }, request);
assert.equal(
h.field(form, reason).props.value,
'SYNTHETIC independent review with evidence.',
);
const next = h.submit(form);
assert.notEqual(next.data.client_key, request.data.client_key);
});
@@ -0,0 +1,164 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url),
Empty = () => null;
const mocks = {
react: React,
'@inertiajs/react': {
Link: ({ href, children }) =>
React.createElement('a', { href }, children),
router: {},
useForm: (data) => ({
data,
errors: {},
processing: false,
isDirty: false,
}),
},
'@/lib/portal-api': {
newSubmissionKey: () => '00000000-0000-4000-8000-000000000001',
},
'@/components/education-submitted-snapshot': { default: Empty },
'@/components/investment-territory': { TerritoryFields: Empty },
'../management/shared': {
Management: ({ children }) =>
React.createElement('main', null, children),
Field: ({ label, children }) =>
React.createElement('label', null, label, children),
Pagination: Empty,
control: '',
button: '',
},
};
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/pages/education/index.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) => mocks[name] ?? require(name),
module,
module.exports,
);
const Index = module.exports.default;
const counts = {
total: 3,
submitted: 1,
reviewed: 1,
rejected: 0,
expired: 1,
to_review: 2,
};
const group = (data) => ({
data,
total: data.length,
current_page: 1,
last_page: 1,
links: [],
});
const base = {
today: '2026-11-03',
territories: [],
projects: [],
providers: [],
courses: [],
occupations: [],
skills: [],
draftsAvailable: false,
ownDrafts: null,
filters: { scope: 'all' },
workQueue: {
actor_id: 1,
drafts: 1,
demands: counts,
capacities: { ...counts, total: 1, submitted: 0, to_review: 4 },
},
indicators: {
demand_records: 42,
capacity_records: 17,
pending_demands: 9,
expired_demands: 4,
},
demands: group([
{
id: 'one',
qualification: 'SYNTHETIC qualification',
quantity: 1000,
status: 'submitted',
version_no: 1,
valid_until: '2027-12-31',
period_start: '2027-01-01',
period_end: '2027-06-30',
source: 'SYNTHETIC source',
can_review: false,
review_unavailable: 'self',
details_url: '/management/education/demands/one?scope=mine',
},
]),
capacities: group([]),
};
const render = (patch) =>
renderToStaticMarkup(React.createElement(Index, { ...base, ...patch }));
test('personal record counts coexist with the unchanged global indicators and retain separate categories', () => {
const html = render();
assert.match(html, /O meu acompanhamento/);
assert.match(html, /Declarações de procura:.*?<strong>42/s);
assert.match(html, /Submetidas por mim: 3/);
assert.match(html, /Submetidas por mim: 1/);
assert.doesNotMatch(html, /Submetidas por mim: 1000/);
assert.match(html, /Disponíveis para a minha revisão independente: 2/);
assert.match(html, /Disponíveis para a minha revisão independente: 4/);
});
test('a declaration links to its detailed context and the list no longer asks for repeated review forms', () => {
const html = render();
assert.ok(
html.includes('href="/management/education/demands/one?scope=mine"'),
);
assert.match(html, /Consultar declaração/);
assert.match(html, /a revisão cabe a outro gestor/);
assert.doesNotMatch(
html,
/Guardar decisão|Justificação e evidência da revisão/,
);
});
test('the independent review scope hides an inapplicable status question and preserves the normal filters', () => {
const html = render({
filters: { scope: 'review', q: 'SYNTHETIC', status: '' },
});
assert.match(html, /value="review" selected/);
assert.doesNotMatch(html, /<label>Estado/);
assert.match(html, /Qualificação/);
assert.match(html, /SYNTHETIC/);
assert.match(render({ filters: { scope: 'mine' } }), /<label>Estado/);
});
test('an unavailable draft count is not presented as zero and declaration text is escaped', () => {
const html = render({
workQueue: { ...base.workQueue, drafts: null },
demands: group([
{
...base.demands.data[0],
qualification: '<img src=x onerror=alert(1)>',
},
]),
});
assert.doesNotMatch(html, /Rascunhos privados por concluir: 0|<img/);
assert.ok(html.includes('&lt;img'));
});
@@ -0,0 +1,175 @@
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 setup(request) {
const state = [];
let cursor = 0;
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/funding-criteria-assessment.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
const module = { exports: {} };
const mocks = {
react: {
useState(initial) {
const index = cursor++;
if (!(index in state)) state[index] = initial;
return [
state[index],
(value) => {
state[index] = value;
},
];
},
},
'@/lib/portal-api': { portalRequest: request },
'@/pages/investment/shared': { card: '', button: '' },
};
compileFunction(output, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return {
render(record) {
cursor = 0;
return module.exports.default({ record });
},
};
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const criterion = (code, applies_to) => ({
code,
applies_to,
question: `Question ${code}`,
explanation: 'Synthetic condition',
source_reference: 'Synthetic source',
expected: 'yes',
});
const record = {
id: 'qa-fund',
version_id: 'qa-version',
payload: {
criteria: [
criterion('general', 'all'),
criterion('personal', 'individual'),
criterion('company', 'entity'),
],
windows: [
{
code: 'qa-window',
title: 'Synthetic window',
criteria: [criterion('window-rule', 'all')],
},
],
},
};
const field = (tree, name) =>
nodes(tree).find((node) => node.props?.name === name);
await test('only applicable answers are submitted while hidden answers survive candidate and window changes', async () => {
let sent;
const component = setup(async (url, options) => {
sent = { url, body: JSON.parse(options.body) };
return { notice: 'Synthetic assessment', criteria: [] };
});
let tree = component.render(record);
assert.ok(field(tree, 'criterion-general'));
assert.equal(field(tree, 'criterion-personal'), undefined);
assert.equal(field(tree, 'criterion-company'), undefined);
assert.ok(
renderToStaticMarkup(tree).includes('Escolha o tipo de candidato'),
);
field(tree, 'applicant-kind').props.onChange({
target: { value: 'individual' },
});
tree = component.render(record);
field(tree, 'criterion-personal').props.onChange({
target: { value: 'yes' },
});
field(tree, 'funding-window').props.onChange({
target: { value: 'qa-window' },
});
tree = component.render(record);
field(tree, 'criterion-window-rule').props.onChange({
target: { value: 'no' },
});
field(tree, 'funding-window').props.onChange({ target: { value: '' } });
tree = component.render(record);
field(tree, 'applicant-kind').props.onChange({
target: { value: 'entity' },
});
tree = component.render(record);
assert.equal(field(tree, 'criterion-personal'), undefined);
assert.equal(field(tree, 'criterion-window-rule'), undefined);
field(tree, 'criterion-company').props.onChange({
target: { value: 'no' },
});
tree = component.render(record);
nodes(tree)
.find((node) => node.type === 'button')
.props.onClick();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(sent.url, '/fundos/qa-fund/criterios');
assert.equal(sent.body.version_id, 'qa-version');
assert.equal(sent.body.applicant_kind, 'entity');
assert.deepEqual(sent.body.answers, { general: 'unknown', company: 'no' });
tree = component.render(record);
field(tree, 'applicant-kind').props.onChange({
target: { value: 'individual' },
});
tree = component.render(record);
assert.equal(field(tree, 'criterion-personal').props.value, 'yes');
field(tree, 'funding-window').props.onChange({
target: { value: 'qa-window' },
});
tree = component.render(record);
assert.equal(field(tree, 'criterion-window-rule').props.value, 'no');
assert.ok(!renderToStaticMarkup(tree).includes('Synthetic assessment'));
});
await test('failed assessment is cleared on a new selection and a programme without windows does not ask for one', async () => {
const component = setup(async () => {
throw new Error('Synthetic stale-version error');
});
const item = { ...record, payload: { ...record.payload, windows: [] } };
let tree = component.render(item);
assert.equal(field(tree, 'funding-window'), undefined);
nodes(tree)
.find((node) => node.type === 'button')
.props.onClick();
await new Promise((resolve) => setImmediate(resolve));
tree = component.render(item);
assert.ok(
renderToStaticMarkup(tree).includes('Synthetic stale-version error'),
);
field(tree, 'applicant-kind').props.onChange({
target: { value: 'individual' },
});
tree = component.render(item);
assert.ok(
!renderToStaticMarkup(tree).includes('Synthetic stale-version error'),
);
});
@@ -0,0 +1,437 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const leadId = '10000000-0000-4000-8000-000000000001';
export function props(patch = {}) {
return {
lead: {
id: leadId,
version_no: 1,
title: 'SYNTHETIC lead',
status: 'new',
owner_user_id: 1,
tasks: [],
},
contacts: [],
owners: [
{ id: 1, name: 'SYNTHETIC manager' },
{ id: 2, name: 'SYNTHETIC colleague' },
],
nextAction: { future_tasks: 0 },
taskCreation: { lead_id: leadId, actor_id: 1, commands: [] },
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
const clone = (value) =>
Array.isArray(value)
? value.map(clone)
: value && Object.getPrototypeOf(value) === Object.prototype
? Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, clone(v)]),
)
: value;
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
const mocks = {
react: hooks,
'@inertiajs/react': {
usePage: () => ({
props: { auth: { user: { id: current.actorId ?? 1 } } },
}),
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
post(url, data) {
sent.push({ method: 'post', url, data, options: {} });
},
},
useForm(initialData) {
const i = cursor++;
if (active.cells[i]) return active.cells[i];
const form = {
data: clone(initialData),
defaults: clone(initialData),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
changed = true;
},
setDefaults(data) {
this.defaults = clone(data);
},
clearErrors() {
this.errors = {};
changed = true;
},
reset(...keys) {
for (const key of keys)
this.data[key] = this.defaults[key];
changed = true;
},
transform(callback) {
this.transformer = callback;
},
};
for (const method of ['post', 'put', 'patch'])
form[method] = (url, options) => {
form.processing = true;
changed = true;
sent.push({
method,
url,
options,
data: clone(
form.transformer
? form.transformer(form.data)
: form.data,
),
form,
});
};
active.cells[i] = form;
return form;
},
},
'../management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'@/pages/management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'@/components/crm-edit-comparison': { default: () => null },
'@/lib/crm-record-edit': {
useCrmRecordEdit: ({ values }) => ({
form: { processing: false },
values,
error: () => undefined,
blocked: false,
}),
},
'./types': {
leadStates: { new: 'Novo', qualified: 'Qualificado' },
taskStates: { open: 'Aberta', done: 'Conclu?da' },
},
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['./operation-key'] = operation;
mocks['@/lib/operation-key'] = operation;
function load(path) {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../../' + path, import.meta.url),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['./profile-json'] = load('resources/js/lib/profile-json.ts');
mocks['./crm-task-preparation'] = load(
'resources/js/lib/crm-task-preparation.ts',
);
for (const [name, path] of [
['@/lib/crm-task-creation', 'resources/js/lib/crm-task-creation.ts'],
[
'@/components/crm-task-creation',
'resources/js/components/crm-task-creation.tsx',
],
])
if (fs.existsSync(new URL('../../../' + path, import.meta.url)))
mocks[name] = load(path);
const Page = load('resources/js/pages/crm/lead.tsx').default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
all: () => nodes(tree),
form(name) {
return nodes(tree).find((node) => node.props?.id === name);
},
button(label, scope = tree) {
return nodes(scope).find(
(node) => node.type === 'button' && text(node) === label,
);
},
field(name, label) {
const root = this.form(name);
const field = nodes(root).find(
(node) => node.type === 'label' && node.props.label === label,
);
return nodes(field).find((node) =>
['input', 'select', 'textarea'].includes(node.type),
);
},
change(name, label, value, rerender = true) {
const field = this.field(name, label);
if (!field) throw Error('Missing field ' + name + '/' + label);
field.props.onChange({
target: { value, checked: value, files: value ? [value] : [] },
});
if (rerender) render();
},
submit(name) {
const form = this.form(name);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, scope = tree) {
const button = this.button(label, scope);
if (!button) throw Error('Missing button ' + label);
button.props.onClick();
render();
return sent.at(-1);
},
success(next, request = sent.at(-1)) {
render(next);
request.options.onSuccess?.({ props: next });
request.form.processing = false;
render(next);
},
validation(errors, request = sent.at(-1)) {
request.form.errors = errors;
request.options.onError?.(errors);
request.form.processing = false;
render();
},
fail(request = sent.at(-1), status = null) {
if (status === null) request.options.onNetworkError();
else request.options.onHttpException({ status });
request.form.processing = false;
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = previousWindow;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
@@ -0,0 +1,505 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const leadId = '10000000-0000-4000-8000-000000000001';
export function props(patch = {}) {
return {
lead: {
id: leadId,
version_no: 1,
title: 'SYNTHETIC lead',
status: 'new',
owner_user_id: 1,
tasks: [],
},
contacts: [],
owners: [
{ id: 1, name: 'SYNTHETIC manager' },
{ id: 2, name: 'SYNTHETIC colleague' },
],
nextAction: { future_tasks: 0 },
taskCreation: {
lead_id: leadId,
actor_id: 1,
commands: [],
preparation: {
installed: true,
version: 0,
snapshot: null,
operation_key: null,
updated_at: null,
unavailable: false,
},
},
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
const clone = (value) =>
Array.isArray(value)
? value.map(clone)
: value && Object.getPrototypeOf(value) === Object.prototype
? Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, clone(v)]),
)
: value;
export function harness(initial = props()) {
const draftRequests = [],
timers = new Map();
let timerSequence = 0;
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
const mocks = {
react: hooks,
'@inertiajs/react': {
usePage: () => ({
props: { auth: { user: { id: current.actorId ?? 1 } } },
}),
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
post(url, data) {
sent.push({ method: 'post', url, data, options: {} });
},
},
useForm(initialData) {
const i = cursor++;
if (active.cells[i]) return active.cells[i];
const form = {
data: clone(initialData),
defaults: clone(initialData),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
changed = true;
},
setDefaults(data) {
this.defaults = clone(data);
},
clearErrors() {
this.errors = {};
changed = true;
},
reset(...keys) {
for (const key of keys)
this.data[key] = this.defaults[key];
changed = true;
},
transform(callback) {
this.transformer = callback;
},
};
for (const method of ['post', 'put', 'patch'])
form[method] = (url, options) => {
form.processing = true;
changed = true;
sent.push({
method,
url,
options,
data: clone(
form.transformer
? form.transformer(form.data)
: form.data,
),
form,
});
};
active.cells[i] = form;
return form;
},
},
'../management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'@/pages/management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'@/components/crm-edit-comparison': { default: () => null },
'@/lib/crm-record-edit': {
useCrmRecordEdit: ({ values }) => ({
form: { processing: false },
values,
error: () => undefined,
blocked: false,
}),
},
'./types': {
leadStates: { new: 'Novo', qualified: 'Qualificado' },
taskStates: { open: 'Aberta', done: 'Conclu?da' },
},
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['./operation-key'] = operation;
mocks['@/lib/operation-key'] = operation;
function load(path) {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../../' + path, import.meta.url),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, [
'require',
'module',
'exports',
'setTimeout',
'clearTimeout',
])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
(callback) => {
const id = ++timerSequence;
timers.set(id, callback);
return id;
},
(id) => timers.delete(id),
);
return module.exports;
}
mocks['./profile-json'] = {
...load('resources/js/lib/profile-json.ts'),
profileJson: (url, data, method = 'POST') =>
new Promise((resolve, reject) =>
draftRequests.push({ url, data, method, resolve, reject }),
),
};
mocks['./crm-task-preparation'] = load(
'resources/js/lib/crm-task-preparation.ts',
);
for (const [name, path] of [
['@/lib/crm-task-creation', 'resources/js/lib/crm-task-creation.ts'],
[
'@/components/crm-task-creation',
'resources/js/components/crm-task-creation.tsx',
],
])
if (fs.existsSync(new URL('../../../' + path, import.meta.url)))
mocks[name] = load(path);
const Page = load('resources/js/pages/crm/lead.tsx').default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
draftRequests,
async validationDraft(fields, request = draftRequests.at(-1)) {
request.reject(
new mocks['./profile-json'].ProfileValidationError(
'SYNTHETIC validation',
fields,
),
);
await new Promise((resolve) => setImmediate(resolve));
render();
},
async flush() {
await new Promise((resolve) => setImmediate(resolve));
render();
},
async tick() {
const queue = [...timers.values()];
timers.clear();
queue.forEach((fn) => fn());
await Promise.resolve();
render();
},
async respond(value, request = draftRequests.at(-1)) {
request.resolve(value);
await new Promise((resolve) => setImmediate(resolve));
render();
},
async rejectDraft(request = draftRequests.at(-1)) {
request.reject(new Error('SYNTHETIC network failure'));
await new Promise((resolve) => setImmediate(resolve));
render();
},
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
all: () => nodes(tree),
form(name) {
return nodes(tree).find((node) => node.props?.id === name);
},
button(label, scope = tree) {
return nodes(scope).find(
(node) => node.type === 'button' && text(node) === label,
);
},
field(name, label) {
const root = this.form(name);
const field = nodes(root).find(
(node) =>
node.type === 'label' &&
(node.props.label === label ||
text(node).startsWith(label)),
);
return nodes(field).find((node) =>
['input', 'select', 'textarea'].includes(node.type),
);
},
change(name, label, value, rerender = true) {
const field = this.field(name, label);
if (!field) throw Error('Missing field ' + name + '/' + label);
field.props.onChange({
target: { value, checked: value, files: value ? [value] : [] },
});
if (rerender) render();
},
submit(name) {
const form = this.form(name);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, scope = tree) {
const button = this.button(label, scope);
if (!button) throw Error('Missing button ' + label);
button.props.onClick();
render();
return sent.at(-1);
},
success(next, request = sent.at(-1)) {
render(next);
request.options.onSuccess?.({ props: next });
request.form.processing = false;
render(next);
},
validation(errors, request = sent.at(-1)) {
request.form.errors = errors;
request.options.onError?.(errors);
request.form.processing = false;
render();
},
fail(request = sent.at(-1), status = null) {
if (status === null) request.options.onNetworkError();
else request.options.onHttpException({ status });
request.form.processing = false;
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = previousWindow;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
+475
View File
@@ -0,0 +1,475 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
import React from 'react';
const require = createRequire(import.meta.url);
export const recordId = '10000000-0000-4000-8000-000000000001';
export function props(patch = {}) {
return {
declaration: {
id: recordId,
qualification: 'SYNTHETIC qualification',
quantity: 5,
status: 'submitted',
version_no: 1,
valid_until: '2027-12-31',
period_start: '2027-01-01',
period_end: '2027-06-30',
reference_date: '2026-10-01',
source: 'SYNTHETIC source',
submitted_by: 2,
reviewed_by: null,
review_reason: null,
can_review: true,
review_unavailable: null,
review_context: { actor_id: 1, commands: [] },
},
kind: 'demands',
actorId: 1,
today: '2026-11-03',
backUrl: '/management/education',
references: {},
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
const clone = (value) =>
Array.isArray(value)
? value.map(clone)
: value && Object.getPrototypeOf(value) === Object.prototype
? Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, clone(v)]),
)
: value;
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
const mocks = {
react: hooks,
'@inertiajs/react': {
usePage: () => ({
props: { auth: { user: { id: current.actorId ?? 1 } } },
}),
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
post(url, data) {
sent.push({ method: 'post', url, data, options: {} });
},
},
useForm(initialData) {
const i = cursor++;
if (active.cells[i]) return active.cells[i];
const form = {
data: clone(initialData),
defaults: clone(initialData),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
changed = true;
},
setDefaults(data) {
this.defaults = clone(data);
},
clearErrors() {
this.errors = {};
changed = true;
},
reset(...keys) {
for (const key of keys)
this.data[key] = this.defaults[key];
changed = true;
},
transform(callback) {
this.transformer = callback;
},
};
for (const method of ['post', 'put', 'patch'])
form[method] = (url, options) => {
form.processing = true;
changed = true;
sent.push({
method,
url,
options,
data: clone(
form.transformer
? form.transformer(form.data)
: form.data,
),
form,
});
};
active.cells[i] = form;
return form;
},
},
'../management/shared': {
Management: 'main',
Pagination: ({ page }) =>
React.createElement(
'a',
{ href: page.next_page_url },
'Mais registos',
),
Field: 'label',
button: '',
control: '',
},
'@/pages/management/shared': {
Management: 'main',
Field: 'label',
button: '',
control: '',
},
'@/components/crm-edit-comparison': { default: () => null },
'@/lib/crm-record-edit': {
useCrmRecordEdit: ({ values }) => ({
form: { processing: false },
values,
error: () => undefined,
blocked: false,
}),
},
'./types': {
leadStates: { new: 'Novo', qualified: 'Qualificado' },
taskStates: { open: 'Aberta', done: 'Conclu?da' },
},
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['./operation-key'] = operation;
mocks['@/lib/operation-key'] = operation;
function load(path, extra = '') {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../../' + path, import.meta.url),
'utf8',
) + extra,
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/lib/portal-api'] = {};
mocks['@/components/education-submitted-snapshot'] = {
default: () => null,
};
mocks['@/components/investment-territory'] = {
TerritoryFields: () => null,
};
for (const [name, path] of [
['@/lib/education-review', 'resources/js/lib/education-review.ts'],
[
'@/components/education-review',
'resources/js/components/education-review.tsx',
],
])
if (fs.existsSync(new URL('../../../' + path, import.meta.url)))
mocks[name] = load(path);
let Page;
if (
fs.existsSync(
new URL(
'../../../resources/js/pages/education/declaration.tsx',
import.meta.url,
),
)
)
Page = load('resources/js/pages/education/declaration.tsx').default;
else {
const Review = load(
'resources/js/pages/education/index.tsx',
'\nexport { Review };',
).Review;
Page = ({ declaration: row, kind, today, actorId }) =>
Review({ row, kind, today, actorId });
}
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
all: () => nodes(tree),
form(name) {
return (
nodes(tree).find((node) => node.props?.id === name) ??
nodes(tree).find((node) => node.type === 'form')
);
},
button(label, scope = tree) {
return nodes(scope).find(
(node) => node.type === 'button' && text(node) === label,
);
},
field(name, label) {
const root = this.form(name);
const field = nodes(root).find(
(node) => node.type === 'label' && node.props.label === label,
);
return nodes(field).find((node) =>
['input', 'select', 'textarea'].includes(node.type),
);
},
change(name, label, value, rerender = true) {
const field = this.field(name, label);
if (!field) throw Error('Missing field ' + name + '/' + label);
field.props.onChange({
target: { value, checked: value, files: value ? [value] : [] },
});
if (rerender) render();
},
submit(name) {
const form = this.form(name);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, scope = tree) {
const button = this.button(label, scope);
if (!button) throw Error('Missing button ' + label);
button.props.onClick();
render();
return sent.at(-1);
},
success(next, request = sent.at(-1)) {
render(next);
request.options.onSuccess?.({ props: next });
request.form.processing = false;
render(next);
},
validation(errors, request = sent.at(-1)) {
request.form.errors = errors;
request.options.onError?.(errors);
request.form.processing = false;
render();
},
fail(request = sent.at(-1), status = null) {
if (status === null) request.options.onNetworkError();
else request.options.onHttpException({ status });
request.form.processing = false;
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = previousWindow;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
@@ -0,0 +1,402 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const companyId = '10000000-0000-4000-8000-000000000001';
export function props(patch = {}) {
return {
actorId: 1,
account: {
version: 1,
payload: {
residence_country_code: 'PT',
phone: 'SYNTHETIC phone',
country: 'SYNTHETIC historical',
},
},
companies: [
{
id: companyId,
version: 1,
payload: {
name: 'SYNTHETIC company',
incorporation_country_code: 'MZ',
role: 'SYNTHETIC role',
},
},
],
countries: [
{ code: 'PT', name: 'Portugal', name_en: 'Portugal' },
{ code: 'FR', name: 'France', name_en: 'France' },
{ code: 'MZ', name: 'Mo\u00e7ambique', name_en: 'Mozambique' },
{ code: 'ZA', name: '\u00c1frica do Sul', name_en: 'South Africa' },
],
organizations: [],
organizationCountryAvailable: true,
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useId() {
const i = cursor++;
active.cells[i] ??= 'SYNTHETIC-id-' + ++sequence;
return active.cells[i];
},
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
class ApiError extends Error {
constructor(status, errors = {}) {
super('SYNTHETIC HTTP ' + status);
this.status = status;
this.errors = errors;
}
}
const mocks = {
react: hooks,
'@inertiajs/react': {
Link: 'a',
router: {
reload: (options) => reloads.push(options),
on(name, fn) {
if (name === 'before') before.add(fn);
return () => before.delete(fn);
},
},
},
'./shared': {
Frame: 'main',
Field: 'label',
input: '',
button: '',
card: '',
},
'@/pages/investment/shared': {
Field: 'label',
input: '',
button: '',
card: '',
},
'@/components/partnership-source-links': { default: () => null },
'@/pages/management/shared': { button: '', control: '' },
};
mocks['./portal-api'] = {
PortalApiError: ApiError,
portalRequest: (url, options = {}) =>
new Promise((resolve, reject) =>
sent.push({
url,
data: options.body ? JSON.parse(options.body) : undefined,
method: options.method ?? 'GET',
resolve,
reject,
}),
),
};
mocks['./operation-key'] = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['@/lib/portal-api'] = mocks['./portal-api'];
function load(path) {
const code = 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(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/lib/page-preparation-guard'] = load(
'resources/js/lib/page-preparation-guard.ts',
);
mocks['@/lib/investment-profile-editor'] = load(
'resources/js/lib/investment-profile-editor.ts',
);
mocks['./country-select'] = load(
'resources/js/components/country-select.tsx',
);
mocks['@/components/country-select'] = mocks['./country-select'];
mocks['@/lib/organization-country-reuse'] = load(
'resources/js/lib/organization-country-reuse.ts',
);
mocks['./organization-country-reuse'] = load(
'resources/js/components/organization-country-reuse.tsx',
);
mocks['@/components/investment-profile-editor'] = load(
'resources/js/components/investment-profile-editor.tsx',
);
mocks['@/components/organization-country-editor'] = load(
'resources/js/components/organization-country-editor.tsx',
);
const Page = load('resources/js/pages/investment/profile.tsx').default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window,
previousDocument = globalThis.document;
globalThis.window = windowMock;
globalThis.document = {
getElementById: () => ({ querySelector: () => ({ focus() {} }) }),
};
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
globalThis.document = previousDocument;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
get confirmCalls() {
return confirmCalls;
},
form(label) {
return nodes(tree).find(
(n) => n.type === 'form' && n.props['aria-label'] === label,
);
},
field(label, formLabel) {
return nodes(formLabel ? this.form(formLabel) : tree).find(
(n) =>
['input', 'textarea', 'select'].includes(n.type) &&
n.props['aria-label'] === label,
);
},
value(label, formLabel) {
return this.field(label, formLabel)?.props.value;
},
change(label, value, formLabel) {
const field = this.field(label, formLabel);
if (!field) throw Error('Missing field ' + label);
field.props.onChange({ target: { value } });
render();
},
button(label, formLabel) {
return nodes(formLabel ? this.form(formLabel) : tree).find(
(n) => n.type === 'button' && text(n) === label,
);
},
submit(formLabel) {
const form = this.form(formLabel);
if (!form) throw Error('Missing form ' + formLabel);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, formLabel) {
const node = this.button(label, formLabel);
if (!node) throw Error('Missing button ' + label);
const priorWindow = globalThis.window;
globalThis.window = windowMock;
try {
node.props.onClick();
} finally {
globalThis.window = priorWindow;
}
render();
return sent.at(-1);
},
async reply(value, request = sent.at(-1)) {
request.resolve(value);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
async fail(status = null, request = sent.at(-1), errors = {}) {
request.reject(
status === null
? new Error('SYNTHETIC network loss')
: new ApiError(status, errors),
);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const old = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = old;
}
return prevented;
},
};
}
@@ -0,0 +1,548 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const criteria = [
{
code: 'capacity',
label: 'Capacidade técnica/produtiva',
weight: 20,
mandatory: true,
state: 'unknown',
evidence: null,
explanation: 'SYNTHETIC unknown',
},
{
code: 'experience',
label: 'Experiência comprovada',
weight: 10,
mandatory: false,
state: 'unknown',
evidence: null,
explanation: 'SYNTHETIC unknown',
},
];
export const original = {
id: 10,
user_id: 2,
partnership_id: 1,
version: 1,
status: 'submitted',
organization_id: null,
proposal: 'SYNTHETIC original proposal',
payload: {
capacity: 'SYNTHETIC original capacity',
availability: 'SYNTHETIC original availability',
contribution: 'SYNTHETIC original contribution',
conflicts: 'SYNTHETIC original conflicts',
consent: true,
},
assessment: [],
decision_reason: null,
can_edit: true,
commands: [],
match: {
weights_hash: 'a'.repeat(64),
score_min: 0,
score_max: 100,
eligibility: 'unknown',
criteria,
},
room_id: null,
};
export function props(patch = {}) {
return {
actorId: 2,
record: {
id: 1,
version: 4,
title: 'SYNTHETIC partnership',
kind: 'seeking',
partnership_type: 'joint_venture',
sector_id: null,
deadline: null,
status: 'published',
offer: 'SYNTHETIC offer',
seeking: 'SYNTHETIC cooperation',
payload: {
summary: 'SYNTHETIC summary',
requirements: 'SYNTHETIC requirements',
consent: true,
},
},
owner: false,
moderator: false,
canEdit: false,
acceptingInterests: true,
canStartInterest: false,
interests: [structuredClone(original)],
organizations: [],
types: { joint_venture: 'Consórcio' },
sectors: [],
territories: [],
criteria: {},
sources: [],
origins: [],
locations: [],
historySummary: Object.hasOwn(patch, 'historySummary')
? patch.historySummary
: patch.owner || patch.moderator
? {
limit: 5,
entries: [],
has_more: false,
href: `/parcerias/${patch.record?.id ?? 1}/historico`,
}
: null,
publicationActions: [],
publicationCommands: [],
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
const clone = (value) =>
Array.isArray(value)
? value.map(clone)
: value && Object.getPrototypeOf(value) === Object.prototype
? Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, clone(v)]),
)
: value;
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const setters = new WeakMap();
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
if (!setters.has(frame)) setters.set(frame, new Map());
const stable = setters.get(frame);
if (!stable.has(i))
stable.set(i, (value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
});
return [frame.cells[i], stable.get(i)];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
const mocks = {
react: hooks,
'@inertiajs/react': {
usePage: () => ({
props: {
auth: {
user:
current.actorId === null
? null
: { id: current.actorId ?? 2 },
},
},
}),
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
post(url, data) {
sent.push({ method: 'post', url, data, options: {} });
},
},
useForm(initialData) {
const i = cursor++;
if (active.cells[i]) return active.cells[i];
const form = {
data: clone(initialData),
defaults: clone(initialData),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
changed = true;
},
setDefaults(data) {
this.defaults = clone(data);
},
clearErrors() {
this.errors = {};
changed = true;
},
transform(callback) {
this.transformer = callback;
},
};
for (const method of ['post', 'put'])
form[method] = (url, options) => {
form.processing = true;
changed = true;
sent.push({
method,
url,
options,
data: clone(
form.transformer
? form.transformer(form.data)
: form.data,
),
form,
});
};
active.cells[i] = form;
return form;
},
},
'@/pages/partnerships/shared': {
labels: {
negotiation: 'Em negociação',
agreement_recorded: 'Acordo registado',
agreed: 'Confirmado pelas partes',
execution: 'Em execução',
closed: 'Concluída',
cancelled: 'Cancelada',
pending: 'Pendente',
progress: 'Em curso',
completed: 'Concluído',
},
},
'./shared': {
Frame: 'main',
Field: 'label',
Errors: 'errors',
labels: {
pending: 'Submetida — legado',
progress: 'Em curso',
completed: 'Concluído',
},
},
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['./operation-key'] = operation;
mocks['@/lib/operation-key'] = operation;
function load(path) {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../../' + path, import.meta.url),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['./shared'].labels = {
draft: 'Rascunho',
pending: 'Submetida — legado',
submitted: 'Submetida',
returned: 'Devolvida',
rejected: 'Rejeitada',
published: 'Publicada',
suspended: 'Suspensa',
archived: 'Arquivada',
withdrawn: 'Retirada',
clarification: 'Em esclarecimento',
shortlisted: 'Lista curta',
negotiation: 'Em negociação',
agreement_recorded: 'Acordo registado',
agreed: 'Confirmado pelas partes',
execution: 'Em execução',
closed: 'Concluída',
cancelled: 'Cancelada',
progress: 'Em curso',
completed: 'Concluído',
met: 'Comprovadamente cumprido',
unmet: 'Comprovadamente incumprido',
unknown: 'Informação insuficiente',
};
mocks['@/pages/partnerships/shared'] = mocks['./shared'];
mocks['@/components/investment-complements'] = {
ComplementEntryActions: 'complements',
};
mocks['@/components/structure-geography'] = {
__esModule: true,
default: 'geography',
};
mocks['@/lib/partnership-candidacy-edit'] = load(
'resources/js/lib/partnership-candidacy-edit.ts',
);
mocks['@/components/partnership-candidacies'] = load(
'resources/js/components/partnership-candidacies.tsx',
);
mocks['@/lib/partnership-publication'] = load(
'resources/js/lib/partnership-publication.ts',
);
mocks['@/components/partnership-publication'] = load(
'resources/js/components/partnership-publication.tsx',
);
mocks['@/lib/partnership-history'] = load(
'resources/js/lib/partnership-history.ts',
);
mocks['@/components/partnership-publication-summary'] = load(
'resources/js/components/partnership-publication-summary.tsx',
);
const Page = load('resources/js/pages/partnerships/detail.tsx').default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
all: () => nodes(tree),
form(name) {
return nodes(tree).find(
(node) => node.props?.['data-candidacy-form'] === name,
);
},
button(label, scope = tree) {
return nodes(scope).find(
(node) => node.type === 'button' && text(node) === label,
);
},
field(name, label) {
const root = this.form(name);
const field = nodes(root).find(
(node) => node.type === 'label' && node.props.label === label,
);
return nodes(field).find((node) =>
['input', 'select', 'textarea'].includes(node.type),
);
},
change(name, label, value, rerender = true) {
const field = this.field(name, label);
if (!field) throw Error('Missing field ' + name + '/' + label);
field.props.onChange({
target: { value, checked: value, files: value ? [value] : [] },
});
if (rerender) render();
},
submit(name) {
const form = this.form(name);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, scope = tree) {
const button = this.button(label, scope);
if (!button) throw Error('Missing button ' + label);
button.props.onClick();
render();
return sent.at(-1);
},
success(next, request = sent.at(-1)) {
render(next);
request.options.onSuccess({ props: next });
request.form.processing = false;
render(next);
},
fail(request = sent.at(-1), status = null) {
if (status === null) request.options.onNetworkError();
else request.options.onHttpException({ status });
request.form.processing = false;
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = previousWindow;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
+459
View File
@@ -0,0 +1,459 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const participant = (id, name, parties = ['proponent']) => ({
id,
name,
parties,
});
export const original = {
id: 7,
title: 'SYNTHETIC milestone',
responsible_id: 1,
responsible_name: 'SYNTHETIC original author',
responsible_is_participant: true,
due_date: null,
status: 'pending',
evidence: null,
version: 3,
client_key: null,
};
export function props(patch = {}) {
return {
room: {
id: 10,
version: 2,
status: 'agreement_recorded',
agreement: {
title: 'SYNTHETIC instrument',
terms: 'SYNTHETIC terms',
confirmations: {},
legal_signature_status: 'not_verified',
},
},
agreementActorId: 1,
agreementCommands: [],
agreementParty: 'proponent',
partnership: {
id: 1,
title: 'SYNTHETIC partnership',
user_id: 1,
version: 4,
},
interest: { id: 2, user_id: 2, version: 3 },
canWrite: true,
participants: [
participant(1, 'SYNTHETIC original author'),
participant(2, 'SYNTHETIC original candidate', ['candidate']),
participant(4, 'SYNTHETIC authorised officer'),
],
milestones: [],
messages: [],
documents: [],
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
const clone = (value) =>
Array.isArray(value)
? value.map(clone)
: value && Object.getPrototypeOf(value) === Object.prototype
? Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, clone(v)]),
)
: value;
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
const mocks = {
react: hooks,
'@inertiajs/react': {
usePage: () => ({
props: { auth: { user: { id: current.actorId ?? 1 } } },
}),
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
post(url, data) {
sent.push({ method: 'post', url, data, options: {} });
},
},
useForm(initialData) {
const i = cursor++;
if (active.cells[i]) return active.cells[i];
const form = {
data: clone(initialData),
defaults: clone(initialData),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
changed = true;
},
setDefaults(data) {
this.defaults = clone(data);
},
clearErrors() {
this.errors = {};
changed = true;
},
transform(callback) {
this.transformer = callback;
},
};
for (const method of ['post', 'put'])
form[method] = (url, options) => {
form.processing = true;
changed = true;
sent.push({
method,
url,
options,
data: clone(
form.transformer
? form.transformer(form.data)
: form.data,
),
form,
});
};
active.cells[i] = form;
return form;
},
},
'@/pages/partnerships/shared': {
labels: {
negotiation: 'Em negociação',
agreement_recorded: 'Acordo registado',
agreed: 'Confirmado pelas partes',
execution: 'Em execução',
closed: 'Concluída',
cancelled: 'Cancelada',
pending: 'Pendente',
progress: 'Em curso',
completed: 'Concluído',
},
},
'./shared': {
Frame: 'main',
Field: 'label',
Errors: 'errors',
labels: {
pending: 'Submetida — legado',
progress: 'Em curso',
completed: 'Concluído',
},
},
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['./operation-key'] = operation;
mocks['@/lib/operation-key'] = operation;
function load(path) {
const code = ts.transpileModule(
fs.readFileSync(
new URL('../../../' + path, import.meta.url),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/lib/partnership-agreement'] = load(
'resources/js/lib/partnership-agreement.ts',
);
mocks['@/components/partnership-agreement-instrument'] = load(
'resources/js/components/partnership-agreement-instrument.tsx',
);
mocks['@/lib/partnership-room-edit'] = load(
'resources/js/lib/partnership-room-edit.ts',
);
mocks['@/lib/partnership-room-delivery'] = load(
'resources/js/lib/partnership-room-delivery.ts',
);
mocks['@/components/partnership-room-comparison'] = load(
'resources/js/components/partnership-room-comparison.tsx',
);
const Page = load('resources/js/pages/partnerships/room.tsx').default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
all: () => nodes(tree),
form(name) {
return nodes(tree).find(
(node) => node.props?.['data-room-form'] === name,
);
},
button(label, scope = tree) {
return nodes(scope).find(
(node) => node.type === 'button' && text(node) === label,
);
},
field(name, label) {
const root = this.form(name);
const field = nodes(root).find(
(node) => node.type === 'label' && node.props.label === label,
);
return nodes(field).find((node) =>
['input', 'select', 'textarea'].includes(node.type),
);
},
change(name, label, value, rerender = true) {
const field = this.field(name, label);
if (!field) throw Error('Missing field ' + name + '/' + label);
field.props.onChange({
target: { value, checked: value, files: value ? [value] : [] },
});
if (rerender) render();
},
submit(name) {
const form = this.form(name);
form.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
},
click(label, scope = tree) {
const button = this.button(label, scope);
if (!button) throw Error('Missing button ' + label);
button.props.onClick();
render();
return sent.at(-1);
},
success(next, request = sent.at(-1)) {
render(next);
request.options.onSuccess({ props: next });
request.form.processing = false;
render(next);
},
fail(request = sent.at(-1), status = null) {
if (status === null) request.options.onNetworkError();
else request.options.onHttpException({ status });
request.form.processing = false;
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = previousWindow;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
@@ -0,0 +1,378 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const apply = 'Aplicar actualiza\u00e7\u00e3o do Suporte t\u00e9cnico';
export const refresh = 'Actualizar pr\u00e9via';
export const adopt = 'Confirmar leitura da pr\u00e9via actual';
export const retry = 'Repetir envio original';
export const reason = 'Actualizacao sintetica explicitamente fundamentada';
export function props(patch = {}) {
return {
actorId: 1,
target: { database: 'support_profile_installation_test', port: 55441 },
hash: 'a'.repeat(64),
code_hash: 'b'.repeat(64),
installed: false,
consistent: true,
repairable: false,
ready: true,
action: 'install',
schema: { state: 'base', ledger: false },
dependencies: { profiles_installed: true },
changes: [],
backupDate: '2026-11-03T00:00:00Z',
rollback: 'Conservar historico',
commands: [],
mfa_confirmed: true,
...patch,
};
}
export function result(request, patch = {}) {
return {
actor_id: 1,
command_key: request.data.idempotency_key,
target: props().target,
migration: '2026_11_03_080000_add_technical_support_profile',
code_hash: props().code_hash,
installed: true,
...patch,
};
}
export function committed(request, patch = {}) {
return props({
installed: true,
action: 'none',
hash: 'c'.repeat(64),
schema: { state: 'support', ledger: true },
commands: [
{ key: request.data.idempotency_key, code_hash: props().code_hash },
],
...patch,
});
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
export function harness(initial = props(), mode = 'support') {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
class ApiError extends Error {
constructor(status, errors = {}) {
super('SYNTHETIC HTTP ' + status);
this.status = status;
this.errors = errors;
}
}
const mocks = {
react: hooks,
'@inertiajs/react': {
Link: 'a',
router: {
reload: (options) => reloads.push(options),
on(name, fn) {
if (name === 'before') before.add(fn);
return () => before.delete(fn);
},
},
},
'../management/shared': { Management: 'main', button: '', control: '' },
'@/pages/management/shared': {
Management: 'main',
button: '',
control: '',
},
};
const request = (url, options = {}) =>
new Promise((resolve, reject) => {
const entry = {
url,
data: options.body ? JSON.parse(options.body) : null,
resolve,
reject,
};
(options.method === 'POST' ? sent : reloads).push(entry);
});
mocks['./portal-api'] = {
PortalApiError: ApiError,
portalRequest: request,
};
mocks['@/lib/profile-json'] = {
profileJson: (url, data, method = 'POST') =>
request(url, { method, body: JSON.stringify(data) }),
};
mocks['./operation-key'] = mocks['@/lib/operation-key'] = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
function load(path) {
const code = 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(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['./page-preparation-guard'] = mocks['@/lib/page-preparation-guard'] =
load('resources/js/lib/page-preparation-guard.ts');
mocks['@/lib/profile-support-installation'] = load(
'resources/js/lib/profile-support-installation.ts',
);
const Page = load(
'resources/js/pages/profiles/' +
(mode === 'support' ? 'support-installation' : 'installation') +
'.tsx',
).default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
get confirmCalls() {
return confirmCalls;
},
get reason() {
return nodes(tree).find((n) => n.type === 'textarea').props.value;
},
button(label) {
return nodes(tree).find(
(n) => n.type === 'button' && text(n) === label,
);
},
change(value) {
nodes(tree)
.find((n) => n.type === 'textarea')
.props.onChange({ target: { value } });
render();
},
confirm(value = true) {
nodes(tree)
.find((n) => n.type === 'input' && n.props.type === 'checkbox')
.props.onChange({ target: { checked: value } });
render();
},
number(index, value) {
nodes(tree)
.filter((n) => n.type === 'input' && n.props.type === 'number')
[index].props.onChange({ target: { value } });
render();
},
get guards() {
return before.size;
},
click(label) {
const node = this.button(label);
if (!node) throw Error('Missing button ' + label);
node.props.onClick();
render();
return sent.at(-1);
},
async reply(value, request = sent.at(-1)) {
request.resolve(value);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
async fail(status = null, request = sent.at(-1)) {
request.reject(
status === null
? new Error('SYNTHETIC network loss')
: new ApiError(
status,
status === 422
? { note: ['SYNTHETIC rejected note'] }
: {},
),
);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
leave(preserveState = false) {
let prevented = false;
const old = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = old;
}
return prevented;
},
};
}
@@ -0,0 +1,334 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export function props(patch = {}) {
return {
opportunity: {
id: 1,
title: 'SYNTHETIC resource investment',
status: 'draft',
deleted_at: null,
},
etag: 'a'.repeat(64),
resources: { documents: [], images: [], locations: [] },
existingLocations: [],
assessment: [],
imageProcessingAvailable: true,
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0;
const windowMock = {
confirm() {
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
class Form {
constructor() {
this.values = new Map();
}
set(k, v) {
this.values.set(k, v);
}
get(k) {
return this.values.get(k);
}
}
function globals() {
const saved = {
document: globalThis.document,
fetch: globalThis.fetch,
FormData: globalThis.FormData,
setTimeout: globalThis.setTimeout,
};
globalThis.document = {
cookie: 'XSRF-TOKEN=SYNTHETIC',
getElementById: () => ({ focus() {} }),
};
globalThis.FormData = Form;
globalThis.setTimeout = (fn) => {
fn();
return 0;
};
globalThis.fetch = (url, options) =>
new Promise((resolve, reject) =>
sent.push({ url, form: options.body, resolve, reject }),
);
return () => Object.assign(globalThis, saved);
}
const mocks = {
react: hooks,
'@inertiajs/react': {
Link: 'a',
usePage: () => ({
props: {
basePath: '/minhas-oportunidades',
countries: [],
readOnly: false,
},
url: '/minhas-oportunidades/1/resources',
}),
router: { reload: (o) => reloads.push(o) },
},
'@/components/opportunity-library-reuse': { default: () => null },
'@/components/territory-geometry-preview': { default: () => null },
'@/components/investment-territory': { TerritoryLevel: () => null },
'./shared': {
Management: 'main',
Field: ({ label, children }) => ({
type: 'label',
props: { children: [label, children] },
}),
button: '',
control: '',
},
'@/lib/operation-key': {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
},
};
function load(path) {
const code = 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(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/lib/technical-incident-labels'] = load(
'resources/js/lib/technical-incident-labels.ts',
);
mocks['@/lib/value-text'] = load('resources/js/lib/value-text.ts');
mocks['@/components/opportunity-technical-incidents'] = load(
'resources/js/components/opportunity-technical-incidents.tsx',
);
const Page = load(
'resources/js/pages/management/opportunity-resources.tsx',
).default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
const field = (label) =>
nodes(tree).find(
(n) =>
['input', 'textarea', 'select'].includes(n.type) &&
n.props['aria-label'] === label,
);
return {
sent,
reloads,
render,
get tree() {
return tree;
},
get props() {
return current;
},
value(label) {
return field(label)?.props.value;
},
change(label, value) {
field(label).props.onChange({ target: { value } });
render();
},
choose(label) {
nodes(tree)
.find((n) => n.type === 'button' && text(n) === label)
.props.onClick();
render();
},
attach(value) {
nodes(tree)
.find((n) => n.type === 'input' && n.props.type === 'file')
.props.onChange({ target: { files: [value] } });
render();
},
submit() {
const restore = globals();
try {
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
render();
return sent.at(-1);
} finally {
restore();
}
},
async reply(status, data, request = sent.at(-1)) {
const restore = globals();
try {
request.resolve({
ok: status >= 200 && status < 300,
status,
json: async () => data,
});
for (let i = 0; i < 8; i++) await Promise.resolve();
render();
} finally {
restore();
}
},
};
}
@@ -0,0 +1,348 @@
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
const require = createRequire(import.meta.url);
export const reference = '10000000-0000-4000-8000-000000000001';
export function props(patch = {}) {
return {
actorId: 1,
commands: [],
backUrl: '/suporte-tecnico/incidentes',
history: {
data: [],
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
},
incident: {
reference,
operation: 'submit',
observed_version: 4,
occurred_at: '2026-11-03',
error_code: 'workflow_unavailable',
handling: {
version: 0,
status: 'open',
assignee_user_id: null,
assignee_name: null,
updated_at: null,
resolved_at: null,
},
},
...patch,
};
}
export function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
export function text(tree) {
return Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'string' || typeof tree === 'number'
? String(tree)
: '';
}
export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
before = new Set(),
unload = new Set();
let active,
cursor = 0,
changed = false,
effects = [],
current = initial,
tree,
sequence = 0,
confirmCalls = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, callback) {
if (name === 'beforeunload') unload.add(callback);
},
removeEventListener(name, callback) {
if (name === 'beforeunload') unload.delete(callback);
},
};
const state = (initialValue) => {
const frame = active,
i = cursor++;
if (!(i in frame.cells))
frame.cells[i] =
typeof initialValue === 'function'
? initialValue()
: initialValue;
return [
frame.cells[i],
(value) => {
const next =
typeof value === 'function' ? value(frame.cells[i]) : value;
if (!Object.is(next, frame.cells[i])) {
frame.cells[i] = next;
changed = true;
}
},
];
};
const hooks = {
useState: state,
useRef(value) {
const i = cursor++;
active.cells[i] ??= { current: value };
return active.cells[i];
},
useEffect(callback, deps) {
const frame = active,
i = cursor++,
prior = frame.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j])) {
frame.cells[i] = { deps };
effects.push(() => {
prior?.cleanup?.();
frame.cells[i].cleanup = callback();
});
}
},
useCallback(callback, deps) {
const i = cursor++,
prior = active.cells[i];
if (!prior || !deps.every((value, j) => value === prior.deps[j]))
active.cells[i] = { deps, callback };
return active.cells[i].callback;
},
};
class ApiError extends Error {
constructor(status, errors = {}) {
super('SYNTHETIC HTTP ' + status);
this.status = status;
this.errors = errors;
}
}
const mocks = {
react: hooks,
'@inertiajs/react': {
Link: 'a',
router: {
reload: (options) => reloads.push(options),
on(name, fn) {
if (name === 'before') before.add(fn);
return () => before.delete(fn);
},
},
},
'../management/shared': { Management: 'main', Pagination: () => null },
'@/pages/management/shared': { button: '', control: '' },
};
mocks['./portal-api'] = {
PortalApiError: ApiError,
portalRequest: (url, options) =>
new Promise((resolve, reject) =>
sent.push({
url,
data: JSON.parse(options.body),
resolve,
reject,
}),
),
};
mocks['./operation-key'] = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
};
mocks['@/lib/portal-api'] = mocks['./portal-api'];
function load(path) {
const code = 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(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
mocks['@/lib/technical-incident-labels'] = load(
'resources/js/lib/technical-incident-labels.ts',
);
mocks['@/lib/technical-incident-handling'] = load(
'resources/js/lib/technical-incident-handling.ts',
);
mocks['@/components/technical-incident-handling'] = load(
'resources/js/components/technical-incident-handling.tsx',
);
mocks['@/components/technical-incident-notice'] = load(
'resources/js/components/technical-incident-notice.tsx',
);
const Page = load(
'resources/js/pages/profiles/technical-incident.tsx',
).default;
function expand(value, path, seen) {
if (Array.isArray(value))
return value.map((child, i) =>
expand(child, path + '/' + (child?.key ?? i), seen),
);
if (!value || typeof value !== 'object' || !value.props) return value;
if (typeof value.type === 'function') {
const id = path + '/' + value.type.name + ':' + (value.key ?? '');
seen.add(id);
const frame = frames.get(id) ?? { cells: [] };
frames.set(id, frame);
const previous = active,
priorCursor = cursor;
active = frame;
cursor = 0;
const rendered = value.type(value.props);
active = previous;
cursor = priorCursor;
return {
type: 'component',
props: {
name: value.type.name,
children: expand(rendered, id, seen),
},
};
}
return {
...value,
props: {
...value.props,
children: expand(
value.props.children,
path + '/children',
seen,
),
},
};
}
function render(next = current) {
current = next;
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
let loops = 0;
do {
changed = false;
const seen = new Set();
tree = expand(
{ type: Page, key: 'page', props: current },
'root',
seen,
);
for (const [id, frame] of frames)
if (!seen.has(id)) {
frame.cells.forEach((cell) => cell?.cleanup?.());
frames.delete(id);
}
const queue = effects;
effects = [];
queue.forEach((effect) => effect());
if (++loops > 12) throw Error('Component state did not settle');
} while (changed);
return tree;
} finally {
globalThis.window = previousWindow;
}
}
render();
return {
sent,
reloads,
render,
get props() {
return current;
},
get tree() {
return tree;
},
get confirmCalls() {
return confirmCalls;
},
get note() {
return nodes(tree).find((n) => n.type === 'textarea').props.value;
},
button(label) {
return nodes(tree).find(
(n) => n.type === 'button' && text(n) === label,
);
},
change(value) {
nodes(tree)
.find((n) => n.type === 'textarea')
.props.onChange({ target: { value } });
render();
},
click(label) {
const node = this.button(label);
if (!node) throw Error('Missing button ' + label);
node.props.onClick();
render();
return sent.at(-1);
},
async reply(value, request = sent.at(-1)) {
request.resolve(value);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
async fail(status = null, request = sent.at(-1)) {
request.reject(
status === null
? new Error('SYNTHETIC network loss')
: new ApiError(
status,
status === 422
? { note: ['SYNTHETIC rejected note'] }
: {},
),
);
for (let i = 0; i < 6; i++) await Promise.resolve();
render();
},
refreshed(next, request = reloads.at(-1)) {
render(next);
request.onSuccess?.({ props: next });
request.onFinish?.();
render(next);
},
leave(preserveState = false) {
let prevented = false;
const old = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = old;
}
return prevented;
},
};
}
+431
View File
@@ -0,0 +1,431 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/investment-guides.ts');
const guide = {
slug: 'capitalizacao',
version: 'SYNTHETIC-v1',
sha256: 'a'.repeat(64),
title: 'SYNTHETIC capital guide',
reviewed_on: '2026-11-02',
scope: 'SYNTHETIC information, not approval',
instruments: {
debt: {
title: 'SYNTHETIC debt',
description: 'SYNTHETIC repayments',
risks: ['SYNTHETIC default'],
prepare: ['SYNTHETIC cashflows'],
sources: ['primary'],
},
equity: {
title: 'SYNTHETIC equity',
description: 'SYNTHETIC ownership',
risks: ['SYNTHETIC dilution'],
prepare: ['SYNTHETIC ownership'],
sources: ['primary'],
},
},
sources: {
primary: {
title: 'Primary <SYNTHETIC>',
url: 'https://primary.test/page',
edition: 'SYNTHETIC edition',
locator: 'SYNTHETIC paragraph',
consulted_on: '2026-11-02',
sha256: 'b'.repeat(64),
},
},
eligibility: [
{ text: 'SYNTHETIC provider criteria', sources: ['primary'] },
],
preparation: [
{
title: 'SYNTHETIC documents',
text: 'SYNTHETIC proposed list',
sources: ['primary'],
},
],
next: ['SYNTHETIC next action'],
limits: ['SYNTHETIC no automatic submission'],
};
const props = {
guide,
instruments: [],
note: '',
case: null,
saved: null,
canWrite: false,
historical: false,
olderEdition: false,
currentAvailable: true,
workingCopy: false,
contextChanged: false,
unavailableInstruments: [],
history: [],
historyNext: null,
};
const dossier = {
id: 'SYNTHETIC-case',
title: 'SYNTHETIC destination',
version: 1,
};
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const byName = (tree, name) => nodes(tree).find((n) => n.props?.name === name);
const button = (tree, label) =>
nodes(tree).find((n) => n.type === 'button' && n.props.children === label);
const tick = () => new Promise((resolve) => setImmediate(resolve));
function harness() {
let cursor = 0,
reject = false,
withdrawn = false;
const values = [],
refs = [],
requests = [],
visits = [];
class ValidationError extends Error {}
const hooks = {
useState(initial) {
const i = cursor++;
if (!(i in values))
values[i] = structuredClone(
typeof initial === 'function' ? initial() : initial,
);
return [
values[i],
(v) => {
values[i] = typeof v === 'function' ? v(values[i]) : v;
},
];
},
useRef(initial) {
const i = cursor++;
if (!(i in values)) {
values[i] = { current: initial };
refs.push(values[i]);
}
return values[i];
},
};
const component = load('../../resources/js/pages/investment/guide.tsx', {
react: hooks,
'@inertiajs/react': {
Link: 'a',
router: { visit: (...args) => visits.push(args) },
},
'./shared': { Frame: 'main', input: '', card: '', button: '' },
'@/lib/investment-guides': lib,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
},
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
profileJson: async (...args) => {
requests.push(args);
if (args[2] === 'GET')
return {
...props,
case: { ...dossier, version: 4 },
canWrite: true,
olderEdition: withdrawn,
currentAvailable: !withdrawn,
note: 'SYNTHETIC saved by coeditor',
};
if (reject) throw new Error('SYNTHETIC conflict');
return { saved: true };
},
},
});
return {
render(extra = {}) {
cursor = 0;
const outer = component.default({ ...props, ...extra });
return outer.type(outer.props);
},
refs,
requests,
visits,
fail() {
reject = true;
},
withdraw() {
withdrawn = true;
},
};
}
async function withData(data, fn) {
const original = globalThis.FormData;
globalThis.FormData = class {
get(key) {
return data[key] ?? null;
}
getAll(key) {
return data[key] ?? [];
}
};
try {
return await fn();
} finally {
globalThis.FormData = original;
}
}
await test('public guide distinguishes instruments, risks, provider criteria, documents and exact source edition without identity fields', () => {
const tree = harness().render(),
html = renderToStaticMarkup(tree);
for (const text of [
'SYNTHETIC debt',
'SYNTHETIC equity',
'SYNTHETIC default',
'SYNTHETIC dilution',
'SYNTHETIC provider criteria',
'SYNTHETIC documents',
'SYNTHETIC next action',
'SYNTHETIC edition',
'SYNTHETIC paragraph',
])
assert.match(html, new RegExp(text));
assert.match(html, /Primary &lt;SYNTHETIC&gt;/);
assert.match(html, /https:\/\/primary.test\/page/);
assert.equal(byName(tree, 'note'), undefined);
assert.doesNotMatch(html, /name="(name|email|nuit|amount|return)"/);
});
await test('selection filters only the visible instruments and can return to the whole guide', () => {
const h = harness();
const checkbox = nodes(h.render()).find((n) => n.props?.value === 'debt');
checkbox.props.onChange({ target: { checked: true } });
let html = renderToStaticMarkup(h.render());
assert.match(html, /SYNTHETIC default/);
assert.doesNotMatch(html, /SYNTHETIC dilution/);
nodes(h.render())
.find((n) => n.props?.value === 'debt')
.props.onChange({ target: { checked: false } });
html = renderToStaticMarkup(h.render());
assert.match(html, /SYNTHETIC dilution/);
});
await test('authentication URLs carry only coded choices and edition pins, including an explicitly empty selection', async () => {
const h = harness();
h.render();
h.refs[0].current = {};
await withData(
{ 'instruments[]': ['equity'], note: 'PRIVATE MUST NOT TRAVEL' },
async () => {
nodes(h.render())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
},
);
const url = new URL(h.visits[0][0], 'https://portal.test');
assert.equal(url.pathname, '/investimentos');
assert.equal(
url.searchParams.get('investment_guide[sha256]'),
guide.sha256,
);
assert.deepEqual(
url.searchParams.getAll('investment_guide[instruments][]'),
['equity'],
);
assert.doesNotMatch(url.href, /PRIVATE|note/);
const empty = new URL(
lib.guideUrl('/investimentos/id/guias/capitalizacao', {
slug: guide.slug,
sha256: guide.sha256,
instruments: [],
}),
'https://portal.test',
);
assert.equal(empty.searchParams.get('current'), '1');
assert.equal(empty.searchParams.get('selection'), '1');
assert.equal(empty.searchParams.get('sha256'), guide.sha256);
});
await test('private saves use actual browser values and return to the same dossier without putting notes in URLs', async () => {
const h = harness(),
extra = { case: dossier, canWrite: true };
h.render(extra);
h.refs[0].current = {};
await withData(
{
'instruments[]': ['debt'],
note: 'SYNTHETIC autofilled private note',
},
async () => {
nodes(h.render(extra))
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
},
);
assert.equal(h.requests[0][1].note, 'SYNTHETIC autofilled private note');
assert.deepEqual(h.requests[0][1].instruments, ['debt']);
assert.equal(h.requests[0][1].sha256, guide.sha256);
assert.deepEqual(h.visits, [
[
'/investimentos/SYNTHETIC-case/guias/capitalizacao',
{ preserveState: false },
],
]);
});
await test('conflicts preserve private notes and require explicit comparison before adopting the current dossier version', async () => {
const h = harness(),
extra = { case: dossier, canWrite: true };
h.render(extra);
h.refs[0].current = {};
h.fail();
await withData(
{ 'instruments[]': ['debt'], note: 'SYNTHETIC unsaved note' },
async () => {
nodes(h.render(extra))
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
},
);
assert.equal(
byName(h.render(extra), 'note').props.value,
'SYNTHETIC unsaved note',
);
assert.equal(h.visits.length, 0);
await button(
h.render(extra),
'Conferir a referência actual sem perder a nota',
).props.onClick();
assert.equal(h.requests[1][2], 'GET');
assert.match(
renderToStaticMarkup(h.render(extra)),
/SYNTHETIC saved by coeditor/,
);
button(
h.render(extra),
'Conferi: manter a minha preparação numa nova revisão',
).props.onClick();
await withData({ 'instruments[]': ['debt'] }, async () => {
nodes(h.render(extra))
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
});
assert.equal(h.requests[2][1].version, 4);
assert.equal(h.requests[2][1].note, 'SYNTHETIC unsaved note');
h.withdraw();
await button(
h.render(extra),
'Conferir a referência actual sem perder a nota',
).props.onClick();
assert.equal(
button(
h.render(extra),
'Conferi: manter a minha preparação numa nova revisão',
),
undefined,
);
assert.equal(
byName(h.render(extra), 'note').props.value,
'SYNTHETIC unsaved note',
);
assert.match(
renderToStaticMarkup(h.render(extra)),
/guia utilizado foi alterado/,
);
});
await test('historical or withdrawn guides and consultation members cannot write or silently upgrade a saved edition', async () => {
for (const flags of [
{ historical: true },
{ olderEdition: true, currentAvailable: false },
{ canWrite: false },
]) {
const h = harness(),
tree = h.render({ case: dossier, canWrite: true, ...flags });
assert.equal(
nodes(tree).find((n) => n.type === 'fieldset').props.disabled,
true,
);
nodes(tree)
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
await tick();
assert.equal(h.requests.length, 0);
if (flags.currentAvailable === false) {
const html = renderToStaticMarkup(tree);
assert.match(html, /retirado da consulta actual/);
assert.doesNotMatch(html, /\?current=1/);
}
}
});
await test('dossier chooser preserves the selected source edition on existing and newly created investment paths', () => {
let created;
const selection = {
slug: guide.slug,
sha256: guide.sha256,
instruments: ['debt'],
};
const module = load('../../resources/js/pages/investor-path/index.tsx', {
react: { useState: (fn) => [typeof fn === 'function' ? fn() : fn] },
'@inertiajs/react': {
Head: 'title',
Link: 'a',
router: {},
useForm: (data) => {
created = data;
return { data, errors: {}, processing: false };
},
},
'@/lib/investment-guides': lib,
'@/lib/operation-key': {
createOperationKey: () => 'SYNTHETIC-operation',
},
'@/lib/company-comparison': {},
});
const tree = module.default({
contexts: [{ ...dossier, updated_at: '2026-11-02' }],
guideSelection: selection,
});
assert.deepEqual(created.investment_guide, selection);
const link = nodes(tree).find(
(n) =>
typeof n.props?.href === 'string' &&
n.props.href.includes('/guias/'),
);
const url = new URL(link.props.href, 'https://portal.test');
assert.equal(
url.pathname,
'/investimentos/SYNTHETIC-case/guias/capitalizacao',
);
assert.equal(url.searchParams.get('sha256'), guide.sha256);
assert.match(
renderToStaticMarkup(tree),
/só serão guardados quando confirmar/,
);
});
@@ -0,0 +1,234 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
text,
nodes,
companyId,
} from './helpers/investment-profile-editor.mjs';
const account = 'Perfil de investimento',
company = 'Declaração de empresa',
fresh = 'Nova declaração de empresa',
residence = 'País de residência do investidor';
test('the actual profile preserves the ISO selection and repeats the exact command after a lost response', async () => {
const h = harness();
h.change(residence, 'ZA', account);
const first = h.submit(account);
assert.equal(first.data.payload.residence_country_code, 'ZA');
await h.fail();
assert.equal(h.value(residence, account), 'ZA');
assert.equal(h.field(residence, account).props.disabled, true);
assert.match(text(h.tree), /preparação foi conservada/);
assert.equal(h.sent.length, 1);
h.submit(account);
assert.deepEqual(h.sent[1].data, first.data);
await h.reply({ version: 2 });
assert.equal(h.reloads.length, 1);
assert.match(text(h.tree), /Gravação confirmada/);
assert.equal(h.leave(), false);
});
test('a new company retry uses the original creation key and clears only its confirmed preparation', async () => {
const h = harness();
h.change('Nome da empresa', 'SYNTHETIC new', fresh);
h.change('País de constituição da entidade', 'MZ', fresh);
h.change('Função ou relação com a empresa', 'SYNTHETIC role', fresh);
h.change('Telefone', 'SYNTHETIC unsaved phone', account);
const first = h.submit(fresh);
await h.fail(503);
const second = h.submit(fresh);
assert.deepEqual(second.data, first.data);
await h.reply({ id: '10000000-0000-4000-8000-000000000002', version: 1 });
assert.equal(h.value('Nome da empresa', fresh), '');
assert.equal(h.value('Telefone', account), 'SYNTHETIC unsaved phone');
assert.equal(h.leave(), true);
});
test('a refreshed newer version preserves local edits until explicit comparison and adoption', async () => {
const h = harness();
h.change(residence, 'ZA', account);
h.render(
props({
account: {
version: 2,
payload: {
residence_country_code: 'MZ',
country: 'SYNTHETIC historical',
},
},
}),
);
assert.equal(h.value(residence, account), 'ZA');
assert.equal(
h.button('Guardar perfil de investimento', account).props.disabled,
true,
);
const read = h.click('Consultar registo guardado', account);
assert.equal(read.method, 'GET');
await h.reply(
props({
account: { version: 2, payload: { residence_country_code: 'MZ' } },
}),
);
assert.match(text(h.form(account)), /Compar|Preparação nesta página/);
h.click('Usar versão actual e manter a preparação', account);
assert.equal(h.value(residence, account), 'ZA');
const command = h.submit(account);
assert.equal(command.data.version, 2);
assert.equal(command.data.payload.residence_country_code, 'ZA');
});
test('conflict recovery reads current data without applying a write automatically', async () => {
const h = harness();
h.change('Nome da empresa', 'SYNTHETIC local name', company);
h.submit(company);
await h.fail(409);
assert.equal(h.value('Nome da empresa', company), 'SYNTHETIC local name');
const read = h.click('Consultar registo guardado', company);
await h.reply(
props({
companies: [
{
id: companyId,
version: 3,
payload: {
name: 'SYNTHETIC server name',
incorporation_country_code: 'MZ',
role: 'SYNTHETIC role',
},
},
],
}),
);
assert.equal(h.sent.length, 2);
assert.equal(read.method, 'GET');
h.click('Usar versão actual e manter a preparação', company);
const command = h.submit(company);
assert.equal(command.data.version, 3);
assert.equal(command.data.payload.name, 'SYNTHETIC local name');
});
test('validation shows each field message once and preserves its value', async () => {
const h = harness();
h.change(residence, 'ZZ', account);
const sent = h.submit(account);
await h.fail(422, sent, {
'payload.residence_country_code': ['SYNTHETIC invalid country'],
});
assert.equal(
text(h.form(account)).split('SYNTHETIC invalid country').length - 1,
1,
);
assert.equal(h.value(residence, account), 'ZZ');
assert.equal(h.field(residence, account).props['aria-invalid'], true);
});
test('one page leave guard covers multiple dirty profile declarations', () => {
const h = harness();
h.change(residence, 'ZA', account);
h.change('Nome da empresa', 'SYNTHETIC edit', company);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.leave(true), false);
});
test('a response from the prior actor cannot confirm or reload another account', async () => {
const h = harness();
h.change(residence, 'ZA', account);
const old = h.submit(account);
h.render(
props({
actorId: 2,
account: { version: 0, payload: {} },
companies: [],
}),
);
await h.reply({ version: 2 }, old);
assert.equal(h.reloads.length, 0);
assert.equal(h.value(residence, account), '');
assert.doesNotMatch(text(h.tree), /Gravação confirmada/);
});
test('an invalid creation acknowledgement keeps the new company and command unresolved', async () => {
const h = harness();
h.change('Nome da empresa', 'SYNTHETIC retained', fresh);
h.submit(fresh);
await h.reply({ version: 1, id: 'invalid-id' });
assert.equal(h.value('Nome da empresa', fresh), 'SYNTHETIC retained');
assert.equal(h.reloads.length, 0);
assert.match(text(h.tree), /Não foi possível confirmar/);
});
test('long answers use multiline controls and text limits match the server', () => {
const h = harness();
assert.equal(h.field('Experiência relevante', account).type, 'textarea');
assert.equal(h.field('Telefone', account).props.maxLength, 30);
assert.equal(
h.field('Referência de registo / NUIT', company).props.maxLength,
100,
);
assert.equal(
nodes(h.form(account)).filter(
(node) => node.type === 'input' && node.props.required,
).length,
0,
);
});
test('consulting after an uncertain creation never unlocks editing or replaces its original command', async () => {
const h = harness();
h.change('Nome da empresa', 'SYNTHETIC original attempt', fresh);
const first = h.submit(fresh);
await h.fail();
h.click('Consultar registo guardado', fresh);
await h.reply(props());
assert.equal(
h.value('Nome da empresa', fresh),
'SYNTHETIC original attempt',
);
assert.equal(h.field('Nome da empresa', fresh).props.disabled, true);
assert.equal(
h.button('Usar versão actual e manter a preparação', fresh),
undefined,
);
const retry = h.submit(fresh);
assert.deepEqual(retry.data, first.data);
});
test('company country validation is attached once to the selectable country field', async () => {
const h = harness();
const request = h.submit(fresh);
await h.fail(422, request, {
'payload.country': ['SYNTHETIC company country required'],
});
assert.equal(
h.field('País de constituição da entidade', fresh).props[
'aria-invalid'
],
true,
);
assert.equal(
text(h.form(fresh)).split('SYNTHETIC company country required').length -
1,
1,
);
});
test('preparing a manifestation cannot discard unsaved profile data without the existing leave confirmation', () => {
const h = harness();
h.change(residence, 'ZA', account);
h.click('Preparar manifestação desta empresa');
assert.equal(h.confirmCalls, 1);
assert.equal(h.value(residence, account), 'ZA');
assert.equal(h.sent.length, 0);
});
test('a newer value read from the server requires explicit adoption before another write', async () => {
const h = harness();
h.change(residence, 'ZA', account);
h.click('Consultar registo guardado', account);
await h.reply(
props({
account: { version: 4, payload: { residence_country_code: 'MZ' } },
}),
);
const count = h.sent.length;
h.submit(account);
assert.equal(h.sent.length, count);
assert.equal(
h.button('Guardar perfil de investimento', account).props.disabled,
true,
);
h.click('Usar versão actual e manter a preparação', account);
assert.equal(h.submit(account).data.version, 4);
});
@@ -0,0 +1,354 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url),
module = { exports: {} };
const output = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/opportunity-technical-incidents.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
compileFunction(output, ['require', 'module', 'exports'])(
(name) =>
name === '@/lib/technical-incident-labels'
? load('resources/js/lib/technical-incident-labels.ts')
: require(name),
module,
module.exports,
);
const render = (incidents) =>
renderToStaticMarkup(
React.createElement(module.exports.default, { incidents }),
);
const base = {
reference: 'SYNTHETIC-reference',
operation: 'submit',
version: 4,
occurred_at: '2026-11-03',
error_code: 'database_failure',
};
test('no incident produces no empty form or duplicate question', () =>
assert.equal(render([]), ''));
test('the reader identifies the attempt and support scope without a business retry or decision', () => {
const html = render([base]);
assert.match(html, /Submissão para validação/);
assert.match(html, /versão observada 4/);
assert.match(html, /SYNTHETIC-reference/);
assert.match(html, /Consulte o estado actual antes de repetir/);
assert.match(html, /Suporte técnico consulta os incidentes/);
assert.doesNotMatch(html, /<button|<form|href=/);
});
function load(path, mocks = {}) {
const result = { exports: {} };
const code = 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;
compileFunction(code, ['require', 'module', 'exports'])(
(name) =>
mocks[name] ??
(name === '@/components/technical-incident-notice'
? { default: () => null }
: undefined) ??
(name.startsWith('@/')
? load('resources/js/' + name.slice(2) + '.ts')
: require(name)),
result,
result.exports,
);
return result.exports;
}
test('the actual profile navigation exposes the support queue only through the server capability', () => {
const { profileLinks } = load(
'resources/js/components/profile-navigation.tsx',
{ '@inertiajs/react': { Link: 'a', usePage: () => ({ props: {} }) } },
);
const access = {
mine: null,
create: null,
request: '/perfil/promotor',
review: null,
administration: null,
};
assert.equal(
profileLinks(access).some(
(link) => link.href === '/suporte-tecnico/incidentes',
),
false,
);
assert.equal(
profileLinks({
...access,
technicalSupport: '/suporte-tecnico/incidentes',
}).find((link) => link.href === '/suporte-tecnico/incidentes').title,
'Suporte técnico',
);
});
test('the actual queue presents minimal metadata and an honest empty state without private process links', () => {
const Queue = load('resources/js/pages/profiles/technical-support.tsx', {
'@inertiajs/react': {
Link: ({ href, children, ...rest }) =>
React.createElement('a', { href, ...rest }, children),
},
'../management/shared': {
Management: ({ children }) =>
React.createElement('main', null, children),
Pagination: () => null,
},
}).default;
const page = (data) =>
renderToStaticMarkup(
React.createElement(Queue, {
incidents: {
data,
total: data.length,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.match(page([]), /Não existem incidentes disponíveis neste âmbito/);
const html = page([base]);
assert.match(html, /SYNTHETIC-reference/);
assert.match(html, /não concede acesso aos processos ou documentos/);
assert.doesNotMatch(html, /minhas-oportunidades|<form|<button/);
});
test('the support queue exposes the authorised treatment link and preserves its state and page', () => {
const Queue = load('resources/js/pages/profiles/technical-support.tsx', {
'@inertiajs/react': {
Link: ({ href, children, ...rest }) =>
React.createElement('a', { href, ...rest }, children),
},
'../management/shared': {
Management: ({ children }) =>
React.createElement('main', null, children),
Pagination: () => null,
},
}).default;
const html = renderToStaticMarkup(
React.createElement(Queue, {
filters: { status: 'resolved' },
incidents: {
data: [
{
...base,
details_url: '/suporte-tecnico/incidentes/one',
handling: {
status: 'resolved',
assignee_name: 'SYNTHETIC support',
},
},
],
total: 1,
current_page: 3,
last_page: 3,
prev_page_url: null,
next_page_url: null,
},
}),
);
assert.ok(
html.includes(
'href="/suporte-tecnico/incidentes/one?page=3&amp;status=resolved"',
),
);
assert.match(html, /Estado técnico: Resolvido/);
assert.match(html, /aria-current="page"/);
assert.doesNotMatch(html, /minhas-oportunidades/);
});
test('the existing JSON transport preserves the incident reference and never repeats a failed write', async () => {
const transport = load('resources/js/lib/profile-json.ts');
const oldFetch = globalThis.fetch,
oldDocument = globalThis.document;
let calls = 0;
globalThis.document = { cookie: 'XSRF-TOKEN=SYNTHETIC' };
globalThis.fetch = async () => {
calls++;
return {
ok: false,
status: 503,
headers: { get: () => null },
json: async () => ({
message: 'SYNTHETIC incident reference: one',
reference: 'one',
incident_recorded: true,
}),
};
};
try {
await assert.rejects(
transport.profileJson('/minhas-oportunidades/1/workflow', {
action: 'submit',
}),
/SYNTHETIC incident reference: one/,
);
assert.equal(calls, 1);
} finally {
globalThis.fetch = oldFetch;
globalThis.document = oldDocument;
}
});
test('publication is distinct and untrusted reference text remains escaped', () => {
const html = render([
{
...base,
operation: 'publish',
error_code: 'workflow_unavailable',
reference: '<img src=x onerror=alert(1)>',
},
]);
assert.match(html, /Publicação/);
assert.match(html, /Falha técnica/);
assert.doesNotMatch(html, /<img/);
assert.match(html, /&lt;img/);
});
for (const [operation, label] of [
['upload_document', 'Carregamento de documento'],
['upload_image', 'Carregamento de imagem'],
['prepare_image', 'Preparação de imagens WebP'],
]) {
test('the reader distinguishes ' + operation + ' from publication', () => {
const html = render([{ ...base, operation }]);
assert.ok(html.includes(label));
assert.doesNotMatch(html, />Publicação/);
});
}
test('the support link exposes only a valid count alongside the server capability', () => {
const { profileLinks } = load(
'resources/js/components/profile-navigation.tsx',
{ '@inertiajs/react': { Link: 'a', usePage: () => ({ props: {} }) } },
);
const access = {
request: '/perfil/promotor',
technicalSupport: '/suporte-tecnico/incidentes',
};
assert.match(
profileLinks({ ...access, technicalSupportUnread: 3 }).find(
(link) => link.href === access.technicalSupport,
).title,
/3 por consultar/,
);
for (const count of [null, -1, 0, 1.2, Infinity, '4'])
assert.equal(
profileLinks({ ...access, technicalSupportUnread: count }).find(
(link) => link.href === access.technicalSupport,
).title,
'Suporte técnico',
);
assert.equal(
profileLinks({
request: access.request,
technicalSupportUnread: 3,
}).some((link) => link.href === access.technicalSupport),
false,
);
});
test('an unknown technical operation is not labelled as a publication', () => {
const html = render([{ ...base, operation: 'unknown_operation' }]);
assert.match(html, /Operação técnica não identificada/);
assert.doesNotMatch(html, />Publicação/);
});
for (const [code, label] of [
['scan_dispatch_unconfirmed', 'Encaminhamento da análise sem confirmação.'],
['scan_inconclusive', 'Análise de segurança inconclusiva.'],
['scan_worker_failed', 'Falha na execução da análise de segurança.'],
[
'scan_cleanup_unconfirmed',
'Limpeza do ficheiro temporário por confirmar.',
],
]) {
test(
'the scan reader distinguishes ' +
code +
' from a failed resource save',
() => {
const html = render([
{ ...base, operation: 'scan_document', error_code: code },
]);
assert.ok(html.includes(label));
assert.match(html, /Análise de segurança de documento/);
assert.match(html, /O recurso já foi registado/);
assert.doesNotMatch(html, />Publicação/);
},
);
}
test('the scan reader never renders an unrecognized internal error code', () => {
const html = render([
{
...base,
operation: 'scan_document',
error_code: 'PRIVATE INTERNAL TOKEN',
},
]);
assert.doesNotMatch(html, /PRIVATE INTERNAL/);
assert.match(html, /Falha técnica durante a operação/);
});
test('unread and technical status filters preserve each other and the detail return context', () => {
const Queue = load('resources/js/pages/profiles/technical-support.tsx', {
'@inertiajs/react': {
Link: ({ children, ...rest }) =>
React.createElement('a', rest, children),
},
'../management/shared': {
Management: ({ children }) =>
React.createElement('main', null, children),
Pagination: () => null,
},
}).default;
const html = renderToStaticMarkup(
React.createElement(Queue, {
filters: { status: 'resolved', unread: true },
incidents: {
data: [
{ ...base, details_url: '/suporte-tecnico/incidentes/one' },
],
current_page: 2,
total: 1,
last_page: 2,
},
}),
);
assert.ok(
html.includes(
'href="/suporte-tecnico/incidentes?status=open&amp;unread=1"',
),
);
assert.ok(
html.includes('href="/suporte-tecnico/incidentes?status=resolved"'),
);
assert.ok(
html.includes(
'href="/suporte-tecnico/incidentes/one?page=2&amp;status=resolved&amp;unread=1"',
),
);
});
@@ -0,0 +1,165 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/investment-profile-editor.mjs';
const id = '20000000-0000-4000-8000-000000000001',
form = 'País da organização: SYNTHETIC master',
country = 'País de constituição da organização',
source = 'Fonte ou referência deste país';
const org = (patch = {}) => ({
id,
name: 'SYNTHETIC master',
version: 1,
country: 'MZ',
canEdit: true,
provenance: {
kind: 'representative_declaration',
reference: 'SYNTHETIC saved reference',
},
...patch,
});
const state = (organization = org(), patch = {}) =>
props({ organizations: [organization], ...patch });
test('organization country and source are frozen and repeated together after an uncertain write', async () => {
const h = harness(state());
h.change(country, 'ZA', form);
h.change(source, 'SYNTHETIC new source', form);
const first = h.submit(form);
assert.equal(first.method, 'PUT');
assert.equal(
first.url,
'/api/v1/investment/organizations/' + id + '/country',
);
assert.equal(first.data.country, 'ZA');
assert.equal(first.data.source_reference, 'SYNTHETIC new source');
assert.equal(first.data.payload, undefined);
await h.fail();
assert.equal(h.field(source, form).props.disabled, true);
assert.equal(h.value(country, form), 'ZA');
const retry = h.submit(form);
assert.deepEqual(retry.data, first.data);
await h.reply({ version: 2, country: 'ZA' });
assert.match(text(h.form(form)), /Gravação confirmada/);
assert.deepEqual(h.reloads[0].only, ['organizations']);
});
test('an organization version refresh preserves both local values and uses explicit comparison before another write', async () => {
const h = harness(state());
h.change(country, 'ZA', form);
h.change(source, 'SYNTHETIC local reference', form);
h.render(
state(
org({
version: 3,
country: 'PT',
provenance: {
kind: 'representative_declaration',
reference: 'SYNTHETIC remote source',
},
}),
),
);
assert.equal(h.value(source, form), 'SYNTHETIC local reference');
assert.equal(
h.button('Guardar país da organização', form).props.disabled,
true,
);
h.click('Consultar país guardado', form);
await h.reply(
state(
org({
version: 3,
country: 'PT',
provenance: {
kind: 'representative_declaration',
reference: 'SYNTHETIC remote source',
},
}),
),
);
assert.match(text(h.form(form)), /SYNTHETIC remote source/);
h.click('Usar versão actual e manter a preparação', form);
const next = h.submit(form);
assert.equal(next.data.version, 3);
assert.equal(next.data.country, 'ZA');
assert.equal(next.data.source_reference, 'SYNTHETIC local reference');
});
test('a validation error belongs to the organization field once and does not remove the reference', async () => {
const h = harness(state());
h.change(source, 'x', form);
const sent = h.submit(form);
await h.fail(422, sent, {
source_reference: ['SYNTHETIC source too short'],
});
assert.equal(h.value(source, form), 'x');
assert.equal(h.field(source, form).props['aria-invalid'], true);
assert.equal(
text(h.form(form)).split('SYNTHETIC source too short').length - 1,
1,
);
});
test('read-only representation has no write command and cannot send one by direct form submission', () => {
const h = harness(state(org({ canEdit: false })));
assert.equal(h.button('Guardar país da organização', form), undefined);
assert.equal(h.field(country, form).props.disabled, true);
h.submit(form);
assert.equal(h.sent.length, 0);
});
test('a lost write followed by revoked representation remains prepared but cannot be repeated', async () => {
const h = harness(state());
h.change(source, 'SYNTHETIC retained source', form);
h.submit(form);
await h.fail();
h.click('Consultar país guardado', form);
await h.reply(state(org({ canEdit: false })));
const count = h.sent.length;
h.submit(form);
assert.equal(h.sent.length, count);
assert.equal(h.value(source, form), 'SYNTHETIC retained source');
assert.equal(h.button('Repetir o mesmo pedido', form), undefined);
});
test('organization edits share one leave guard with the private profile', () => {
const h = harness(state());
h.change(source, 'SYNTHETIC dirty organization', form);
h.change('Telefone', 'SYNTHETIC dirty profile', 'Perfil de investimento');
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
});
test('an acknowledgement with the wrong country cannot confirm or erase the prepared source', async () => {
const h = harness(state());
h.change(country, 'ZA', form);
h.change(source, 'SYNTHETIC prepared source', form);
h.submit(form);
await h.reply({ version: 2, country: 'PT' });
assert.equal(h.reloads.length, 0);
assert.equal(h.value(source, form), 'SYNTHETIC prepared source');
assert.match(text(h.form(form)), /Não foi possível confirmar/);
});
test('two rapid consultations share one in-flight read and never write automatically', async () => {
const h = harness(state());
const read = h.button('Consultar país guardado', form);
read.props.onClick();
read.props.onClick();
h.render();
assert.equal(h.sent.length, 1);
assert.equal(h.sent[0].method, 'GET');
await h.reply(state());
assert.equal(h.sent.length, 1);
assert.equal(
h.button('Guardar país da organização', form).props.disabled,
true,
);
});
test('a fresh authorized read can restore editing after a membership is restored while old page props are read-only', async () => {
const h = harness(state(org({ canEdit: false })));
h.click('Consultar país guardado', form);
await h.reply(state(org({ canEdit: true })));
h.click('Usar versão actual e manter a preparação', form);
assert.equal(h.field(source, form).props.disabled, false);
h.change(source, 'SYNTHETIC restored representation source', form);
const sent = h.submit(form);
assert.equal(
sent.data.source_reference,
'SYNTHETIC restored representation source',
);
assert.equal(sent.method, 'PUT');
});
@@ -0,0 +1,158 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
companyId,
text,
} from './helpers/investment-profile-editor.mjs';
const sourceId = '30000000-0000-4000-8000-000000000001',
form = 'Declaração de empresa',
country = 'País de constituição da entidade';
const source = (patch = {}) => ({
id: sourceId,
name: 'SYNTHETIC reuse source',
version: 3,
country: 'FR',
canEdit: false,
provenance: {
kind: 'representative_declaration',
reference: 'SYNTHETIC stored reference',
},
...patch,
});
const state = (patch = {}) => props({ organizations: [source()], ...patch });
async function preview(h, response = state()) {
const read = h.click('Consultar país de SYNTHETIC reuse source');
assert.equal(read.method, 'GET');
await h.reply(response, read);
}
test('the actual reuse starts with a fresh preview and writes only after explicit confirmation', async () => {
const h = harness(state());
await preview(h);
assert.equal(h.sent.length, 1);
assert.equal(h.value(country, form), 'MZ');
assert.match(text(h.tree), /SYNTHETIC stored reference/);
const request = h.click('Confirmar reutilização do país');
assert.equal(request.method, 'POST');
assert.equal(
request.url,
'/api/v1/investment/companies/' + companyId + '/organization-country',
);
assert.equal(request.data.organization_id, sourceId);
assert.equal(request.data.organization_version, 3);
assert.equal(request.data.version, 1);
assert.equal(request.data.payload, undefined);
await h.reply({ version: 2, country: 'FR' });
assert.equal(h.value(country, form), 'FR');
assert.equal(h.value('Nome da empresa', form), 'SYNTHETIC company');
assert.match(text(h.tree), /gravação confirmada/);
assert.deepEqual(h.reloads[0].only, ['companies', 'organizations']);
});
test('an uncertain reuse locks the company and repeats exactly the frozen source command', async () => {
const h = harness(state());
await preview(h);
const first = h.click('Confirmar reutilização do país');
await h.fail();
assert.equal(h.field(country, form).props.disabled, true);
const count = h.sent.length;
h.submit(form);
assert.equal(h.sent.length, count);
h.render(state({ organizations: [source({ version: 4, country: 'ZA' })] }));
const second = h.click('Repetir a mesma reutilização');
assert.deepEqual(second.data, first.data);
await h.reply({ version: 2, country: 'FR' });
assert.equal(h.value(country, form), 'FR');
assert.equal(h.field(country, form).props.disabled, false);
});
test('unsaved company edits prevent preview and a later edit also prevents confirming a prepared reuse', async () => {
const h = harness(state());
h.change('Nome da empresa', 'SYNTHETIC dirty company', form);
h.click('Consultar país de SYNTHETIC reuse source');
assert.equal(h.sent.length, 0);
h.change('Nome da empresa', 'SYNTHETIC company', form);
await preview(h);
h.change('Nome da empresa', 'SYNTHETIC later edit', form);
const count = h.sent.length;
h.click('Confirmar reutilização do país');
assert.equal(h.sent.length, count);
assert.equal(h.value('Nome da empresa', form), 'SYNTHETIC later edit');
});
test('a conflicting copy preserves the target and requires a new preview and key', async () => {
const h = harness(state());
await preview(h);
const first = h.click('Confirmar reutilização do país');
await h.fail(409);
assert.equal(h.value(country, form), 'MZ');
assert.equal(h.field(country, form).props.disabled, false);
assert.equal(h.button('Confirmar reutilização do país'), undefined);
await preview(
h,
state({ organizations: [source({ version: 4, country: 'ZA' })] }),
);
const next = h.click('Confirmar reutilização do país');
assert.notEqual(next.data.operation_key, first.data.operation_key);
assert.equal(next.data.organization_version, 4);
});
test('a known newer source on the page blocks a stale preview before any write', async () => {
const h = harness(state());
await preview(h);
h.render(state({ organizations: [source({ version: 4, country: 'ZA' })] }));
const count = h.sent.length;
h.click('Confirmar reutilização do país');
assert.equal(h.sent.length, count);
assert.match(text(h.tree), /organização.*alterada|organização mudou/);
});
test('an invalid acknowledgement retains the original copy and never clears the company', async () => {
const h = harness(state());
await preview(h);
const first = h.click('Confirmar reutilização do país');
await h.reply({ version: 2, country: 'ZA' });
assert.equal(h.value(country, form), 'MZ');
assert.equal(h.field(country, form).props.disabled, true);
assert.equal(h.reloads.length, 0);
const retry = h.click('Repetir a mesma reutilização');
assert.deepEqual(retry.data, first.data);
});
test('restored read representation can confirm an original copy while consulting never changes its command', async () => {
const h = harness(state());
await preview(h);
const first = h.click('Confirmar reutilização do país');
await h.fail(403);
const count = h.sent.length;
h.click('Repetir a mesma reutilização');
assert.equal(h.sent.length, count);
h.click('Consultar estado da reutilização');
await h.reply(
state({ organizations: [source({ version: 5, country: null })] }),
);
assert.equal(h.field(country, form).props.disabled, true);
const retry = h.click('Repetir a mesma reutilização');
assert.deepEqual(retry.data, first.data);
});
test('a receipt from a prior actor cannot update the new actor or reload their page', async () => {
const h = harness(state());
await preview(h);
const request = h.click('Confirmar reutilização do país');
h.render(state({ actorId: 2, companies: [], organizations: [] }));
await h.reply({ version: 2, country: 'FR' }, request);
assert.equal(h.reloads.length, 0);
assert.doesNotMatch(text(h.tree), /País reutilizado e gravação confirmada/);
});
test('a changed target discovered by preview directs comparison without applying a write', async () => {
const h = harness(state());
const company = { ...h.props.companies[0], version: 2 };
await preview(h, state({ companies: [company] }));
assert.equal(h.sent.length, 1);
assert.equal(h.button('Confirmar reutilização do país'), undefined);
assert.match(text(h.tree), /Consulte e compare/);
assert.equal(h.value(country, form), 'MZ');
});
test('reuse and another dirty form share one page leave guard', async () => {
const h = harness(state());
await preview(h);
h.change('Telefone', 'SYNTHETIC dirty profile', 'Perfil de investimento');
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
});
@@ -0,0 +1,284 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/partnership-room.mjs';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
test('a legacy instrument without a confirmation map remains readable without inventing pending confirmations', () => {
for (const confirmations of [undefined, null, 'SYNTHETIC malformed map']) {
const initial = props();
initial.room.agreement.confirmations = confirmations;
const h = harness(initial);
assert.match(text(h.tree), /SYNTHETIC instrument/);
assert.match(text(h.tree), /confirmações.*(não.*registad|estrutura)/i);
assert.doesNotMatch(text(h.tree), /Confirmações: Pendentes/);
}
});
const require = createRequire(import.meta.url);
const modules = {};
const shared = fs.readFileSync(
'resources/js/pages/partnerships/shared.tsx',
'utf8',
);
const labels = compileFunction(
`return (${shared.match(/export const labels: Record<string, string> = (\{[\s\S]*?\n\});/)[1]});`,
[],
)();
function load(file) {
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (Object.hasOwn(modules, name)) return modules[name];
if (name === './shared')
return {
labels,
Frame: ({ title, children }) =>
React.createElement(
'main',
{},
React.createElement('h1', {}, title),
children,
),
};
if (name === '@inertiajs/react')
return {
Link: ({ children, ...attributes }) =>
React.createElement('a', attributes, children),
};
return require(name);
},
module,
module.exports,
);
return module.exports;
}
modules['@/lib/partnership-agreement'] = load(
'resources/js/lib/partnership-agreement.ts',
);
modules['@/components/partnership-agreement-instrument'] = load(
'resources/js/components/partnership-agreement-instrument.tsx',
);
const Instrument =
modules['@/components/partnership-agreement-instrument'].default;
const Page = load(
'resources/js/pages/partnerships/agreement-history.tsx',
).default;
const instrument = () => ({
title: 'SYNTHETIC frozen title',
terms: 'SYNTHETIC frozen terms',
confirmations: {},
legal_signature_status: 'not_verified',
});
const snapshot = () => ({
availability: 'available',
version: 2,
status: 'agreement_recorded',
instrument_availability: 'available',
instrument: instrument(),
instrument_partnership_version: 4,
instrument_interest_version: 3,
});
const entry = () => ({
version: 2,
restricted: false,
action: 'record',
actor_name: 'SYNTHETIC actor',
occurred_at: '2026-11-03',
reason: 'SYNTHETIC reason',
confirmation_party: null,
partnership_version: 4,
interest_version: 3,
previous: { availability: 'not_recorded' },
after: snapshot(),
});
const history = () => ({
room_id: 1,
entries: [entry()],
first_url: '/parcerias/salas/1/historico',
next_url: null,
older_page: false,
room_href: '/parcerias/salas/1',
dashboard_href: '/parcerias/painel',
});
const render = (p) => renderToStaticMarkup(React.createElement(Page, p));
test('the stored empty array is an empty confirmation map while nonempty lists stay unrecognized', () => {
const value = instrument();
value.confirmations = [];
assert.match(
renderToStaticMarkup(React.createElement(Instrument, { value })),
/Confirmações: Pendentes/,
);
value.confirmations = [{ actor_id: 1 }];
assert.match(
renderToStaticMarkup(React.createElement(Instrument, { value })),
/não têm uma estrutura reconhecida/,
);
});
test('invalid instrument fields never become React children or fabricated confirmations', () => {
for (const value of [
false,
['SYNTHETIC invalid'],
{
title: { secret: 'SYNTHETIC PRIVATE' },
terms: ['SYNTHETIC PRIVATE'],
confirmations: null,
},
]) {
const html = renderToStaticMarkup(
React.createElement(Instrument, { value }),
);
assert.doesNotMatch(
html,
/SYNTHETIC PRIVATE|\[object Object\]|Pendentes/,
);
assert.match(html, /estrutura reconhecida|Título não registado/);
}
});
test('incomplete and unknown confirmation references do not impersonate a party', () => {
const initial = props();
initial.room.agreement.confirmations = {
proponent: { actor_id: 'wrong', date: {}, reason: [] },
unknown: { actor_id: 2 },
};
const h = harness(initial);
assert.match(text(h.tree), /Registo de confirmação incompleto/);
assert.match(text(h.tree), /não substituem a confirmação de cada parte/);
assert.ok(h.button('Confirmar pela minha parte'));
assert.equal(h.button('Actualizar confirmação da minha parte'), undefined);
assert.doesNotMatch(text(h.tree), /\[object Object\]/);
});
test('history renders frozen before and after instruments with their decision context and no write actions', () => {
const p = history();
p.entries[0].previous = snapshot();
p.entries[0].previous.instrument.title = 'SYNTHETIC previous title';
p.entries[0].after.instrument.confirmations = {
candidate: {
actor_id: 2,
actor_name: 'SYNTHETIC candidate',
reason: 'SYNTHETIC confirmation reason',
date: '2026-11-03',
},
};
p.entries[0].confirmation_party = 'candidate';
const html = render(p);
for (const fragment of [
'SYNTHETIC previous title',
'SYNTHETIC frozen title',
'SYNTHETIC candidate',
'SYNTHETIC confirmation reason',
'Contexto da decisão: proposta 4',
'candidatura 3',
'não verificada',
'Parte que confirmou: Candidata',
])
assert.ok(html.includes(fragment), fragment);
assert.doesNotMatch(html, /<form|<button|Registar versão do acordo/);
});
test('restricted and unknown history states never render supplied private fields', () => {
for (const availability of [
'restricted',
'scope_unknown',
'not_recorded',
'malformed',
]) {
const p = history();
p.entries[0].restricted = true;
p.entries[0].reason = 'SYNTHETIC HIDDEN reason';
p.entries[0].actor_name = 'SYNTHETIC HIDDEN actor';
p.entries[0].previous = {
...snapshot(),
availability,
instrument: { title: 'SYNTHETIC HIDDEN instrument' },
};
p.entries[0].after = {
...snapshot(),
instrument_availability: availability,
instrument: { title: 'SYNTHETIC HIDDEN instrument' },
};
const html = render(p);
assert.doesNotMatch(html, /SYNTHETIC HIDDEN/);
assert.match(html, /Conteúdo reservado/);
}
});
test('legacy absence is explicit and history never fills it with a current instrument', () => {
const p = history();
p.entries[0].after = { availability: 'not_recorded' };
const html = render(p);
assert.match(html, /Não foi preenchida com a versão actual/);
assert.doesNotMatch(html, /SYNTHETIC frozen/);
});
test('history navigation uses the scoped server URLs and distinguishes older pages', () => {
const p = history();
p.older_page = true;
p.next_url = '/parcerias/salas/1/historico?before=SYNTHETIC-token';
const html = render(p);
for (const fragment of [
'Voltar à sala',
'Versões mais recentes',
'Consultar versões anteriores',
'before=SYNTHETIC-token',
'href="/parcerias/painel"',
])
assert.ok(html.includes(fragment));
assert.doesNotMatch(html, /<button/);
});
test('an empty history explains the absence without creating a historical instrument', () => {
const p = history();
p.entries = [];
const html = render(p);
assert.match(html, /Ainda não existem alterações do acordo guardadas/);
assert.doesNotMatch(
html,
/Consultar versões anteriores|Antes da alteração/,
);
});
test('stored conditions and reasons are escaped and cannot add links or markup', () => {
const p = history();
p.entries[0].reason = '<script>SYNTHETIC</script>';
p.entries[0].after.instrument.terms =
'<a href="https://example.invalid">SYNTHETIC</a>';
const html = render(p);
assert.ok(html.includes('&lt;script&gt;SYNTHETIC&lt;/script&gt;'));
assert.ok(html.includes('&lt;a href='));
assert.doesNotMatch(html, /<script>|<a href="https:\/\/example.invalid/);
});
test('the room history link shares the existing leave guard without erasing an unsent reason', () => {
const h = harness(props());
h.change('agreement', 'Motivo da ação', 'SYNTHETIC unsent reason');
const link = h
.all()
.find(
(node) =>
node.type === 'a' &&
node.props.href ===
`/parcerias/salas/${h.props.room.id}/historico`,
);
assert.ok(link);
assert.equal(h.leave(), true);
assert.equal(
h.field('agreement', 'Motivo da ação').props.value,
'SYNTHETIC unsent reason',
);
assert.equal(h.sent.length, 0);
});
@@ -0,0 +1,257 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/partnership-room.mjs';
test('an uncertain agreement action exposes recovery of the frozen attempt', () => {
const h = harness(props());
h.change('agreement', 'Motivo da ação', 'SYNTHETIC reason');
const request = h.click('Confirmar pela minha parte');
h.fail(request);
assert.ok(h.button('Recuperar a mesma acção'));
});
function ack(h, request, patch = {}) {
const command = request.data;
const statuses = {
record: 'agreement_recorded',
confirm: 'agreement_recorded',
start: 'execution',
complete: 'closed',
cancel: 'cancelled',
renew: 'negotiation',
};
const agreement = { ...h.props.room.agreement };
if (command.action === 'record') {
agreement.title = command.title.trim();
agreement.terms = command.terms.trim();
agreement.confirmations = {};
} else if (command.action === 'confirm') {
agreement.confirmations = {
...agreement.confirmations,
[h.props.agreementParty]: {
actor_id: h.props.agreementActorId,
date: '2026-11-03',
reason: command.reason.trim(),
},
};
}
return {
...h.props,
room: {
...h.props.room,
agreement,
version: command.version + 1,
status: statuses[command.action],
...patch,
},
agreementCommands: [
{
key: command.client_key,
action: command.action,
version: command.version + 1,
status: patch.status ?? statuses[command.action],
party:
command.action === 'confirm'
? h.props.agreementParty
: null,
},
],
};
}
const adopt = 'Usar este contexto e conservar as alterações escolhidas';
const recover = 'Recuperar a mesma acção';
const refresh = 'Comparar com os dados actuais da sala';
function prepared() {
const h = harness(props());
h.change('agreement', 'Motivo da ação', 'SYNTHETIC decision');
return h;
}
test('confirmation recovery freezes context and reason while preserving later preparation', () => {
const h = prepared();
h.change(
'agreement',
'Título do instrumento',
'SYNTHETIC unrecorded title',
);
const first = h.click('Confirmar pela minha parte');
const frozen = { ...first.data };
assert.equal(first.data.partnership_version, 4);
assert.equal(first.data.interest_version, 3);
assert.equal(first.data.title, undefined);
h.fail(first);
h.change('agreement', 'Motivo da ação', 'SYNTHETIC next reason');
const repeated = h.click(recover);
assert.deepEqual(repeated.data, frozen);
h.success(ack(h, repeated), repeated);
assert.equal(
h.field('agreement', 'Motivo da ação').props.value,
'SYNTHETIC next reason',
);
assert.equal(
h.field('agreement', 'Título do instrumento').props.value,
'SYNTHETIC unrecorded title',
);
assert.equal(h.button(recover), undefined);
});
test('record recovery preserves terms written after the original command', () => {
const h = prepared();
h.change(
'agreement',
'Condições e plano de valor',
'SYNTHETIC submitted terms',
);
const first = h.click('Registar versão do acordo');
h.fail(first);
h.change('agreement', 'Condições e plano de valor', 'SYNTHETIC next terms');
const repeated = h.click(recover);
assert.equal(repeated.data.terms, 'SYNTHETIC submitted terms');
h.success(ack(h, repeated), repeated);
assert.equal(
h.field('agreement', 'Condições e plano de valor').props.value,
'SYNTHETIC next terms',
);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
});
test('a terminal cancellation still permits recovery of the same command', () => {
const h = prepared();
const first = h.click('Cancelar conexão com motivo');
h.fail(first);
const terminal = ack(h, first);
h.render(terminal);
assert.equal(h.button(recover).props.disabled, false);
const repeated = h.click(recover);
assert.deepEqual(repeated.data, first.data);
h.success(terminal, repeated);
assert.equal(h.button(recover), undefined);
});
test('a fresh read can acknowledge a committed attempt without another write', () => {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
h.fail(first);
h.click(refresh);
h.refreshed(ack(h, first));
assert.equal(h.sent.length, 1);
assert.equal(h.button(recover), undefined);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
});
test('a recovered command followed by a bilateral decision requires explicit review', () => {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
h.fail(first);
const repeated = h.click(recover);
const later = ack(h, repeated, {
version: first.data.version + 2,
status: 'agreed',
});
later.room.agreement.confirmations.candidate = {
actor_id: 2,
date: '2026-11-03',
reason: 'SYNTHETIC other decision',
};
later.agreementCommands[0].status = 'agreement_recorded';
h.success(later, repeated);
assert.ok(h.button(adopt));
assert.equal(h.button('Iniciar acompanhamento').props.disabled, true);
h.click(adopt);
h.change('agreement', 'Motivo da ação', 'SYNTHETIC start after review');
assert.equal(h.button('Iniciar acompanhamento').props.disabled, false);
});
test('a changed proposal with the same room version requires context adoption', () => {
const h = prepared();
h.render({
...h.props,
partnership: { ...h.props.partnership, version: 5 },
});
assert.equal(h.button('Confirmar pela minha parte').props.disabled, true);
h.click(adopt);
const request = h.click('Confirmar pela minha parte');
assert.equal(request.data.partnership_version, 5);
assert.equal(request.data.version, 2);
});
test('an exact command receipt with a newer parent context still requires review', () => {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
const next = ack(h, first);
next.interest = { ...next.interest, version: 4 };
h.success(next, first);
assert.ok(h.button(adopt));
assert.equal(
h.button('Actualizar confirmação da minha parte').props.disabled,
true,
);
h.click(adopt);
h.change('agreement', 'Motivo da ação', 'SYNTHETIC updated context');
assert.equal(
h.button('Actualizar confirmação da minha parte').props.disabled,
false,
);
});
test('missing own receipt or an incompatible confirmation stamp never clears a draft', () => {
for (const wrong of ['receipt', 'stamp']) {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
const next = ack(h, first);
if (wrong === 'receipt') next.agreementCommands = [];
else next.room.agreement.confirmations.proponent.actor_id = 9;
h.success(next, first);
assert.equal(
h.field('agreement', 'Motivo da ação').props.value,
'SYNTHETIC decision',
);
assert.ok(h.button(recover));
assert.equal(h.button(adopt).props.disabled, true);
}
});
test('lost write authority blocks recovery and another actor does not inherit its draft', () => {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
h.fail(first);
h.fail(first, 403);
assert.equal(h.button(recover).props.disabled, true);
h.render({
...h.props,
actorId: 2,
agreementActorId: 2,
agreementParty: 'candidate',
agreementCommands: [],
});
h.success(ack(h, first), first);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
assert.equal(h.button(recover), undefined);
});
test('a current confirmation is identified as an update rather than another party', () => {
const initial = props();
initial.room.agreement.confirmations.proponent = {
actor_id: 1,
reason: 'SYNTHETIC old',
date: '2026-11-02',
};
const h = harness(initial);
assert.ok(h.button('Actualizar confirmação da minha parte'));
assert.equal(h.button('Confirmar pela minha parte'), undefined);
assert.match(text(h.tree), /proponente/i);
});
test('a callback from an abandoned attempt does not freeze its replacement', () => {
const h = prepared();
const first = h.click('Confirmar pela minha parte');
h.fail(first);
h.click(refresh);
h.refreshed(h.props);
h.click(adopt);
const second = h.click('Confirmar pela minha parte');
assert.notEqual(second.data.client_key, first.data.client_key);
h.fail(first);
h.success(ack(h, second), second);
assert.equal(h.button(recover), undefined);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
});
@@ -0,0 +1,611 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
original,
nodes,
text,
} from './helpers/partnership-candidacy.mjs';
const ownProps = (patch = {}) =>
props({
owner: true,
canEdit: true,
actorId: 1,
interests: [{ ...structuredClone(original), can_edit: false }],
...patch,
});
test('current candidacy card links to its history without changing a prepared submission', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC unsaved');
assert.ok(
nodes(h.render()).some(
(node) =>
node.props?.href === '/parcerias/candidaturas/10/historico',
),
);
assert.equal(h.submit('submission:10').data.proposal, 'SYNTHETIC unsaved');
});
const row = (scope, label) =>
nodes(scope).find(
(node) => node.type === 'tr' && text(node).startsWith(label),
);
function consent(h, name, checked) {
const input = nodes(h.form(name)).find(
(node) => node.type === 'input' && node.props.type === 'checkbox',
);
input.props.onChange({ target: { checked } });
h.render();
}
function saved(h, request = h.sent.at(-1), patch = {}) {
const action = request.data.action ?? 'submit';
const entry = structuredClone(
h.props.interests.find(
(interest) => interest.id === request.data.interest_id,
) ??
h.props.interests[0] ??
original,
);
entry.version = Number(request.data.version ?? 0) + 1;
if (action === 'submit') {
entry.organization_id = request.data.organization_id || null;
entry.proposal = request.data.proposal.trim();
entry.payload = Object.fromEntries(
Object.entries(request.data.payload).map(([key, value]) => [
key,
typeof value === 'string' ? value.trim() || null : value,
]),
);
entry.assessment = [];
entry.status = 'submitted';
entry.can_edit = true;
} else if (action === 'assess')
entry.assessment = structuredClone(request.data.assessment);
else
entry.status = {
clarify: 'clarification',
shortlist: 'shortlisted',
reject: 'rejected',
connect: 'negotiation',
withdraw: 'withdrawn',
}[action];
entry.commands = [
...(entry.commands ?? []),
{ key: request.data.client_key, version: entry.version, action },
];
return {
...h.props,
canStartInterest: false,
interests: [{ ...entry, ...patch }],
};
}
test('editing identifies the exact candidature and current proposal version, preserving accepted consent', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC revised proposal');
const request = h.submit('submission:10');
assert.equal(request.data.interest_id, 10);
assert.equal(request.data.version, 1);
assert.equal(request.data.partnership_version, 4);
assert.equal(request.data.payload.consent, true);
assert.equal(request.data.payload.capacity, original.payload.capacity);
assert.match(text(h.form('submission:10')), /reinicia a avaliação actual/);
});
test('batched declaration and consent edits do not erase siblings', () => {
const h = harness();
h.change(
'submission:10',
'Capacidade disponível',
'SYNTHETIC new capacity',
false,
);
h.change(
'submission:10',
'Disponibilidade',
'SYNTHETIC new availability',
false,
);
h.render();
consent(h, 'submission:10', false);
const request = h.submit('submission:10');
assert.equal(request.data.payload.capacity, 'SYNTHETIC new capacity');
assert.equal(
request.data.payload.availability,
'SYNTHETIC new availability',
);
assert.equal(
request.data.payload.contribution,
original.payload.contribution,
);
assert.equal(request.data.payload.consent, false);
});
test('read only representation offers consultation without update or withdrawal forms', () => {
const h = harness(
props({
interests: [{ ...structuredClone(original), can_edit: false }],
}),
);
assert.equal(h.form('submission:10'), undefined);
assert.equal(h.form('decision:10'), undefined);
assert.equal(h.form('submission:new'), undefined);
assert.match(text(h.tree), /SYNTHETIC original proposal/);
});
test('remote edits require an explicit choice and merge untouched declarations only after adoption', () => {
const h = harness();
h.change(
'submission:10',
'Capacidade disponível',
'SYNTHETIC local capacity',
);
h.render({
...h.props,
interests: [
{
...structuredClone(original),
version: 2,
payload: {
...original.payload,
capacity: 'SYNTHETIC remote capacity',
availability: 'SYNTHETIC remote availability',
},
},
],
});
assert.equal(
h.button('Guardar interesse', h.form('submission:10')).props.disabled,
true,
);
h.click(
'Manter minha alteração',
row(h.form('submission:10'), 'Capacidade disponível'),
);
h.click(
'Usar este contexto e conservar as alterações escolhidas',
h.form('submission:10'),
);
const request = h.submit('submission:10');
assert.equal(request.data.version, 2);
assert.equal(request.data.payload.capacity, 'SYNTHETIC local capacity');
assert.equal(
request.data.payload.availability,
'SYNTHETIC remote availability',
);
});
test('a deliberate return to the original declaration is not treated as untouched', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC temporary');
h.change('submission:10', 'Proposta curta', original.proposal);
h.render({
...h.props,
interests: [
{
...structuredClone(original),
version: 2,
proposal: 'SYNTHETIC remote proposal',
},
],
});
assert.match(
text(row(h.form('submission:10'), 'Proposta curta')),
/Escolha o valor a conservar/,
);
});
test('creation becomes the same editable candidature and preserves input made after sending', () => {
const h = harness(props({ interests: [], canStartInterest: true }));
h.change('submission:new', 'Proposta curta', 'SYNTHETIC first proposal');
consent(h, 'submission:new', true);
const first = h.submit('submission:new');
h.change('submission:new', 'Capacidade disponível', 'SYNTHETIC after send');
h.success(saved(h, first, { id: 12 }), first);
assert.equal(h.form('submission:12'), undefined);
assert.equal(
h.field('submission:new', 'Capacidade disponível').props.value,
'SYNTHETIC after send',
);
const next = h.submit('submission:new');
assert.equal(next.data.interest_id, 12);
assert.equal(next.data.version, 1);
assert.notEqual(next.data.client_key, first.data.client_key);
});
test('losing access to a candidature keeps only its local preparation mounted and disables commands', () => {
const h = harness();
h.change(
'submission:10',
'Capacidade disponível',
'SYNTHETIC retained private preparation',
);
h.render({ ...h.props, interests: [], canStartInterest: false });
assert.equal(
h.field('submission:10', 'Capacidade disponível').props.value,
'SYNTHETIC retained private preparation',
);
assert.equal(
h.button('Guardar interesse', h.form('submission:10')).props.disabled,
true,
);
assert.match(text(h.tree), /deixou de estar disponível/);
assert.equal(h.form('submission:new'), undefined);
});
test('withdrawal remains available when the proposal changes or its submission window closes', () => {
const h = harness();
h.change(
'decision:10',
'Motivo da retirada',
'SYNTHETIC voluntary withdrawal',
);
h.render({
...h.props,
acceptingInterests: false,
record: { ...h.props.record, version: 9, status: 'archived' },
});
assert.equal(h.button('Retirar candidatura').props.disabled, false);
const request = h.click('Retirar candidatura');
assert.equal(request.data.action, 'withdraw');
assert.equal(request.data.partnership_version, undefined);
assert.equal(request.data.weights_hash, undefined);
});
test('assessment edits keep state and evidence atomic across batched events', () => {
const h = harness(ownProps());
h.change('decision:10', 'Capacidade técnica/produtiva', 'met', false);
h.change(
'decision:10',
'Referência da evidência — Capacidade técnica/produtiva',
'SYNTHETIC checked evidence',
false,
);
h.render();
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC evidence reviewed',
);
const request = h.click('Guardar avaliação');
assert.deepEqual(request.data.assessment.capacity, {
state: 'met',
evidence: 'SYNTHETIC checked evidence',
});
assert.equal(request.data.partnership_version, 4);
assert.equal(request.data.weights_hash, 'a'.repeat(64));
});
test('proposal and criteria changes force review without silently changing prepared assessment', () => {
const h = harness(ownProps());
h.change('decision:10', 'Capacidade técnica/produtiva', 'met');
h.change(
'decision:10',
'Referência da evidência — Capacidade técnica/produtiva',
'SYNTHETIC own evidence',
);
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC review',
);
h.render({
...h.props,
record: { ...h.props.record, version: 5 },
interests: [
{
...h.props.interests[0],
match: {
...h.props.interests[0].match,
weights_hash: 'b'.repeat(64),
},
},
],
});
assert.equal(h.button('Guardar avaliação').props.disabled, true);
assert.equal(
h.field('decision:10', 'Capacidade técnica/produtiva').props.value,
'met',
);
h.click(
'Usar este contexto e conservar as alterações escolhidas',
h.form('decision:10'),
);
const request = h.click('Guardar avaliação');
assert.equal(request.data.partnership_version, 5);
assert.equal(request.data.weights_hash, 'b'.repeat(64));
});
test('separate criterion conflicts retain independent choices while the reason is edited', () => {
const h = harness(ownProps());
h.change('decision:10', 'Capacidade técnica/produtiva', 'met');
h.change('decision:10', 'Experiência comprovada', 'met');
h.render({
...h.props,
interests: [
{
...h.props.interests[0],
version: 2,
assessment: {
capacity: {
state: 'unmet',
evidence: 'SYNTHETIC remote capacity',
},
experience: {
state: 'unmet',
evidence: 'SYNTHETIC remote experience',
},
},
},
],
});
h.click(
'Manter minha alteração',
row(h.form('decision:10'), 'Capacidade técnica/produtiva'),
);
h.click(
'Usar valor actual',
row(h.form('decision:10'), 'Experiência comprovada'),
);
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC combined review',
);
assert.equal(
h.button(
'Usar este contexto e conservar as alterações escolhidas',
h.form('decision:10'),
).props.disabled,
false,
);
h.click(
'Usar este contexto e conservar as alterações escolhidas',
h.form('decision:10'),
);
assert.equal(
h.field('decision:10', 'Capacidade técnica/produtiva').props.value,
'met',
);
assert.equal(
h.field('decision:10', 'Experiência comprovada').props.value,
'unmet',
);
});
test('uncertain submission repeats the frozen command and retains later declarations', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC first command');
const first = h.submit('submission:10');
h.fail(first);
h.change('submission:10', 'Proposta curta', 'SYNTHETIC later text');
const retry = h.submit('submission:10');
assert.deepEqual(retry.data, first.data);
h.success(saved(h, retry), retry);
assert.equal(
h.field('submission:10', 'Proposta curta').props.value,
'SYNTHETIC later text',
);
const next = h.submit('submission:10');
assert.equal(next.data.version, 2);
assert.notEqual(next.data.client_key, first.data.client_key);
});
test('uncertain owner decisions expose one recovery action and do not resend later changes', () => {
const h = harness(ownProps());
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC original decision',
);
const first = h.click('Guardar avaliação');
h.fail(first);
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC later reason',
);
assert.equal(h.button('Adicionar à lista curta'), undefined);
const retry = h.click('Recuperar acção enviada');
assert.deepEqual(retry.data, first.data);
h.success(saved(h, retry), retry);
assert.equal(
h.field('decision:10', 'Motivo da decisão ou pedido de esclarecimento')
.props.value,
'SYNTHETIC later reason',
);
});
test('non-assessment decisions use saved criteria and preserve unsubmitted assessment edits', () => {
const h = harness(ownProps());
h.change('decision:10', 'Capacidade técnica/produtiva', 'met');
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC shortlist saved unknown assessment',
);
assert.match(
text(h.form('decision:10')),
/outras decisões usam a avaliação actualmente guardada/,
);
const request = h.click('Adicionar à lista curta');
assert.deepEqual(request.data.assessment, {});
h.success(saved(h, request), request);
assert.equal(
h.field('decision:10', 'Capacidade técnica/produtiva').props.value,
'met',
);
assert.equal(
h.field('decision:10', 'Motivo da decisão ou pedido de esclarecimento')
.props.value,
'',
);
});
test('obsolete criteria remain in local preparation but are excluded from the current command', () => {
const h = harness(ownProps());
h.change(
'decision:10',
'Referência da evidência — Experiência comprovada',
'SYNTHETIC retired evidence',
);
h.render({
...h.props,
interests: [
{
...h.props.interests[0],
match: {
...h.props.interests[0].match,
weights_hash: 'b'.repeat(64),
criteria: [h.props.interests[0].match.criteria[0]],
},
},
],
});
assert.match(text(h.form('decision:10')), /SYNTHETIC retired evidence/);
h.click(
'Usar este contexto e conservar as alterações escolhidas',
h.form('decision:10'),
);
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC current criteria only',
);
const request = h.click('Guardar avaliação');
assert.equal(request.data.assessment.experience, undefined);
h.success(saved(h, request), request);
assert.equal(
h.button(
'Usar este contexto e conservar as alterações escolhidas',
h.form('decision:10'),
),
undefined,
);
h.click(
'Descartar preparação dos critérios anteriores',
h.form('decision:10'),
);
assert.equal(h.unload(), false);
});
test('an acknowledgement of an older committed operation cannot accept someone else’s later values', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC submitted text');
const request = h.submit('submission:10');
h.change(
'submission:10',
'Contribuição proposta',
'SYNTHETIC unsent contribution',
);
const later = saved(h, request, {
version: 3,
payload: {
...request.data.payload,
contribution: 'SYNTHETIC remote contribution',
},
});
h.success(later, request);
assert.equal(
h.field('submission:10', 'Contribuição proposta').props.value,
'SYNTHETIC unsent contribution',
);
assert.equal(
h.button('Guardar interesse', h.form('submission:10')).props.disabled,
true,
);
assert.match(text(h.form('submission:10')), /dados posteriores/);
});
test('wrong record acknowledgement conserves preparation and never authorizes another target', () => {
const h = harness();
h.change('submission:10', 'Proposta curta', 'SYNTHETIC local preparation');
const request = h.submit('submission:10');
h.success({ ...h.props, record: { ...h.props.record, id: 999 } }, request);
assert.equal(
h.field('submission:10', 'Proposta curta').props.value,
'SYNTHETIC local preparation',
);
assert.equal(
h.button('Recuperar submissão enviada', h.form('submission:10')).props
.disabled,
true,
);
});
test('one navigation guard covers independent candidature drafts and permits preserved comparison refresh', () => {
const h = harness();
h.change('submission:10', 'Capacidade disponível', 'SYNTHETIC draft');
h.change('decision:10', 'Motivo da retirada', 'SYNTHETIC reason');
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.leave(true), false);
assert.equal(h.unload(), true);
});
test('a different authenticated account receives no private unsent preparation', () => {
const h = harness();
h.change(
'submission:10',
'Proposta curta',
'SYNTHETIC private unsent text',
);
h.render({ ...h.props, actorId: 3 });
assert.equal(
h.field('submission:10', 'Proposta curta').props.value,
original.proposal,
);
});
test('real API empty-array assessments and legacy accepted consent remain editable without fabricated assessment', () => {
const h = harness(
props({
interests: [
{
...structuredClone(original),
assessment: [],
payload: { ...original.payload, consent: 'yes' },
},
],
}),
);
assert.ok(h.form('submission:10'));
const input = nodes(h.form('submission:10')).find(
(node) => node.type === 'input' && node.props.type === 'checkbox',
);
assert.equal(input.props.checked, true);
const owner = harness(ownProps());
assert.equal(
owner.field('decision:10', 'Capacidade técnica/produtiva').props.value,
'unknown',
);
});
test('an indeterminate matching range is explained without a false percentage', () => {
const h = harness(
props({
interests: [
{
...structuredClone(original),
match: {
...original.match,
score_min: null,
score_max: null,
},
},
],
}),
);
assert.match(text(h.tree), /Correspondência: Por determinar/);
assert.doesNotMatch(text(h.tree), /–%/);
});
test('saved matching weights, mandatory status, evidence and explanation remain visible to the parties', () => {
const criterion = {
...original.match.criteria[0],
state: 'met',
evidence: 'SYNTHETIC preserved source',
explanation: 'SYNTHETIC preserved explanation',
};
const h = harness(
props({
interests: [
{
...structuredClone(original),
assessment: {
capacity: {
state: 'met',
evidence: criterion.evidence,
},
},
match: { ...original.match, criteria: [criterion] },
},
],
}),
);
const item = nodes(h.tree).find(
(node) => node.type === 'li' && text(node).includes(criterion.label),
);
assert.match(text(item), /peso 20/);
assert.match(text(item), /Obrigatório/);
assert.match(text(item), /Evidência: SYNTHETIC preserved source/);
assert.match(text(item), /SYNTHETIC preserved explanation/);
});
@@ -0,0 +1,142 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url),
calls = [];
const labelsSource = fs
.readFileSync('resources/js/pages/partnerships/shared.tsx', 'utf8')
.match(
/export const labels: Record<string, string> = (\{[\s\S]*?\n\});/,
)[1];
const labels = compileFunction(`return (${labelsSource});`, [])();
const module = { exports: {} };
const source = ts.transpileModule(
fs.readFileSync('resources/js/pages/partnerships/dashboard.tsx', 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
compileFunction(source, ['require', 'module', 'exports'])(
(id) => {
if (id === './shared')
return {
Frame: ({ title, children }) =>
React.createElement(
'main',
{},
React.createElement('h1', {}, title),
children,
),
labels,
};
if (id === '@inertiajs/react')
return {
Link: ({ children, ...props }) =>
React.createElement('a', props, children),
router: { post: (...args) => calls.push(args) },
};
return require(id);
},
module,
module.exports,
);
const Dashboard = module.exports.default;
const props = () => ({
mine: [],
interests: [
{
id: 10,
partnership_id: 1,
title: null,
partnership_href: null,
status: 'withdrawn',
decision_reason: null,
room_id: null,
},
],
moderation: [],
notifications: [],
});
const render = (p) => renderToStaticMarkup(React.createElement(Dashboard, p));
const nodes = (value) =>
Array.isArray(value)
? value.flatMap(nodes)
: React.isValidElement(value)
? [value, ...nodes(value.props.children)]
: [];
test('unavailable parent has an explanation and history link without a broken proposal link', () => {
const html = render(props());
assert.ok(html.includes('consulta da proposta indisponível'));
assert.ok(!html.includes('href="/parcerias/1"'));
assert.ok(html.includes('href="/parcerias/candidaturas/10/historico"'));
});
test('authorized parent title and supplied proposal link are preserved', () => {
const p = props();
p.interests[0].title = 'SYNTHETIC published title';
p.interests[0].partnership_href = '/parcerias/1';
const html = render(p);
assert.ok(html.includes('SYNTHETIC published title'));
assert.ok(html.includes('href="/parcerias/1"'));
});
test('authorized room remains reachable independently of parent publication', () => {
const p = props();
p.interests[0].room_id = 7;
const html = render(p);
assert.ok(html.includes('href="/parcerias/salas/7"'));
assert.ok(!html.includes('href="/parcerias/1"'));
});
test('notification titles are escaped and the historical scope limitation is explained', () => {
const p = props();
p.notifications = [
{
id: 30,
title: '<script>synthetic()</script>',
href: '/parcerias/candidaturas/10/historico',
read_at: null,
},
];
const html = render(p);
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(!html.includes('<script>'));
assert.ok(html.includes('avisos cuja consulta está autorizada'));
assert.ok(html.includes('permanecem no registo'));
});
test('only an unread supplied notice offers its own read acknowledgement', () => {
const p = props();
p.notifications = [
{
id: 30,
title: 'SYNTHETIC unread',
href: '/parcerias/1',
read_at: null,
},
{
id: 31,
title: 'SYNTHETIC read',
href: '/parcerias/1',
read_at: '2026-11-03',
},
];
const buttons = nodes(Dashboard(p)).filter((n) => n.type === 'button');
assert.equal(buttons.length, 1);
calls.length = 0;
buttons[0].props.onClick();
assert.deepEqual(calls, [['/parcerias/notificacoes/30/ler']]);
});
test('privacy-safe empty notification list does not remove the existing proposal and moderation sections', () => {
const p = props();
p.mine = [{ id: 8, title: 'SYNTHETIC own draft', status: 'draft' }];
p.moderation = [{ id: 9, title: 'SYNTHETIC pending', status: 'submitted' }];
const html = render(p);
for (const href of ['/parcerias/criar', '/parcerias/8', '/parcerias/9'])
assert.ok(html.includes(`href="${href}"`));
assert.ok(!html.includes('Marcar como lida'));
});
+878
View File
@@ -0,0 +1,878 @@
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 ts from 'typescript';
const require = createRequire(import.meta.url);
function load(file, mocks = {}) {
const code = ts.transpileModule(
fs.readFileSync(new URL(file, import.meta.url), 'utf8'),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
target: ts.ScriptTarget.ES2022,
},
},
).outputText;
const module = { exports: {} };
compileFunction(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
const clone = structuredClone;
test('an unconfirmed edit exposes recovery of the same submitted command', () => {
const h = harness();
h.set('title', 'SYNTHETIC frozen revision');
h.edit.save();
h.sent[0].options.onNetworkError();
h.render();
assert.equal(h.edit.retryingSave, true);
});
test('uncertain edit repeats the frozen operation and retains later typing', () => {
const h = harness();
h.set('title', 'SYNTHETIC sent');
h.edit.save();
const first = h.sent[0];
h.set('offer', 'SYNTHETIC later offer');
first.options.onNetworkError();
h.render();
h.edit.recoverSave();
assert.deepEqual(h.sent[1].data, first.data);
h.success(1, saved(h.sent[1].data));
assert.equal(h.data.offer, 'SYNTHETIC later offer');
assert.equal(h.edit.retryingSave, false);
});
test('refresh recognises an already committed edit from its own operation metadata', () => {
const h = harness();
h.set('title', 'SYNTHETIC saved');
h.edit.save();
h.sent[0].options.onNetworkError();
h.render();
h.edit.refresh();
const next = saved(h.sent[0].data);
h.render(next);
h.reloads[0].onSuccess({ props: next });
h.reloads[0].onFinish();
h.render();
assert.equal(h.edit.retryingSave, false);
assert.equal(h.data.version, 3);
assert.equal(h.edit.dirty, false);
});
test('recognising an edit preserves post-send preparation and does not adopt a later state', () => {
const h = harness();
h.set('title', 'SYNTHETIC committed');
h.edit.save();
h.set('title', 'SYNTHETIC later preparation');
h.success(0, saved(h.sent[0].data, { version: 4, status: 'submitted' }));
assert.equal(h.data.title, 'SYNTHETIC later preparation');
assert.equal(h.data.version, 3);
assert.equal(h.edit.stale, true);
assert.equal(h.edit.editable, false);
h.edit.adopt();
h.render();
assert.equal(h.data.version, 4);
assert.equal(h.data.title, 'SYNTHETIC later preparation');
assert.equal(h.sent.length, 1);
});
test('lost access disables recovery until a successful authorized refresh', () => {
const h = harness();
h.set('title', 'SYNTHETIC retained');
h.edit.save();
h.sent[0].options.onHttpException({ status: 403 });
h.render();
assert.equal(h.edit.canRecoverSave, false);
h.edit.recoverSave();
assert.equal(h.sent.length, 1);
h.edit.refresh();
h.reloads[0].onSuccess({ props: props() });
h.reloads[0].onFinish();
h.render();
assert.equal(h.edit.canRecoverSave, true);
});
test('new attempt after comparison gets a new key and ignores late failure of the abandoned attempt', () => {
const h = harness();
h.set('title', 'SYNTHETIC original attempt');
h.edit.save();
const first = h.sent[0];
first.options.onNetworkError();
h.render();
h.set('title', 'SYNTHETIC new preparation');
h.edit.adopt();
h.render();
assert.equal(h.edit.retryingSave, true);
h.edit.refresh();
h.reloads[0].onSuccess({ props: props() });
h.reloads[0].onFinish();
h.render();
h.edit.adopt();
h.render();
h.edit.save();
assert.equal(h.sent.length, 2);
assert.notEqual(h.sent[1].data.operation_key, first.data.operation_key);
assert.equal(h.sent[1].data.title, 'SYNTHETIC new preparation');
first.options.onNetworkError();
h.render();
assert.equal(h.edit.retryingSave, false);
});
test('another account starts a separate preparation and ignores an old acknowledgement', () => {
const h = harness();
h.set('title', 'SYNTHETIC former actor draft');
h.edit.save();
const first = h.sent[0],
next = props({ editorActorId: 99 });
h.render(next);
assert.equal(h.data.title, 'SYNTHETIC original');
first.options.onSuccess({ props: saved(first.data) });
h.render(next);
assert.equal(h.data.title, 'SYNTHETIC original');
assert.equal(h.edit.retryingSave, false);
});
test('response without matching operation metadata cannot clear the preparation', () => {
const h = harness();
h.set('title', 'SYNTHETIC conserved');
h.edit.save();
const next = saved(h.sent[0].data);
next.saveCommands = [];
h.success(0, next);
assert.equal(h.data.title, 'SYNTHETIC conserved');
assert.equal(h.edit.retryingSave, true);
assert.equal(h.edit.blocked, true);
});
test('recovery is offered outside the disabled editing fieldset in a later read-only state', () => {
const h = harness();
h.set('title', 'SYNTHETIC committed');
h.edit.save();
const first = h.sent[0];
first.options.onNetworkError();
const next = saved(first.data, { version: 4, status: 'submitted' });
next.saveCommands = [];
h.render(next);
assert.equal(h.edit.editable, false);
assert.equal(h.edit.canRecoverSave, true);
assert.ok(
nodes(h.panel()).some(
(n) =>
n.type === 'button' && text(n) === 'Recuperar a mesma gravação',
),
);
h.edit.recoverSave();
assert.deepEqual(h.sent[1].data, first.data);
h.success(1, saved(first.data, { version: 4, status: 'submitted' }));
assert.equal(h.edit.retryingSave, false);
assert.equal(h.edit.editable, false);
});
test('retired catalogue selections remain in the frozen recovery command', () => {
const h = harness();
h.payload('mandatory', ['capacity']);
h.edit.save();
const first = h.sent[0];
first.options.onNetworkError();
h.render({ ...props(), types: {}, criteria: {} });
assert.ok(
h
.all()
.some(
(node) =>
node.type === 'option' &&
text(node).includes('Tipo anteriormente indicado'),
),
);
const remove = h
.all()
.find(
(node) =>
node.type === 'button' &&
text(node) === 'Retirar da preparação',
);
assert.ok(remove);
remove.props.onClick();
h.render();
assert.deepEqual(h.data.payload.mandatory, []);
h.edit.recoverSave();
assert.deepEqual(h.sent[1].data, first.data);
assert.deepEqual(h.sent[1].data.payload.mandatory, ['capacity']);
h.success(1, saved(h.sent[1].data));
assert.deepEqual(h.data.payload.mandatory, []);
});
test('cancelled uncertain edits remain recoverable and protect navigation even with unchanged values', () => {
const h = harness();
h.edit.save();
h.sent[0].options.onCancel();
h.render();
assert.equal(h.edit.retryingSave, true);
assert.equal(h.edit.dirty, true);
assert.equal(h.before(), true);
assert.equal(h.unload(), true);
});
test('empty API dictionaries are valid while malformed operation metadata suspends writing', () => {
const p = props();
p.record.payload = [];
const h = harness(p);
assert.equal(h.edit.invalid, false);
h.set('title', 'SYNTHETIC draft without payload');
h.edit.save();
assert.equal(h.sent.length, 1);
const invalid = harness(props({ saveCommands: null }));
assert.equal(invalid.edit.invalid, true);
invalid.edit.save();
assert.equal(invalid.sent.length, 0);
});
const key = '11111111-1111-4111-8111-111111111111';
const catalogues = {
types: { joint_venture: 'Consórcio' },
criteria: {
capacity: 'Capacidade',
experience: 'Experiência',
impact: 'Impacto',
},
sectors: [{ id: 1, name: 'Agricultura' }],
territories: [{ id: 'place', name: 'Local de ensaio' }],
organizations: [],
sources: [],
};
function props(patch = {}) {
return {
...catalogues,
editorActorId: 2,
saveCommands: [],
record: {
id: 1,
version: 2,
status: 'draft',
client_key: key,
title: 'SYNTHETIC original',
offer: 'SYNTHETIC offer',
seeking: 'SYNTHETIC collaboration',
organization_id: null,
sector_id: 1,
kind: 'seeking',
partnership_type: 'joint_venture',
deadline: null,
payload: {
summary: 'SYNTHETIC summary',
requirements: 'SYNTHETIC requirements',
mandatory: ['capacity'],
confidentiality: 'private',
consent: true,
availability: 'SYNTHETIC November availability',
},
},
origins: [],
locations: [],
...patch,
};
}
function saved(data, { id = 1, version = 3, status = 'draft' } = {}) {
const trim = (value) => (typeof value === 'string' ? value.trim() : value);
const record = {
id,
version,
status,
client_key: data.client_key,
title: trim(data.title),
offer: trim(data.offer),
seeking: trim(data.seeking),
organization_id: data.organization_id || null,
sector_id: data.sector_id ? Number(data.sector_id) : null,
kind: data.kind,
partnership_type: data.partnership_type || null,
deadline: data.deadline || null,
payload: Object.fromEntries(
Object.entries(data.payload).map(([k, v]) => [k, trim(v)]),
),
};
return props({
saveCommands: data.operation_key
? [{ key: data.operation_key, version: Number(data.version) + 1 }]
: [],
record,
origins: clone(data.origins),
locations: data.locations.map((item) => ({
...item,
source_reference: trim(item.source_reference),
})),
});
}
function nodes(tree) {
return Array.isArray(tree)
? tree.flatMap(nodes)
: tree && typeof tree === 'object'
? [tree, ...nodes(tree.props?.children)]
: [];
}
function text(tree) {
return typeof tree === 'string'
? tree
: Array.isArray(tree)
? tree.map(text).join('')
: tree?.props
? text(tree.props.children)
: typeof tree === 'number'
? String(tree)
: '';
}
function harness(initial = props()) {
let cells = [],
forms = [],
cursor = 0,
formCursor = 0,
currentProps = initial,
currentKey,
initialized = false,
tree,
editor;
const sent = [],
reloads = [],
effects = [],
before = new Set(),
unload = new Set();
let confirmCalls = 0,
operationSequence = 0;
const windowMock = {
confirm() {
confirmCalls++;
return false;
},
addEventListener(name, fn) {
if (name === 'beforeunload') unload.add(fn);
},
removeEventListener(name, fn) {
if (name === 'beforeunload') unload.delete(fn);
},
};
const mocks = {
react: {
useRef(value) {
const i = cursor++;
cells[i] ??= { current: value };
return cells[i];
},
useState(value) {
const i = cursor++;
if (!(i in cells))
cells[i] = typeof value === 'function' ? value() : value;
return [
cells[i],
(value) => {
cells[i] =
typeof value === 'function'
? value(cells[i])
: value;
},
];
},
useEffect(callback, deps) {
const i = cursor++;
if (
!cells[i] ||
!deps.every((v, j) => v === cells[i].deps[j])
) {
cells[i]?.cleanup?.();
cells[i] = { deps };
effects.push(() => {
const original = globalThis.window;
globalThis.window = windowMock;
try {
cells[i].cleanup = callback();
} finally {
globalThis.window = original;
}
});
}
},
},
'@inertiajs/react': {
Link: 'a',
router: {
reload(options) {
reloads.push(options);
},
on(name, callback) {
if (name === 'before') before.add(callback);
return () => before.delete(callback);
},
},
useForm(initial) {
const i = formCursor++;
forms[i] ??= {
data: clone(initial),
errors: {},
processing: false,
setData(key, value) {
this.data =
typeof key === 'function'
? key(this.data)
: typeof key === 'object'
? key
: { ...this.data, [key]: value };
},
setDefaults(value) {
this.defaults = clone(value);
},
clearErrors() {
this.errors = {};
},
transform(callback) {
this.transformer = callback;
},
post(url, options) {
sent.push({
method: 'post',
url,
options,
data: clone(this.transformer(this.data)),
});
},
put(url, options) {
sent.push({
method: 'put',
url,
options,
data: clone(this.transformer(this.data)),
});
},
};
return forms[i];
},
},
'@/lib/operation-key': {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++operationSequence).padStart(12, '0')}`,
},
'./shared': {
Frame: 'main',
Field: 'label',
Errors: 'errors',
control: '',
button: '',
},
'@/pages/partnerships/shared': {
labels: {
draft: 'Rascunho',
submitted: 'Submetida',
published: 'Publicada',
archived: 'Arquivada',
},
},
};
const actual = load('../../resources/js/lib/partnership-edit.ts', mocks);
mocks['@/lib/partnership-edit'] = {
usePartnershipEdit(p) {
editor = actual.usePartnershipEdit(p);
return editor;
},
};
const Panel = load(
'../../resources/js/components/partnership-edit-comparison.tsx',
mocks,
).default;
mocks['@/components/partnership-edit-comparison'] = { default: Panel };
const Page = load(
'../../resources/js/pages/partnerships/editor.tsx',
mocks,
).default;
function render(next = currentProps) {
const original = globalThis.window;
globalThis.window = windowMock;
try {
currentProps = next;
const root = Page(next);
if (initialized && root.key !== currentKey) {
for (const cell of cells) cell?.cleanup?.();
cells = [];
forms = [];
}
currentKey = root.key;
initialized = true;
cursor = 0;
formCursor = 0;
tree = root.type(root.props);
while (effects.length) effects.shift()();
return editor;
} finally {
globalThis.window = original;
}
}
render();
return {
sent,
reloads,
render,
get edit() {
return editor;
},
get data() {
return editor.form.data;
},
all: () => nodes(tree),
panel: () => Panel({ editor, catalogues: currentProps }),
set(key, value) {
editor.setData(key, value);
render();
},
payload(key, value) {
editor.setData('payload', {
...editor.form.data.payload,
[key]: value,
});
render();
},
success(index, next) {
render(next);
sent[index].options.onSuccess({ props: next });
render();
},
before(preserveState = false) {
let prevented = false;
const original = globalThis.window;
globalThis.window = windowMock;
try {
for (const fn of before)
fn({
detail: { visit: { method: 'get', preserveState } },
preventDefault() {
prevented = true;
},
});
} finally {
globalThis.window = original;
}
return prevented;
},
unload() {
let prevented = false;
for (const fn of unload)
fn({
preventDefault() {
prevented = true;
},
returnValue: null,
});
return prevented;
},
get confirmCalls() {
return confirmCalls;
},
};
}
test('availability is presented and sent independently from the deadline', () => {
const h = harness();
assert.equal(
h.data.payload.availability,
'SYNTHETIC November availability',
);
const availability = h
.all()
.find(
(n) =>
n.type === 'textarea' &&
n.props.value === 'SYNTHETIC November availability',
);
assert.equal(availability.props.maxLength, 1000);
h.payload('availability', 'SYNTHETIC December resources');
h.edit.save();
assert.equal(
h.sent[0].data.payload.availability,
'SYNTHETIC December resources',
);
assert.equal(h.sent[0].data.deadline, '');
});
test('refreshing another version preserves edits and merges independent fields only after adoption', () => {
const h = harness();
h.set('title', 'SYNTHETIC deliberate title');
const next = props();
next.record.version = 3;
next.record.payload.availability = 'SYNTHETIC remote availability';
h.render(next);
assert.equal(h.data.title, 'SYNTHETIC deliberate title');
h.edit.save();
assert.equal(h.sent.length, 0);
assert.deepEqual(h.edit.unresolved, []);
h.edit.adopt();
h.render();
assert.equal(h.data.payload.availability, 'SYNTHETIC remote availability');
assert.equal(h.data.title, 'SYNTHETIC deliberate title');
assert.equal(h.data.version, 3);
});
test('choices for multiple conflicting sections are explicit and independent', () => {
const h = harness();
h.set('title', 'mine');
h.payload('availability', 'my availability');
const next = props();
next.record.version = 3;
next.record.title = 'remote';
next.record.payload.availability = 'remote availability';
h.render(next);
assert.equal(h.edit.unresolved.length, 2);
h.edit.choose('title', 'mine');
h.render();
h.edit.choose('availability', 'current');
h.render();
assert.deepEqual(h.edit.unresolved, []);
h.edit.adopt();
h.render();
assert.equal(h.data.title, 'mine');
assert.equal(h.data.payload.availability, 'remote availability');
});
test('returning deliberately to the original text does not count as permission to overwrite it', () => {
const h = harness();
h.set('title', 'temporary');
h.set('title', 'SYNTHETIC original');
const next = props();
next.record.version = 3;
next.record.title = 'remote';
h.render(next);
assert.deepEqual(h.edit.unresolved, ['title']);
assert.equal(h.edit.dirty, true);
h.edit.choose('title', 'mine');
h.render();
h.edit.adopt();
h.render();
assert.equal(h.data.title, 'SYNTHETIC original');
});
test('sets ignore database order while locations, origins and criteria keep their own conflicts', () => {
const initial = props({
origins: [
{ type: 'project', target_id: 'a' },
{ type: 'project', target_id: 'b' },
],
locations: [
{
geo_location_id: 'place',
role: 'primary',
source_reference: 'SYNTHETIC original reference',
},
],
});
const h = harness(initial);
h.payload('mandatory', ['capacity', 'impact']);
const next = clone(initial);
next.record.version = 3;
next.origins.reverse();
next.locations[0].source_reference = 'SYNTHETIC current source';
next.record.payload.mandatory = ['experience'];
h.render(next);
assert.ok(!h.edit.changed.includes('origins'));
assert.deepEqual(h.edit.unresolved, ['mandatory']);
h.edit.choose('mandatory', 'mine');
h.render();
h.edit.adopt();
h.render();
assert.deepEqual(h.data.payload.mandatory, ['capacity', 'impact']);
assert.equal(
h.data.locations[0].source_reference,
'SYNTHETIC current source',
);
});
test('success uses normalized server values while preserving typing during the request', () => {
const h = harness();
h.set('title', ' SYNTHETIC saved title ');
h.edit.save();
h.set('offer', 'SYNTHETIC after send');
const next = saved(h.sent[0].data);
h.success(0, next);
assert.equal(h.data.title, 'SYNTHETIC saved title');
assert.equal(h.data.offer, 'SYNTHETIC after send');
assert.equal(h.data.version, 3);
assert.equal(h.edit.dirty, true);
});
test('new creation becomes the same editor with an assigned identity without losing in-flight edits', () => {
const h = harness(props({ record: null }));
h.set('title', 'SYNTHETIC first draft');
h.edit.save();
h.set('title', 'SYNTHETIC typed during creation');
h.success(0, saved(h.sent[0].data, { id: 73, version: 2 }));
assert.equal(h.data.title, 'SYNTHETIC typed during creation');
h.edit.save();
assert.equal(h.sent[1].method, 'put');
assert.equal(h.sent[1].url, '/parcerias/73');
assert.equal(h.sent[1].data.version, 2);
});
test('an unconfirmed creation repeats the exact original command and keeps edits made before retry', () => {
const h = harness(props({ record: null }));
h.set('title', 'SYNTHETIC original command');
h.edit.save();
h.sent[0].options.onNetworkError(new Error('synthetic timeout'));
h.render();
h.set('title', 'SYNTHETIC later draft');
h.edit.save();
assert.deepEqual(h.sent[1].data, h.sent[0].data);
h.success(1, saved(h.sent[1].data, { id: 74, version: 2 }));
assert.equal(h.data.title, 'SYNTHETIC later draft');
h.edit.save();
assert.equal(h.sent[2].url, '/parcerias/74');
assert.equal(h.sent[2].data.title, 'SYNTHETIC later draft');
});
test('a version conflict is handled without discarding fields or showing a generic HTTP modal', () => {
const h = harness();
h.set('title', 'draft');
h.edit.save();
assert.equal(h.sent[0].options.onHttpException({ status: 409 }), false);
h.render();
assert.equal(h.edit.blocked, true);
h.edit.save();
assert.equal(h.sent.length, 1);
h.edit.refresh();
assert.deepEqual(h.reloads[0].only, [
'record',
'locations',
'origins',
'editorActorId',
'saveCommands',
]);
h.reloads[0].onSuccess({ props: props() });
h.reloads[0].onFinish();
h.render();
assert.equal(h.data.title, 'draft');
assert.equal(h.edit.blocked, false);
});
test('submitted or archived proposals preserve the draft but disable writing in the existing workflow', () => {
for (const status of ['submitted', 'archived']) {
const h = harness();
h.set('title', 'unsaved');
const next = props();
next.record.version = 3;
next.record.status = status;
h.render(next);
assert.equal(h.data.title, 'unsaved');
assert.equal(h.edit.editable, false);
assert.equal(
h.all().find((n) => n.type === 'fieldset').props.disabled,
true,
);
h.edit.save();
assert.equal(h.sent.length, 0);
assert.match(text(h.panel()), /não pode ser gravada neste estado/);
}
});
test('a newer server revision after saving requires comparison instead of acknowledging another persons edits', () => {
const h = harness();
h.set('title', 'SYNTHETIC sent');
h.edit.save();
h.set('offer', 'SYNTHETIC in flight');
const next = saved(h.sent[0].data, { version: 4 });
next.record.title = 'SYNTHETIC another author';
h.success(0, next);
assert.equal(h.data.title, 'SYNTHETIC sent');
assert.equal(h.data.offer, 'SYNTHETIC in flight');
assert.equal(h.edit.blocked, true);
assert.ok(h.edit.changed.includes('title'));
assert.ok(!h.edit.unresolved.includes('title'));
h.edit.adopt();
h.render();
assert.equal(h.data.version, 4);
assert.equal(h.data.title, 'SYNTHETIC another author');
assert.equal(h.data.offer, 'SYNTHETIC in flight');
});
test('unsaved navigation and unload are protected while a preserving refresh stays available', () => {
const h = harness();
assert.equal(h.unload(), false);
h.set('title', 'dirty');
assert.equal(h.unload(), true);
assert.equal(h.before(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.before(true), false);
h.edit.save();
h.success(0, saved(h.sent[0].data));
assert.equal(h.unload(), false);
assert.equal(h.before(), false);
});
test('wrong or malformed responses cannot reset or submit another record', () => {
const h = harness();
h.set('title', 'draft');
h.edit.save();
const wrong = saved(h.sent[0].data, { id: 99 });
h.success(0, wrong);
assert.equal(h.data.title, 'draft');
assert.equal(h.edit.invalid, true);
h.edit.save();
assert.equal(h.sent.length, 1);
const invalid = harness();
const bad = props();
bad.record.version = '3';
invalid.render(bad);
assert.equal(invalid.edit.invalid, true);
invalid.edit.save();
assert.equal(invalid.sent.length, 0);
});
test('published revision impact and an unavailable prior sector are visible without silently changing values', () => {
const initial = props();
initial.record.status = 'published';
initial.record.sector_id = 99;
const h = harness(initial);
assert.match(text(h.panel()), /volta a rascunho/);
assert.match(text(h.panel()), /nova submissão e revisão/);
assert.ok(
h.all().some((n) => n.type === 'option' && n.props.value === '99'),
);
assert.equal(h.data.sector_id, '99');
assert.ok(
h
.all()
.some(
(n) =>
n.type === 'button' &&
text(n).includes('Guardar revisão em rascunho'),
),
);
});
test('comparison actions cannot accidentally submit the form', () => {
const h = harness();
h.set('title', 'mine');
const next = props();
next.record.version = 3;
next.record.title = 'remote';
h.render(next);
const buttons = nodes(h.panel()).filter((n) => n.type === 'button');
assert.ok(buttons.every((n) => n.props.type === 'button'));
assert.equal(buttons.at(-1).props.disabled, true);
assert.match(text(h.panel()), /Actualmente guardado/);
});
test('batched payload edits and removals preserve all deliberate changes', () => {
const h = harness(
props({
locations: [
{
geo_location_id: 'place-a',
role: 'primary',
source_reference: 'SYNTHETIC a',
},
{
geo_location_id: 'place-b',
role: 'coverage',
source_reference: 'SYNTHETIC b',
},
],
origins: [
{ type: 'project', target_id: 'a' },
{ type: 'project', target_id: 'b' },
],
}),
);
h.edit.setData('payload', (previous) => ({
...previous,
summary: 'SYNTHETIC first change',
}));
h.edit.setData('payload', (previous) => ({
...previous,
availability: 'SYNTHETIC second change',
}));
h.render();
assert.equal(h.data.payload.summary, 'SYNTHETIC first change');
assert.equal(h.data.payload.availability, 'SYNTHETIC second change');
const remove = h
.all()
.filter((node) => node.type === 'button' && text(node) === 'Remover');
assert.equal(remove.length, 4);
for (const button of remove) button.props.onClick();
h.render();
assert.deepEqual(h.data.locations, []);
assert.deepEqual(h.data.origins, []);
});
+237
View File
@@ -0,0 +1,237 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
const require = createRequire(import.meta.url);
const sharedText = fs.readFileSync(
'resources/js/pages/partnerships/shared.tsx',
'utf8',
);
const labelSource = sharedText.match(
/export const labels: Record<string, string> = (\{[\s\S]*?\n\});/,
)[1];
const labels = compileFunction(`return (${labelSource});`, [])();
function load(file) {
const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(source, ['require', 'module', 'exports'])(
(id) => {
if (id === './shared')
return {
Frame: ({ title, children }) =>
React.createElement(
'main',
{},
React.createElement('h1', {}, title),
children,
),
labels,
};
if (id === '@inertiajs/react')
return {
Link: ({ children, ...props }) =>
React.createElement('a', props, children),
router: {},
};
return require(id);
},
module,
module.exports,
);
return module.exports.default;
}
const Page = load('resources/js/pages/partnerships/interest-history.tsx');
const Dashboard = load('resources/js/pages/partnerships/dashboard.tsx');
const snapshot = () => ({
availability: 'available',
version: 1,
status: 'submitted',
scope_known: true,
organization_id: null,
fields: { proposal: 'SYNTHETIC proposal', capacity: null },
consent_known: true,
consent: false,
assessment_recorded: true,
assessment: [],
references: [],
complete: true,
});
const entry = () => ({
version: 2,
restricted: false,
action: 'assess',
actor_name: 'SYNTHETIC owner',
occurred_at: '2026-11-03',
reason: 'SYNTHETIC reason',
previous: snapshot(),
after: snapshot(),
partnership_version: 4,
matching: {
score_min: 0,
score_max: 0,
eligibility: 'unknown',
algorithm_version: 'synthetic-v1',
weights_hash: 'synthetic-hash',
unknown_weight: 0,
criteria: [
{
code: 'capacity',
label: 'SYNTHETIC frozen label',
weight: 20,
mandatory: true,
state: 'unknown',
evidence: 'SYNTHETIC frozen evidence',
explanation: 'SYNTHETIC frozen explanation',
},
],
},
});
const props = () => ({
candidacy_id: 10,
entries: [entry()],
next_url: null,
first_url: '/parcerias/candidaturas/10/historico',
older_page: false,
partnership_href: null,
dashboard_href: '/parcerias/painel',
});
const render = (p = props()) =>
renderToStaticMarkup(React.createElement(Page, p));
test('history renders frozen decision parameters, including valid zero scores', () => {
const html = render();
for (const value of [
'0–0%',
'Peso: 20',
'Obrigatório',
'SYNTHETIC frozen label',
'SYNTHETIC frozen evidence',
'SYNTHETIC frozen explanation',
'synthetic-v1',
'synthetic-hash',
])
assert.ok(html.includes(value), value);
assert.ok(!html.includes('Por determinar'));
});
test('missing frozen scores and obligations remain unknown instead of false or zero', () => {
const p = props();
p.entries[0].matching.score_min = null;
p.entries[0].matching.criteria[0].mandatory = null;
p.entries[0].matching.criteria[0].weight = null;
const html = render(p);
assert.ok(html.includes('Por determinar'));
assert.ok(html.includes('Obrigatoriedade não registada'));
assert.ok(!html.includes('0–0%'));
assert.ok(!html.includes('Não obrigatório'));
});
test('old incomplete events are explicit and never supplied from a current proposal', () => {
const p = props();
p.entries[0].after = {
availability: 'available',
complete: false,
fields: [],
assessment: [],
assessment_recorded: false,
scope_known: false,
};
p.entries[0].matching = null;
p.entries[0].action = null;
const html = render(p);
for (const value of [
'Registo parcial',
'Não consta do registo',
'Âmbito não registado',
'Não foi recalculado',
'Alteração registada',
])
assert.ok(html.includes(value), value);
});
test('missing and intentionally empty fields or consent are distinguished', () => {
const html = render();
assert.match(html, /Capacidade disponível<\/dt><dd[^>]*>Não indicado/);
assert.match(
html,
/Contribuição proposta<\/dt><dd[^>]*>Não consta do registo/,
);
assert.ok(html.includes('Não autorizada'));
assert.ok(html.includes('Sem critérios avaliados nesta versão'));
});
test('restricted scope and missing legacy scope have different explanations', () => {
const p = props();
p.entries = [
{
...entry(),
restricted: true,
previous: { availability: 'restricted' },
after: { availability: 'scope_unknown' },
matching: null,
actor_name: null,
reason: null,
},
];
const html = render(p);
assert.ok(html.includes('Conteúdo reservado'));
assert.ok(html.includes('acesso actual'));
assert.ok(html.includes('âmbito desta versão antiga'));
assert.ok(!html.includes('SYNTHETIC owner'));
assert.ok(!html.includes('SYNTHETIC proposal'));
assert.ok(!html.includes('Correspondência guardada'));
});
test('read-only page has no write or restore controls and uses only supplied cursor navigation', () => {
const p = props();
p.next_url = '/parcerias/candidaturas/10/historico?before=opaque%2Btoken';
p.older_page = true;
const html = render(p);
assert.ok(html.includes('before=opaque%2Btoken'));
assert.ok(html.includes('Versões mais recentes'));
assert.ok(!/<(?:form|button|input|select|textarea)\b/.test(html));
assert.ok(!html.includes('Consultar parceria'));
p.partnership_href = '/parcerias/1';
assert.ok(render(p).includes('href="/parcerias/1"'));
});
test('saved user text is escaped and current catalogue names are identified', () => {
const p = props();
p.entries[0].after.fields.proposal = '<script>synthetic()</script>';
p.entries[0].after.assessment = [
{
code: 'capacity',
label: 'SYNTHETIC current catalogue',
state: 'unknown',
evidence: 'SYNTHETIC recorded evidence',
},
];
const html = render(p);
assert.ok(!html.includes('<script>'));
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(html.includes('catálogo actual'));
assert.ok(html.includes('cadastro actual'));
assert.ok(html.includes('SYNTHETIC recorded evidence'));
});
test('candidate dashboard links directly to each history without relying on proposal publication', () => {
const html = renderToStaticMarkup(
React.createElement(Dashboard, {
mine: [],
interests: [
{
id: 10,
partnership_id: 1,
title: 'SYNTHETIC',
status: 'withdrawn',
room_id: null,
},
],
moderation: [],
notifications: [],
}),
);
assert.ok(html.includes('href="/parcerias/candidaturas/10/historico"'));
assert.ok(html.includes('Consultar versões e decisões'));
});
@@ -0,0 +1,149 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
participant,
props,
original,
nodes,
text,
} from './helpers/partnership-room.mjs';
test('new milestone selects named current representatives explicitly and submits the selected person', () => {
const h = harness();
assert.equal(
h.field('milestone:new', 'Responsável pelo marco').props.value,
'',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:new')).props.disabled,
true,
);
assert.match(
text(h.field('milestone:new', 'Responsável pelo marco')),
/SYNTHETIC authorised officer — Proponente/,
);
h.change('milestone:new', 'Responsável pelo marco', '4');
assert.equal(
h.button('Guardar marco', h.form('milestone:new')).props.disabled,
false,
);
const request = h.submit('milestone:new');
assert.equal(request.url, '/parcerias/salas/10/marcos');
assert.equal(request.data.responsible_id, '4');
});
test('a revoked original assignment stays visible and requires explicit replacement', () => {
const h = harness(
props({
milestones: [{ ...original, responsible_is_participant: false }],
participants: [participant(4, 'SYNTHETIC current officer')],
}),
);
const select = h.field('milestone:7', 'Responsável pelo marco');
assert.equal(select.props.value, '1');
const historical = nodes(select).find(
(node) => node.type === 'option' && node.props.value === '1',
);
assert.equal(historical.props.disabled, true);
assert.match(
text(historical),
/SYNTHETIC original author — sem representação actual/,
);
assert.match(
text(h.form('milestone:7')),
/consultar não altera o responsável/,
);
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
true,
);
h.change('milestone:7', 'Responsável pelo marco', '4');
const request = h.submit('milestone:7');
assert.equal(request.method, 'put');
assert.equal(request.data.version, 3);
assert.equal(request.data.responsible_id, '4');
});
test('read only, negotiation and terminal rooms keep names/history and expose no clean milestone form', () => {
for (const status of ['negotiation', 'closed', 'cancelled']) {
const h = harness(
props({
room: { id: 10, version: 3, status, agreement: null },
milestones: [original],
participants: [],
}),
);
assert.equal(h.form('milestone:7'), undefined);
assert.equal(h.form('milestone:new'), undefined);
assert.match(text(h.tree), /Responsável: SYNTHETIC original author/);
assert.doesNotMatch(text(h.tree), /Responsável ID/);
}
const readOnly = harness(
props({ canWrite: false, milestones: [original], participants: [] }),
);
assert.equal(readOnly.form('milestone:7'), undefined);
});
test('current assignment remains selected and person representing both parties appears once', () => {
const h = harness(
props({
milestones: [original],
participants: [
participant(1, 'SYNTHETIC dual representative', [
'proponent',
'candidate',
]),
],
}),
);
const select = h.field('milestone:7', 'Responsável pelo marco');
assert.equal(select.props.value, '1');
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
false,
);
assert.equal(
nodes(select).filter(
(node) => node.type === 'option' && node.props.value === '1',
).length,
1,
);
assert.match(text(select), /Proponente \/ Candidato/);
});
test('refreshed participant choices invalidate a cached selection without silently changing it', () => {
const h = harness();
h.change('milestone:new', 'Responsável pelo marco', '4');
h.render({
...h.props,
participants: [participant(2, 'SYNTHETIC candidate', ['candidate'])],
});
assert.equal(
h.field('milestone:new', 'Responsável pelo marco').props.value,
'4',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:new')).props.disabled,
true,
);
assert.match(
text(h.form('milestone:new')),
/participante seleccionado deixou de estar disponível/,
);
h.submit('milestone:new');
assert.equal(h.sent.length, 0);
});
test('missing historical name is reported without asking for an account identifier', () => {
const h = harness(
props({
canWrite: false,
milestones: [
{
...original,
responsible_name: null,
responsible_is_participant: false,
},
],
participants: [],
}),
);
assert.match(text(h.tree), /Responsável registado indisponível/);
assert.match(text(h.tree), /atribuição anterior conservada/);
assert.doesNotMatch(text(h.tree), /Responsável ID/);
});
@@ -0,0 +1,269 @@
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 ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import {
harness,
props as detailProps,
nodes,
} from './helpers/partnership-candidacy.mjs';
const require = createRequire(import.meta.url);
const historyModule = {};
compileFunction(
ts.transpileModule(
fs.readFileSync('resources/js/lib/partnership-history.ts', 'utf8'),
{ compilerOptions: { module: ts.ModuleKind.CommonJS } },
).outputText,
['exports'],
)(historyModule);
const labels = compileFunction(
`return (${fs.readFileSync('resources/js/pages/partnerships/shared.tsx', 'utf8').match(/export const labels: Record<string, string> = (\{[\s\S]*?\n\});/)[1]});`,
[],
)();
function load(file) {
const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
const module = { exports: {} };
compileFunction(source, ['require', 'module', 'exports'])(
(id) => {
if (id === '@/lib/partnership-history') return historyModule;
if (id === './shared')
return {
Frame: ({ title, children }) =>
React.createElement(
'main',
{},
React.createElement('h1', {}, title),
children,
),
labels,
};
if (id === '@inertiajs/react')
return {
Link: ({ children, ...p }) =>
React.createElement('a', p, children),
router: {},
};
return require(id);
},
module,
module.exports,
);
return module.exports.default;
}
const Page = load('resources/js/pages/partnerships/publication-history.tsx'),
Dashboard = load('resources/js/pages/partnerships/dashboard.tsx');
const snapshot = () => ({
availability: 'available',
version: 2,
status: 'draft',
scope_known: true,
organization_id: null,
fields: {
title: 'SYNTHETIC frozen title',
offer: 'SYNTHETIC frozen offer',
kind: 'seeking',
confidentiality: 'private',
deadline: null,
},
sector_recorded: true,
sector_id: '19',
consent_known: true,
consent: false,
mandatory_known: true,
mandatory: [],
origins_recorded: true,
origins: [{ type: 'project', target_id: 'synthetic-project-id' }],
locations_recorded: true,
locations: [
{
geo_location_id: 'synthetic-location-id',
role: 'coverage',
source_reference: 'SYNTHETIC recorded source',
},
],
complete: true,
});
const entry = () => ({
version: 3,
restricted: false,
action: 'edit',
actor_name: 'SYNTHETIC actor',
occurred_at: '2026-11-03',
reason: null,
previous: snapshot(),
after: {
...snapshot(),
version: 3,
fields: { ...snapshot().fields, title: 'SYNTHETIC changed title' },
},
});
const props = () => ({
partnership_id: 1,
entries: [entry()],
first_url: '/parcerias/1/historico',
next_url: null,
older_page: false,
partnership_href: '/parcerias/1',
dashboard_href: '/parcerias/painel',
});
const render = (p) => renderToStaticMarkup(React.createElement(Page, p));
test('publication history compares saved before and after values with recorded references', () => {
const html = render(props());
for (const value of [
'SYNTHETIC frozen title',
'SYNTHETIC changed title',
'SYNTHETIC frozen offer',
'SYNTHETIC recorded source',
'synthetic-project-id',
'synthetic-location-id',
'Edição do rascunho',
'Antes da alteração',
'Após a alteração',
])
assert.ok(html.includes(value), value);
assert.ok(!html.includes('href="synthetic-project-id"'));
});
test('empty values consent and source lists are distinct from absent or malformed records', () => {
const p = props();
p.entries[0].after.fields.offer = '';
p.entries[0].after.origins = [];
p.entries[0].previous.origins = [];
p.entries[0].previous.origins_incomplete = true;
p.entries[0].previous.complete = false;
const html = render(p);
assert.match(html, /O que oferece<\/dt><dd[^>]*>Não indicado/);
assert.match(html, /Requisitos<\/dt><dd[^>]*>Não consta do registo/);
assert.ok(html.includes('Não autorizada'));
assert.ok(html.includes('Sem critérios obrigatórios nesta versão'));
assert.ok(html.includes('Há referências incompletas'));
assert.ok(html.includes('Sem origens ligadas nesta versão'));
});
test('scope restriction and unknown historical identity are explained without actor or reason disclosure', () => {
const p = props();
p.entries = [
{
...entry(),
restricted: true,
actor_name: null,
reason: null,
previous: { availability: 'restricted' },
after: { availability: 'scope_unknown' },
},
];
const html = render(p);
assert.ok(html.includes('Conteúdo reservado'));
assert.ok(html.includes('acesso actual'));
assert.ok(html.includes('identidade desta versão antiga'));
assert.ok(!html.includes('SYNTHETIC actor'));
assert.ok(!html.includes('SYNTHETIC frozen title'));
});
test('legacy partial states do not imply personal scope or current proposal content', () => {
const p = props();
p.entries[0] = {
...entry(),
action: null,
previous: { availability: 'not_recorded' },
after: {
availability: 'available',
complete: false,
scope_known: false,
status: 'returned',
fields: [],
origins_recorded: false,
locations_recorded: false,
},
};
const html = render(p);
for (const value of [
'Alteração registada',
'Registo parcial',
'Âmbito não registado',
'Não constam do registo',
])
assert.ok(html.includes(value), value);
assert.ok(!html.includes('Em nome pessoal'));
assert.ok(!html.includes('SYNTHETIC changed title'));
});
test('read-only navigation uses opaque cursors without restoration or publication commands', () => {
const p = props();
p.older_page = true;
p.next_url = '/parcerias/1/historico?before=opaque%2Bcursor';
const html = render(p);
assert.ok(html.includes('before=opaque%2Bcursor'));
assert.ok(html.includes('Versões mais recentes'));
assert.ok(!/<(?:form|button|input|select|textarea)\b/.test(html));
assert.ok(!html.includes('/estado'));
});
test('stored text is escaped and current registry names are explicitly identified', () => {
const p = props();
p.entries[0].after.fields.offer = '<script>synthetic()</script>';
p.entries[0].reason = '<b>synthetic reason</b>';
const html = render(p);
assert.ok(!html.includes('<script>'));
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(html.includes('&lt;b&gt;synthetic reason&lt;/b&gt;'));
assert.ok(html.includes('cadastro actual'));
assert.ok(html.includes('não restaura nem volta a publicar'));
});
test('actual proposal detail offers owner history without erasing prepared publication reason', () => {
const h = harness(
detailProps({
owner: true,
canEdit: true,
publicationActions: ['archive'],
}),
);
const field = nodes(h.tree).find(
(n) => n.type === 'label' && n.props.label === 'Motivo da ação',
);
nodes(field)
.find((n) => n.type === 'textarea')
.props.onChange({ target: { value: 'SYNTHETIC unsent reason' } });
h.render();
assert.ok(
nodes(h.tree).some((n) => n.props?.href === '/parcerias/1/historico'),
);
assert.equal(h.leave(), true);
const publicDetail = harness(
detailProps({ owner: false, moderator: false }),
);
assert.ok(
!nodes(publicDetail.tree).some(
(n) => n.props?.href === '/parcerias/1/historico',
),
);
});
test('dashboard links own and moderation proposals to history without granting a candidate that link', () => {
const html = renderToStaticMarkup(
React.createElement(Dashboard, {
mine: [{ id: 1, title: 'SYNTHETIC mine', status: 'archived' }],
moderation: [
{ id: 2, title: 'SYNTHETIC pending', status: 'submitted' },
],
interests: [
{
id: 10,
partnership_id: 3,
title: null,
partnership_href: null,
status: 'submitted',
room_id: null,
},
],
notifications: [],
}),
);
assert.ok(html.includes('href="/parcerias/1/historico"'));
assert.ok(html.includes('href="/parcerias/2/historico"'));
assert.ok(!html.includes('href="/parcerias/3/historico"'));
assert.ok(html.includes('href="/parcerias/candidaturas/10/historico"'));
});
@@ -0,0 +1,244 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
text,
nodes,
} from './helpers/partnership-candidacy.mjs';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { compileFunction } from 'node:vm';
import ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
test('detail presents the publication decision using business language', () => {
const h = harness(
props({
owner: true,
historySummary: {
limit: 5,
has_more: false,
href: '/parcerias/1/historico',
entries: [
{
version: 5,
restricted: false,
action: 'edit',
actor_name: 'SYNTHETIC editor',
occurred_at: '2026-11-03',
reason: 'SYNTHETIC reviewed content',
status_before: 'draft',
status_after: 'draft',
},
],
},
}),
);
assert.match(text(h.tree), /Edição do rascunho/);
});
const entry = () => ({
version: 4,
restricted: false,
action: 'edit',
actor_name: 'SYNTHETIC editor',
occurred_at: '2026-11-03',
reason: 'SYNTHETIC saved reason',
status_before: 'draft',
status_after: 'draft',
});
const summary = () => ({
limit: 5,
has_more: false,
href: '/parcerias/1/historico',
entries: [entry()],
});
const section = (h) =>
nodes(h.tree).find(
(node) => node.props?.['aria-label'] === 'Histórico e decisões',
);
const reasonField = (h) =>
nodes(
nodes(h.tree).find(
(node) =>
node.type === 'label' && node.props.label === 'Motivo da ação',
),
).find((node) => node.type === 'textarea');
test('reserved metadata never renders even if extra private fields are supplied', () => {
const value = summary();
value.entries[0] = {
...entry(),
restricted: true,
actor_name: 'SYNTHETIC PRIVATE actor',
occurred_at: 'SYNTHETIC PRIVATE date',
reason: 'SYNTHETIC PRIVATE reason',
action: 'publish',
status_before: 'SYNTHETIC PRIVATE state',
status_after: 'published',
actor_id: 999999,
};
const h = harness(props({ owner: true, historySummary: value }));
assert.match(text(section(h)), /Conteúdo reservado/);
assert.doesNotMatch(text(section(h)), /PRIVATE|999999|Publicação/);
});
test('public and candidate details do not display a supplied private summary or its history link', () => {
const h = harness(
props({ owner: false, moderator: false, historySummary: summary() }),
);
assert.equal(section(h), undefined);
assert.equal(
nodes(h.tree).some(
(node) => node.props?.href === '/parcerias/1/historico',
),
false,
);
assert.doesNotMatch(text(h.tree), /SYNTHETIC saved reason/);
});
test('empty and limited summaries explain their scope and have only one complete-history link', () => {
const value = { ...summary(), entries: [] };
const h = harness(props({ owner: true, historySummary: value }));
assert.match(text(section(h)), /Ainda não existem alterações guardadas/);
assert.doesNotMatch(text(section(h)), /Existem alterações anteriores/);
assert.equal(
nodes(h.tree).filter((node) => node.props?.href === value.href).length,
1,
);
h.render({
...h.props,
historySummary: { ...summary(), limit: 1, has_more: true },
});
assert.match(text(section(h)), /Até 1 alteração mais recente/);
assert.match(text(section(h)), /Existem alterações anteriores/);
assert.equal(
nodes(h.tree).filter((node) => node.props?.href === value.href).length,
1,
);
});
test('legacy unknown actions and states are not presented as technical identifiers or inferred decisions', () => {
const value = summary();
value.entries[0] = {
...entry(),
version: null,
action: 'partnership_opportunity.changed.v1',
status_before: null,
status_after: 'legacy_internal_status_v2',
actor_name: null,
occurred_at: null,
reason: null,
actor_id: 999999,
};
const h = harness(props({ owner: true, historySummary: value }));
assert.match(text(section(h)), /Versão não registada/);
assert.match(text(section(h)), /Alteração registada/);
assert.match(text(section(h)), /Autor não registado/);
assert.match(text(section(h)), /Estado não identificado/);
assert.doesNotMatch(
text(section(h)),
/partnership_opportunity|legacy_internal|999999/,
);
});
test('refreshing the summary keeps the prepared publication reason and the existing leave guard', () => {
const h = harness(
props({
owner: true,
canEdit: true,
publicationActions: ['submit', 'archive'],
record: { ...props().record, status: 'draft' },
historySummary: summary(),
}),
);
reasonField(h).props.onChange({
target: { value: 'SYNTHETIC unsent decision reason' },
});
h.render();
h.click('Comparar com a proposta actual');
assert.ok(h.reloads.at(-1).only.includes('historySummary'));
h.refreshed({
...h.props,
historySummary: { ...summary(), has_more: true },
});
h.click('Comparar com os dados actuais da candidatura');
for (const key of [
'historySummary',
'moderator',
'publicationActions',
'publicationCommands',
])
assert.ok(h.reloads.at(-1).only.includes(key), key);
h.refreshed({ ...h.props, historySummary: summary() });
assert.equal(
reasonField(h).props.value,
'SYNTHETIC unsent decision reason',
);
assert.equal(h.leave(), true);
assert.equal(h.sent.length, 0);
assert.equal(
nodes(h.tree).filter(
(node) => node.props?.href === '/parcerias/1/historico',
).length,
1,
);
});
test('summary strings are escaped by the actual React component', () => {
const require = createRequire(import.meta.url);
const modules = {};
const labels = compileFunction(
`return (${fs.readFileSync('resources/js/pages/partnerships/shared.tsx', 'utf8').match(/export const labels: Record<string, string> = (\{[\s\S]*?\n\});/)[1]});`,
[],
)();
function load(file) {
const module = { exports: {} };
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(id) =>
modules[id] ??
(id === '@inertiajs/react'
? {
Link: ({ children, ...p }) =>
React.createElement('a', p, children),
}
: id === '@/pages/partnerships/shared'
? { labels }
: require(id)),
module,
module.exports,
);
return module.exports;
}
modules['@/lib/partnership-history'] = load(
'resources/js/lib/partnership-history.ts',
);
const Component = load(
'resources/js/components/partnership-publication-summary.tsx',
).default;
const value = summary();
value.entries[0].reason = '<script>SYNTHETIC</script>';
value.entries[0].actor_name = '<a>SYNTHETIC actor</a>';
const html = renderToStaticMarkup(
React.createElement(Component, { value }),
);
assert.ok(html.includes('&lt;script&gt;SYNTHETIC&lt;/script&gt;'));
assert.ok(html.includes('&lt;a&gt;SYNTHETIC actor&lt;/a&gt;'));
assert.doesNotMatch(html, /<script>|<a>SYNTHETIC/);
});
test('losing the owner or moderator context hides a stale summary without exposing its metadata', () => {
const h = harness(props({ moderator: true, historySummary: summary() }));
assert.ok(section(h));
h.render({ ...h.props, moderator: false, owner: false });
assert.equal(section(h), undefined);
assert.doesNotMatch(text(h.tree), /SYNTHETIC saved reason/);
});
@@ -0,0 +1,267 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
nodes,
text,
} from './helpers/partnership-candidacy.mjs';
const reason = (h) =>
nodes(h.tree).find(
(node) =>
node.type === 'label' && node.props.label === 'Motivo da ação',
)?.props.children;
const field = (h) => nodes(reason(h)).find((node) => node.type === 'textarea');
test('publication reason survives a proposal version refresh', () => {
const p = props({
owner: true,
canEdit: true,
record: { ...props().record, status: 'draft' },
publicationActions: ['submit', 'archive'],
publicationCommands: [],
});
const h = harness(p);
field(h).props.onChange({ target: { value: 'SYNTHETIC prepared reason' } });
h.render();
h.render({ ...p, record: { ...p.record, version: p.record.version + 1 } });
assert.equal(field(h).props.value, 'SYNTHETIC prepared reason');
});
const prepared = (patch = {}) =>
harness(
props({
owner: true,
canEdit: true,
record: { ...props().record, status: 'draft' },
publicationActions: ['submit', 'archive'],
publicationCommands: [],
...patch,
}),
);
function change(h, value) {
field(h).props.onChange({ target: { value } });
h.render();
}
const adopt = 'Revi esta versão; conservar o motivo e preparar nova acção';
const compare = 'Comparar com a proposta actual';
function saved(h, request = h.sent.at(-1), patch = {}) {
const status = {
submit: 'submitted',
publish: 'published',
return: 'returned',
reject: 'rejected',
suspend: 'suspended',
archive: 'archived',
renew: 'draft',
}[request.data.action];
return {
...h.props,
record: {
...h.props.record,
version: request.data.version + 1,
status,
},
publicationActions: [],
publicationCommands: [
{
key: request.data.client_key,
action: request.data.action,
version: request.data.version + 1,
},
],
...patch,
};
}
test('publication sends the reviewed version with a private operation key and one frozen reason', () => {
const h = prepared();
change(h, 'SYNTHETIC reason');
const request = h.click('Submeter para publicação');
assert.equal(request.url, '/parcerias/1/estado');
assert.equal(request.data.version, 4);
assert.equal(request.data.action, 'submit');
assert.equal(request.data.reason, 'SYNTHETIC reason');
assert.match(request.data.client_key, /^[0-9a-f-]{36}$/);
});
test('a content refresh requires explicit review and retains the prepared reason', () => {
const h = prepared();
change(h, 'SYNTHETIC deliberate reason');
h.render({
...h.props,
record: {
...h.props.record,
version: 5,
title: 'SYNTHETIC revised title',
},
});
assert.equal(h.button('Submeter para publicação').props.disabled, true);
assert.ok(text(h.tree).includes('SYNTHETIC revised title'));
h.click(adopt);
const request = h.click('Submeter para publicação');
assert.equal(request.data.version, 5);
assert.equal(request.data.reason, 'SYNTHETIC deliberate reason');
});
test('an untouched publication adopts current data without a stale empty form', () => {
const h = prepared();
h.render({ ...h.props, record: { ...h.props.record, version: 5 } });
change(h, 'SYNTHETIC new preparation');
assert.equal(h.button('Submeter para publicação').props.disabled, false);
assert.equal(h.click('Submeter para publicação').data.version, 5);
});
test('network recovery repeats the original command and preserves text typed afterwards', () => {
const h = prepared();
change(h, 'SYNTHETIC original reason');
const first = h.click('Submeter para publicação');
change(h, 'SYNTHETIC later reason');
h.fail(first);
const retry = h.click(
'Recuperar a mesma tentativa: Submeter para publicação',
);
assert.deepEqual(retry.data, first.data);
h.success(saved(h, retry), retry);
assert.equal(field(h).props.value, 'SYNTHETIC later reason');
});
test('successful acknowledgement clears only the unchanged reason', () => {
const h = prepared();
change(h, 'SYNTHETIC sent reason');
const request = h.click('Submeter para publicação');
h.success(saved(h, request), request);
assert.equal(
nodes(h.tree).find((node) => node.props?.['data-publication-form']) !==
undefined,
true,
);
assert.equal(h.leave(), false);
assert.equal(h.sent.length, 1);
});
test('deliberate changes back to an earlier string are preserved by their generation', () => {
const h = prepared();
change(h, 'SYNTHETIC sent');
const request = h.click('Submeter para publicação');
change(h, 'SYNTHETIC different');
change(h, 'SYNTHETIC sent');
h.success(saved(h, request), request);
assert.equal(field(h).props.value, 'SYNTHETIC sent');
});
test('a conflict requires an actual refresh before adopting a new attempt', () => {
const h = prepared();
change(h, 'SYNTHETIC retained');
const request = h.click('Submeter para publicação');
h.fail(request, 409);
assert.equal(h.button(adopt).props.disabled, true);
h.click(compare);
h.refreshed({ ...h.props, record: { ...h.props.record, version: 6 } });
assert.equal(h.button(adopt).props.disabled, false);
h.click(adopt);
const retry = h.click('Submeter para publicação');
assert.equal(retry.data.version, 6);
assert.notEqual(retry.data.client_key, request.data.client_key);
assert.equal(retry.data.reason, 'SYNTHETIC retained');
});
test('a refresh can recognize a lost response from the actors own command ledger', () => {
const h = prepared();
change(h, 'SYNTHETIC sent');
const request = h.click('Submeter para publicação');
h.fail(request);
h.click(compare);
h.refreshed(saved(h, request));
assert.equal(
h.button('Recuperar a mesma tentativa: Submeter para publicação'),
undefined,
);
assert.equal(h.leave(), false);
});
test('a recognised operation does not silently adopt later proposal edits', () => {
const h = prepared();
change(h, 'SYNTHETIC sent');
const request = h.click('Submeter para publicação');
change(h, 'SYNTHETIC next reason');
h.success(
saved(h, request, {
record: {
...h.props.record,
version: 7,
status: 'draft',
title: 'SYNTHETIC changed later',
},
publicationActions: ['submit', 'archive'],
}),
request,
);
assert.equal(field(h).props.value, 'SYNTHETIC next reason');
assert.equal(h.button('Submeter para publicação').props.disabled, true);
h.click(adopt);
assert.equal(h.click('Submeter para publicação').data.version, 7);
});
test('an incompatible response does not confirm the attempt or clear the reason', () => {
const h = prepared();
change(h, 'SYNTHETIC conserved');
const request = h.click('Submeter para publicação');
h.success(saved(h, request, { publicationCommands: [] }), request);
assert.equal(field(h).props.value, 'SYNTHETIC conserved');
assert.ok(
h.button('Recuperar a mesma tentativa: Submeter para publicação'),
);
assert.equal(h.button(adopt).props.disabled, true);
});
test('loss of authority keeps local preparation and disables recovery', () => {
const h = prepared();
change(h, 'SYNTHETIC preserved');
const request = h.click('Submeter para publicação');
h.fail(request);
h.render({
...h.props,
owner: false,
canEdit: false,
moderator: false,
publicationActions: [],
publicationCommands: [],
});
assert.equal(field(h).props.value, 'SYNTHETIC preserved');
assert.equal(
h.button('Recuperar a mesma tentativa: Submeter para publicação').props
.disabled,
true,
);
assert.equal(h.button('Submeter para publicação'), undefined);
});
test('a different actor starts with a separate preparation and ignores an old callback', () => {
const h = prepared();
change(h, 'SYNTHETIC former actor reason');
const request = h.click('Submeter para publicação');
h.render({ ...h.props, actorId: 99 });
assert.equal(field(h).props.value, '');
request.options.onSuccess({ props: saved(h, request) });
request.form.processing = false;
h.render();
assert.equal(field(h).props.value, '');
});
test('publication and candidacy drafts share one leave warning', () => {
const h = prepared();
change(h, 'SYNTHETIC publication preparation');
h.change(
'decision:10',
'Motivo da decisão ou pedido de esclarecimento',
'SYNTHETIC candidacy preparation',
);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.unload(), true);
});
test('suspension is displayed when authorized by the server and uses its existing command', () => {
const h = prepared({
owner: false,
canEdit: false,
moderator: true,
record: { ...props().record, status: 'published' },
publicationActions: ['suspend'],
});
change(h, 'SYNTHETIC suspension');
assert.equal(h.click('Suspender publicação').data.action, 'suspend');
assert.equal(h.button('Publicar'), undefined);
});
test('an empty API payload dictionary remains a valid draft for archival', () => {
const h = prepared({
record: { ...props().record, payload: [], status: 'draft' },
});
change(h, 'SYNTHETIC incomplete idea');
assert.equal(h.button('Arquivar publicação').props.disabled, false);
});
@@ -0,0 +1,420 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { File } from 'node:buffer';
import {
harness,
props,
original,
nodes,
text,
} from './helpers/partnership-room.mjs';
const newerRoom = (h, patch = {}) => ({
...h.props,
room: { ...h.props.room, version: h.props.room.version + 1, ...patch },
});
const mutableMilestone = (h, patch = {}) => ({
...h.props,
milestones: [{ ...h.props.milestones[0], ...patch }],
});
function row(scope, label) {
return nodes(scope).find(
(node) => node.type === 'tr' && text(node).startsWith(label),
);
}
test('untouched controls follow current data without requiring comparison of an empty new milestone', () => {
const h = harness(props({ milestones: [original] }));
h.change('message', 'Mensagem privada', 'SYNTHETIC separate draft');
h.render({
...newerRoom(h),
milestones: [
{
...original,
version: 4,
title: 'SYNTHETIC updated remote deliverable',
},
],
});
assert.equal(
h.field('milestone:7', 'Entregável').props.value,
'SYNTHETIC updated remote deliverable',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
false,
);
assert.equal(
h.field('message', 'Mensagem privada').props.value,
'SYNTHETIC separate draft',
);
assert.equal(
h.button('Usar este contexto e conservar as alterações escolhidas'),
undefined,
);
h.change('milestone:new', 'Responsável pelo marco', '1');
assert.equal(
h.button('Guardar marco', h.form('milestone:new')).props.disabled,
false,
);
});
test('room version changes retain every independent form, including a selected File', () => {
const h = harness(props({ milestones: [original] }));
const file = new File(['SYNTHETIC bytes'], 'synthetic.pdf', {
type: 'application/pdf',
});
h.change('message', 'Mensagem privada', 'SYNTHETIC unsent question');
h.change('upload', 'Anexar PDF ou imagem', file);
h.change('agreement', 'Condições e plano de valor', 'SYNTHETIC own terms');
h.change(
'milestone:7',
'Evidência ou referência do resultado',
'SYNTHETIC own evidence',
);
h.render(newerRoom(h));
assert.equal(
h.field('message', 'Mensagem privada').props.value,
'SYNTHETIC unsent question',
);
assert.match(text(h.form('upload')), /synthetic.pdf/);
assert.equal(
h.field('agreement', 'Condições e plano de valor').props.value,
'SYNTHETIC own terms',
);
assert.equal(
h.field('milestone:7', 'Evidência ou referência do resultado').props
.value,
'SYNTHETIC own evidence',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
true,
);
});
test('milestone conflicts are compared explicitly and return-to-original remains a deliberate edit', () => {
const h = harness(props({ milestones: [original] }));
h.change('milestone:7', 'Entregável', 'SYNTHETIC temporarily changed');
h.change('milestone:7', 'Entregável', original.title);
h.render(
mutableMilestone(h, {
title: 'SYNTHETIC remote title',
version: 4,
status: 'progress',
}),
);
const scope = h.form('milestone:7');
assert.match(text(scope), /Escolha o valor a conservar/);
assert.match(text(row(scope, 'Estado')), /Pendente/);
assert.doesNotMatch(text(row(scope, 'Estado')), /Submetida/);
h.click('Manter minha alteração', row(scope, 'Entregável'));
h.click(
'Usar este contexto e conservar as alterações escolhidas',
h.form('milestone:7'),
);
const request = h.submit('milestone:7');
assert.equal(request.data.version, 4);
assert.equal(request.data.title, original.title);
});
test('independent agreement conflicts keep previous choices while another field is edited', () => {
const h = harness();
h.change('agreement', 'Título do instrumento', 'SYNTHETIC local title');
h.change(
'agreement',
'Condições e plano de valor',
'SYNTHETIC local terms',
);
h.render(
newerRoom(h, {
agreement: {
...h.props.room.agreement,
title: 'SYNTHETIC remote title',
terms: 'SYNTHETIC remote terms',
},
}),
);
h.click('Manter minha alteração', row(h.tree, 'Título do instrumento'));
h.click(
'Manter minha alteração',
row(h.tree, 'Condições e plano de valor'),
);
h.change('agreement', 'Motivo da ação', 'SYNTHETIC compare decision');
const adopt = h.button(
'Usar este contexto e conservar as alterações escolhidas',
);
assert.equal(adopt.props.disabled, false);
h.click('Usar este contexto e conservar as alterações escolhidas');
const request = h.click('Registar versão do acordo');
assert.equal(request.data.version, 3);
assert.equal(request.data.title, 'SYNTHETIC local title');
assert.equal(request.data.terms, 'SYNTHETIC local terms');
});
test('context-only change requires adoption and a confirmed record clears only its sent reason', () => {
const h = harness();
h.change('agreement', 'Motivo da ação', 'SYNTHETIC edit');
h.render(newerRoom(h));
assert.equal(h.button('Registar versão do acordo').props.disabled, true);
h.click('Usar este contexto e conservar as alterações escolhidas');
const request = h.click('Registar versão do acordo');
const confirmed = newerRoom(h);
confirmed.agreementCommands = [
{
key: request.data.client_key,
action: 'record',
version: request.data.version + 1,
status: confirmed.room.status,
party: null,
},
];
h.success(confirmed, request);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
assert.equal(h.button('Registar versão do acordo').props.disabled, true);
});
test('milestone acknowledgement uses canonical data and conserves edits made after send', () => {
const h = harness(props({ milestones: [original] }));
h.change('milestone:7', 'Entregável', ' SYNTHETIC trimmed title ');
const request = h.submit('milestone:7');
h.change(
'milestone:7',
'Evidência ou referência do resultado',
'SYNTHETIC later evidence',
);
h.success(
mutableMilestone(h, { title: 'SYNTHETIC trimmed title', version: 4 }),
request,
);
assert.equal(
h.field('milestone:7', 'Entregável').props.value,
'SYNTHETIC trimmed title',
);
assert.equal(
h.field('milestone:7', 'Evidência ou referência do resultado').props
.value,
'SYNTHETIC later evidence',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
false,
);
});
test('uncertain milestone creation repeats original bytes and retains later changes as new preparation', () => {
const h = harness();
h.change('milestone:new', 'Entregável', 'SYNTHETIC original creation');
h.change('milestone:new', 'Responsável pelo marco', '1');
const first = h.submit('milestone:new');
h.fail(first);
h.change('milestone:new', 'Entregável', 'SYNTHETIC later draft');
const retry = h.submit('milestone:new');
assert.deepEqual(retry.data, first.data);
const saved = {
...original,
id: 11,
version: 1,
title: first.data.title,
client_key: first.data.client_key,
};
h.success({ ...h.props, milestones: [saved] }, retry);
assert.equal(
h.field('milestone:new', 'Entregável').props.value,
'SYNTHETIC later draft',
);
assert.match(text(h.form('milestone:new')), /como nova preparação/);
assert.ok(h.form('milestone:11'));
});
test('closed room keeps drafts mounted and blocks new changes until context and authority permit them', () => {
const h = harness(props({ milestones: [original] }));
h.change('milestone:7', 'Entregável', 'SYNTHETIC kept milestone');
h.change(
'agreement',
'Condições e plano de valor',
'SYNTHETIC kept agreement',
);
h.change('message', 'Mensagem privada', 'SYNTHETIC kept message');
h.render(newerRoom(h, { status: 'cancelled' }));
assert.ok(h.form('milestone:7'));
assert.equal(
h.field('milestone:7', 'Entregável').props.value,
'SYNTHETIC kept milestone',
);
assert.equal(
nodes(h.form('milestone:7')).find((node) => node.type === 'fieldset')
.props.disabled,
true,
);
assert.equal(
h.field('agreement', 'Condições e plano de valor').props.value,
'SYNTHETIC kept agreement',
);
assert.equal(h.button('Enviar mensagem').props.disabled, true);
assert.match(text(h.tree), /preparação.*conservada/);
});
test('uncertain messages retain their original key while later text is prepared separately', () => {
const h = harness();
h.change('message', 'Mensagem privada', 'SYNTHETIC first message');
const first = h.submit('message');
h.fail(first);
h.change('message', 'Mensagem privada', 'SYNTHETIC next message');
const retry = h.submit('message');
assert.deepEqual(retry.data, first.data);
h.success(
{
...h.props,
messages: [
{
id: 1,
author_id: 1,
client_key: first.data.client_key,
body: first.data.body,
name: 'SYNTHETIC owner',
created_at: 'synthetic',
},
],
},
retry,
);
assert.equal(
h.field('message', 'Mensagem privada').props.value,
'SYNTHETIC next message',
);
const next = h.submit('message');
assert.notEqual(next.data.client_key, first.data.client_key);
assert.equal(next.data.body, 'SYNTHETIC next message');
});
test('uncertain upload retains the immutable File and original sharing consent through retry', () => {
const h = harness();
const firstFile = new File(['SYNTHETIC first'], 'first.pdf'),
laterFile = new File(['SYNTHETIC later'], 'later.pdf');
h.change('upload', 'Anexar PDF ou imagem', firstFile);
const first = h.submit('upload');
h.fail(first);
h.change('upload', 'Anexar PDF ou imagem', laterFile);
const retry = h.submit('upload');
assert.equal(retry.data.file, firstFile);
assert.equal(retry.data.client_key, first.data.client_key);
assert.equal(retry.data.shared, false);
h.success(
{
...h.props,
documents: [
{
id: 1,
document_id: 'synthetic-document',
owner_id: 1,
file_name: 'first.pdf',
shared: false,
status: 'quarantined',
malware_scan_status: 'pending',
},
],
flash: { uploaded_document_id: 'synthetic-document' },
},
retry,
);
assert.match(text(h.form('upload')), /later.pdf/);
const next = h.submit('upload');
assert.equal(next.data.file, laterFile);
assert.notEqual(next.data.client_key, first.data.client_key);
});
test('unrelated or malformed acknowledgement never erases message or upload preparation', () => {
const h = harness();
h.change('message', 'Mensagem privada', 'SYNTHETIC retained');
const request = h.submit('message');
h.success({ ...h.props, room: { ...h.props.room, id: 999 } }, request);
assert.equal(
h.field('message', 'Mensagem privada').props.value,
'SYNTHETIC retained',
);
assert.match(text(h.form('message')), /não foi confirmado/);
});
test('one leave guard covers all drafts; comparison refresh does not trigger a leave prompt', () => {
const h = harness(props({ milestones: [original] }));
h.change('message', 'Mensagem privada', 'SYNTHETIC message');
h.change('milestone:7', 'Entregável', 'SYNTHETIC draft');
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.unload(), true);
assert.equal(h.leave(true), false);
assert.equal(h.confirmCalls, 1);
});
test('losing write access conserves preparation and another account gets a fresh room editor', () => {
const h = harness();
h.change('message', 'Mensagem privada', 'SYNTHETIC private local draft');
h.render({ ...h.props, canWrite: false, participants: [] });
assert.equal(h.button('Enviar mensagem').props.disabled, true);
assert.equal(
h.field('message', 'Mensagem privada').props.value,
'SYNTHETIC private local draft',
);
h.render({ ...h.props, canWrite: true, actorId: 2 });
assert.equal(h.field('message', 'Mensagem privada').props.value, '');
});
test('HTTP409 preserves agreement text and a successful refresh of the unchanged base permits a retry', () => {
const h = harness();
h.change('agreement', 'Motivo da ação', 'SYNTHETIC retry');
const request = h.click('Registar versão do acordo');
h.fail(request, 409);
assert.equal(h.button('Registar versão do acordo').props.disabled, true);
h.click('Comparar com os dados actuais da sala');
h.refreshed(h.props);
assert.equal(h.button('Registar versão do acordo').props.disabled, false);
assert.equal(
h.field('agreement', 'Motivo da ação').props.value,
'SYNTHETIC retry',
);
});
test('confirmation uses a fresh reviewed room version and preserves unsent instrument changes', () => {
const h = harness();
h.change(
'agreement',
'Título do instrumento',
'SYNTHETIC local unrecorded title',
);
h.change(
'agreement',
'Motivo da ação',
'SYNTHETIC confirm published terms',
);
const request = h.click('Confirmar pela minha parte');
assert.equal(request.data.title, undefined);
assert.equal(request.data.version, 2);
const confirmed = newerRoom(h);
confirmed.room.agreement = {
...confirmed.room.agreement,
confirmations: {
proponent: {
actor_id: 1,
date: 'SYNTHETIC',
reason: request.data.reason,
},
},
};
confirmed.agreementCommands = [
{
key: request.data.client_key,
action: 'confirm',
version: request.data.version + 1,
status: confirmed.room.status,
party: 'proponent',
},
];
h.success(confirmed, request);
assert.equal(
h.field('agreement', 'Título do instrumento').props.value,
'SYNTHETIC local unrecorded title',
);
assert.equal(h.field('agreement', 'Motivo da ação').props.value, '');
});
test('a newer unexpected acknowledgement is compared instead of being accepted as the sent edit', () => {
const h = harness(props({ milestones: [original] }));
h.change('milestone:7', 'Entregável', 'SYNTHETIC own title');
const request = h.submit('milestone:7');
h.success(
mutableMilestone(h, { title: 'SYNTHETIC another edit', version: 5 }),
request,
);
assert.equal(
h.field('milestone:7', 'Entregável').props.value,
'SYNTHETIC own title',
);
assert.equal(
h.button('Guardar marco', h.form('milestone:7')).props.disabled,
true,
);
});
@@ -0,0 +1,405 @@
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 code = 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(code, ['require', 'module', 'exports'])(
(name) => mocks[name] ?? require(name),
module,
module.exports,
);
return module.exports;
}
function nodes(tree) {
if (!tree || typeof tree !== 'object') return [];
if (Array.isArray(tree)) return tree.flatMap(nodes);
return [tree, ...nodes(tree.props?.children)];
}
const source = 'a'.repeat(64),
observation = 'b'.repeat(64),
duplicate = 'c'.repeat(64);
const module = load(
'../../resources/js/pages/management/proactive-supply-review.tsx',
{
'@inertiajs/react': { Link: 'a' },
'./shared': { Management: 'main', button: '', control: '' },
},
);
const props = {
installed: true,
filters: {
status: 'repeated',
source_hash: source,
q: '100% & algodão',
page: 2,
},
recordId: 35,
total: 26,
per_page: 25,
limitations: 'Historical partial source',
status: 'Administrative observations',
sources: [
{
sha256: source,
name: 'SYNTHETIC source.xlsx',
period: '2018–2020',
limitations: 'Historical, not current capacity',
imported_at: '2026-10-28',
receipt: { contact: 'PRIVATE NEVER DISPLAY' },
},
],
coverage: {
observations: 50,
distinct_observations: 30,
repeated: 20,
unmapped: 10,
ambiguous: 4,
territory_unavailable: 1,
identity_conflict: 2,
unclassified: 3,
unnamed: 2,
},
rows: [
{
id: observation,
name: '<SYNTHETIC company>',
province: 'Original province',
district: 'Original district',
territory_id: null,
territory_resolution: 'ambiguous',
canonical_territory: null,
canonical_type: null,
cae: '',
activity: '',
sector: '',
source_date: 'Serial Excel original: 45000',
sheet: 'Original sheet',
row_number: 4,
source_hash: source,
identity_conflict: true,
duplicate_of: duplicate,
source_name: 'SYNTHETIC source.xlsx',
source_period: '2018–2020',
imported_at: '2026-10-28',
entity_key: 'PRIVATE NEVER DISPLAY',
},
],
};
await test('private review preserves source lineage and distinguishes observations, repetitions, ambiguity and unavailable dates', () => {
const tree = module.default(props);
const html = renderToStaticMarkup(tree);
assert.match(html, /&lt;SYNTHETIC company&gt;/);
assert.match(html, /Serial Excel original: 45000/);
assert.match(html, /Original sheet, linha 4/);
assert.match(html, /não são números de empresas únicas/);
assert.match(html, /podem sobrepor-se/);
assert.match(
html,
/Várias correspondências possíveis, sem escolha automática/,
);
assert.doesNotMatch(html, /PRIVATE NEVER DISPLAY/);
const form = nodes(tree).find((node) => node.type === 'form');
assert.equal(form.props.method, 'get');
assert.equal(
form.props.action,
'/minhas-oportunidades/oferta-interna/revisao',
);
assert.equal(form.props.onSubmit, undefined);
const links = nodes(tree).filter((node) => node.type === 'a');
const root = new URL(
links.find(
(node) =>
node.props.children === 'Conferir a observação de referência',
).props.href,
'https://portal.invalid',
);
assert.equal(root.searchParams.get('observation_id'), duplicate);
assert.equal(root.searchParams.get('status'), 'all');
assert.equal(
root.searchParams.has('source_hash'),
false,
'A repeated sighting can point to an earlier original source.',
);
const previous = new URL(
links.find((node) => node.props.children === 'Anterior').props.href,
'https://portal.invalid',
);
assert.equal(previous.searchParams.get('q'), '100% & algodão');
assert.equal(previous.searchParams.get('record_id'), '35');
assert.equal(previous.searchParams.get('source_hash'), source);
assert.equal(previous.searchParams.get('page'), '1');
assert.ok(
links.some(
(node) =>
node.props.children === 'Ligação para recuperar esta linha' &&
node.props.href.includes(observation),
),
);
});
await test('missing or empty coverage never means no businesses, and exact-row filters can be removed without losing the source context', () => {
const html = renderToStaticMarkup(
module.default({
...props,
installed: false,
rows: [],
total: null,
coverage: null,
sources: [],
filters: { ...props.filters, observation_id: observation },
errors: { source_hash: 'SYNTHETIC source unavailable' },
}),
);
assert.match(html, /base interna ainda não está carregada/);
assert.match(html, /SYNTHETIC source unavailable/);
assert.doesNotMatch(
html,
/Página 2|0 empresas|Cobertura documental da origem/,
);
const url = module.supplyReviewUrl(
{ ...props.filters, observation_id: null, page: 1 },
35,
);
assert.equal(
new URL(url, 'https://portal.invalid').searchParams.has(
'observation_id',
),
false,
);
assert.equal(
new URL(url, 'https://portal.invalid').searchParams.get('source_hash'),
source,
);
});
function browserHarness() {
let cursor = 0;
const state = [],
effects = [],
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) {
effects.push(fn);
},
};
const Browser = load('../../resources/js/components/proactive-supply.tsx', {
react: hooks,
'@inertiajs/react': { Link: 'a' },
'@/pages/management/shared': {
button: '',
control: '',
Field: 'label',
},
'@/lib/operation-key': { createOperationKey: () => 'qa' },
}).ProactiveSupplyBrowser;
const previousFetch = globalThis.fetch;
globalThis.fetch = (url, options) =>
new Promise((resolve, reject) =>
requests.push({
url,
options,
fail: reject,
finish(data) {
resolve({ ok: true, json: async () => data });
},
}),
);
return {
render(next = {}) {
cursor = 0;
effects.length = 0;
return Browser({
value: { evidence: [], supply_comparisons: [] },
onChange() {},
territoryId: 'area-a',
recordId: 1,
...next,
});
},
start: () => effects[1](),
resetTerritory: () => effects[0](),
requests,
restore: () => {
globalThis.fetch = previousFetch;
},
};
}
const result = (title) => ({
installed: true,
rows: [
{
id: title,
name: title,
province: 'P',
district: 'D',
cae: '1',
activity: 'QA',
sector: 'QA',
source_date: '2020',
sheet: 'QA',
row_number: 2,
source_hash: source,
source_name: 'QA source',
source_period: '2020',
identity_conflict: false,
},
],
total: 1,
limitations: 'Historical',
status: 'Historical',
});
const flush = () => new Promise((resolve) => setImmediate(resolve));
await test('a late supply response cannot revive rows from a previous territory', async () => {
const h = browserHarness();
try {
let tree = h.render();
nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Consultar oferta da localização',
)
.props.onClick();
h.render();
const abort = h.start();
h.render({ territoryId: 'area-b' });
abort();
h.resetTerritory();
h.requests[0].finish(result('PRIVATE OLD AREA'));
await flush();
assert.doesNotMatch(
renderToStaticMarkup(h.render({ territoryId: 'area-b' })),
/PRIVATE OLD AREA/,
);
assert.equal(h.requests[0].options.signal.aborted, true);
} finally {
h.restore();
}
});
await test('changing the record hides prior supply results until the response scoped to that record arrives', async () => {
const h = browserHarness();
try {
let tree = h.render();
nodes(tree)
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Consultar oferta da localização',
)
.props.onClick();
h.render();
const abort = h.start();
h.requests[0].finish(result('PRIVATE OLD RECORD'));
await flush();
assert.match(renderToStaticMarkup(h.render()), /PRIVATE OLD RECORD/);
assert.doesNotMatch(
renderToStaticMarkup(h.render({ recordId: 2 })),
/PRIVATE OLD RECORD/,
);
abort();
h.start();
assert.equal(
new URL(
h.requests[1].url,
'https://portal.invalid',
).searchParams.get('record_id'),
'2',
);
h.requests[1].finish(result('CURRENT RECORD RESULT'));
await flush();
const html = renderToStaticMarkup(h.render({ recordId: 2 }));
assert.match(html, /CURRENT RECORD RESULT/);
assert.doesNotMatch(html, /PRIVATE OLD RECORD/);
} finally {
h.restore();
}
});
await test('filter navigation resets native inputs to the applied query and keeps the record context', () => {
const first = nodes(module.default(props)).find(
(node) => node.type === 'form',
);
const nextProps = {
...props,
filters: { status: 'all', page: 1, observation_id: duplicate },
};
const next = nodes(module.default(nextProps)).find(
(node) => node.type === 'form',
);
assert.notEqual(first.key, next.key);
assert.equal(
nodes(next).find((node) => node.props?.name === 'source_hash').props
.defaultValue,
'',
);
assert.equal(
nodes(next).find((node) => node.props?.name === 'q').props.defaultValue,
'',
);
assert.equal(
nodes(next).find((node) => node.props?.name === 'record_id').props
.value,
35,
);
});
await test('a late failure from an aborted request cannot clear the current record results', async () => {
const h = browserHarness();
try {
nodes(h.render())
.find(
(node) =>
node.type === 'button' &&
node.props.children === 'Consultar oferta da localização',
)
.props.onClick();
h.render();
const abort = h.start();
h.render({ recordId: 2 });
abort();
h.start();
h.requests[1].finish(result('CURRENT RESULT MUST REMAIN'));
await flush();
h.requests[0].fail(
new Error('OLD ERROR MUST NOT REPLACE CURRENT RESULT'),
);
await flush();
const html = renderToStaticMarkup(h.render({ recordId: 2 }));
assert.match(html, /CURRENT RESULT MUST REMAIN/);
assert.doesNotMatch(html, /OLD ERROR MUST NOT/);
} finally {
h.restore();
}
});
+479
View File
@@ -0,0 +1,479 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/product-experiments.ts');
const usage = load('../../resources/js/lib/product-usage.ts');
const fields = [
'title',
'state',
'change_kind',
'reference',
'hypothesis',
'indicator_id',
'indicator_title',
'indicator_definition',
'indicator_unit',
'period_from',
'period_to',
'segment',
'control',
'variant',
'assignment',
'criterion',
'transparency',
'consent',
'security',
'equality',
'preserves_requirements',
'observed_from',
'observed_to',
'control_result',
'variant_result',
'result',
'limitations',
'evidence',
'decision',
'decision_reason',
'report_service',
];
const values = {
...Object.fromEntries(fields.map((k) => [k, ''])),
title: 'SYNTHETIC experiment',
state: 'planned',
change_kind: 'form',
hypothesis: 'SYNTHETIC base hypothesis',
segment: 'SYNTHETIC base segment',
indicator_id: 'submission_rate',
indicator_title: 'SYNTHETIC inactive custom title',
indicator_definition: 'SYNTHETIC inactive definition',
indicator_unit: '%',
period_from: '2026-11-02',
period_to: '2026-11-04',
preserves_requirements: 'yes',
};
const indicator = {
id: 'submission_rate',
title: 'Submission rate',
unit: '%',
source: 'SYNTHETIC frozen definition',
limits: 'SYNTHETIC limits',
definition_version: 'SYNTHETIC-v1',
};
const document = {
definition_version: 'SYNTHETIC registry',
version: 1,
at: '2026-11-03T12:00:00Z',
actor: { id: 1, name: 'SYNTHETIC actor' },
reason: 'SYNTHETIC reason',
values,
indicator,
plan_sha256: 'a'.repeat(64),
observation_plan_sha256: 'a'.repeat(64),
registration: {
first_at: '2026-11-03T12:00:00Z',
original_plan_sha256: 'a'.repeat(64),
amendments: 0,
amended_after_observation: false,
},
operational_report: null,
report_matches_observation: null,
report_scope: 'operational_cohort_not_experiment_arm',
};
const props = {
installed: true,
id: 'synthetic-id',
currentVersion: 1,
historical: false,
document,
values,
states: {
draft: 'Draft',
planned: 'Plan registered',
observing: 'Observing',
reviewed: 'Decision recorded',
cancelled: 'Cancelled',
},
changeKinds: { form: 'Form' },
decisions: { inconclusive: 'Inconclusive' },
labels: Object.fromEntries(fields.map((k) => [k, 'Label ' + k])),
catalogue: {
definition_version: 'SYNTHETIC-v2',
items: [{ ...indicator, source: 'SYNTHETIC current definition' }],
services: [],
},
history: [
{
version: 1,
at: document.at,
actor: 'SYNTHETIC actor',
state: 'planned',
reason: 'SYNTHETIC reason',
},
],
historyNext: null,
};
class ValidationError extends Error {
constructor(message, fields = {}) {
super(message);
this.fields = fields;
}
}
function harness(
initial = props,
respond = async () => ({ id: 'synthetic-id' }),
) {
const slots = [];
let cursor = 0,
key = 0;
const calls = [],
visits = [];
const page = load(
'../../resources/js/pages/management/experiments/edit.tsx',
{
react: {
...require('react'),
useState: (value) => {
const index = cursor++;
if (!(index in slots))
slots[index] =
typeof value === 'function' ? value() : value;
return [
slots[index],
(v) => {
slots[index] =
typeof v === 'function' ? v(slots[index]) : v;
},
];
},
},
'@inertiajs/react': {
Link: 'a',
router: { visit: (...args) => visits.push(args) },
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/lib/profile-json': {
ProfileValidationError: ValidationError,
profileJson: async (...args) => {
calls.push(args);
return respond(...args);
},
},
'@/lib/operation-key': {
createOperationKey: () => `SYNTHETIC-operation-${++key}`,
},
'@/lib/product-experiments': lib,
'@/lib/product-usage': usage,
},
);
return {
calls,
visits,
render() {
cursor = 0;
const outer = page.default(initial);
return outer.type(outer.props);
},
};
}
function walk(node, predicate) {
if (Array.isArray(node)) return node.flatMap((n) => walk(n, predicate));
if (!node || typeof node !== 'object' || !node.props) return [];
return [
...(predicate(node) ? [node] : []),
...walk(node.props.children, predicate),
];
}
function content(node) {
if (Array.isArray(node)) return node.map(content).join('');
if (node === null || node === undefined || typeof node === 'boolean')
return '';
if (typeof node === 'object') return content(node.props?.children);
return String(node);
}
function button(tree, text) {
const node = walk(
tree,
(n) => n.type === 'button' && content(n).includes(text),
)[0];
assert.ok(node, 'button ' + text);
return node;
}
function inputValue(tree, value) {
const node = walk(
tree,
(n) =>
['input', 'textarea'].includes(n.type) && n.props.value === value,
)[0];
assert.ok(node, 'input ' + value);
return node;
}
function check(tree, text) {
const label = walk(
tree,
(n) => n.type === 'label' && content(n).includes(text),
)[0];
assert.ok(label, 'checkbox ' + text);
return walk(
label,
(n) => n.type === 'input' && n.props.type === 'checkbox',
)[0];
}
test('three-way comparison reports actual conflicts and merges untouched fields without losing deliberate edits', () => {
const base = { hypothesis: 'base', segment: 'old', title: 'same' };
const mine = { ...base, hypothesis: 'mine' };
const current = { ...base, hypothesis: 'theirs', segment: 'new' };
assert.deepEqual(lib.experimentDifferences(base, mine, current), [
'hypothesis',
]);
assert.deepEqual(
lib.experimentDifferences(base, base, current, ['hypothesis']),
['hypothesis'],
);
assert.equal(
lib.mergeExperimentValues(base, base, current, ['hypothesis'])
.hypothesis,
'base',
);
assert.deepEqual(lib.mergeExperimentValues(base, mine, current), {
hypothesis: 'mine',
segment: 'new',
title: 'same',
});
assert.deepEqual(base, {
hypothesis: 'base',
segment: 'old',
title: 'same',
});
});
test('stored indicator edition remains visible, explicit refresh can be reversed, and inactive custom fields are hidden', () => {
const h = harness();
let tree = h.render(),
html = renderToStaticMarkup(tree);
assert.match(html, /SYNTHETIC frozen definition/);
assert.doesNotMatch(
html,
/SYNTHETIC current definition|SYNTHETIC inactive definition/,
);
check(tree, 'Adoptar explicitamente').props.onChange({
target: { checked: true },
});
tree = h.render();
html = renderToStaticMarkup(tree);
assert.match(html, /SYNTHETIC current definition/);
check(tree, 'Adoptar explicitamente').props.onChange({
target: { checked: false },
});
assert.match(
renderToStaticMarkup(h.render()),
/SYNTHETIC frozen definition/,
);
const manual = harness({
...props,
values: { ...values, indicator_id: 'manual' },
document: { ...document, indicator: { ...indicator, id: 'manual' } },
});
assert.doesNotMatch(
renderToStaticMarkup(manual.render()),
/Adoptar explicitamente/,
);
});
test('conflict recovery preserves the draft, compares changed fields, and saves against the reviewed current version', async () => {
const current = {
...props,
currentVersion: 2,
values: {
...values,
hypothesis: 'SYNTHETIC their hypothesis',
segment: 'SYNTHETIC their segment',
},
document: { ...document, version: 2 },
};
let writes = 0;
const h = harness(props, async (url, data, method) => {
if (method === 'GET') return current;
if (++writes === 1) throw new ValidationError('SYNTHETIC conflict');
return { id: 'synthetic-id', version: 3 };
});
inputValue(h.render(), values.hypothesis).props.onChange({
target: { value: 'SYNTHETIC my deliberate hypothesis' },
});
walk(
h.render(),
(n) => n.type === 'textarea' && n.props.maxLength === 3000,
)[0].props.onChange({ target: { value: 'SYNTHETIC reviewed conflict' } });
walk(h.render(), (n) => n.type === 'form')[0].props.onSubmit({
preventDefault() {},
});
await new Promise(setImmediate);
assert.match(
renderToStaticMarkup(h.render()),
/SYNTHETIC my deliberate hypothesis/,
);
inputValue(h.render(), 'SYNTHETIC my deliberate hypothesis').props.onChange(
{ target: { value: values.hypothesis } },
);
await button(h.render(), 'Consultar versão actual').props.onClick();
const beforeReview = h.calls.length;
walk(h.render(), (n) => n.type === 'form')[0].props.onSubmit({
preventDefault() {},
});
await new Promise(setImmediate);
assert.equal(
h.calls.length,
beforeReview,
'Do not submit before the current version has been reviewed',
);
assert.match(
renderToStaticMarkup(h.render()),
/SYNTHETIC their hypothesis/,
);
button(h.render(), 'Manter a minha edição').props.onClick();
button(h.render(), 'Usar esta versão como base').props.onClick();
let tree = h.render();
assert.equal(
inputValue(tree, values.hypothesis).props.value,
values.hypothesis,
);
assert.equal(
inputValue(tree, 'SYNTHETIC their segment').props.value,
'SYNTHETIC their segment',
);
walk(tree, (n) => n.type === 'form')[0].props.onSubmit({
preventDefault() {},
});
await new Promise(setImmediate);
const requests = h.calls.filter((c) => c[2] !== 'GET');
assert.equal(requests[1][1].version, 2);
assert.notEqual(requests[0][1].operation_key, requests[1][1].operation_key);
assert.equal(requests[1][1].values.hypothesis, values.hypothesis);
assert.equal(requests[1][1].values.segment, 'SYNTHETIC their segment');
assert.equal(
requests[1][1].values.indicator_definition,
'SYNTHETIC inactive definition',
);
assert.ok(h.calls.every((c) => !c[0].includes('hypothesis')));
assert.equal(h.visits.length, 1);
});
test('historical versions are read only and an unavailable registry is distinct from an empty one', async () => {
const h = harness({ ...props, historical: true, currentVersion: 3 });
const tree = h.render(),
html = renderToStaticMarkup(tree);
assert.match(html, /Consulta da versão 1/);
assert.match(html, /SYNTHETIC frozen definition/);
assert.doesNotMatch(
html,
/Guardar versão do registo|Consultar versão actual para comparar/,
);
assert.equal(
walk(tree, (n) => n.type === 'fieldset' && !n.props.disabled).length,
0,
);
walk(tree, (n) => n.type === 'form')[0].props.onSubmit({
preventDefault() {},
});
await new Promise(setImmediate);
assert.equal(
h.calls.length,
0,
'Historical consultation cannot submit even if a submit event is dispatched',
);
const index = load(
'../../resources/js/pages/management/experiments/index.tsx',
{
'@inertiajs/react': { Link: 'a' },
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
},
).default;
const missing = renderToStaticMarkup(
index({
installed: false,
states: {},
filters: { state: '' },
items: [],
page: 1,
pages: 1,
total: 0,
}),
);
assert.match(missing, /ainda não está disponível/);
assert.doesNotMatch(
missing,
/0 registos|Preparar experiência|Ainda não existem registos/,
);
});
test('an attached operational report is labelled as context and retains unknown values without inventing arm results', () => {
const report = {
filters: { from: '2026-11-02', to: '2026-11-02', service_code: null },
generated_at: '2026-11-03T12:00:00Z',
metrics: [
{
id: 'rate',
title: 'SYNTHETIC rate',
value: null,
unit: '%',
state: 'unmeasured',
},
],
};
const h = harness({
...props,
values: {
...values,
state: 'reviewed',
result: 'SYNTHETIC declared result',
},
document: {
...document,
operational_report: report,
report_matches_observation: false,
},
});
const html = renderToStaticMarkup(h.render());
assert.match(
html,
/Não separa grupos da experiência nem comprova causalidade/,
);
assert.match(html, /filtros deste relatório diferem/);
assert.match(html, /Sem medição/);
assert.doesNotMatch(html, />0 %</);
});
+131
View File
@@ -0,0 +1,131 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/product-usage.ts');
const searchComponent = load(
'../../resources/js/components/search-usage-report.tsx',
{
'@/lib/product-usage': lib,
'@/pages/investment/shared': { card: '' },
},
);
const report = {
definition_version: 'SYNTHETIC-v1',
generated_at: '2026-11-03T12:00:00Z',
observed_before: '2026-11-03T00:00:00Z',
timezone: 'UTC',
filters: { from: '2026-11-02', to: '2026-11-02', service_code: null },
services: [{ code: 'test', title: 'SYNTHETIC <service>', version: 1 }],
coverage: {
cohort_requests: 2,
complete_histories: 1,
unknown_histories: 1,
},
metrics: [
{
id: 'rate',
title: 'SYNTHETIC rate',
value: null,
unit: '%',
numerator: 0,
denominator: 1,
state: 'partial',
source: 'SYNTHETIC source',
limits: 'SYNTHETIC unknown',
},
{
id: 'count',
title: 'SYNTHETIC count',
value: 0,
unit: 'pedidos',
numerator: null,
denominator: null,
state: 'observed',
source: 'SYNTHETIC count source',
limits: 'SYNTHETIC count limit',
},
],
unmeasured: [
{
id: 'investment',
title: 'Investimento confirmado',
reason: 'Sem fonte canónica',
},
],
limits: ['Não somar pessoas e pedidos'],
fingerprint: 'a'.repeat(64),
read_consistency: 'repeatable_read',
};
const component = load(
'../../resources/js/pages/management/product-usage.tsx',
{
'@inertiajs/react': {
Link: 'a',
usePage: () => ({ props: { errors: {} } }),
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/lib/product-usage': lib,
'@/components/search-usage-report': searchComponent,
},
);
test('unknown values remain distinct from measured zero and rates retain numerator and denominator', () => {
assert.equal(lib.usageValue(null, '%'), 'Sem medição');
assert.equal(lib.usageValue(0, '%'), '0 %');
const html = renderToStaticMarkup(component.default({ report }));
assert.match(html, /Cobertura parcial/);
assert.match(html, /Numerador:.*0/);
assert.match(html, /Denominador:.*1/);
assert.match(html, /Sem medição/);
assert.match(html, /0 pedidos/);
assert.match(html, /Investimento confirmado/);
assert.doesNotMatch(html, />0 %</);
});
test('filters and export use the applied report with no new telemetry or private request parameters', () => {
const html = renderToStaticMarkup(component.default({ report }));
assert.match(html, /action="\/management\/product-usage" method="get"/);
assert.match(html, /name="from"[^>]*value="2026-11-02"/);
assert.match(html, /SYNTHETIC &lt;service&gt;/);
assert.match(html, /Período aplicado/);
assert.match(html, /Observações anteriores a/);
assert.deepEqual(JSON.parse(lib.usageExport(report)), report);
const src = fs.readFileSync(
new URL(
'../../resources/js/pages/management/product-usage.tsx',
import.meta.url,
),
'utf8',
);
assert.doesNotMatch(
src,
/fetch\(|document\.cookie|localStorage|sessionStorage/,
);
});
@@ -0,0 +1,237 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
result,
committed,
text,
apply,
refresh,
adopt,
retry,
reason,
} from './helpers/profile-support-installation.mjs';
const prepare = (h) => {
h.change(reason);
h.confirm();
};
test('installation requires current proof, MFA, confirmation and a substantive reason; duplicate clicks send once', () => {
for (const patch of [
{ ready: false },
{ mfa_confirmed: false },
{ consistent: false },
]) {
const h = harness(props(patch));
prepare(h);
assert.equal(h.button(apply).props.disabled, true);
h.click(apply);
assert.equal(h.sent.length, 0);
}
const h = harness();
h.click(apply);
assert.equal(h.sent.length, 0);
h.change('short');
h.confirm();
h.click(apply);
assert.equal(h.sent.length, 0);
prepare(h);
h.click(apply);
h.click(apply);
assert.equal(h.sent.length, 1);
});
test('uncertain retry freezes the original body and preserves edits made after sending', async () => {
const h = harness();
prepare(h);
const first = h.click(apply);
h.change(reason + ' later');
await h.fail(null, first);
h.click(retry);
assert.deepEqual(h.sent[1].data, first.data);
await h.reply(result(first));
assert.equal(h.reason, reason + ' later');
await h.reply(committed(first), h.reloads[0]);
assert.equal(h.reason, reason + ' later');
assert.equal(h.leave(), true);
});
test('a matching acknowledgement clears only the unchanged preparation and confirms via a fresh preview', async () => {
const h = harness();
prepare(h);
const request = h.click(apply);
await h.reply(result(request));
assert.equal(h.reason, '');
await h.reply(committed(request), h.reloads[0]);
assert.equal(h.leave(), false);
assert.equal(h.button(apply).props.disabled, true);
});
test('an authenticated own receipt resolves uncertainty through GET without a second POST', async () => {
const h = harness();
prepare(h);
const request = h.click(apply);
await h.fail();
h.click(refresh);
await h.reply(committed(request), h.reloads[0]);
assert.equal(h.reason, '');
assert.equal(h.sent.length, 1);
assert.equal(h.button(retry), undefined);
});
test('absence from a preview does not discard an uncertain attempt', async () => {
const h = harness();
prepare(h);
const request = h.click(apply);
await h.fail();
h.click(refresh);
await h.reply(props({ hash: 'd'.repeat(64) }), h.reloads[0]);
assert.equal(h.button(adopt).props.disabled, true);
h.click(retry);
assert.deepEqual(h.sent[1].data, request.data);
});
test('changed proof requires explicit comparison and renewed confirmation', async () => {
const h = harness();
prepare(h);
h.click(refresh);
await h.reply(props({ hash: 'd'.repeat(64) }), h.reloads[0]);
assert.equal(h.button(apply).props.disabled, true);
h.click(adopt);
assert.equal(h.button(apply).props.disabled, true);
assert.equal(h.reason, reason);
h.confirm();
h.click(apply);
assert.equal(h.sent[0].data.hash, 'd'.repeat(64));
});
test('a definitive rejection retains the reason and prepares a fresh command only after review', async () => {
for (const status of [409, 422]) {
const h = harness();
prepare(h);
const first = h.click(apply);
await h.fail(status);
if (status === 409) {
await h.reply(props({ hash: 'd'.repeat(64) }), h.reloads[0]);
h.click(adopt);
}
assert.equal(h.reason, reason);
assert.equal(h.button(retry), undefined);
h.confirm();
h.click(apply);
assert.notEqual(
h.sent[1].data.idempotency_key,
first.data.idempotency_key,
);
}
});
test('responses for another actor, destination, command or code cannot acknowledge this attempt', async () => {
for (const patch of [
{ actor_id: 2 },
{ target: { database: 'another_test', port: 55441 } },
{ command_key: 'other' },
{ code_hash: 'e'.repeat(64) },
]) {
const h = harness();
prepare(h);
const request = h.click(apply);
await h.reply(result(request, patch));
assert.equal(h.reason, reason);
assert.ok(h.button(retry));
assert.equal(h.reloads.length, 0);
}
});
test('restored access without fresh MFA cannot repeat the pending command', async () => {
const h = harness();
prepare(h);
const request = h.click(apply);
await h.fail(403);
assert.equal(h.button(retry), undefined);
h.click(refresh);
await h.reply(props({ mfa_confirmed: false }), h.reloads[0]);
assert.equal(h.button(retry), undefined);
h.click(refresh);
await h.reply(props(), h.reloads[1]);
h.click(retry);
assert.deepEqual(h.sent[1].data, request.data);
});
test('an older GET cannot erase an acknowledged result; the later own receipt restores readiness', async () => {
const h = harness();
prepare(h);
const request = h.click(apply);
h.click(refresh);
await h.reply(result(request));
await h.reply(props(), h.reloads[0]);
assert.match(text(h.tree), /ainda n\u00e3o confirma/);
h.click(refresh);
await h.reply(committed(request), h.reloads[1]);
assert.doesNotMatch(text(h.tree), /ainda n\u00e3o confirma/);
});
test('a successful refresh clears a previous refresh failure', async () => {
const h = harness();
h.click(refresh);
await h.fail(null, h.reloads[0]);
assert.match(text(h.tree), /poss\u00edvel actualizar/);
h.click(refresh);
await h.reply(props(), h.reloads[1]);
assert.doesNotMatch(text(h.tree), /poss\u00edvel actualizar/);
});
test('late writes and reads cannot alter a form belonging to another actor or destination', async () => {
for (const patch of [
{ actorId: 2 },
{ target: { database: 'other_test', port: 55441 } },
]) {
const h = harness();
prepare(h);
const old = h.click(apply);
h.click(refresh);
const oldRead = h.reloads[0];
h.render(props(patch));
h.change('New actor preparation');
await h.reply(result(old), old);
await h.reply(committed(old), oldRead);
assert.equal(h.reason, 'New actor preparation');
assert.equal(h.sent.length, 1);
assert.equal(h.guards, 1);
}
});
test('only one leave guard protects the draft and preserves internal refreshes', () => {
const h = harness();
assert.equal(h.guards, 1);
assert.equal(h.leave(), false);
h.change(reason);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.leave(true), false);
assert.equal(h.confirmCalls, 1);
});
const baseProps = (patch = {}) => ({
...props(),
bootstrap: {
initialized: false,
holders: [],
version: null,
rule: 'Existing rule',
pending: null,
},
...patch,
});
test('base installer guards both designated accounts and its submitted preparation', async () => {
const h = harness(baseProps({ installed: true }), 'base');
h.number(0, '1');
h.number(1, '2');
h.change(reason);
h.confirm();
assert.equal(h.leave(), true);
h.click('Pedir confirma\u00e7\u00e3o ao segundo titular');
await h.reply({ confirmation_url: '/synthetic-confirmation' });
assert.equal(h.leave(), false);
h.number(1, '3');
assert.equal(h.leave(), true);
assert.equal(h.guards, 1);
});
test('known base installation success does not prompt on sent fields when the follow-up read fails', async () => {
const h = harness(baseProps(), 'base');
prepare(h);
h.click('Instalar schema 040000');
await h.reply({ changed: true });
await h.fail(null, h.reloads[0]);
assert.equal(h.reason, reason);
assert.equal(h.leave(), false);
h.change(reason + ' later');
assert.equal(h.leave(), true);
});
@@ -0,0 +1,56 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/resource-incident-form.mjs';
const reasonLabel = 'Motivo (20–1000 caracteres)',
title = 'Título';
test('an upload incident response preserves the actual form fields, selected file and creation command without retrying', async () => {
const h = harness();
h.choose('Documentos');
h.change(title, 'SYNTHETIC document title');
h.change(reasonLabel, 'SYNTHETIC preserved upload reason');
const file = { name: 'synthetic.pdf' };
h.attach(file);
const request = h.submit();
await h.reply(503, {
message: 'Incidente técnico registado. Referência: SYNTHETIC-REFERENCE',
reference: 'SYNTHETIC-REFERENCE',
incident_recorded: true,
});
assert.equal(h.sent.length, 1);
assert.equal(h.reloads.length, 0);
assert.equal(h.value(title), 'SYNTHETIC document title');
assert.equal(h.value(reasonLabel), 'SYNTHETIC preserved upload reason');
assert.match(text(h.tree), /SYNTHETIC-REFERENCE/);
const retry = h.submit();
assert.equal(retry.form.get('file'), file);
assert.equal(
retry.form.get('creation_key'),
request.form.get('creation_key'),
);
assert.equal(retry.form.get('etag'), request.form.get('etag'));
});
test('reading the recorded upload incident adds its own operation label without resetting the preparation', () => {
const h = harness();
h.choose('Documentos');
h.change(title, 'SYNTHETIC draft');
h.change(reasonLabel, 'SYNTHETIC retained reason');
const file = { name: 'retained.pdf' };
h.attach(file);
h.render(
props({
technicalIncidents: [
{
reference: 'SYNTHETIC-REFERENCE',
operation: 'upload_document',
version: 4,
occurred_at: '2026-11-03',
error_code: 'database_failure',
},
],
}),
);
assert.match(text(h.tree), /Carregamento de documento/);
assert.equal(h.value(title), 'SYNTHETIC draft');
assert.equal(h.value(reasonLabel), 'SYNTHETIC retained reason');
assert.equal(h.submit().form.get('file'), file);
});
+152
View File
@@ -0,0 +1,152 @@
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 load(file, mocks = {}) {
const code = 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(code, ['require', 'module', 'exports'])(
(key) => mocks[key] ?? require(key),
module,
module.exports,
);
return module.exports;
}
const lib = load('../../resources/js/lib/product-usage.ts');
const child = load('../../resources/js/components/search-usage-report.tsx', {
'@/lib/product-usage': lib,
'@/pages/investment/shared': { card: '' },
});
const search = {
installed: true,
enabled_now: true,
applicable: true,
from: '2026-11-02',
to: '2026-11-03',
timezone: 'UTC',
read_at: '2026-11-03T12:00:00Z',
definition_version: 'SYNTHETIC-v1',
available_definitions: ['SYNTHETIC-v1', 'SYNTHETIC-v2'],
definition_conflict_now: false,
responses: 2,
zero_responses: 0,
zero_rate: 0,
channels: [
{
id: 'known',
label: 'SYNTHETIC archived <edition>',
responses: 2,
zero_responses: 0,
zero_rate: 0,
first_recorded_at: '2026-11-02T10:00:00Z',
last_recorded_at: '2026-11-02T11:00:00Z',
definition_versions: ['SYNTHETIC-v1'],
},
{
id: 'unknown',
label: 'SYNTHETIC unobserved channel',
responses: null,
zero_responses: null,
zero_rate: null,
first_recorded_at: null,
last_recorded_at: null,
definition_versions: [],
},
],
limits: ['SYNTHETIC recorded subset only'],
exclusions: ['SYNTHETIC autocomplete excluded'],
completeness: 'unverified_best_effort',
temporal_basis: 'daily_aggregate_at_report_snapshot',
};
test('daily capture shows measured zero separately from missing channel data and discloses its actual unit and coverage', () => {
const html = renderToStaticMarkup(child.default({ search }));
assert.match(html, /0 %/);
assert.match(html, /Sem medição/);
assert.match(html, /Cobertura parcial/);
assert.match(html, /dia actual é parcial/);
assert.match(html, /não há corte por fracção de segundo/);
assert.match(
html,
/pessoas, bots e pesquisas únicas não são identificados/,
);
assert.match(html, /SYNTHETIC archived &lt;edition&gt;/);
assert.match(html, /SYNTHETIC autocomplete excluded/);
const missing = renderToStaticMarkup(
child.default({
search: {
...search,
installed: false,
enabled_now: false,
applicable: false,
responses: null,
zero_responses: null,
zero_rate: null,
definition_conflict_now: true,
},
}),
);
assert.match(missing, /Ainda não há dados de recolha/);
assert.match(missing, /histórico registado mantém-se/);
assert.match(missing, /não têm associação comprovada ao serviço/);
assert.match(missing, /configuração diferente com o mesmo identificador/);
assert.match(missing, /Respostas: Sem medição/);
});
test('the applied collection edition survives the GET filter and export and has a separate time basis from desk events', () => {
const report = {
definition_version: 'SYNTHETIC report',
generated_at: '2026-11-03T12:00:00Z',
observed_before: '2026-11-03T12:00:00Z',
timezone: 'UTC',
filters: {
from: '2026-11-02',
to: '2026-11-03',
service_code: null,
search_definition: 'SYNTHETIC-v1',
},
services: [],
coverage: {},
metrics: [],
unmeasured: [],
limits: [],
fingerprint: 'a'.repeat(64),
read_consistency: 'repeatable_read',
search,
};
const page = load('../../resources/js/pages/management/product-usage.tsx', {
'@inertiajs/react': {
Link: 'a',
usePage: () => ({ props: { errors: {} } }),
},
'@/pages/investment/shared': {
Frame: 'main',
card: '',
input: '',
button: '',
},
'@/lib/product-usage': lib,
'@/components/search-usage-report': child,
}).default;
const html = renderToStaticMarkup(page({ report }));
assert.match(html, /name="search_definition"/);
assert.match(html, /<option(?=[^>]*value="SYNTHETIC-v1")(?=[^>]*selected)/);
assert.match(html, /Eventos do Balcão anteriores/);
assert.match(html, /Pesquisas usam as contagens diárias/);
assert.deepEqual(JSON.parse(lib.usageExport(report)).search, search);
assert.equal(
JSON.parse(lib.usageExport(report)).filters.search_definition,
'SYNTHETIC-v1',
);
});
+126
View File
@@ -81,6 +81,132 @@ const props = {
criteria: ['Venda da empresa', 'Agricultura'],
};
const flush = () => new Promise((resolve) => setImmediate(resolve));
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('radius replaces only the area, combines public classification, preserves links and reports missing point coverage', async () => {
const h = harness();
const scoped = {
...props,
radiusAvailable: true,
areaLabel: 'Synthetic province',
catalogueUrl:
props.catalogueUrl +
'&province_id=qa-province&district_id=qa-district',
classifications: [
{ target_type: 'sector', target_id: '4', label: 'QA sector' },
],
};
let tree = h.render(scoped);
const radius = nodes(tree).find((node) => node.type === 'fieldset').props
.children[1].props.children[1];
radius.props.onChange({ target: { value: '25' } });
const classification = nodes(tree).find(
(node) =>
node.type === 'select' &&
node.props.children[0]?.props?.children ===
'Sem classificação adicional',
);
classification.props.onChange({ target: { value: 'sector:4:' } });
tree = h.render(scoped);
h.start();
const url = new URL(h.requests[0].url, 'https://portal.invalid');
assert.equal(url.searchParams.get('near_business'), 'current');
assert.equal(url.searchParams.get('radius_km'), '25');
assert.equal(url.searchParams.has('province_id'), false);
assert.equal(url.searchParams.has('district_id'), false);
assert.equal(url.searchParams.get('sector'), '4');
assert.equal(url.searchParams.get('association_target'), '4');
h.requests[0].resolve({
data: [
{
id: 'near',
slug: 'near',
title: 'Nearby',
distance_km: 1.5,
location_recorded_at: '2026-10-02T10:00:00Z',
},
],
geographicCoverage: {
origin_id: 'current',
origin_title: 'Public reference',
radius_km: 25,
origin_recorded_at: '2026-10-01T10:00:00Z',
with_public_point: 4,
without_public_point: 8,
source: 'Published location register',
method: 'Geodesic, not road',
},
});
await flush();
let html = renderToStaticMarkup(h.render(scoped));
assert.match(html, /Raio de 25 km/);
assert.match(html, /4 com ponto utilizável; 8 sem ponto público/);
assert.match(html, /Localização registada em/);
assert.match(html, /Published location register/);
assert.match(html, /near_business=current&amp;radius_km=25/);
assert.match(html, /Geodesic, not road/);
tree = h.render(scoped);
nodes(tree)
.find((node) => node.type === 'fieldset')
.props.children[1].props.children[1].props.onChange({
target: { value: '' },
});
html = renderToStaticMarkup(h.render(scoped));
assert.match(html, /A consultar/);
assert.doesNotMatch(html, /Nearby|8 sem ponto/);
h.start();
assert.equal(
new URL(h.requests[1].url, 'https://portal.invalid').searchParams.get(
'province_id',
),
'qa-province',
);
assert.equal(
new URL(h.requests[1].url, 'https://portal.invalid').searchParams.has(
'radius_km',
),
false,
);
const changed = { ...scoped, currentId: 'new-reference' };
h.render(changed);
h.start();
assert.equal(
new URL(h.requests[2].url, 'https://portal.invalid').searchParams.has(
'near_business',
),
false,
);
});
await test('missing point reference has no radius selector, and a radius response without coverage is a recoverable failure', async () => {
const h = harness();
assert.match(
renderToStaticMarkup(h.render(props)),
/requer um ponto primário público exacto/,
);
assert.equal(
nodes(h.render(props)).some((node) => node.type === 'fieldset'),
false,
);
const scoped = { ...props, radiusAvailable: true };
const tree = h.render(scoped);
nodes(tree)
.find((node) => node.type === 'fieldset')
.props.children[1].props.children[1].props.onChange({
target: { value: '10' },
});
h.render(scoped);
h.start();
h.requests[0].resolve({ data: [] });
await flush();
const html = renderToStaticMarkup(h.render(scoped));
assert.match(html, /Tentar novamente/);
assert.doesNotMatch(html, /Não foram encontrados/);
});
await test('explicit public classification changes matching criteria and is cleared when the source record changes', async () => {
const h = harness();
@@ -0,0 +1,288 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
text,
} from './helpers/technical-incident-handling.mjs';
const note = 'PRIVATE SYNTHETIC prepared note with evidence.';
test('the actual scan incident detail identifies its failure and retains the ordinary technical treatment command', () => {
const initial = props();
const h = harness(
props({
incident: {
...initial.incident,
operation: 'scan_document',
error_code: 'scan_worker_failed',
},
}),
);
assert.match(text(h.tree), /Análise de segurança de documento/);
assert.match(text(h.tree), /Falha na execução da análise de segurança/);
h.change(note);
h.click('Assumir tratamento');
assert.equal(h.sent[0].data.action, 'claim');
assert.equal(
h.sent[0].url,
'/suporte-tecnico/incidentes/' + initial.incident.reference,
);
});
function prepare(h, action = 'Assumir tratamento') {
h.change(note);
return h.click(action);
}
function next(h, request = h.sent.at(-1), patch = {}) {
return {
...h.props,
commands: [
...h.props.commands,
{
key: request.data.operation_key,
version: request.data.version + 1,
},
],
incident: {
...h.props.incident,
handling: {
...h.props.incident.handling,
version: request.data.version + 1,
status: 'in_progress',
assignee_user_id: h.props.actorId,
assignee_name: 'SYNTHETIC support',
updated_at: '2026-11-03',
...patch,
},
},
};
}
function result(h, request = h.sent.at(-1), patch = {}) {
return {
reference: h.props.incident.reference,
actor_id: h.props.actorId,
operation_key: request.data.operation_key,
result_version: request.data.version + 1,
handling: next(h, request).incident.handling,
...patch,
};
}
test('commands match the technical state and a note is required without sending an empty request', () => {
const h = harness();
h.click('Assumir tratamento');
assert.equal(h.sent.length, 0);
assert.match(text(h.tree), /10 a 3000/);
const resolved = harness(
props({
incident: {
...props().incident,
handling: {
...props().incident.handling,
status: 'resolved',
version: 2,
},
},
}),
);
assert.ok(resolved.button('Reabrir incidente'));
assert.equal(resolved.button('Resolver incidente'), undefined);
assert.equal(resolved.button('Assumir tratamento'), undefined);
});
test('a command freezes the analysed version and a rapid second click sends no duplicate', () => {
const h = harness(),
request = prepare(h);
h.click('Resolver incidente');
assert.equal(h.sent.length, 1);
assert.equal(request.data.version, 0);
assert.equal(request.data.action, 'claim');
assert.equal(request.data.note, note);
});
test('confirmation preserves a note edited during the request and reloads the authorised detail', async () => {
const h = harness(),
request = prepare(h);
h.change('PRIVATE SYNTHETIC later note');
await h.reply(result(h, request), request);
assert.equal(h.note, 'PRIVATE SYNTHETIC later note');
assert.equal(h.reloads.length, 1);
h.refreshed(next(h, request));
const second = h.click('Acrescentar nota');
assert.equal(second.data.version, 1);
assert.notEqual(second.data.operation_key, request.data.operation_key);
});
test('a lost response repeats exactly the frozen command and leaves later text intact', async () => {
const h = harness(),
request = prepare(h);
await h.fail();
h.change('PRIVATE SYNTHETIC later note');
const retry = h.click('Repetir o registo original');
assert.deepEqual(retry.data, request.data);
await h.reply(result(h, retry), retry);
assert.equal(h.note, 'PRIVATE SYNTHETIC later note');
});
test('an authorised refresh confirms a committed command without another write', async () => {
const h = harness(),
request = prepare(h);
await h.fail(503);
h.click('Actualizar incidente');
assert.deepEqual(h.reloads[0].only, [
'incident',
'history',
'commands',
'actorId',
]);
h.refreshed(next(h, request));
assert.equal(h.sent.length, 1);
assert.equal(h.note, '');
assert.equal(h.leave(), false);
});
test('a mismatched success remains uncertain and cannot erase the prepared note', async () => {
const h = harness(),
request = prepare(h);
await h.reply(result(h, request, { actor_id: 99 }));
assert.equal(h.note, note);
assert.ok(h.button('Repetir o registo original'));
assert.equal(h.leave(), true);
});
test('an older receipt does not silently adopt a later team decision', async () => {
const h = harness(),
request = prepare(h);
await h.fail();
h.click('Actualizar incidente');
h.refreshed(
next(h, request, {
version: 3,
status: 'resolved',
assignee_name: 'SYNTHETIC colleague',
}),
);
assert.equal(h.note, '');
assert.match(text(h.tree), /O incidente mudou/);
assert.equal(h.button('Acrescentar nota').props.disabled, true);
h.click('Confirmar leitura do estado actual');
h.change(note);
assert.equal(h.click('Acrescentar nota').data.version, 3);
});
test('stale props require explicit comparison and preserve the prepared note', () => {
const h = harness();
h.change(note);
h.render({
...h.props,
incident: {
...h.props.incident,
handling: {
...h.props.incident.handling,
version: 1,
status: 'in_progress',
assignee_name: 'SYNTHETIC colleague',
},
},
});
h.click('Resolver incidente');
assert.equal(h.sent.length, 0);
h.click('Confirmar leitura do estado actual');
assert.equal(h.click('Resolver incidente').data.version, 1);
assert.equal(h.note, note);
});
test('a conflicting command is abandoned only after a newer authorised state is explicitly adopted', async () => {
const h = harness(),
request = prepare(h);
await h.fail(409);
h.click('Actualizar incidente');
h.refreshed({
...h.props,
incident: {
...h.props.incident,
handling: {
...h.props.incident.handling,
version: 2,
status: 'resolved',
},
},
});
assert.equal(h.sent.length, 1);
h.click('Confirmar leitura do estado actual');
const retry = h.click('Reabrir incidente');
assert.equal(retry.data.version, 2);
assert.notEqual(retry.data.operation_key, request.data.operation_key);
assert.equal(retry.data.note, note);
});
test('a read at the same version cannot discard a still uncertain command', async () => {
const h = harness(),
request = prepare(h);
await h.fail();
h.click('Actualizar incidente');
h.refreshed({ ...h.props });
assert.equal(h.button('Confirmar leitura do estado actual'), undefined);
assert.deepEqual(h.click('Repetir o registo original').data, request.data);
});
test('a definitive validation rejection preserves text and permits a corrected new command', async () => {
const h = harness(),
request = prepare(h);
await h.fail(422);
assert.equal(h.note, note);
assert.match(text(h.tree), /SYNTHETIC rejected note/);
h.change('PRIVATE SYNTHETIC corrected note');
const fresh = h.click('Acrescentar nota');
assert.notEqual(fresh.data.operation_key, request.data.operation_key);
assert.equal(fresh.data.version, 0);
});
test('access loss preserves the original attempt until a fresh authorised read', async () => {
const h = harness(),
request = prepare(h);
await h.fail(403);
assert.equal(h.button('Repetir o registo original'), undefined);
assert.equal(h.note, note);
h.click('Actualizar incidente');
h.refreshed({ ...h.props });
assert.deepEqual(h.click('Repetir o registo original').data, request.data);
});
test('late callbacks from another account cannot acknowledge or overwrite its note', async () => {
const h = harness(),
request = prepare(h);
h.render({ ...h.props, actorId: 2 });
assert.equal(h.note, '');
h.change('PRIVATE SYNTHETIC next account note');
await h.reply(result(h, request, { actor_id: 1 }), request);
assert.equal(h.note, 'PRIVATE SYNTHETIC next account note');
assert.equal(h.sent.length, 1);
});
test('a late response to an already confirmed command cannot clear or unlock the next request', async () => {
const h = harness(),
first = prepare(h);
h.click('Actualizar incidente');
h.refreshed(next(h, first));
h.change('PRIVATE SYNTHETIC next command note');
const second = h.click('Acrescentar nota');
await h.reply(result(h, first), first);
assert.equal(h.note, 'PRIVATE SYNTHETIC next command note');
assert.equal(h.button('Acrescentar nota').props.disabled, true);
assert.equal(h.sent.length, 2);
await h.reply(result(h, second), second);
assert.equal(h.note, '');
});
test('the detail uses one leave guard and keeps unsent text through history refresh', () => {
const h = harness();
h.change(note);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
assert.equal(h.leave(true), false);
h.click('Actualizar incidente');
h.refreshed({
...h.props,
history: {
...h.props.history,
data: [
{
id: 'one',
version: 1,
action: 'note',
status: 'open',
actor: 'SYNTHETIC colleague',
occurred_at: '2026-11-03',
note: 'SYNTHETIC previous treatment',
note_available: true,
},
],
},
});
assert.equal(h.note, note);
assert.match(text(h.tree), /SYNTHETIC previous treatment/);
});
@@ -0,0 +1,102 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
harness,
props,
reference,
text,
} from './helpers/technical-incident-handling.mjs';
const label = 'Marcar aviso como consultado',
retry = 'Repetir confirma\u00e7\u00e3o de consulta';
const initial = (patch = {}) => props({ notice: { unread: true }, ...patch });
const receipt = (patch = {}) => ({
actor_id: 1,
reference,
read: true,
...patch,
});
test('consultation acknowledgement sends once without a treatment command or another leave guard', async () => {
const h = harness(initial());
h.change('SYNTHETIC prepared treatment');
const req = h.click(label);
h.click(label);
assert.equal(h.sent.length, 1);
assert.equal(
req.url,
`/suporte-tecnico/incidentes/${reference}/consultado`,
);
assert.deepEqual(req.data, {});
await h.reply(receipt());
assert.equal(h.note, 'SYNTHETIC prepared treatment');
assert.match(text(h.tree), /Aviso consultado por si/);
assert.deepEqual(h.reloads[0].only, [
'incidents',
'profileAccess',
'notice',
]);
assert.equal(h.leave(), true);
assert.equal(h.confirmCalls, 1);
});
test('an uncertain read acknowledgement can be explicitly repeated with the same empty command', async () => {
const h = harness(initial());
const first = h.click(label);
await h.fail();
assert.ok(h.button(retry));
h.click(retry);
assert.equal(h.sent[1].url, first.url);
assert.deepEqual(h.sent[1].data, first.data);
await h.reply(receipt());
assert.equal(h.button(retry), undefined);
});
test('a receipt for another actor, root or read state cannot acknowledge this notice', async () => {
for (const patch of [
{ actor_id: 2 },
{ reference: 'other' },
{ read: false },
]) {
const h = harness(initial());
h.click(label);
await h.reply(receipt(patch));
assert.ok(h.button(retry));
assert.equal(h.reloads.length, 0);
}
});
test('late replies cannot change the notice or draft after changing accounts', async () => {
const h = harness(initial());
const old = h.click(label);
h.render(initial({ actorId: 2 }));
h.change('New actor treatment preparation');
await h.reply(receipt(), old);
assert.ok(h.button(label));
assert.equal(h.note, 'New actor treatment preparation');
assert.equal(h.reloads.length, 0);
});
test('a refreshed own acknowledgement wins over a late failed POST and older unread props', async () => {
const h = harness(initial());
const old = h.click(label);
h.render(initial({ notice: { unread: false } }));
await h.fail(null, old);
assert.match(text(h.tree), /Aviso consultado por si/);
assert.doesNotMatch(text(h.tree), /poss\u00edvel confirmar/);
h.render(initial());
assert.equal(h.button(label), undefined);
assert.equal(h.button(retry), undefined);
});
test('known acknowledgement remains confirmed if the subsequent preview has no response', async () => {
const h = harness(initial());
h.click(label);
await h.reply(receipt());
assert.equal(h.sent.length, 1);
assert.equal(h.button(label), undefined);
assert.equal(h.leave(), false);
assert.equal(h.confirmCalls, 0);
});
test('revoked access preserves the treatment preparation and exposes no server exception text', async () => {
const h = harness(initial());
h.change('PRIVATE SYNTHETIC treatment draft');
h.click(label);
await h.fail(403);
assert.equal(h.note, 'PRIVATE SYNTHETIC treatment draft');
assert.ok(h.button(retry));
assert.doesNotMatch(text(h.tree), /SYNTHETIC HTTP/);
});