Add automatic contextual help to adaptive investment stages
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-17 08:55:48 +02:00
parent b60c231ddc
commit e11b5592c7
10 changed files with 2532 additions and 1762 deletions
@@ -0,0 +1,88 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
investmentStageHelp,
preparationHelp,
helpPreferenceKey,
readHelpPreference,
} from '../../resources/js/lib/investment-step-help.ts';
test('each of the 19 existing stages has specific orientation, an example and a purpose', () => {
const instructions = new Set();
for (let i = 1; i <= 19; i++) {
const code = `S${String(i).padStart(2, '0')}`;
const help = investmentStageHelp(code, `Título ${i}`);
assert.equal(help.code, code);
assert.equal(help.title, `Título ${i}`);
assert.ok(help.instruction.length > 30);
assert.ok(help.example.length > 25);
assert.ok(help.purpose.length > 25);
instructions.add(help.instruction);
}
assert.equal(instructions.size, 19);
assert.equal(
investmentStageHelp('future-stage', 'Nova etapa').title,
'Nova etapa',
);
});
test('preparation guidance preserves the review before confirmation sequence', () => {
assert.deepEqual(
preparationHelp.map((step) => step.code),
['help-choices', 'help-declarations', 'help-review'],
);
assert.match(preparationHelp[2].instruction, /Compare.*confirme/);
});
test('preferences default safely, survive malformed storage and remain separate per user and flow', () => {
assert.deepEqual(readHelpPreference(null), {
automatic: true,
seen: false,
});
assert.deepEqual(readHelpPreference('{bad'), {
automatic: true,
seen: false,
});
assert.deepEqual(readHelpPreference('{"automatic":false,"seen":true}'), {
automatic: false,
seen: true,
});
assert.deepEqual(readHelpPreference('{"automatic":true,"seen":true}'), {
automatic: true,
seen: true,
});
assert.notEqual(helpPreferenceKey(1, 'path'), helpPreferenceKey(2, 'path'));
assert.notEqual(
helpPreferenceKey(1, 'path'),
helpPreferenceKey(1, 'preparation'),
);
assert.notEqual(
helpPreferenceKey('a:b', 'c'),
helpPreferenceKey('a', 'b:c'),
);
});
test('dossier help follows only the steps already permitted by the adaptive path', () => {
const page = readFileSync(
new URL(
'../../resources/js/pages/investor-path/show.tsx',
import.meta.url,
),
'utf8',
);
assert.match(
page,
/steps=\{path\.steps\s*\.filter\(\(step\) => step\.preparation_allowed\)/,
);
assert.match(page, /<HelpAtStep code=\{step.code\}/);
const component = readFileSync(
new URL(
'../../resources/js/components/investment-step-help.tsx',
import.meta.url,
),
'utf8',
);
assert.doesNotMatch(component, /router\.|fetch\(|\.submit\(|\.post\(/);
assert.doesNotMatch(component, /location\.(assign|reload)|window\.history/);
});
@@ -23,7 +23,9 @@ function load(path, mocks = {}, exportName = 'default', extra = '') {
compileFunction(output + extra, ['require', 'module', 'exports'])(
(name) =>
mocks[name] ??
(name.startsWith('@/') ? { default: () => null } : require(name)),
(name === '@/components/investment-step-help'
? { HelpAtStep: () => null, InvestmentHelpGuide: ({ children }) => children }
: name.startsWith('@/') ? { default: () => null } : require(name)),
module,
module.exports,
);
@@ -508,7 +510,7 @@ function contextPreviewHarness(overrides = {}) {
const pending = [];
const Editor = load('../../resources/js/pages/investor-path/context.tsx', {
react: hooks,
'@inertiajs/react': { Link: () => null, router: {} },
'@inertiajs/react': { usePage: () => ({ props: { auth: { user: { id: 1 } } } }), Link: () => null, router: {} },
'@/components/navigation-context': {
useNavigationContext: () => ({ refresh() {} }),
},
+132 -85
View File
@@ -1,31 +1,35 @@
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 ts from "typescript";
import React from "react";
import { revealPathStage } from "../../resources/js/lib/investor-path-stage.ts";
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 ts from 'typescript';
import React from 'react';
import { revealPathStage } from '../../resources/js/lib/investor-path-stage.ts';
import { investmentStageHelp } from '../../resources/js/lib/investment-step-help.ts';
const require = createRequire(import.meta.url);
const flatten = (node) =>
Array.isArray(node)
? node.flatMap(flatten)
: node && typeof node === "object"
: node && typeof node === 'object'
? [node, ...flatten(node.props?.children)]
: [];
const text = (node) =>
Array.isArray(node)
? node.map(text).join("")
: node && typeof node === "object"
? node.map(text).join('')
: node && typeof node === 'object'
? text(node.props?.children)
: String(node ?? "");
: String(node ?? '');
function harness(overrides = {}, react = React) {
const requests = [];
let form;
const module = { exports: {} };
const source = fs.readFileSync(
new URL("../../resources/js/pages/investor-path/show.tsx", import.meta.url),
"utf8",
new URL(
'../../resources/js/pages/investor-path/show.tsx',
import.meta.url,
),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
@@ -33,13 +37,19 @@ function harness(overrides = {}, react = React) {
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code + "\nmodule.exports.Stage = Stage;", ["require", "module", "exports"])(
compileFunction(code + '\nmodule.exports.Stage = Stage;', [
'require',
'module',
'exports',
])(
(name) =>
name === "react"
name === 'react'
? react
: name === "@inertiajs/react"
: name === '@inertiajs/react'
? {
usePage: () => ({ props: { auth: { user: { id: 1 } }, flash: {} } }),
usePage: () => ({
props: { auth: { user: { id: 1 } }, flash: {} },
}),
useForm(initial) {
form ??= {
data: initial,
@@ -52,115 +62,145 @@ function harness(overrides = {}, react = React) {
this.convert = fn;
},
post(url, options) {
requests.push({ url, options, data: this.convert(this.data) });
requests.push({
url,
options,
data: this.convert(this.data),
});
},
};
return form;
},
}
: name === "@/lib/investor-path"
? { pathStates: { preparing: "Em preparação" } }
: name === "@/lib/operation-key" ? { createOperationKey: () => 'qa-key' }
: name === "@/lib/investor-path-stage" ? { revealPathStage }
: name === "@/components/proactive-investment" ? { proactiveView: () => null }
: name.startsWith("@/")
? {}
: require(name),
: name === '@/lib/investor-path'
? { pathStates: { preparing: 'Em preparação' } }
: name === '@/lib/operation-key'
? { createOperationKey: () => 'qa-key' }
: name === '@/lib/investor-path-stage'
? { revealPathStage }
: name === '@/lib/investment-step-help'
? { investmentStageHelp }
: name === '@/components/proactive-investment'
? { proactiveView: () => null }
: name.startsWith('@/')
? {}
: require(name),
module,
module.exports,
);
const path = {
case: { id: "dossier-qa", version: 7 },
context_opportunity: "opportunity:42",
case: { id: 'dossier-qa', version: 7 },
context_opportunity: 'opportunity:42',
investment_context: { revision: 3 },
canWrite: true,
canReview: false,
steps: [],
next: { code: "S02" },
documents: [{ document_id: "doc-qa", file_name: "Prova QA", malware_scan_status: "clean" }],
next: { code: 'S02' },
documents: [
{
document_id: 'doc-qa',
file_name: 'Prova QA',
malware_scan_status: 'clean',
},
],
...overrides,
};
const step = {
code: "S08",
title: "Licenciamento prévio",
state: "preparing",
code: 'S08',
title: 'Licenciamento prévio',
state: 'preparing',
preparation_allowed: true,
action_gaps: {},
detail: {},
source_paragraph: 8,
};
return {
render: (changes = {}) => module.exports.Stage({ step: { ...step, ...changes }, path }),
render: (changes = {}) =>
module.exports.Stage({ step: { ...step, ...changes }, path }),
renderPage: () => module.exports.default(path),
requests,
form: () => form,
path,
};
}
test("S08 has one current state, a visible primary save action and no nested disclosure", () => {
test('S08 has one current state, a visible primary save action and no nested disclosure', () => {
const h = harness();
const tree = h.render();
const nodes = flatten(tree);
assert.equal(tree.type, "section");
assert.equal(nodes.filter((n) => n.type === "details").length, 0);
assert.equal(tree.type, 'section');
assert.equal(nodes.filter((n) => n.type === 'details').length, 0);
assert.equal(
nodes.filter((n) => ["h3", "p"].includes(n.type) && text(n).includes("Em preparação"))
.length,
nodes.filter(
(n) =>
['h3', 'p'].includes(n.type) &&
text(n).includes('Em preparação'),
).length,
1,
);
assert.equal(nodes.find((n) => n.type === "button").props.disabled, false);
assert.match(nodes.find((n) => n.type === "button").props.className, /bg-emerald/);
assert.equal(nodes.filter((n) => n.type === "form").length, 1);
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, false);
assert.match(
nodes.find((n) => n.type === 'button').props.className,
/bg-emerald/,
);
assert.equal(nodes.filter((n) => n.type === 'form').length, 1);
assert.equal(tree.props.tabIndex, -1);
});
test("editing and saving retain context, current version, fields and existing endpoint", () => {
test('editing and saving retain context, current version, fields and existing endpoint', () => {
const h = harness({ canReview: true });
let tree = h.render();
const form = h.form();
Object.assign(form.data, {
reason: "Fundamento deliberado",
reference: "REF-QA",
authority: "Entidade QA",
document_id: "doc-qa",
decision_date: "2026-11-10",
reason: 'Fundamento deliberado',
reference: 'REF-QA',
authority: 'Entidade QA',
document_id: 'doc-qa',
decision_date: '2026-11-10',
context_reviewed: true,
});
h.path.case.version = 8;
tree = h.render();
assert.equal(form.data.reason, "Fundamento deliberado");
assert.equal(flatten(tree).filter((n) => n.type === "input").length, 3);
assert.equal(form.data.reason, 'Fundamento deliberado');
assert.equal(flatten(tree).filter((n) => n.type === 'input').length, 3);
flatten(tree)
.find((n) => n.type === "form")
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.deepEqual(h.requests, [
{
url: "/investimentos/dossier-qa/etapas/S08",
url: '/investimentos/dossier-qa/etapas/S08',
options: { preserveScroll: true },
data: { ...form.data, version: 8 },
},
]);
});
test("read-only and inapplicable stages do not acquire write controls; errors and processing remain visible", () => {
test('read-only and inapplicable stages do not acquire write controls; errors and processing remain visible', () => {
const read = harness({ canWrite: false, canReview: false });
assert.equal(flatten(read.render()).filter((n) => n.type === "form").length, 0);
assert.equal(
flatten(read.render()).filter((n) => n.type === 'form').length,
0,
);
const h = harness();
h.render();
assert.equal(
flatten(h.render({ preparation_allowed: false })).filter((n) => n.type === "form").length,
flatten(h.render({ preparation_allowed: false })).filter(
(n) => n.type === 'form',
).length,
0,
);
h.form().processing = true;
h.form().errors = { reason: "Conflito de versão" };
h.form().errors = { reason: 'Conflito de versão' };
const nodes = flatten(h.render());
assert.equal(nodes.find((n) => n.type === "button").props.disabled, true);
assert.equal(text(nodes.find((n) => n.props.role === "alert")), "Conflito de versão");
assert.equal(nodes.find((n) => n.type === 'button').props.disabled, true);
assert.equal(
text(nodes.find((n) => n.props.role === 'alert')),
'Conflito de versão',
);
});
test("other stages keep their existing disclosure and reviewer fields/action choices", () => {
test('other stages keep their existing disclosure and reviewer fields/action choices', () => {
const h = harness({ canWrite: false, canReview: true });
const tree = h.render({ code: "S07" });
assert.equal(tree.type, "details");
assert.equal(flatten(tree).filter((n) => n.type === "details").length, 3);
assert.equal(h.form().data.action, "review");
const tree = h.render({ code: 'S07' });
assert.equal(tree.type, 'details');
assert.equal(flatten(tree).filter((n) => n.type === 'details').length, 3);
assert.equal(h.form().data.action, 'review');
assert.match(text(tree), /Registar acto externo/);
assert.match(text(tree), /Documento de suporte/);
});
@@ -168,46 +208,48 @@ function targetFixture() {
const calls = [];
const root = {
contains: (node) => node === target,
ownerDocument: { getElementById: (id) => (id === "S08" ? target : null) },
ownerDocument: {
getElementById: (id) => (id === 'S08' ? target : null),
},
};
const phase = { tagName: "DETAILS", open: false, parentElement: root };
const phase = { tagName: 'DETAILS', open: false, parentElement: root };
const target = {
tagName: "SECTION",
tagName: 'SECTION',
parentElement: phase,
scrollIntoView: (options) => calls.push(["scroll", options]),
focus: (options) => calls.push(["focus", options]),
scrollIntoView: (options) => calls.push(['scroll', options]),
focus: (options) => calls.push(['focus', options]),
};
return { root, phase, target, calls };
}
test("deep-link opens the containing phase and focuses S08 without navigation or changing fields", () => {
test('deep-link opens the containing phase and focuses S08 without navigation or changing fields', () => {
const f = targetFixture();
assert.equal(revealPathStage(f.root, "#S08", ["S02", "S08"]), true);
assert.equal(revealPathStage(f.root, '#S08', ['S02', 'S08']), true);
assert.equal(f.phase.open, true);
assert.deepEqual(f.calls, [
["scroll", { block: "start" }],
["focus", { preventScroll: true }],
['scroll', { block: 'start' }],
['focus', { preventScroll: true }],
]);
f.phase.open = false;
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), true);
assert.equal(revealPathStage(f.root, '#S08', ['S08']), true);
assert.equal(f.phase.open, true);
});
test("unknown, absent or out-of-scope hash targets have no effect", () => {
test('unknown, absent or out-of-scope hash targets have no effect', () => {
const f = targetFixture();
for (const hash of ["", "#unknown", "#S08%22", "#S07"])
assert.equal(revealPathStage(f.root, hash, ["S08"]), false);
for (const hash of ['', '#unknown', '#S08%22', '#S07'])
assert.equal(revealPathStage(f.root, hash, ['S08']), false);
f.root.contains = () => false;
assert.equal(revealPathStage(f.root, "#S08", ["S08"]), false);
assert.equal(revealPathStage(f.root, '#S08', ['S08']), false);
assert.equal(f.phase.open, false);
assert.deepEqual(f.calls, []);
});
test("page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up", () => {
test('page reveals the initial hash and server next-stage updates, listens for hash changes and cleans up', () => {
const f = targetFixture(),
effects = [],
listeners = new Map();
const previousWindow = globalThis.window;
let previousDependencies;
globalThis.window = {
location: { hash: "#S08" },
location: { hash: '#S08' },
addEventListener: (type, fn) => listeners.set(type, fn),
removeEventListener: (type, fn) => {
assert.equal(listeners.get(type), fn);
@@ -229,19 +271,24 @@ test("page reveals the initial hash and server next-stage updates, listens for h
tools: {},
content_sources: [],
services: [],
steps: [{ code: "S08", preparation_allowed: true }],
steps: [{ code: 'S08', preparation_allowed: true }],
},
{
...React,
useRef: () => ({ current: f.root }),
useEffect: (effect, dependencies) => {
if (!previousDependencies || dependencies.some((value, i) => value !== previousDependencies[i])) {
if (
!previousDependencies ||
dependencies.some(
(value, i) => value !== previousDependencies[i],
)
) {
effects.push(effect);
}
previousDependencies = dependencies;
},
useState: (initial) => [
typeof initial === "function" ? initial() : initial,
typeof initial === 'function' ? initial() : initial,
() => {},
],
},
@@ -251,14 +298,14 @@ test("page reveals the initial hash and server next-stage updates, listens for h
const cleanup = effects[0]();
assert.equal(f.phase.open, true);
f.phase.open = false;
listeners.get("hashchange")();
listeners.get('hashchange')();
assert.equal(f.phase.open, true);
cleanup();
assert.equal(listeners.size, 0);
h.renderPage();
assert.equal(effects.length, 1);
// A saved transition changes the controlled phase's `open` prop.
h.path.next = { code: "S09" };
h.path.next = { code: 'S09' };
f.phase.open = false;
h.renderPage();
assert.equal(effects.length, 2);
+2 -1
View File
@@ -27,7 +27,7 @@ function load(file, mocks = {}) {
return {
Link: ({ children, ...props }) =>
React.createElement('a', props, children),
usePage: () => ({ url: '/sectores/test' }),
usePage: () => ({ url: '/sectores/test', props: { auth: { user: { id: 1 } } } }),
};
if (id.startsWith('.') || id.startsWith('@/')) {
const base = id.startsWith('@/')
@@ -111,6 +111,7 @@ test('demographic comparison retains four saved places and requires a province b
test('the real preparation editor opens an own idea with its budget and no mandatory advert or duplicate reference selector', () => {
const Empty = () => null;
const Editor = load('pages/investor-path/context.tsx', {
'@/components/investment-step-help': { HelpAtStep: Empty, InvestmentHelpGuide: ({ children }) => children },
'@/pages/investment/shared': {
Frame: ({ children }) =>
React.createElement('main', null, children),