Merge branch 'main' of https://git.tempo.co.mz/nala/Investidor-V2
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 15:33:56 +02:00
110 changed files with 4105 additions and 266 deletions
@@ -1788,7 +1788,7 @@ void test('business plan export carries its assumptions, formulas, period, curre
assert.match(csv, /business-plan-v17/);
assert.match(
csv,
/Valores do formulário; os valores iniciais podem ser exemplos demonstrativos/,
/Pressupostos introduzidos pelo investidor no formulário/,
);
assert.match(csv, /Ponte contabilístico-fiscal,incomplete/);
assert.match(csv, /Matéria colectável,indeterminate/);
+11 -5
View File
@@ -196,16 +196,22 @@ function editor(initialSnapshot) {
};
}
void test('annual example snapshot is saved through the existing parent callback and recovered by a fresh editor', () => {
void test('legacy example snapshot stays preserved but cannot be loaded from the investor editor', () => {
const form = editor();
form.edit('Preço por unidade', '100');
const saved = JSON.parse(form.snapshot());
const exampleSnapshot = serializeAnnualExampleSnapshot(
newAnnualReferencePlan(),
);
form.example().onSnapshotChange(exampleSnapshot);
const recovered = editor(form.snapshot());
assert.equal(recovered.example().snapshot, exampleSnapshot);
saved.plan.annualExampleSnapshot = exampleSnapshot;
const recovered = editor(JSON.stringify(saved));
assert.equal(recovered.example(), undefined);
recovered.edit('Preço por unidade', '250.50');
assert.equal(recovered.example().snapshot, exampleSnapshot);
assert.equal(
JSON.parse(recovered.snapshot()).plan.annualExampleSnapshot,
exampleSnapshot,
);
assert.equal(recovered.field('Preço por unidade').value, '250.50');
});
void test('monthly units, unit price, variable cost and operating expenses remain editable after snapshot echo', () => {
@@ -0,0 +1,130 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import * as navigation from '../../resources/js/lib/portal-navigation.ts';
const require = createRequire(import.meta.url);
function render(props, summaryAvailable = false) {
const module = { exports: {} };
const code = ts.transpileModule(
fs.readFileSync(
new URL(
'../../resources/js/components/dashboard-management.tsx',
import.meta.url,
),
'utf8',
),
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
},
).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (name === '@/lib/portal-navigation') return navigation;
if (name === '@/components/profile-navigation')
return {
default: () =>
React.createElement(
'div',
{},
'Existing personal access',
),
};
if (name === '@inertiajs/react')
return {
usePage: () => ({ props }),
Head: () => null,
Link: ({ children, href, ...rest }) =>
React.createElement('a', { href, ...rest }, children),
};
return require(name);
},
module,
module.exports,
);
return renderToStaticMarkup(
React.createElement(module.exports.default, { summaryAvailable }),
);
}
void test('dashboard leads with the same authorised administration destinations as the portal menu', () => {
const html = render(
{
auth: {
user: { id: 'synthetic-manager' },
canManagePortal: true,
legacyManagementAccess: true,
},
administrationNavigation: [
{
label: 'Biblioteca e documentos',
href: '/gestao-conteudos/documentos',
},
],
contentManagementHref: '/gestao-conteudos',
dashboardNavigation: [{ label: 'Visão geral', href: '/dashboard' }],
scopedAdministration: [
{
label: 'Atribuições de interesses',
href: '/management/interests/atribuicoes',
},
],
profileAccess: {
administration: '/management/profiles',
request: '/profiles/request',
},
},
true,
);
assert.match(html, /Dashboard de gestão do portal/);
assert.match(html, /Conteúdos e oportunidades/);
assert.match(html, /Acessos e configuração/);
assert.match(html, /href="\/management\/profiles"/);
assert.match(html, /href="\/gestao-conteudos\/documentos"/);
assert.match(html, /Existing personal access/);
assert.equal(
(html.match(/href="\/management\/profiles"/g) ?? []).length,
1,
);
assert.doesNotMatch(html, /href="\/dashboard"/);
});
void test('scoped editor sees its granted destinations without inherited manager or access controls', () => {
const html = render({
auth: {
user: { id: 'synthetic-editor' },
canManagePortal: true,
legacyManagementAccess: false,
},
contentManagementHref: '/gestao-conteudos',
administrationNavigation: [
{ label: 'Documentos', href: '/gestao-conteudos/documentos' },
],
});
assert.match(html, /Dashboard de gestão do portal/);
assert.match(html, /href="\/gestao-conteudos\/documentos"/);
assert.doesNotMatch(
html,
/href="\/management\/profiles"|href="\/management\/interests"/,
);
});
void test('ordinary investor keeps personal workspace and never gains administrative cards', () => {
const html = render({
auth: { user: { id: 'synthetic-investor' }, canManagePortal: false },
});
assert.match(html, /A minha área de trabalho/);
assert.match(html, /Existing personal access/);
assert.doesNotMatch(
html,
/aria-label="Gestão do portal"|href="\/management\//,
);
});
@@ -11,7 +11,7 @@ new Function('require','module','exports',code)(name=>name==='@inertiajs/react'?
test('each manager dashboard menu anchor resolves to a real section',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{summary:{requestsByStatus:{},publishedOpportunities:0,draftOpportunities:0,activeSectors:0,recentRequests:[]},workQueue:null}));
for(const id of ['meu-trabalho','manifestacoes','indicadores-oportunidades','pedidos-recentes','accoes-rapidas'])assert.match(html,new RegExp('id="'+id+'"'));
assert.match(html,/Painel do portal/);
});
test('investor section remains distinct from administrative summary',()=>{
const html=renderToStaticMarkup(React.createElement(module.exports.default,{summary:null,investorPath:{contexts:[],current:null}}));
@@ -42,6 +42,7 @@ const Dashboard = load('../../resources/js/pages/dashboard.tsx', {
...mocks,
'@/components/dashboard-work-queue': { default: Queue },
'@/components/profile-navigation': { default: Empty },
'@/components/dashboard-management': { default: Empty },
'@/components/content-management-entry': { default: Empty },
'@/routes': { dashboard: () => '/dashboard' },
}).default;
+195
View File
@@ -0,0 +1,195 @@
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 { renderToStaticMarkup } from 'react-dom/server';
import * as normal from '../../resources/js/lib/irpc-normal.ts';
import * as rational from '../../resources/js/lib/fiscal-rational.ts';
import * as inputText from '../../resources/js/lib/input-text.ts';
import {
monthlyIvaInput,
monthlyIvaKey,
} from '../../resources/js/lib/monthly-iva.ts';
import {
partitionSimulationDraft,
restoreSimulationDraft,
} from '../../resources/js/lib/simulation-form.ts';
const require = createRequire(import.meta.url);
function load(file, mocks) {
const module = { exports: {} };
const source = fs.readFileSync(
new URL('../../resources/js/components/' + file, import.meta.url),
'utf8',
);
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(n) => mocks[n] ?? require(n),
module,
module.exports,
);
return module.exports;
}
const nodes = (n) =>
Array.isArray(n)
? n.flatMap(nodes)
: n && typeof n === 'object'
? [n, ...nodes(n.props?.children)]
: [];
const settings = {
start: '2026-01',
basis: 'net',
declared: true,
auto: false,
};
const seed = () =>
JSON.parse(
fs.readFileSync(
new URL('./fixtures/irpc-base-preserved.json', import.meta.url),
'utf8',
),
);
void test('IVA plan source forwards current sales, never the old independent base; operation choice is explicit and recoverable', () => {
const Monthly = () => null;
const { SimulationPublishedIva } = load('simulation-published-iva.tsx', {
'../lib/input-text.ts': inputText,
'./simulation-monthly-iva': { SimulationMonthlyIva: Monthly },
});
const draft = {
...seed(),
currency: 'MZN',
fiscal_period: '2026',
published_iva_base: '999999',
monthly_iva_settings: JSON.stringify(settings),
};
const calls = [];
const onCalculate = async (input) => {
calls.push(input);
};
let changed;
const props = {
draft,
busy: false,
onCalculate,
onChange: (field, value) => {
changed = [field, value];
},
};
let tree = SimulationPublishedIva(props);
let monthly = nodes(tree).find((n) => n.type === Monthly);
assert.ok(monthly);
assert.equal(monthly.props.onCalculate, onCalculate);
assert.equal(monthly.props.draft, draft);
const linked = SimulationPublishedIva({
...props,
planAlreadyVisible: true,
});
assert.equal(
nodes(linked).some((n) => n.type === Monthly),
false,
);
assert.equal(
nodes(linked).find((n) => n.type === 'a').props.href,
'#monthly-projected-iva',
);
const request = monthlyIvaInput(monthly.props.draft, settings);
assert.ok(request.monthly_sales.every((r) => r.amount !== '999999'));
assert.equal('base' in request, false);
assert.equal(
nodes(tree).some((n) => n.type === 'input'),
false,
);
nodes(tree)
.find((n) => n.type === 'select')
.props.onChange({ target: { value: 'operation' } });
assert.deepEqual(changed, ['published_iva_base_source', 'operation']);
const partition = partitionSimulationDraft({
...draft,
published_iva_base_source: 'operation',
});
const restored = restoreSimulationDraft(
partition.economic_snapshot,
partition.personal_snapshot,
);
tree = SimulationPublishedIva({ ...props, draft: restored });
assert.equal(
nodes(tree).some((n) => n.type === Monthly),
false,
);
assert.equal(restored.published_iva_base, '999999');
const modified = structuredClone(draft);
const saved = JSON.parse(modified.business_plan_snapshot);
saved.plan.products[0].unitPrice = String(
Number(saved.plan.products[0].unitPrice) + 10,
);
modified.business_plan_snapshot = JSON.stringify(saved);
assert.notEqual(
monthlyIvaKey(monthlyIvaInput(modified, settings)),
monthlyIvaKey(request),
);
assert.equal(
monthlyIvaInput(draft, { ...settings, basis: 'included' })
.sales_vat_basis,
'included',
);
assert.equal(calls.length, 0);
});
void test('IVA plan selected without source cannot silently fall back to a hand-entered base', () => {
const Monthly = () => null;
const { SimulationPublishedIva } = load('simulation-published-iva.tsx', {
'../lib/input-text.ts': inputText,
'./simulation-monthly-iva': { SimulationMonthlyIva: Monthly },
});
const html = renderToStaticMarkup(
SimulationPublishedIva({
draft: {
published_iva_base_source: 'plan',
published_iva_base: '100',
},
busy: false,
onCalculate: async () => {},
onChange() {},
}),
);
assert.match(html, /Prepare as vendas no plano/);
assert.doesNotMatch(html, /aria-label="Base tributável líquida"/);
});
void test('IRPC readonly base tracks current deductions, marks stale saved results, preserves history and leaves missing inputs indeterminate', () => {
const Component = load('irpc-current-base.tsx', {
'@/lib/irpc-normal': normal,
'@/lib/fiscal-rational': rational,
}).default;
const draft = seed(),
before = JSON.stringify(draft);
const html = () =>
renderToStaticMarkup(React.createElement(Component, { draft }));
assert.match(html(), /4400\.00 MZN/);
assert.doesNotMatch(html(), /<input|Os dados mudaram/);
assert.equal(JSON.stringify(draft), before);
const book = normal.normalBook(draft),
oldResult = structuredClone(book.result);
book.base.losses.forEach((l) => {
l.requested = '0';
});
draft.modelo_a_snapshot = normal.saveNormalBook(draft, book);
assert.match(html(), /6700\.00 MZN/);
assert.match(html(), /Os dados mudaram/);
assert.deepEqual(normal.normalBook(draft).result, oldResult);
book.base.benefits = { state: '', amount: '', reference: '' };
draft.modelo_a_snapshot = normal.saveNormalBook(draft, book);
assert.match(
html(),
/aria-label="Matéria colectável actual">Por determinar/,
);
assert.equal(normal.calculateNormal(draft, book).taxableBase, null);
});
@@ -0,0 +1,114 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import JSZip from 'jszip';
import {
simulationFieldGroups,
partitionSimulationDraft,
restoreSimulationDraft,
validateSimulationDraft,
} from '../../resources/js/lib/simulation-form.ts';
import {
buildProjectDossierRows,
exportProjectDossierCsv,
} from '../../resources/js/lib/project-dossier.ts';
import {
createProjectDossierReport,
createProjectDossierPrintHtml,
generateProjectDossierDocx,
} from '../../resources/js/lib/project-dossier-report.ts';
const texts = {
project_summary:
'EMPRESA SINTÉTICA QA: organização própria, sem dados da TEMPO.',
products_services: 'PRODUTOS QA: prestação de serviços declarada.',
competitor_assumption: 'CONCORRÊNCIA QA: hipótese por confirmar.',
sales_channel_assumption: 'VENDAS QA: canais propostos pelo investidor.',
marketing_approach: 'MARKETING QA: estratégia própria por validar.',
web_plan:
'WEB QA: <script>não executar</script> & presença digital prevista.',
management_summary:
'GESTÃO QA: responsabilidades declaradas, sem criar permissões no portal.',
};
const draft = {
journey_type: 'investor',
detail_level: 'advanced',
purpose: 'simulate_only',
...texts,
};
void test('F24 optional web/management use existing guided business journey and preserve economic roundtrip without required errors', () => {
for (const key of ['web_plan', 'management_summary']) {
const field = simulationFieldGroups.market.find((f) => f.key === key);
assert.ok(field);
assert.equal(field.type, 'textarea');
assert.equal(field.required, undefined);
assert.equal(field.showWhen(draft), true);
assert.equal(
field.showWhen({ ...draft, journey_type: 'personal' }),
false,
);
}
const parts = partitionSimulationDraft(draft, false),
recovered = restoreSimulationDraft(
parts.personal_snapshot,
parts.economic_snapshot,
);
for (const [key, value] of Object.entries(texts))
assert.equal(recovered[key], value);
const errors = validateSimulationDraft(
{ ...draft, web_plan: '', management_summary: '' },
'market',
);
assert.ok(!errors.web_plan && !errors.management_summary);
const legacy = { project_summary: 'Legado próprio' };
assert.deepEqual(
buildProjectDossierRows({
...legacy,
web_plan: '',
management_summary: '',
}),
buildProjectDossierRows(legacy),
);
});
void test('F24 own optional texts reach CSV, print and Word as escaped narrative without invented business or financial effects', async () => {
const before = JSON.stringify(draft),
rows = buildProjectDossierRows(draft),
csv = exportProjectDossierCsv(draft);
for (const value of Object.values(texts))
assert.ok(rows.some((r) => r[2] === value));
assert.ok(csv.includes('WEB QA'));
assert.ok(csv.includes('GESTÃO QA'));
const report = createProjectDossierReport(draft, {
selectedSections: new Set(['summary', 'project', 'market', 'team']),
generatedAt: '2026-11-22T10:00:00Z',
}),
html = await createProjectDossierPrintHtml(report, [], true);
for (const marker of [
'EMPRESA SINTÉTICA',
'PRODUTOS QA',
'CONCORRÊNCIA QA',
'VENDAS QA',
'MARKETING QA',
'WEB QA',
'GESTÃO QA',
])
assert.ok(html.includes(marker));
assert.ok(html.includes('&lt;script&gt;'));
assert.ok(!html.includes('<script>não executar'));
const zip = await JSZip.loadAsync(
await (
await generateProjectDossierDocx(report, [], true)
).arrayBuffer(),
),
xml = await zip.file('word/document.xml').async('string');
for (const marker of [
'EMPRESA SINTÉTICA',
'PRODUTOS QA',
'CONCORRÊNCIA QA',
'VENDAS QA',
'MARKETING QA',
'WEB QA',
'GESTÃO QA',
])
assert.ok(xml.includes(marker));
assert.ok(!report.sections.some((s) => s.id === 'finance'));
assert.equal(JSON.stringify(draft), before);
});
@@ -142,7 +142,7 @@ void test('operating components replace rather than add the old aggregate; capit
assert.equal(reload({ ...p, dividendsByPeriod: [5] }), null);
});
void test('the full example shares the saved snapshot and its eleven tables and exports change together, leaving investor inputs untouched', async () => {
void test('archived example preserves its eleven tables but is excluded from investor exports', async () => {
const p = financialReportFixture(13),
annual = newAnnualReferencePlan();
annual.years[0].sales = '14537.25';
@@ -174,22 +174,21 @@ void test('the full example shares the saved snapshot and its eleven tables and
generatedAt: '2026-11-20T12:00:00Z',
},
);
const all = report.sections.flatMap((s) => s.tables ?? []);
assert.equal(all.length, 11);
assert.deepEqual(
all.find((t) => t.id === 'sales'),
tables.find((t) => t.id === 'sales'),
assert.equal(
report.sections.find((section) => section.id === 'finance').tables
.length,
0,
);
const html = await createProjectDossierPrintHtml(report, []);
assert.match(html, /14 537,25/);
assert.match(html, /Exemplo sintético/);
assert.doesNotMatch(html, /14 537,25|Exemplo sintético/);
assert.match(html, /Seleccione o plano do investidor/);
const blob = await generateProjectDossierDocx(report, []),
zip = await JSZip.loadAsync(
blob instanceof Blob ? await blob.arrayBuffer() : blob,
),
xml = await zip.file('word/document.xml').async('string');
assert.match(xml, /14 537,25/);
assert.match(xml, /Capital por mobilizar/);
assert.doesNotMatch(xml, /14 537,25|Exemplo sintético/);
assert.match(xml, /Seleccione o plano do investidor/);
recovered.reportSource = 'investor';
assert.equal(
buildIntegralFinancialTables(recovered)
@@ -405,12 +404,25 @@ void test('actual editor controls preserve declarations through snapshot reload
field('Planear dividendos').props.onChange({ target: { checked: true } });
field('Dividendos, mês 1').props.onChange({ target: { value: '12.25' } });
assert.equal(plan.dividendsByPeriod[0], '12.25');
const select = () => nodes(render()).find((n) => n.type === 'select');
select().props.onChange({ target: { value: 'annual_example' } });
assert.equal(plan.reportSource, 'annual_example');
assert.ok(plan.annualExampleSnapshot);
assert.equal(buildAnnualExampleTables(plan).length, 11);
select().props.onChange({ target: { value: 'investor' } });
assert.equal(
nodes(render()).some(
(n) => n.type === 'option' && n.props.value === 'annual_example',
),
false,
);
plan = {
...plan,
reportSource: 'annual_example',
annualExampleSnapshot: serializeAnnualExampleSnapshot(
newAnnualReferencePlan(),
),
};
nodes(render())
.find(
(n) =>
n.type === 'button' && text(n) === 'Usar plano do investidor',
)
.props.onClick();
assert.equal(plan.reportSource, 'investor');
assert.equal(plan.dividendsByPeriod[0], '12.25');
assert.equal(plan.products[0].monthlyUnits, '10');
@@ -330,7 +330,7 @@ void test('contradictory record criteria remain explicit until the user chooses
);
});
void test('search needs both location and purpose; Enter and missing criteria cannot submit', () => {
void test('search explains missing location/purpose on click or Enter and never sends an invalid search', () => {
for (const filters of [
{},
{ need: 'investment' },
@@ -340,15 +340,21 @@ void test('search needs both location and purpose; Enter and missing criteria ca
const submit = nodes(h.tree()).find(
(n) => n.type === 'button' && text(n) === 'Pesquisar',
);
assert.equal(submit.props.disabled, true);
assert.equal(submit.props.disabled, false);
nodes(h.tree())
.find((n) => n.type === 'form')
.props.onSubmit({ preventDefault() {} });
assert.equal(h.submitted(), undefined);
assert.match(
text(h.tree()),
/Escolha a localização a pesquisar e a necessidade/,
);
h.render();
assert.ok(nodes(h.tree()).some((n) => n.props?.role === 'alert'));
if (!filters.need)
assert.match(
text(h.tree()),
/Seleccione a necessidade do processo/,
);
if (!filters.province_id)
assert.match(text(h.tree()), /Seleccione a província/);
assert.match(text(h.tree()), /A pesquisa não foi executada/);
}
for (const location of [
{ province_id: 'province-qa' },
@@ -24,8 +24,13 @@ function load(path, mocks = {}, exportName = 'default', extra = '') {
(name) =>
mocks[name] ??
(name === '@/components/investment-step-help'
? { HelpAtStep: () => null, InvestmentHelpGuide: ({ children }) => children }
: name.startsWith('@/') ? { default: () => null } : require(name)),
? {
HelpAtStep: () => null,
InvestmentHelpGuide: ({ children }) => children,
}
: name.startsWith('@/')
? { default: () => null }
: require(name)),
module,
module.exports,
);
@@ -60,7 +65,12 @@ function stateHooks() {
const flat = (node) =>
!node || typeof node !== 'object'
? []
: [node, ...(node.type?.name === 'InvestmentBudgetRange' ? flat(node.type(node.props)) : React.Children.toArray(node.props?.children).flatMap(flat))];
: [
node,
...(node.type?.name === 'InvestmentBudgetRange'
? flat(node.type(node.props))
: React.Children.toArray(node.props?.children).flatMap(flat)),
];
void test('free navigation keeps every field mounted and reports resource work in the current group', () => {
const state = stateHooks();
const Component = load(
@@ -307,7 +317,7 @@ void test('document entry leads to existing fillable preparation and keeps sourc
assert.match(html, /Valor do investimento/);
assert.match(html, /id="preparation-questions"/);
});
void test('investment stages expose readable next actions while internal codes and sources remain consultable', () => {
void test('investment stages expose readable next actions and context without technical source labels', () => {
const useForm = (data) => ({
data,
errors: {},
@@ -359,7 +369,7 @@ void test('investment stages expose readable next actions while internal codes a
assert.match(html, /<details[^>]*id="S01"[^>]*open/);
assert.match(html, /<summary[^>]*>Sistematizar a ideia/);
assert.doesNotMatch(html, /<summary[^>]*>S01/);
assert.match(html, /Fonte e referência desta etapa/);
assert.match(html, /Enquadramento desta etapa/);
});
function preparationFixture() {
@@ -508,40 +518,60 @@ function contextPreviewHarness(overrides = {}) {
},
};
const pending = [];
const Editor = load('../../resources/js/pages/investor-path/context.tsx', {
react: hooks,
'@inertiajs/react': { usePage: () => ({ props: { auth: { user: { id: 1 } } } }), Link: () => null, router: {} },
'@/components/navigation-context': {
useNavigationContext: () => ({ refresh() {} }),
},
'@/lib/operation-key': {
createOperationKey: () => 'synthetic-operation',
},
'@/lib/investor-context': {
contextFieldNames: {
project_title: 'Título',
project_summary: 'Resumo',
const Editor = load(
'../../resources/js/pages/investor-path/context.tsx',
{
react: hooks,
'@inertiajs/react': {
usePage: () => ({ props: { auth: { user: { id: 1 } } } }),
Link: () => null,
router: {},
},
contextApi: (url, body) =>
new Promise((resolve, reject) =>
pending.push({ url, body, resolve, reject }),
'@/components/navigation-context': {
useNavigationContext: () => ({ refresh() {} }),
},
'@/lib/operation-key': {
createOperationKey: () => 'synthetic-operation',
},
'@/lib/investor-context': {
contextFieldNames: {
project_title: 'Título',
project_summary: 'Resumo',
},
contextApi: (url, body) =>
new Promise((resolve, reject) =>
pending.push({ url, body, resolve, reject }),
),
},
'@/pages/investment/shared': {
Frame: () => null,
card: 'card',
input: 'input',
button: 'button',
},
'@/components/investment-budget-range': {
default: load(
'../../resources/js/components/investment-budget-range.tsx',
{
'./currency-select': {
default: function CurrencySelect() {},
},
},
),
},
'@/lib/preparation-intent': preparationIntent,
'@/components/currency-select': {
default: function CurrencySelect() {},
},
'@/components/investment-complements': {
default: () => null,
SelectedComplements: () => null,
complementInput: (value) => value,
},
},
'@/pages/investment/shared': {
Frame: () => null,
card: 'card',
input: 'input',
button: 'button',
},
'@/components/investment-budget-range': { default: load('../../resources/js/components/investment-budget-range.tsx', { './currency-select': { default: function CurrencySelect() {} } }) },
'@/lib/preparation-intent': preparationIntent,
'@/components/currency-select': { default: function CurrencySelect() {} },
'@/components/investment-complements': {
default: () => null,
SelectedComplements: () => null,
complementInput: (value) => value,
},
}, 'ScopedContextEditor', '\nexports.ScopedContextEditor = ScopedContextEditor;');
'ScopedContextEditor',
'\nexports.ScopedContextEditor = ScopedContextEditor;',
);
const props = {
initial: {
case: { id: 'synthetic', version: 1, title: 'Synthetic' },
@@ -604,12 +634,21 @@ async function withDraftTimers(callback) {
}
}
async function readyDraftHarness() {
const harness = contextPreviewHarness({ territorySelection: [{ id: 'synthetic-province', name: 'Synthetic province', location_type: 'province' }] });
const harness = contextPreviewHarness({
territorySelection: [
{
id: 'synthetic-province',
name: 'Synthetic province',
location_type: 'province',
},
],
});
harness.render();
harness.effects
.find((effect) => effect.dependencies?.length === 4)
.callback();
if (harness.pending[0]) harness.pending[0].resolve({ corridors: [], parks: [] });
if (harness.pending[0])
harness.pending[0].resolve({ corridors: [], parks: [] });
await settlePreview();
harness.render();
return harness;
@@ -695,7 +734,14 @@ void test('large multi-opportunity draft is offered to the transport on exit wit
};
let cleanup;
try {
const harness = contextPreviewHarness({ requestedChoices: [{ opportunity: { key: 'opportunity:1', title: 'Synthetic' }, territory: null }] });
const harness = contextPreviewHarness({
requestedChoices: [
{
opportunity: { key: 'opportunity:1', title: 'Synthetic' },
territory: null,
},
],
});
const initial = harness.render();
cleanup = harness.effects
.find(
@@ -749,7 +795,14 @@ void test('successful save followed by failed recovery offers read-only retry an
};
let cleanup;
try {
const harness = contextPreviewHarness({ requestedChoices: [{ opportunity: { key: 'opportunity:1', title: 'Synthetic' }, territory: null }] });
const harness = contextPreviewHarness({
requestedChoices: [
{
opportunity: { key: 'opportunity:1', title: 'Synthetic' },
territory: null,
},
],
});
const initial = harness.render();
cleanup = harness.effects
.find(
@@ -850,9 +903,8 @@ void test('failed save retains edits and permits retry without claiming that the
);
assert.equal(harness.pending.length, 2);
assert.equal(
flat(failed).find(
(node) => node.props.label === 'Moeda do orçamento',
).props.value,
flat(failed).find((node) => node.props.label === 'Moeda do orçamento')
.props.value,
'MZN',
);
});
@@ -888,9 +940,8 @@ void test('context comparison locks declaration and replacement controls until i
false,
);
assert.equal(
flat(ready).find(
(node) => node.props.label === 'Moeda do orçamento',
).props.disabled,
flat(ready).find((node) => node.props.label === 'Moeda do orçamento')
.props.disabled,
false,
);
});
@@ -922,9 +973,8 @@ void test('context comparison rejects a response for a draft changed while the r
),
);
assert.equal(
flat(stale).find(
(node) => node.props.label === 'Moeda do orçamento',
).props.value,
flat(stale).find((node) => node.props.label === 'Moeda do orçamento')
.props.value,
'USD',
);
});
+6
View File
@@ -128,6 +128,12 @@ test('S08 has one current state, a visible primary save action and no nested dis
const tree = h.render();
const nodes = flatten(tree);
assert.equal(tree.type, 'section');
assert.match(text(tree), /Etapa: Licenciamento prévio/);
assert.doesNotMatch(
text(tree),
/Referência interna S08|Documento original,|parágrafo 8/,
);
assert.equal(nodes.filter((n) => n.type === 'details').length, 0);
assert.equal(
nodes.filter(
@@ -0,0 +1,99 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
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 root = path.resolve('resources/js');
const nativeRequire = createRequire(import.meta.url);
const cache = new Map();
function load(file) {
if (cache.has(file)) return cache.get(file).exports;
const module = { exports: {} };
cache.set(file, module);
const code = ts.transpileModule(fs.readFileSync(file, 'utf8'), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
jsx: ts.JsxEmit.ReactJSX,
},
}).outputText;
compileFunction(code, ['require', 'module', 'exports'])(
(name) => {
if (!name.startsWith('@/') && !name.startsWith('.'))
return nativeRequire(name);
const base = name.startsWith('@/')
? path.join(root, name.slice(2))
: path.resolve(path.dirname(file), name);
const stem = base.replace(/\.(js|ts|tsx)$/, '');
const resolved = [base, stem + '.ts', stem + '.tsx'].find(
(f) => fs.existsSync(f) && fs.statSync(f).isFile(),
);
assert.ok(resolved, name);
return load(resolved);
},
module,
module.exports,
);
return module.exports;
}
void test('financial editor exposes no demonstration loader or source; legacy selection has explicit recovery without overwriting data', () => {
const { SimulationBusinessPlan } = load(
path.join(root, 'components/simulation-business-plan.tsx'),
);
const html = renderToStaticMarkup(
React.createElement(SimulationBusinessPlan, {
currency: 'MZN',
onCurrencyChange() {},
onSnapshotChange() {},
}),
);
assert.doesNotMatch(
html,
/Carregar cenário anual|Cenário anual de exemplo|Exemplo sintético anual editável/,
);
const { FinancialPlanDetails } = load(
path.join(root, 'components/financial-plan-details.tsx'),
);
const plan = {
reportSource: 'annual_example',
annualExampleSnapshot: 'preserved',
currency: 'MZN',
};
let next;
const node = FinancialPlanDetails({
plan,
onChange: (p) => {
next = p;
},
});
const nodes = (n) =>
Array.isArray(n)
? n.flatMap(nodes)
: n && typeof n === 'object'
? [n, ...nodes(n.props?.children)]
: [];
const button = nodes(node).find((n) => n.type === 'button');
assert.ok(button);
button.props.onClick();
assert.equal(next.reportSource, 'investor');
assert.equal(next.annualExampleSnapshot, 'preserved');
assert.equal(plan.reportSource, 'annual_example');
assert.doesNotMatch(
renderToStaticMarkup(node),
/<option[^>]*value="annual_example"/,
);
const { IntegralFinancialPlan } = load(
path.join(root, 'components/integral-financial-plan.tsx'),
);
const report = renderToStaticMarkup(
React.createElement(IntegralFinancialPlan, { plan, onChange() {} }),
);
assert.match(report, /Seleccione o plano do investidor/);
assert.doesNotMatch(report, /<table|Relatório do exemplo/);
});
@@ -381,7 +381,7 @@ void test('F31 carries all 36 calculated months, original service/department row
'Não documentado no exemplo original',
);
});
void test('F16/F31 persistence and existing Word/print exports preserve the same requirements, all months and source gaps', async () => {
void test('Investor exports preserve requirements; legacy example source never exposes demonstration tables', async () => {
const p = startup();
p.assetInvestment = requirements.startupAmount(
requirements.calculateStartupAssetRequirements(p).assetInvestment,
@@ -401,7 +401,10 @@ void test('F16/F31 persistence and existing Word/print exports preserve the same
},
{ generatedAt: '2026-11-20T12:00:00Z' },
);
assert.equal(report.sections[0].tables.length, 11);
assert.equal(
report.sections[0].tables.length,
mode === 'investor' ? 11 : 0,
);
assert.equal(JSON.stringify(p), before);
const html = await createProjectDossierPrintHtml(report, []),
doc = await generateProjectDossierDocx(report, []),
@@ -415,18 +418,14 @@ void test('F16/F31 persistence and existing Word/print exports preserve the same
'Caixa requerida',
'não financiamento realizado',
]
: [
'2025-01',
'2027-12',
'Vendas documentadas no original',
'Departamento documentado',
'Não documentado',
]) {
: ['Seleccione o plano do investidor']) {
assert.ok((html + xml).includes(s), s);
}
if (mode === 'annual_example') {
assert.match(xml, /14 537,25/);
assert.match(xml, /documental/);
assert.doesNotMatch(
html + xml,
/14 537,25|Vendas documentadas no original|Departamento documentado/,
);
}
}
});