Entrega dashboard e correccoes transversais preservando Ofertas instalado
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
catalogueDetailHref,
|
||||
catalogueReturnHref,
|
||||
catalogueQuery,
|
||||
} from '../../resources/js/lib/catalogue-context.ts';
|
||||
|
||||
test('return preserves deliberate destination edits, including cleared ancestors, without stale descendants', () => {
|
||||
const detail = catalogueDetailHref(
|
||||
'/carteira/a',
|
||||
'q=energia&province_id=p&district_id=d&page=4',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/carteira?q=turismo&province_id=', detail),
|
||||
'/carteira?q=turismo&province_id=&page=4',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/carteira?province_id=other', detail),
|
||||
'/carteira?province_id=other&q=energia&page=4',
|
||||
);
|
||||
});
|
||||
test('different catalogue families share geography but not text, kind, price, page or private context', () => {
|
||||
const detail =
|
||||
'/carteira/a?catalogue_query=' +
|
||||
encodeURIComponent(
|
||||
'q=airport&kind=project&page=4&province_id=p&context=private&min_amount=200',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/zonas?category=zee', detail),
|
||||
'/zonas?category=zee&province_id=p',
|
||||
);
|
||||
assert.equal(catalogueReturnHref('/documentos', detail), '/documentos');
|
||||
});
|
||||
test('resource-specific return queries do not inherit from other tabs or mutable storage', () => {
|
||||
const a = catalogueDetailHref(
|
||||
'/oportunidades/a',
|
||||
'q=rice&facets[]=2&facets[]=3¤cy=MZN',
|
||||
);
|
||||
const b = catalogueDetailHref('/oportunidades/b', 'q=gas¤cy=USD');
|
||||
const back = catalogueReturnHref('/oportunidades', a);
|
||||
assert.deepEqual(
|
||||
new URL(back, 'https://portal.invalid').searchParams.getAll('facets[]'),
|
||||
['2', '3'],
|
||||
);
|
||||
assert.match(back, /q=rice/);
|
||||
assert.match(catalogueReturnHref('/oportunidades', b), /q=gas/);
|
||||
assert.equal(
|
||||
catalogueReturnHref('/oportunidades', '/oportunidades/c'),
|
||||
'/oportunidades',
|
||||
);
|
||||
});
|
||||
test('detail URL preserves existing parameters and fragment; unsafe and recursive filters are not carried', () => {
|
||||
const href = catalogueDetailHref(
|
||||
'/oportunidades/a?from_dossier=origin#details',
|
||||
'q=rice&context=other&catalogue_query=recursive&password=secret&kind=cluster',
|
||||
);
|
||||
const url = new URL(href, 'https://portal.invalid');
|
||||
assert.equal(url.searchParams.get('from_dossier'), 'origin');
|
||||
assert.equal(url.hash, '#details');
|
||||
assert.equal(url.searchParams.get('catalogue_query'), 'q=rice');
|
||||
assert.equal(
|
||||
catalogueDetailHref('https://outside.test/a', 'q=rice'),
|
||||
'https://outside.test/a',
|
||||
);
|
||||
});
|
||||
test('only positive finite page numbers survive; repeated scalar criteria have one deliberate value', () => {
|
||||
assert.equal(
|
||||
catalogueQuery(
|
||||
'/carteira',
|
||||
'q=old&q=new&page=-1&per_page=Infinity',
|
||||
).toString(),
|
||||
'q=new',
|
||||
);
|
||||
assert.equal(
|
||||
catalogueReturnHref(
|
||||
'/carteira',
|
||||
'/carteira/a?catalogue_query=' +
|
||||
encodeURIComponent('https://outside.test'),
|
||||
),
|
||||
'/carteira',
|
||||
);
|
||||
});
|
||||
@@ -26,6 +26,23 @@ function load(file, mocks = {}) {
|
||||
return module.exports;
|
||||
}
|
||||
const lib = load('../../resources/js/lib/company-preparation.ts');
|
||||
test('historical delivery wording is presented professionally without changing the stored notice or legal limits', () => {
|
||||
const legal =
|
||||
' Esta ficha prepara dados para revisão; não é uma minuta contratual, assinatura, registo ou licença.';
|
||||
const stored =
|
||||
'Os sete exemplares referidos no complemento ainda não foram fornecidos.' +
|
||||
legal;
|
||||
assert.equal(
|
||||
lib.companyPreparationNotice(stored),
|
||||
'Os modelos contratuais não estão disponíveis nesta preparação.' +
|
||||
legal,
|
||||
);
|
||||
assert.match(stored, /sete exemplares/);
|
||||
assert.equal(
|
||||
lib.companyPreparationNotice('Outro aviso específico.'),
|
||||
'Outro aviso específico.',
|
||||
);
|
||||
});
|
||||
const party = {
|
||||
id: 'SYNTHETIC-party',
|
||||
name: '<SYNTHETIC>',
|
||||
@@ -148,6 +165,7 @@ function harness() {
|
||||
router: { visit: (...args) => visits.push(args) },
|
||||
},
|
||||
'./shared': { Frame: 'main', card: '', input: '', button: '' },
|
||||
'@/components/currency-select': { default: () => null },
|
||||
'@/lib/company-preparation': lib,
|
||||
'@/lib/operation-key': {
|
||||
createOperationKey: () => 'SYNTHETIC-operation',
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
import pathModule from 'node:path';
|
||||
const require = createRequire(import.meta.url);
|
||||
function load(path, overrides = {}) {
|
||||
const source = fs.readFileSync(
|
||||
new URL('../../resources/js/' + path, import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(n) => {
|
||||
if (n in overrides) return overrides[n];
|
||||
const relative = n.startsWith('@/') ? n.slice(2) : n.startsWith('.') ? pathModule.posix.join(pathModule.posix.dirname(path), n) : null;
|
||||
if (relative) {
|
||||
for (const candidate of [relative, relative + '.tsx', relative + '.ts']) {
|
||||
if (fs.existsSync(new URL('../../resources/js/' + candidate, import.meta.url))) return load(candidate, overrides);
|
||||
}
|
||||
}
|
||||
return require(n);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
const helpers = load('lib/demographic-reading.ts');
|
||||
const Summary = load('components/demographic-reading-summary.tsx', {
|
||||
'@/lib/demographic-reading': helpers,
|
||||
}).default;
|
||||
const Details = load('components/evidence-details.tsx').default;
|
||||
const Component = load('components/demographic-evidence.tsx', {
|
||||
'./demographic-reading-summary': { default: Summary },
|
||||
'./evidence-details': { default: Details },
|
||||
}).default;
|
||||
const row = (age, value, residence = 'all', year = 2026, extra = {}) => ({
|
||||
year,
|
||||
indicator: 'population',
|
||||
age_group: age,
|
||||
residence,
|
||||
value,
|
||||
original_value: value,
|
||||
unit: 'pessoas',
|
||||
data_kind: 'projected',
|
||||
sheet: String(year),
|
||||
cell: `${age}-${residence}`,
|
||||
validation_status: 'valid',
|
||||
...extra,
|
||||
});
|
||||
const series = (values) => ({
|
||||
import_id: 'source-one',
|
||||
source: 'INE',
|
||||
version: 'SYNTHETIC test edition',
|
||||
sha256: 'a'.repeat(64),
|
||||
file_name: 'source.xlsx',
|
||||
missing_years: [],
|
||||
issue_counts: {},
|
||||
values,
|
||||
});
|
||||
const ages = [
|
||||
'15-19',
|
||||
'20-24',
|
||||
'25-29',
|
||||
'30-34',
|
||||
'35-39',
|
||||
'40-44',
|
||||
'45-49',
|
||||
'50-54',
|
||||
'55-59',
|
||||
'60-64',
|
||||
];
|
||||
const base = () =>
|
||||
series([
|
||||
row('all', '1000.1234567890123'),
|
||||
row('all', '400', 'urban'),
|
||||
row('all', '600.1234567890123', 'rural'),
|
||||
row('0-4', '100'),
|
||||
row('5-9', '100'),
|
||||
row('10-14', '100'),
|
||||
...ages.map((a) => row(a, '50')),
|
||||
]);
|
||||
const evidence = (s) => ({
|
||||
state: 'available',
|
||||
start_year: 2026,
|
||||
end_year: 2026,
|
||||
sector: 'general',
|
||||
limitations: ['Population is not demand.'],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'district-one',
|
||||
name: 'Báruè',
|
||||
level: 'district',
|
||||
factors_to_assess: [],
|
||||
series: s,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
test('summarises compatible age/residence groups without changing original decimals', () => {
|
||||
const s = base(),
|
||||
before = JSON.stringify(s),
|
||||
r = helpers.demographicReading(s, 2026, 2026);
|
||||
assert.equal(r.last.under15, 300);
|
||||
assert.equal(r.last.age15to64, 500);
|
||||
assert.ok(Math.abs(r.last.ruralShare - 60.00493766) < 0.00001);
|
||||
assert.equal(JSON.stringify(s), before);
|
||||
assert.equal(r.growth, null);
|
||||
});
|
||||
test('missing age bands remain unknown; zeros are preserved', () => {
|
||||
const s = base();
|
||||
s.values = s.values.filter((r) => r.age_group !== '5-9');
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2026).last.under15, null);
|
||||
const r = helpers.demographicReading(
|
||||
series([
|
||||
row('all', '0'),
|
||||
row('all', '0', 'urban'),
|
||||
row('all', '0', 'rural'),
|
||||
]),
|
||||
2026,
|
||||
2026,
|
||||
);
|
||||
assert.equal(r.last.total, 0);
|
||||
assert.equal(r.last.ruralShare, null);
|
||||
});
|
||||
test('duplicate dimensions and incompatible kinds cannot supply invented shares', () => {
|
||||
const s = base();
|
||||
s.values.push(row('0-4', '200'));
|
||||
s.values.find((r) => r.residence === 'rural').data_kind = 'observed';
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(r.under15, null);
|
||||
assert.equal(r.rural, null);
|
||||
assert.equal(r.ruralShare, null);
|
||||
});
|
||||
test('inconsistent residence components do not produce percentages', () => {
|
||||
const s = series([
|
||||
row('all', '100'),
|
||||
row('all', '80', 'urban'),
|
||||
row('all', '80', 'rural'),
|
||||
]);
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(r.urban, 80);
|
||||
assert.equal(r.urbanShare, null);
|
||||
assert.equal(r.ruralShare, null);
|
||||
});
|
||||
test('growth uses explicit comparable endpoints and does not fill missing intermediate years', () => {
|
||||
const s = series([
|
||||
row('all', '100', 'all', 2026),
|
||||
row('all', '120', 'all', 2028),
|
||||
]);
|
||||
const r = helpers.demographicReading(s, 2026, 2028);
|
||||
assert.equal(r.growth, 20);
|
||||
assert.equal(r.years[1].total, null);
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2030).growth, null);
|
||||
s.values[1].data_kind = 'observed';
|
||||
assert.equal(helpers.demographicReading(s, 2026, 2028).growth, null);
|
||||
});
|
||||
test('technical source and full decimals remain available in closed details after a readable summary', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: evidence([base()]) }),
|
||||
);
|
||||
assert.ok(
|
||||
html.indexOf('Retrato da população') <
|
||||
html.indexOf('Valores originais por ano'),
|
||||
);
|
||||
assert.match(html, /1000.1234567890123/);
|
||||
assert.match(html, /Valores por dimensão, fonte e advertências/);
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen\b/);
|
||||
assert.match(html, /um único ano/);
|
||||
assert.match(html, /capacidade instalada/);
|
||||
assert.match(html, /qualificações/);
|
||||
});
|
||||
test('multiple editions receive separate summaries rather than a summed population', () => {
|
||||
const a = series([row('all', '100')]),
|
||||
b = { ...series([row('all', '900')]), import_id: 'source-two' };
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Component, { evidence: evidence([a, b]) }),
|
||||
);
|
||||
assert.equal((html.match(/Retrato da população/g) || []).length, 2);
|
||||
assert.match(html, />100<\/dd>/);
|
||||
assert.match(html, />900<\/dd>/);
|
||||
});
|
||||
test('demographic page offers territory-only preparation independent of old commercial filters', () => {
|
||||
const Page = load('pages/investment/demography.tsx', {
|
||||
'@inertiajs/react': { router: {} },
|
||||
'@/components/demographic-evidence': { default: Component },
|
||||
'./shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
button: '',
|
||||
},
|
||||
}).default;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Page, {
|
||||
evidence: evidence([base()]),
|
||||
filters: { territories: ['district-one'], sector: 'general' },
|
||||
territories: [],
|
||||
sectors: { general: 'Contexto geral' },
|
||||
}),
|
||||
);
|
||||
assert.match(html, /source=territory%3Adistrict-one/);
|
||||
assert.doesNotMatch(html, /compra de propriedade|sector=turismo|modality=/);
|
||||
assert.match(html, /Não é necessário haver uma oportunidade publicada/);
|
||||
});
|
||||
|
||||
test('Barue 2026 provided evidence produces the readable proportions without changing originals', () => {
|
||||
const fixture = JSON.parse(
|
||||
fs.readFileSync(
|
||||
new URL('../Fixtures/demography/barue-2026.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const s = series(fixture.values),
|
||||
before = JSON.stringify(s);
|
||||
const r = helpers.demographicReading(s, 2026, 2026).last;
|
||||
assert.equal(Math.round(r.total), 248518);
|
||||
assert.equal(Number(r.ruralShare.toFixed(1)), 65.1);
|
||||
assert.equal(Number(r.under15Share.toFixed(1)), 45.6);
|
||||
assert.equal(Number(r.age15to64Share.toFixed(1)), 51.3);
|
||||
assert.equal(JSON.stringify(s), before);
|
||||
});
|
||||
@@ -325,7 +325,8 @@ void test('financial tools CSV records reproducible assumptions, periods, formul
|
||||
});
|
||||
assert.match(csv, /^\uFEFF/);
|
||||
assert.match(csv, /financial-tools-v1/);
|
||||
assert.match(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /Pressupostos editáveis introduzidos ou recuperados pelo utilizador/);
|
||||
assert.doesNotMatch(csv, /valores iniciais sao exemplos demonstrativos/);
|
||||
assert.match(csv, /2026-10-02T10:00:00\.000Z/);
|
||||
assert.match(csv, /Período do orçamento e dos custos fixos,Mensal/);
|
||||
assert.match(csv, /saldo decrescente/i);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import * as finance from '../../resources/js/lib/financial-calculators.ts';
|
||||
import * as contract from '../../resources/js/lib/simulation-contract.ts';
|
||||
import * as fundingContext from '../../resources/js/lib/planning-finance-context.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = tree => Array.isArray(tree) ? tree.flatMap(nodes) : tree && typeof tree === 'object' ? [tree, ...nodes(tree.props?.children)] : [];
|
||||
const text = tree => Array.isArray(tree) ? tree.map(text).join('') : tree?.props ? text(tree.props.children) : typeof tree === 'string' ? tree : '';
|
||||
function harness(snapshot = '') {
|
||||
let cursor=0, queue=[], dirty=false, tree;
|
||||
const memory=[], deps=[];
|
||||
const hooks={...React, useState(initial) {const id=cursor++;if(!(id in memory))memory[id]=typeof initial==='function'?initial():initial;return[memory[id],next=>{const value=typeof next==='function'?next(memory[id]):next;if(!Object.is(value,memory[id])){memory[id]=value;dirty=true;}}];},useEffect(effect, next) {const id=cursor++;if(!deps[id]||next.some((value,i)=>!Object.is(value,deps[id][i]))){queue.push(effect);deps[id]=next;}}};
|
||||
const module={exports:{}};
|
||||
compileFunction(ts.transpileModule(fs.readFileSync('resources/js/components/simulation-financial-tools.tsx','utf8'),{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX}}).outputText,['require','module','exports'])(id=>id==='react'?hooks:id==='@/components/currency-select'?{default:()=>null}:id==='@/lib/financial-calculators'?finance:id==='@/lib/simulation-contract'?contract:id==='@/lib/planning-finance-context'?fundingContext:require(id),module,module.exports);
|
||||
const props={currency:'MZN',focus:'funding',loanRelevant:false,snapshot,sourceFunding:{total:'2000000',secured:''},onSnapshotChange(value){props.snapshot=value;dirty=true;},onCurrencyChange(){},onFundingChange(key,value){props.sourceFunding={...props.sourceFunding,[key]:value};dirty=true;}};
|
||||
const render=()=>{for(let i=0;i<12;i++){cursor=0;queue=[];dirty=false;tree=module.exports.SimulationFinancialTools(props);for(const effect of queue)effect();if(!dirty)return;}throw new Error('Render did not settle');};
|
||||
render();
|
||||
return{props,render,text:()=>text(tree),field:label=>nodes(tree).find(node=>node.props?.label===label),button:label=>nodes(tree).find(node=>node.type==='button'&&text(node).startsWith(label))};
|
||||
}
|
||||
|
||||
test('editing canonical mobilised funding updates the attached calculator and snapshot without showing hidden-tool errors',()=>{
|
||||
const h=harness();
|
||||
h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
|
||||
assert.match(h.text(),/1000000.00/);
|
||||
assert.equal(finance.restoreFinancialToolsSnapshot(h.props.snapshot).funding.secured,'1000000');
|
||||
assert.doesNotMatch(h.text(),/Empréstimo:|Ponto de equilíbrio:|Orçamento:|valores da calculadora diferem/);
|
||||
assert.equal(h.button('Exportar resultados'),undefined);
|
||||
});
|
||||
|
||||
test('a known different recovered calculator value is preserved until the user resolves its source',()=>{
|
||||
const snapshot=finance.serializeFinancialToolsSnapshot({budgetPeriod:'Mensal',loan:{principal:'',rate:'',months:'',rateType:'nominal',periodMonths:'1',gracePeriods:'',upfrontFee:'',recurringFee:''},breakEven:{fixed:'',price:'',variable:''},funding:{total:'2000000',secured:'250000'},incomes:[{label:'Receitas',amount:''}],expenses:[{label:'Custos',amount:''}]});
|
||||
const h=harness(snapshot);h.props.sourceFunding={total:'2000000',secured:'1000000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'250000');
|
||||
assert.match(h.text(),/valores da calculadora diferem/);
|
||||
h.button('Usar os valores do investimento').props.onClick();h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1000000');
|
||||
h.props.sourceFunding={total:'2000000',secured:'1500000'};h.render();
|
||||
assert.equal(h.field('Montante já mobilizado').props.value,'1500000');
|
||||
assert.match(h.text(),/500000.00/);
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import { monthlyIvaInput } from '../../resources/js/lib/monthly-iva.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const module = { exports: {} };
|
||||
const Choice = () => null;
|
||||
compileFunction(
|
||||
ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
'resources/js/components/fiscal-operation-picker.tsx',
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) =>
|
||||
id === '@/components/catalogue-choice-select'
|
||||
? { default: Choice }
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
|
||||
test('additional treatments are not mounted until explicitly selected, and removal preserves their stored data', () => {
|
||||
const mounted = [];
|
||||
const state = {
|
||||
selected: ['irpc:normal'],
|
||||
saved: 'unchanged-private-snapshot',
|
||||
};
|
||||
const props = {
|
||||
family: 'iva',
|
||||
selected: state.selected,
|
||||
operations: ['miners', 'fuel', 'travel'].map((id) => ({
|
||||
id,
|
||||
label: `Operação ${id}`,
|
||||
description: 'Confirmar se aplicável.',
|
||||
render() {
|
||||
mounted.push(id);
|
||||
return React.createElement('div', null, id);
|
||||
},
|
||||
})),
|
||||
onChange(selected) {
|
||||
state.selected = selected;
|
||||
props.selected = selected;
|
||||
},
|
||||
};
|
||||
let tree = module.exports.default(props);
|
||||
assert.deepEqual(
|
||||
mounted,
|
||||
[],
|
||||
'a list of available treatments is not a declaration that they apply',
|
||||
);
|
||||
nodes(tree)
|
||||
.find((node) => node.type === Choice)
|
||||
.props.onChange('fuel');
|
||||
assert.deepEqual(state.selected, ['irpc:normal', 'iva:fuel']);
|
||||
tree = module.exports.default(props);
|
||||
assert.deepEqual(mounted, ['fuel']);
|
||||
nodes(tree)
|
||||
.find((node) => node.type === 'button')
|
||||
.props.onClick();
|
||||
assert.deepEqual(state.selected, ['irpc:normal']);
|
||||
assert.equal(state.saved, 'unchanged-private-snapshot');
|
||||
});
|
||||
|
||||
test('a chosen 2027 period cannot silently use a 2026 monthly IVA projection', () => {
|
||||
const settings = {
|
||||
start: '2026-01',
|
||||
basis: 'net',
|
||||
declared: true,
|
||||
auto: false,
|
||||
};
|
||||
assert.throws(
|
||||
() => monthlyIvaInput({ fiscal_period: '2027' }, settings),
|
||||
/nenhum ano foi alterado/,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
monthlyIvaInput(
|
||||
{ fiscal_period: '2027' },
|
||||
{ ...settings, start: '2027-01' },
|
||||
),
|
||||
/cobertura apenas para 2026/,
|
||||
);
|
||||
assert.equal(settings.start, '2026-01');
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: '';
|
||||
|
||||
// Real page event handlers, simulated Inertia transport. Not a browser or visual acceptance.
|
||||
function harness(filters, errors = {}) {
|
||||
const memory = [];
|
||||
let cursor = 0;
|
||||
const state = (initial) => {
|
||||
const id = cursor++;
|
||||
if (!(id in memory)) memory[id] = initial;
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
};
|
||||
let submitted;
|
||||
let form;
|
||||
const TerritoryFields = () => null;
|
||||
const module = { exports: {} };
|
||||
const source = fs.readFileSync(
|
||||
'resources/js/pages/funding/index.tsx',
|
||||
'utf8',
|
||||
);
|
||||
compileFunction(
|
||||
ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) => {
|
||||
if (id === 'react')
|
||||
return {
|
||||
...React,
|
||||
useState: state,
|
||||
useRef(initial) {
|
||||
const [value] = state({ current: initial });
|
||||
return value;
|
||||
},
|
||||
};
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: 'a',
|
||||
useForm(initial) {
|
||||
const [data, set] = state(initial);
|
||||
form = {
|
||||
data,
|
||||
errors: {},
|
||||
processing: false,
|
||||
setData(key, value) {
|
||||
set(
|
||||
typeof key === 'string'
|
||||
? { ...data, [key]: value }
|
||||
: key,
|
||||
);
|
||||
},
|
||||
get(url) {
|
||||
submitted = { url, data };
|
||||
},
|
||||
};
|
||||
return form;
|
||||
},
|
||||
};
|
||||
if (id === '@/pages/investment/shared')
|
||||
return { Frame: 'main', card: '', button: '' };
|
||||
if (id === '@/components/funding-classification')
|
||||
return {
|
||||
financialCategories: {
|
||||
banking: 'Banca',
|
||||
insurance_intermediation: 'Mediação de seguros',
|
||||
},
|
||||
financialTypes: {
|
||||
commercial_bank: 'Banco comercial',
|
||||
broker: 'Corretora',
|
||||
other: 'Outro',
|
||||
},
|
||||
};
|
||||
if (id === '@/components/investment-territory')
|
||||
return { TerritoryFields };
|
||||
if (id === '@/components/funding-institution')
|
||||
return { InstitutionView: 'article' };
|
||||
if (id === './shared') return { windowLabels: {} };
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const props = {
|
||||
filters,
|
||||
criteriaErrors: errors,
|
||||
items: { data: [], links: [] },
|
||||
options: { sectors: [], territories: [] },
|
||||
kinds: { institution: 'Instituição', fund: 'Fundo' },
|
||||
management: false,
|
||||
categoryTypes: {
|
||||
banking: ['commercial_bank'],
|
||||
insurance_intermediation: ['broker'],
|
||||
},
|
||||
};
|
||||
let tree;
|
||||
function render() {
|
||||
cursor = 0;
|
||||
const wrapper = module.exports.default(props);
|
||||
tree = wrapper.type(wrapper.props);
|
||||
return tree;
|
||||
}
|
||||
const select = (label) =>
|
||||
nodes(
|
||||
nodes(tree).find(
|
||||
(n) => n.type === 'label' && text(n).startsWith(label),
|
||||
),
|
||||
).find((n) => n.type === 'select');
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
select,
|
||||
form: () => form,
|
||||
tree: () => tree,
|
||||
submitted: () => submitted,
|
||||
territory: () => nodes(tree).find((n) => n.type === TerritoryFields),
|
||||
};
|
||||
}
|
||||
|
||||
test('institution category restricts types and removes only an incompatible dependent choice', () => {
|
||||
const h = harness({
|
||||
category: 'insurance_intermediation',
|
||||
institution_type: 'broker',
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
});
|
||||
h.select('Categoria da instituição').props.onChange({
|
||||
target: { value: 'banking' },
|
||||
});
|
||||
h.render();
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
for (const [key, value] of Object.entries({
|
||||
sector: '7',
|
||||
need: 'investment',
|
||||
territory: 'district-qa',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
assert.deepEqual(
|
||||
nodes(h.select('Tipo de instituição'))
|
||||
.filter((n) => n.type === 'option')
|
||||
.map((n) => n.props.value),
|
||||
['', 'commercial_bank', 'other'],
|
||||
);
|
||||
assert.match(text(h.tree()), /tipo anterior não pertence/);
|
||||
const results = nodes(h.tree()).find((n) => n.type === 'details');
|
||||
assert.equal(results.props.open, false);
|
||||
assert.match(text(results), /pesquisa anterior/);
|
||||
});
|
||||
|
||||
test('contradictory record criteria remain explicit until the user chooses a correction', () => {
|
||||
const h = harness(
|
||||
{
|
||||
kind: 'fund',
|
||||
category: 'banking',
|
||||
institution_type: 'commercial_bank',
|
||||
location_mode: 'physical',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
},
|
||||
{ kind: ['Combinação incompatível.'] },
|
||||
);
|
||||
assert.match(text(h.tree()), /A pesquisa não foi executada/);
|
||||
assert.equal(h.form().data.kind, 'fund');
|
||||
const action = nodes(h.tree()).find(
|
||||
(n) => n.type === 'button' && /Manter o fundo/.test(text(n)),
|
||||
);
|
||||
action.props.onClick();
|
||||
h.render();
|
||||
assert.equal(h.form().data.category, '');
|
||||
assert.equal(h.form().data.institution_type, '');
|
||||
assert.equal(h.form().data.location_mode, 'coverage');
|
||||
for (const [key, value] of Object.entries({
|
||||
kind: 'fund',
|
||||
province_id: 'province-qa',
|
||||
sector: '8',
|
||||
state: 'closed',
|
||||
certainty: 'documented',
|
||||
}))
|
||||
assert.equal(h.form().data[key], value);
|
||||
nodes(h.tree())
|
||||
.find((n) => n.type === 'form')
|
||||
.props.onSubmit({ preventDefault() {} });
|
||||
assert.equal(h.submitted().url, '/fundos');
|
||||
assert.equal(h.submitted().data.province_id, 'province-qa');
|
||||
assert.ok(
|
||||
h.territory(),
|
||||
'the catalogue consumes the common hierarchical location control',
|
||||
);
|
||||
});
|
||||
@@ -212,6 +212,15 @@ export function harness(initial = props()) {
|
||||
mocks['@/lib/investment-profile-editor'] = load(
|
||||
'resources/js/lib/investment-profile-editor.ts',
|
||||
);
|
||||
mocks['@/lib/catalogue-choice'] = load(
|
||||
'resources/js/lib/catalogue-choice.ts',
|
||||
);
|
||||
mocks['./territory-search-select'] = load(
|
||||
'resources/js/components/territory-search-select.tsx',
|
||||
);
|
||||
mocks['./catalogue-choice-select'] = load(
|
||||
'resources/js/components/catalogue-choice-select.tsx',
|
||||
);
|
||||
mocks['./country-select'] = load(
|
||||
'resources/js/components/country-select.tsx',
|
||||
);
|
||||
@@ -324,17 +333,36 @@ export function harness(initial = props()) {
|
||||
return nodes(formLabel ? this.form(formLabel) : tree).find(
|
||||
(n) =>
|
||||
['input', 'textarea', 'select'].includes(n.type) &&
|
||||
n.props['aria-label'] === label,
|
||||
(n.props['aria-label'] === label ||
|
||||
(n.props.role === 'combobox' &&
|
||||
n.props['aria-label'] === 'Pesquisar ' + label)),
|
||||
);
|
||||
},
|
||||
value(label, formLabel) {
|
||||
return this.field(label, formLabel)?.props.value;
|
||||
const field = this.field(label, formLabel);
|
||||
// The public control shows the readable label; domain assertions use its ISO code.
|
||||
return field?.props.role === 'combobox'
|
||||
? (field.props.value.match(/— ([A-Z]{2})$/)?.[1] ??
|
||||
field.props.value)
|
||||
: field?.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();
|
||||
if (field.props.role === 'combobox') {
|
||||
const option = nodes(
|
||||
formLabel ? this.form(formLabel) : tree,
|
||||
).find(
|
||||
(node) =>
|
||||
node.props?.role === 'option' &&
|
||||
text(node).endsWith('— ' + value),
|
||||
);
|
||||
if (!option) throw Error('Missing selectable country ' + value);
|
||||
option.props.onClick();
|
||||
render();
|
||||
}
|
||||
},
|
||||
button(label, formLabel) {
|
||||
return nodes(formLabel ? this.form(formLabel) : tree).find(
|
||||
|
||||
@@ -70,3 +70,92 @@ await test('blocked browser storage cannot prevent authentication or clearing a
|
||||
'/participar/entrar?return=%2Foportunidades%2Fteste%3Fsector%3D1',
|
||||
);
|
||||
});
|
||||
|
||||
test('reused interest hook isolates opportunities, retains deliberate edits and restores after reload', () => {
|
||||
const source = fs.readFileSync(
|
||||
new URL(
|
||||
'../../resources/js/hooks/use-interest-draft.ts',
|
||||
import.meta.url,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
const output = ts.transpileModule(source, {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
},
|
||||
}).outputText;
|
||||
const saved = new Map();
|
||||
let sequence = 0;
|
||||
function mount(storage = saved) {
|
||||
let value, changed, effect;
|
||||
const module = { exports: {} };
|
||||
compileFunction(output, [
|
||||
'require',
|
||||
'module',
|
||||
'exports',
|
||||
'sessionStorage',
|
||||
'window',
|
||||
'location',
|
||||
])(
|
||||
(name) =>
|
||||
name === 'react'
|
||||
? {
|
||||
useState(init) {
|
||||
value ??= init();
|
||||
return [
|
||||
value,
|
||||
(next) => {
|
||||
value =
|
||||
typeof next === 'function'
|
||||
? next(value)
|
||||
: next;
|
||||
changed = true;
|
||||
},
|
||||
];
|
||||
},
|
||||
useEffect(callback) {
|
||||
effect = callback;
|
||||
},
|
||||
}
|
||||
: { newSubmissionKey: () => 'synthetic-' + ++sequence },
|
||||
module,
|
||||
module.exports,
|
||||
{
|
||||
getItem: (key) => storage.get(key) ?? null,
|
||||
setItem: (key, data) => storage.set(key, data),
|
||||
removeItem: (key) => storage.delete(key),
|
||||
},
|
||||
{ location: { assign() {} } },
|
||||
{ pathname: '/negocios/a', search: '?province_id=p' },
|
||||
);
|
||||
return (name, initial = { message: 'initial ' + name }) => {
|
||||
changed = false;
|
||||
let result = module.exports.useInterestDraft(name, initial);
|
||||
// React discards a render-phase reset and renders the new scoped state.
|
||||
if (changed)
|
||||
result = module.exports.useInterestDraft(name, initial);
|
||||
effect();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
const render = mount();
|
||||
const a = render('business:A');
|
||||
a.setForm({ message: 'deliberate A' });
|
||||
render('business:A');
|
||||
const b = render('business:B');
|
||||
assert.equal(b.form.message, 'initial business:B');
|
||||
assert.notEqual(a.key, b.key);
|
||||
b.setForm({ message: 'deliberate B' });
|
||||
render('business:B');
|
||||
assert.equal(render('business:A').form.message, 'deliberate A');
|
||||
assert.equal(mount()('business:B').form.message, 'deliberate B');
|
||||
assert.equal(
|
||||
mount(new Map())('business:A').form.message,
|
||||
'initial business:A',
|
||||
);
|
||||
assert.equal(
|
||||
JSON.parse(saved.get('investemoz-interest:business:A')).form.message,
|
||||
'deliberate A',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { compileFunction } from 'node:vm';
|
||||
import { createRequire } from 'node:module';
|
||||
import React from 'react';
|
||||
import ts from 'typescript';
|
||||
import * as finance from '../../resources/js/lib/financial-calculators.ts';
|
||||
import * as operating from '../../resources/js/lib/investment-operating-assistance.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const nodes = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.flatMap(nodes)
|
||||
: tree && typeof tree === 'object'
|
||||
? [tree, ...nodes(tree.props?.children)]
|
||||
: [];
|
||||
const text = (tree) =>
|
||||
Array.isArray(tree)
|
||||
? tree.map(text).join('')
|
||||
: tree?.props
|
||||
? text(tree.props.children)
|
||||
: typeof tree === 'string'
|
||||
? tree
|
||||
: '';
|
||||
function harness(file, snapshot = '') {
|
||||
let cursor = 0,
|
||||
tree;
|
||||
const memory = [],
|
||||
changes = [];
|
||||
const module = { exports: {} };
|
||||
const hooks = {
|
||||
...React,
|
||||
useState(initial) {
|
||||
const id = cursor++;
|
||||
if (!(id in memory))
|
||||
memory[id] =
|
||||
typeof initial === 'function' ? initial() : initial;
|
||||
return [
|
||||
memory[id],
|
||||
(next) => {
|
||||
memory[id] =
|
||||
typeof next === 'function' ? next(memory[id]) : next;
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
compileFunction(
|
||||
ts.transpileModule(
|
||||
fs.readFileSync('resources/js/components/' + file, 'utf8'),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText,
|
||||
['require', 'module', 'exports'],
|
||||
)(
|
||||
(id) =>
|
||||
id === 'react'
|
||||
? hooks
|
||||
: id === '@/lib/financial-calculators'
|
||||
? finance
|
||||
: id === '@/lib/investment-operating-assistance'
|
||||
? operating
|
||||
: require(id),
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const props = {
|
||||
snapshot,
|
||||
currency: 'MZN',
|
||||
onChange(key, value) {
|
||||
changes.push([key, value]);
|
||||
},
|
||||
};
|
||||
const render = () => {
|
||||
cursor = 0;
|
||||
tree = module.exports.default(props);
|
||||
};
|
||||
render();
|
||||
return {
|
||||
render,
|
||||
changes,
|
||||
nodes: () => nodes(tree),
|
||||
text: () => text(tree),
|
||||
button: (label) =>
|
||||
nodes(tree).find(
|
||||
(node) =>
|
||||
node.type === 'button' && text(node).startsWith(label),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
test('initial budget has no sample amounts and adopts a sum only through the explicit action', () => {
|
||||
const h = harness('investment-initial-budget.tsx');
|
||||
const amounts = () =>
|
||||
h
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
);
|
||||
assert.deepEqual(
|
||||
amounts().map((node) => node.props.value),
|
||||
['', '', '', ''],
|
||||
);
|
||||
h.button('Usar a soma').props.onClick();
|
||||
h.render();
|
||||
assert.match(h.text(), /montantes em falta/);
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'total_investment'),
|
||||
false,
|
||||
);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
amounts()[i].props.onChange({
|
||||
target: { value: String((i + 1) * 1000) },
|
||||
});
|
||||
h.render();
|
||||
}
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'total_investment'),
|
||||
false,
|
||||
);
|
||||
h.button('Usar a soma').props.onClick();
|
||||
h.render();
|
||||
assert.deepEqual(h.changes.at(-1), ['total_investment', '10000.00']);
|
||||
const saved = h.changes
|
||||
.filter(([key]) => key === 'initial_budget_snapshot')
|
||||
.at(-1)[1];
|
||||
const restored = harness('investment-initial-budget.tsx', saved);
|
||||
assert.deepEqual(
|
||||
restored
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
)
|
||||
.map((node) => node.props.value),
|
||||
['1000', '2000', '3000', '4000'],
|
||||
);
|
||||
});
|
||||
|
||||
test('hotel estimate is selected deliberately, saved as assumptions, then adopted without replacing another field', () => {
|
||||
const h = harness('investment-operating-assistance.tsx');
|
||||
h.nodes()
|
||||
.find((node) => node.type === 'select')
|
||||
.props.onChange({ target: { value: 'hotel' } });
|
||||
h.render();
|
||||
const amounts = () =>
|
||||
h
|
||||
.nodes()
|
||||
.filter(
|
||||
(node) => node.type === 'input' && node.props.type === 'number',
|
||||
);
|
||||
for (const [i, value] of ['10', '5000', '50', '300'].entries()) {
|
||||
amounts()[i].props.onChange({ target: { value } });
|
||||
h.render();
|
||||
}
|
||||
assert.equal(
|
||||
h.changes.some(([key]) => key === 'annual_revenue'),
|
||||
false,
|
||||
);
|
||||
h.button('Usar esta estimativa de receitas').props.onClick();
|
||||
h.render();
|
||||
assert.deepEqual(h.changes.at(-1), ['annual_revenue', '7500000.00']);
|
||||
assert.equal(
|
||||
h.changes.some(
|
||||
([key]) =>
|
||||
key === 'total_investment' || key === 'investment_budget_max',
|
||||
),
|
||||
false,
|
||||
);
|
||||
const saved = h.changes
|
||||
.filter(([key]) => key === 'planning_assumptions_snapshot')
|
||||
.at(-1)[1];
|
||||
const restored = harness('investment-operating-assistance.tsx', saved);
|
||||
assert.equal(
|
||||
restored.nodes().find((node) => node.type === 'select').props.value,
|
||||
'hotel',
|
||||
);
|
||||
assert.match(restored.text(), /ocupação/);
|
||||
});
|
||||
@@ -0,0 +1,214 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
getSimulationSections,
|
||||
simulationFieldsForSection,
|
||||
simulationFieldAvailableAtDetailLevel,
|
||||
simulationDraftFingerprint,
|
||||
validateSimulationDraft,
|
||||
partitionSimulationDraft,
|
||||
restoreSimulationDraft,
|
||||
} from '../../resources/js/lib/simulation-form.ts';
|
||||
import {
|
||||
emptyOperatingAssumptions,
|
||||
estimateOperatingRevenue,
|
||||
estimateOperatingCosts,
|
||||
restoreOperatingAssumptions,
|
||||
} from '../../resources/js/lib/investment-operating-assistance.ts';
|
||||
|
||||
test('confirmed nullable empty inputs match their HTTP-normalised recovery without accepting changed values', () => {
|
||||
const local = {
|
||||
purpose: 'own_investment',
|
||||
context_opportunity: '',
|
||||
total_investment: '2000000',
|
||||
secured_amount: '1000000',
|
||||
};
|
||||
const snapshots = partitionSimulationDraft(local);
|
||||
snapshots.economic_snapshot.context_opportunity = null;
|
||||
const saved = restoreSimulationDraft(
|
||||
snapshots.economic_snapshot,
|
||||
snapshots.personal_snapshot,
|
||||
);
|
||||
const versionedLocal = {
|
||||
...local,
|
||||
project_questionnaire_version: 'legacy-unversioned',
|
||||
};
|
||||
assert.equal(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint(versionedLocal),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint({
|
||||
...versionedLocal,
|
||||
secured_amount: '250000',
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint(saved),
|
||||
simulationDraftFingerprint({
|
||||
...versionedLocal,
|
||||
context_opportunity: 'another-opportunity',
|
||||
}),
|
||||
);
|
||||
assert.notEqual(
|
||||
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '' }),
|
||||
simulationDraftFingerprint({ ...versionedLocal, secured_amount: '0' }),
|
||||
);
|
||||
});
|
||||
|
||||
test('Hotel and Agronegocio reuse a controlled stage contract without requiring adverts, zones or formal financing facts', () => {
|
||||
for (const project_title of ['Criar Hotel', 'Agronegócio em Matola Rio']) {
|
||||
const draft = {
|
||||
journey_type: 'investor',
|
||||
detail_level: 'simple',
|
||||
purpose: 'own_investment',
|
||||
preferred_language: 'pt-MZ',
|
||||
project_title,
|
||||
province_id: 'province-qa',
|
||||
district_id: 'boane-qa',
|
||||
locality_id: 'matola-rio-qa',
|
||||
currency: 'MZN',
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
};
|
||||
const sections = getSimulationSections(draft);
|
||||
assert.equal(sections.length, 8);
|
||||
assert.ok(
|
||||
simulationFieldsForSection(draft, 'purpose').some(
|
||||
(field) => field.key === 'locality_id',
|
||||
),
|
||||
);
|
||||
for (const stage of [
|
||||
'market',
|
||||
'investment',
|
||||
'financial',
|
||||
'operating',
|
||||
'cashflow',
|
||||
'tax',
|
||||
])
|
||||
assert.deepEqual(
|
||||
validateSimulationDraft(draft, stage),
|
||||
{},
|
||||
`${stage} must permit unknown preparation facts`,
|
||||
);
|
||||
const finance = simulationFieldsForSection(draft, 'financial').map(
|
||||
(field) => field.key,
|
||||
);
|
||||
assert.ok(finance.includes('secured_amount'));
|
||||
assert.equal(finance.includes('annual_revenue'), false);
|
||||
assert.ok(
|
||||
simulationFieldsForSection(draft, 'operating').some(
|
||||
(field) => field.key === 'annual_revenue',
|
||||
),
|
||||
);
|
||||
const editableOperating = simulationFieldsForSection(
|
||||
draft,
|
||||
'operating',
|
||||
).filter((field) =>
|
||||
simulationFieldAvailableAtDetailLevel(
|
||||
draft,
|
||||
'operating',
|
||||
field.key,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
editableOperating.some((field) => field.key === 'annual_revenue'),
|
||||
);
|
||||
assert.ok(
|
||||
editableOperating.some(
|
||||
(field) => field.key === 'annual_operating_costs',
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
simulationFieldAvailableAtDetailLevel(draft, 'operating', 'nuit'),
|
||||
false,
|
||||
);
|
||||
const snapshot = JSON.stringify({
|
||||
version: 1,
|
||||
data: {
|
||||
...emptyOperatingAssumptions(),
|
||||
model: 'hotel',
|
||||
capacity: '10',
|
||||
price: '5000',
|
||||
occupancy: '50',
|
||||
frequency: '300',
|
||||
source: 'Synthetic assumptions explicitly entered',
|
||||
},
|
||||
});
|
||||
const original = {
|
||||
...draft,
|
||||
preparation_step: 'operating',
|
||||
planning_assumptions_snapshot: snapshot,
|
||||
};
|
||||
const partitioned = partitionSimulationDraft(original);
|
||||
const recovered = restoreSimulationDraft(
|
||||
partitioned.economic_snapshot,
|
||||
partitioned.personal_snapshot,
|
||||
);
|
||||
for (const key of [
|
||||
'locality_id',
|
||||
'currency',
|
||||
'investment_budget_min',
|
||||
'investment_budget_max',
|
||||
'preparation_step',
|
||||
'planning_assumptions_snapshot',
|
||||
])
|
||||
assert.equal(recovered[key], original[key]);
|
||||
assert.equal(recovered.total_investment, undefined);
|
||||
}
|
||||
});
|
||||
|
||||
test('guided estimates require explicit assumptions, preserve the model and do not use population as revenue', () => {
|
||||
const empty = emptyOperatingAssumptions();
|
||||
assert.throws(() => estimateOperatingRevenue(empty), /Escolha/);
|
||||
const hotel = {
|
||||
...empty,
|
||||
model: 'hotel',
|
||||
capacity: '10',
|
||||
price: '5000',
|
||||
occupancy: '50',
|
||||
frequency: '300',
|
||||
};
|
||||
assert.equal(estimateOperatingRevenue(hotel), '7500000.00');
|
||||
assert.throws(
|
||||
() => estimateOperatingRevenue({ ...hotel, occupancy: '101' }),
|
||||
/100%/,
|
||||
);
|
||||
assert.throws(
|
||||
() => estimateOperatingRevenue({ ...hotel, price: '' }),
|
||||
/falta/,
|
||||
);
|
||||
assert.equal(
|
||||
estimateOperatingRevenue({
|
||||
...hotel,
|
||||
model: 'agriculture',
|
||||
capacity: '1200',
|
||||
price: '25.50',
|
||||
frequency: '2',
|
||||
}),
|
||||
'61200.00',
|
||||
);
|
||||
assert.throws(() => estimateOperatingCosts(empty), /não são zero/);
|
||||
assert.throws(
|
||||
() =>
|
||||
estimateOperatingCosts({
|
||||
...hotel,
|
||||
costs: [{ label: 'Energia', annual: '' }],
|
||||
}),
|
||||
/falta/,
|
||||
);
|
||||
const data = {
|
||||
...hotel,
|
||||
costs: [
|
||||
{ label: 'Energia', annual: '100.10' },
|
||||
{ label: 'Pessoal', annual: '200.20' },
|
||||
],
|
||||
};
|
||||
assert.equal(estimateOperatingCosts(data), '300.30');
|
||||
assert.deepEqual(
|
||||
restoreOperatingAssumptions(JSON.stringify({ version: 1, data })),
|
||||
data,
|
||||
);
|
||||
assert.deepEqual(restoreOperatingAssumptions('{broken'), empty);
|
||||
});
|
||||
@@ -108,7 +108,7 @@ test('conflict recovery reads current data without applying a write automaticall
|
||||
});
|
||||
test('validation shows each field message once and preserves its value', async () => {
|
||||
const h = harness();
|
||||
h.change(residence, 'ZZ', account);
|
||||
h.change(residence, 'ZA', account);
|
||||
const sent = h.submit(account);
|
||||
await h.fail(422, sent, {
|
||||
'payload.residence_country_code': ['SYNTHETIC invalid country'],
|
||||
@@ -117,7 +117,7 @@ test('validation shows each field message once and preserves its value', async (
|
||||
text(h.form(account)).split('SYNTHETIC invalid country').length - 1,
|
||||
1,
|
||||
);
|
||||
assert.equal(h.value(residence, account), 'ZZ');
|
||||
assert.equal(h.value(residence, account), 'ZA');
|
||||
assert.equal(h.field(residence, account).props['aria-invalid'], true);
|
||||
});
|
||||
test('one page leave guard covers multiple dirty profile declarations', () => {
|
||||
|
||||
@@ -138,6 +138,37 @@ function fixture() {
|
||||
};
|
||||
}
|
||||
|
||||
test('a planning budget remains an interval in the same dossier report without inventing an investment amount', () => {
|
||||
const input = fixture();
|
||||
input.context_opportunity = null;
|
||||
input.opportunity_options = [];
|
||||
input.preparation_report.opportunity = null;
|
||||
Object.assign(input.investment_context.fields, {
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
currency: 'MZN',
|
||||
});
|
||||
const report = createInvestorDossierReport(input, '2026-11-15T12:00:00Z');
|
||||
const section = report.sections.find((section) => section.id === 'project');
|
||||
assert.equal(
|
||||
section.rows.find(
|
||||
(row) => row.field === 'Orçamento previsto — mínimo do intervalo',
|
||||
).value,
|
||||
'1000000',
|
||||
);
|
||||
assert.equal(
|
||||
section.rows.find(
|
||||
(row) => row.field === 'Orçamento previsto — máximo do intervalo',
|
||||
).value,
|
||||
'5000000',
|
||||
);
|
||||
assert.equal(
|
||||
section.rows.some((row) => row.field === 'Investimento previsto'),
|
||||
false,
|
||||
);
|
||||
assert.equal(input.context_opportunity, null);
|
||||
});
|
||||
|
||||
void test('one dossier groups stage evidence, SWOT, fiscal and all preserved APIEX versions without modifying sources', () => {
|
||||
const input = fixture();
|
||||
input.documents.push({ ...input.documents[0], id: 'second-link' });
|
||||
@@ -202,6 +233,7 @@ void test('financial results from a different opportunity do not enter the conso
|
||||
id: 'other',
|
||||
context_opportunity: 'op-b',
|
||||
financial_snapshot: 'OTHER-PRIVATE-INPUTS',
|
||||
preparation_snapshot: { annual_revenue: 'OTHER-PRIVATE-PREPARATION' },
|
||||
draft_id: 'other-draft',
|
||||
draft_version: 8,
|
||||
recorded_at: '2026-11-13',
|
||||
@@ -214,6 +246,7 @@ void test('financial results from a different opportunity do not enter the conso
|
||||
'OTHER-PRIVATE-INPUTS',
|
||||
),
|
||||
);
|
||||
assert.equal(JSON.stringify(createInvestorDossierReport(input)).includes('OTHER-PRIVATE-PREPARATION'), false);
|
||||
assert.ok(
|
||||
!investorDossierReportIndex(input).some(
|
||||
(entry) => entry.id === 'finance:other',
|
||||
@@ -249,6 +282,7 @@ void test('the consolidated report reuses loan, break-even, financing and budget
|
||||
input.results = [
|
||||
{
|
||||
id: 'finance-a',
|
||||
preparation_snapshot: { total_investment: '100000', investment_budget_min: '1000000', investment_budget_max: '5000000', annual_revenue: '7500000', planning_assumptions_snapshot: JSON.stringify({ version: 1, data: { model: 'hotel', capacity: '10', price: '5000', occupancy: '50', frequency: '300', source: 'Synthetic assumptions', costs: [{ label: 'Energia', annual: '' }] } }), initial_budget_snapshot: JSON.stringify({ version: 1, rows: [{ label: 'Equipamento', amount: '100000' }] }) },
|
||||
context_opportunity: 'op-a',
|
||||
context_revision: 2,
|
||||
context_state: 'review_required',
|
||||
@@ -287,6 +321,18 @@ void test('the consolidated report reuses loan, break-even, financing and budget
|
||||
);
|
||||
assert.match(rows[0].classification, /Histórico/);
|
||||
assert.equal(input.results[0].financial_snapshot, financial_snapshot);
|
||||
assert.equal(rows.find(item => item.field === 'Receitas anuais estimadas').value, '7500000 MZN');
|
||||
assert.equal(rows.find(item => item.field === 'Quartos disponíveis').value, '10');
|
||||
assert.equal(rows.find(item => item.field === 'Custo anual — Energia').value, 'Por confirmar');
|
||||
assert.equal(rows.find(item => item.field === 'Investimento inicial — Equipamento').value, '100000');
|
||||
});
|
||||
|
||||
test('funding remains calculable without presenting an unchosen empty loan or empty comparisons', () => {
|
||||
const input = fixture();
|
||||
input.results = [{ id: 'funding-only', context_opportunity: 'op-a', context_revision: 3, currency: 'MZN', draft_id: 'draft-a', draft_version: 1, recorded_at: '2026-11-15', engine: 'financial-calculators:v1', preparation_snapshot: { planning_loan: 'no' }, financial_snapshot: serializeFinancialToolsSnapshot({ budgetPeriod: 'Mensal', loan: { principal: '', rate: '', months: '', rateType: 'nominal', periodMonths: '1', gracePeriods: '', upfrontFee: '', recurringFee: '' }, breakEven: { fixed: '', price: '', variable: '' }, funding: { total: '1000000', secured: '1000000' }, incomes: [{ label: 'Receita', amount: '' }], expenses: [{ label: 'Custos', amount: '' }] }) }];
|
||||
const rows = createInvestorDossierReport(input).sections.find(section => section.id === 'finance').rows;
|
||||
assert.equal(rows.find(row => row.field === 'Financiamento — Diferença por financiar').value, '0.00 MZN');
|
||||
assert.equal(rows.some(row => /Empréstimo educativo|Ponto de equilíbrio|Orçamento —/.test(row.field)), false);
|
||||
});
|
||||
|
||||
void test('the existing Word and print exporters retain dossier identity, pending stages, source and history, escaping active HTML', async () => {
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
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 {
|
||||
readNavigationFocus,
|
||||
rememberNavigationFocus,
|
||||
} from '../../resources/js/lib/navigation-focus.ts';
|
||||
const require = createRequire(import.meta.url);
|
||||
const A = '15111500-0000-4000-8000-000000000001';
|
||||
const B = '15111500-0000-4000-8000-000000000002';
|
||||
|
||||
test('dossier provider retains tab focus across navigation/reload, honours explicit URLs and uses the current server version on deliberate change', async () => {
|
||||
const oldStorage = globalThis.sessionStorage,
|
||||
oldWindow = globalThis.window;
|
||||
const storage = new Map(),
|
||||
calls = [],
|
||||
visits = [];
|
||||
globalThis.sessionStorage = {
|
||||
getItem: (k) => storage.get(k),
|
||||
setItem: (k, v) => storage.set(k, v),
|
||||
removeItem: (k) => storage.delete(k),
|
||||
};
|
||||
globalThis.window = {
|
||||
location: { hash: '' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
let pageUrl = '/simulador',
|
||||
serverFocus = { case_id: B, step_code: null, version: 8 };
|
||||
rememberNavigationFocus(7, { case_id: A, step_code: 'S08', version: 1 });
|
||||
const code = ts.transpileModule(
|
||||
fs.readFileSync(
|
||||
'resources/js/components/dossier-navigation-context.tsx',
|
||||
'utf8',
|
||||
),
|
||||
{
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
},
|
||||
).outputText;
|
||||
function mount() {
|
||||
const state = [],
|
||||
dependencies = [],
|
||||
pending = [];
|
||||
let cursor = 0,
|
||||
effectCursor = 0;
|
||||
const hooks = {
|
||||
createContext: () => ({ Provider: 'provider' }),
|
||||
useContext: () => ({}),
|
||||
useState(initial) {
|
||||
const i = cursor++;
|
||||
if (!(i in state))
|
||||
state[i] =
|
||||
typeof initial === 'function' ? initial() : initial;
|
||||
return [
|
||||
state[i],
|
||||
(n) =>
|
||||
(state[i] = typeof n === 'function' ? n(state[i]) : n),
|
||||
];
|
||||
},
|
||||
useEffect(callback, deps) {
|
||||
const i = effectCursor++;
|
||||
if (
|
||||
!dependencies[i] ||
|
||||
deps.some((v, n) => v !== dependencies[i][n])
|
||||
) {
|
||||
dependencies[i] = deps;
|
||||
pending.push(callback);
|
||||
}
|
||||
},
|
||||
};
|
||||
const module = { exports: {} };
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) => {
|
||||
if (id === 'react') return hooks;
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
usePage: () => ({
|
||||
url: pageUrl,
|
||||
props: {
|
||||
auth: { user: { id: 7 } },
|
||||
investorPathEnabled: true,
|
||||
},
|
||||
}),
|
||||
router: { visit: (url) => visits.push(url) },
|
||||
Link: 'a',
|
||||
};
|
||||
if (id === '@/lib/navigation-focus')
|
||||
return { readNavigationFocus, rememberNavigationFocus };
|
||||
if (id === '@/lib/investor-context')
|
||||
return {
|
||||
contextApi: async (url, data, method) => {
|
||||
calls.push({ url, data, method });
|
||||
if (url === '/investimentos')
|
||||
return { contexts: [{ id: A }, { id: B }] };
|
||||
if (url === '/investimentos/contexto-atual') {
|
||||
if (method === 'PUT') {
|
||||
assert.equal(
|
||||
data.version,
|
||||
serverFocus.version,
|
||||
);
|
||||
serverFocus = {
|
||||
...data,
|
||||
version: serverFocus.version + 1,
|
||||
};
|
||||
}
|
||||
return { installed: true, focus: serverFocus };
|
||||
}
|
||||
return { case: { id: url.split('/').pop() } };
|
||||
},
|
||||
};
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
const render = () => {
|
||||
cursor = effectCursor = 0;
|
||||
const tree = module.exports.NavigationContextProvider({
|
||||
children: null,
|
||||
});
|
||||
while (pending.length) pending.shift()();
|
||||
return tree.props.value;
|
||||
};
|
||||
return async () => {
|
||||
render();
|
||||
await new Promise(setImmediate);
|
||||
return render();
|
||||
};
|
||||
}
|
||||
try {
|
||||
let render = mount(),
|
||||
view = await render();
|
||||
assert.equal(view.active, A);
|
||||
assert.equal(view.view.case.id, A);
|
||||
assert.equal(
|
||||
calls.some((c) => c.method === 'PUT'),
|
||||
false,
|
||||
);
|
||||
render = mount();
|
||||
view = await render();
|
||||
assert.equal(
|
||||
view.active,
|
||||
A,
|
||||
'reload must not adopt the other tab server preference',
|
||||
);
|
||||
pageUrl = '/simulador?context=' + B;
|
||||
view = await render();
|
||||
assert.equal(view.active, B, 'explicit authorised dossier wins');
|
||||
assert.equal(readNavigationFocus(7, [A, B]).case_id, B);
|
||||
serverFocus = { case_id: A, step_code: null, version: 15 };
|
||||
view.choose(A, 'S02');
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(
|
||||
calls.filter((c) => c.method === 'PUT').at(-1).data.version,
|
||||
15,
|
||||
);
|
||||
assert.equal(visits.at(-1), '/investimentos/' + A + '#S02');
|
||||
} finally {
|
||||
globalThis.sessionStorage = oldStorage;
|
||||
globalThis.window = oldWindow;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
readNavigationFocus,
|
||||
rememberNavigationFocus,
|
||||
} from '../../resources/js/lib/navigation-focus.ts';
|
||||
|
||||
test('tab focus survives reload but is isolated by actor and rechecked against authorised dossiers', () => {
|
||||
const old = globalThis.sessionStorage,
|
||||
values = new Map();
|
||||
globalThis.sessionStorage = {
|
||||
getItem: (k) => values.get(k),
|
||||
setItem: (k, v) => values.set(k, v),
|
||||
removeItem: (k) => values.delete(k),
|
||||
};
|
||||
try {
|
||||
const focus = { case_id: 'synthetic-A', step_code: 'S08', version: 3 };
|
||||
rememberNavigationFocus(1, focus);
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
assert.equal(readNavigationFocus(2, ['synthetic-A']), null);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-B']), null);
|
||||
const firstTab = globalThis.sessionStorage;
|
||||
globalThis.sessionStorage = {
|
||||
getItem: () => null,
|
||||
setItem: (k, v) => values.set(k, v),
|
||||
removeItem: (k) => values.delete(k),
|
||||
};
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
|
||||
globalThis.sessionStorage = firstTab;
|
||||
assert.deepEqual(readNavigationFocus(1, ['synthetic-A']), focus);
|
||||
rememberNavigationFocus(1, null);
|
||||
assert.equal(readNavigationFocus(1, ['synthetic-A']), null);
|
||||
} finally {
|
||||
globalThis.sessionStorage = old;
|
||||
}
|
||||
});
|
||||
test('corrupt, invalid and unavailable browser persistence cannot become authorisation or prevent use', () => {
|
||||
const old = globalThis.sessionStorage;
|
||||
try {
|
||||
for (const value of [
|
||||
'broken',
|
||||
'{"case_id":"A","step_code":"S99","version":1}',
|
||||
'{"case_id":"A","step_code":null,"version":-1}',
|
||||
]) {
|
||||
globalThis.sessionStorage = { getItem: () => value };
|
||||
assert.equal(readNavigationFocus(1, ['A']), null);
|
||||
}
|
||||
globalThis.sessionStorage = {
|
||||
getItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
setItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
removeItem() {
|
||||
throw Error('blocked');
|
||||
},
|
||||
};
|
||||
assert.equal(readNavigationFocus(1, ['A']), null);
|
||||
assert.doesNotThrow(() =>
|
||||
rememberNavigationFocus(1, {
|
||||
case_id: 'A',
|
||||
step_code: null,
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
globalThis.sessionStorage = old;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
samePlanningAmount,
|
||||
fundingDifferences,
|
||||
draftFundingDifferences,
|
||||
} from '../../resources/js/lib/planning-finance-context.ts';
|
||||
import {
|
||||
serializeFinancialToolsSnapshot,
|
||||
calculateFundingGap,
|
||||
} from '../../resources/js/lib/financial-calculators.ts';
|
||||
import { defaultCashflowDraftInputs } from '../../resources/js/lib/monthly-cashflow.ts';
|
||||
|
||||
test('funding reconciliation compares exact decimals without treating unknown as zero', () => {
|
||||
assert.equal(samePlanningAmount('1000000', '1000000.00'), true);
|
||||
assert.equal(samePlanningAmount('', '0'), false);
|
||||
assert.equal(samePlanningAmount('', ''), true);
|
||||
assert.equal(
|
||||
samePlanningAmount('9007199254740993', '9007199254740992'),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
fundingDifferences(
|
||||
{ total: '1000000', secured: '1000000' },
|
||||
{ total: '1000000', secured: '250000' },
|
||||
),
|
||||
['secured'],
|
||||
);
|
||||
assert.equal(calculateFundingGap('1000000', '1000000').gap, '0.00');
|
||||
});
|
||||
|
||||
test('a recovered snapshot retains deliberate values and reports conflicting funding origins', () => {
|
||||
const data = {
|
||||
budgetPeriod: 'Mensal',
|
||||
loan: {
|
||||
principal: '',
|
||||
rate: '',
|
||||
months: '',
|
||||
rateType: 'nominal',
|
||||
periodMonths: '1',
|
||||
gracePeriods: '',
|
||||
upfrontFee: '',
|
||||
recurringFee: '',
|
||||
},
|
||||
breakEven: { fixed: '', price: '', variable: '' },
|
||||
funding: { total: '2000000', secured: '250000' },
|
||||
incomes: [{ label: 'Receitas', amount: '' }],
|
||||
expenses: [{ label: 'Custos', amount: '' }],
|
||||
};
|
||||
const snapshot = serializeFinancialToolsSnapshot(data);
|
||||
const draft = {
|
||||
total_investment: '2000000',
|
||||
secured_amount: '1000000',
|
||||
financial_tools_snapshot: snapshot,
|
||||
};
|
||||
assert.deepEqual(draftFundingDifferences(draft), ['secured']);
|
||||
assert.equal(
|
||||
draft.financial_tools_snapshot,
|
||||
snapshot,
|
||||
'a check must not silently replace the restored calculator',
|
||||
);
|
||||
assert.deepEqual(
|
||||
draftFundingDifferences({ ...draft, secured_amount: '250000.00' }),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('fresh cashflow assumptions contain no demonstration amounts', () => {
|
||||
for (const [key, value] of Object.entries(defaultCashflowDraftInputs())) {
|
||||
if (typeof value === 'string' && /^\d/.test(value))
|
||||
assert.fail(`Unexpected automatic amount in ${key}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
currencyChoices,
|
||||
matchesChoice,
|
||||
} from '../../resources/js/lib/catalogue-choice.ts';
|
||||
import {
|
||||
createInvestmentHref,
|
||||
preparationSearch,
|
||||
} from '../../resources/js/lib/preparation-intent.ts';
|
||||
|
||||
test('an own investment carries explicit sector, geography and an interval, without an advert or corridor', () => {
|
||||
const path = [
|
||||
{ id: 'province-qa', location_type: 'province' },
|
||||
{ id: 'district-qa', location_type: 'district' },
|
||||
{ id: 'locality-qa', location_type: 'locality' },
|
||||
];
|
||||
const url = new URL(
|
||||
createInvestmentHref(
|
||||
{
|
||||
sector: 'agro',
|
||||
min_amount: '1000000',
|
||||
max_amount: '5000000',
|
||||
currency: 'MZN',
|
||||
q: 'Hotel',
|
||||
corridor_id: 'unrelated',
|
||||
opportunities: [42],
|
||||
},
|
||||
path,
|
||||
),
|
||||
'https://qa.example.test',
|
||||
);
|
||||
assert.equal(url.pathname, '/investimentos/iniciar');
|
||||
assert.equal(url.searchParams.get('investment_budget_min'), '1000000');
|
||||
assert.equal(url.searchParams.get('investment_budget_max'), '5000000');
|
||||
assert.equal(url.searchParams.get('currency'), 'MZN');
|
||||
assert.equal(url.searchParams.get('locality_id'), 'locality-qa');
|
||||
assert.equal(url.searchParams.get('sector'), 'agro');
|
||||
for (const key of [
|
||||
'q',
|
||||
'project_title',
|
||||
'corridor_id',
|
||||
'opportunities',
|
||||
'total_investment',
|
||||
])
|
||||
assert.equal(url.searchParams.has(key), false);
|
||||
const empty = new URL(createInvestmentHref({ q: 'Criar Hotel' }), url);
|
||||
assert.equal(
|
||||
empty.search,
|
||||
'',
|
||||
'a title does not assign a definitive activity or sector',
|
||||
);
|
||||
});
|
||||
|
||||
test('optional opportunity searches use only confirmed criteria and do not carry budget or private declarations', () => {
|
||||
const query = new URLSearchParams(
|
||||
preparationSearch('hotel', 'sector:7', [
|
||||
{ id: 'province-qa', location_type: 'province' },
|
||||
]),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...query.entries()],
|
||||
[
|
||||
['q', 'hotel'],
|
||||
['sector_id', '7'],
|
||||
['province_id', 'province-qa'],
|
||||
],
|
||||
);
|
||||
assert.equal(preparationSearch('', '', []), '');
|
||||
});
|
||||
|
||||
test('country and currency search accepts names, three letters, accents, case and short codes', () => {
|
||||
for (const query of ['MOC', 'moç', 'MZ', 'mocambique'])
|
||||
assert.equal(matchesChoice(query, ['Moçambique — MZ']), true);
|
||||
const metical = currencyChoices().find((choice) => choice.value === 'MZN');
|
||||
assert.ok(metical);
|
||||
assert.match(metical.label, /metical/i);
|
||||
for (const query of ['MET', 'met', 'MZN'])
|
||||
assert.equal(
|
||||
matchesChoice(query, [metical.label, ...metical.keywords]),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(
|
||||
currencyChoices(['MZN', 'USD']).map((choice) => choice.value),
|
||||
['MZN', 'USD'],
|
||||
'preserve a consumer’s approved currency constraints',
|
||||
);
|
||||
assert.equal(matchesChoice('euro', [metical.label]), false);
|
||||
});
|
||||
@@ -0,0 +1,588 @@
|
||||
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 React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const root = path.resolve('resources/js');
|
||||
function load(file, mocks = {}) {
|
||||
const absolute = path.resolve(root, file);
|
||||
const module = { exports: {} };
|
||||
const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), {
|
||||
compilerOptions: {
|
||||
module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
},
|
||||
}).outputText;
|
||||
compileFunction(code, ['require', 'module', 'exports'])(
|
||||
(id) => {
|
||||
if (id in mocks) return mocks[id];
|
||||
if (id === '@inertiajs/react')
|
||||
return {
|
||||
Link: ({ children, ...props }) =>
|
||||
React.createElement('a', props, children),
|
||||
usePage: () => ({ url: '/sectores/test' }),
|
||||
};
|
||||
if (id.startsWith('.') || id.startsWith('@/')) {
|
||||
const base = id.startsWith('@/')
|
||||
? path.resolve(root, id.slice(2))
|
||||
: path.resolve(path.dirname(absolute), id);
|
||||
const found = [base, base + '.tsx', base + '.ts'].find(
|
||||
(p) => fs.existsSync(p) && fs.statSync(p).isFile(),
|
||||
);
|
||||
if (found) return load(path.relative(root, found), mocks);
|
||||
}
|
||||
return require(id);
|
||||
},
|
||||
module,
|
||||
module.exports,
|
||||
);
|
||||
return module.exports;
|
||||
}
|
||||
const render = (file, props) =>
|
||||
renderToStaticMarkup(React.createElement(load(file).default, props));
|
||||
|
||||
test('demographic comparison retains four saved places and requires a province before searching districts', () => {
|
||||
const Page = load('pages/investment/demography.tsx', {
|
||||
'./shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
button: '',
|
||||
},
|
||||
'@/components/demographic-evidence': { default: () => null },
|
||||
}).default;
|
||||
const territories = [
|
||||
{
|
||||
id: 'p1',
|
||||
name: 'Província A',
|
||||
location_type: 'province',
|
||||
parent_id: null,
|
||||
},
|
||||
{
|
||||
id: 'p2',
|
||||
name: 'Província B',
|
||||
location_type: 'province',
|
||||
parent_id: null,
|
||||
},
|
||||
{
|
||||
id: 'd1',
|
||||
name: 'Distrito A',
|
||||
location_type: 'district',
|
||||
parent_id: 'p1',
|
||||
},
|
||||
{
|
||||
id: 'd2',
|
||||
name: 'Distrito B',
|
||||
location_type: 'district',
|
||||
parent_id: 'p2',
|
||||
},
|
||||
];
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Page, {
|
||||
evidence: { territories: [] },
|
||||
filters: {
|
||||
territories: territories.map((t) => t.id),
|
||||
start_year: 2026,
|
||||
end_year: 2027,
|
||||
},
|
||||
territories,
|
||||
sectors: { general: 'Geral' },
|
||||
}),
|
||||
);
|
||||
assert.match(html, /aria-label="Pesquisar Província da comparação"/);
|
||||
assert.match(
|
||||
html,
|
||||
/aria-label="Pesquisar Distrito da comparação \(opcional\)"[^>]*disabled/,
|
||||
);
|
||||
assert.doesNotMatch(html, /<select[^>]*multiple/);
|
||||
for (const t of territories)
|
||||
assert.ok(html.includes(`Retirar ${t.name} —`));
|
||||
assert.match(html, /disabled=""[^>]*>Acrescentar à comparação/);
|
||||
assert.match(html, /value="2026"/);
|
||||
assert.match(html, /value="2027"/);
|
||||
});
|
||||
|
||||
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', {
|
||||
'@/pages/investment/shared': {
|
||||
Frame: ({ children }) =>
|
||||
React.createElement('main', null, children),
|
||||
card: '',
|
||||
button: '',
|
||||
input: '',
|
||||
},
|
||||
'@/components/navigation-context': { useNavigationContext: () => ({}) },
|
||||
'@/components/investment-territory': { TerritoryFields: Empty },
|
||||
'@/components/private-investment-preparation': {
|
||||
PreparationEditor: Empty,
|
||||
PreparationImpact: Empty,
|
||||
},
|
||||
'@/components/investment-complements': {
|
||||
default: Empty,
|
||||
SelectedComplements: Empty,
|
||||
complementInput: (value) => value,
|
||||
},
|
||||
'@/components/context-documents': { default: Empty },
|
||||
'@/components/investment-opportunity-choices': { default: Empty },
|
||||
'@/components/investment-requirements': { default: Empty },
|
||||
'@/lib/operation-key': { createOperationKey: () => 'synthetic-key' },
|
||||
}).default;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(Editor, {
|
||||
initial: {
|
||||
case: {
|
||||
id: 'synthetic-hotel',
|
||||
title: 'Criar Hotel',
|
||||
version: 1,
|
||||
},
|
||||
context: {
|
||||
revision: 0,
|
||||
fields: { project_title: 'Criar Hotel' },
|
||||
selection: {},
|
||||
provenance: {},
|
||||
opportunity_choices: [],
|
||||
},
|
||||
private_investment: null,
|
||||
can_write: true,
|
||||
results: [],
|
||||
requests: [],
|
||||
preparation_documents: [],
|
||||
},
|
||||
source: null,
|
||||
options: {
|
||||
countries: [
|
||||
{ code: 'MZ', name: 'Moçambique', name_en: 'Mozambique' },
|
||||
],
|
||||
sectors: [{ id: 7, name: 'Turismo QA' }],
|
||||
parks: [],
|
||||
search_limited: false,
|
||||
opportunities: [
|
||||
{
|
||||
key: 'opportunity:2',
|
||||
title: 'Açúcar sem pertinência',
|
||||
kind: 'opportunity',
|
||||
},
|
||||
],
|
||||
},
|
||||
entryIdea: {
|
||||
sector_id: '7',
|
||||
currency: 'MZN',
|
||||
investment_budget_min: '1000000',
|
||||
investment_budget_max: '5000000',
|
||||
},
|
||||
}),
|
||||
);
|
||||
assert.match(html, /Criar Hotel/);
|
||||
assert.match(html, /value="1000000"/);
|
||||
assert.match(html, /value="5000000"/);
|
||||
assert.match(html, /value="sector:7" selected=""/);
|
||||
assert.match(html, /Oportunidades relacionadas \(opcional\)/);
|
||||
assert.doesNotMatch(html, /Referência individual|Açúcar sem pertinência/);
|
||||
if (process.env.INVESTMOZ_INTENT_PREVIEW === '1') {
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'public/build-qa-opportunities/manifest.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const css = fs.readFileSync(
|
||||
'public/build-qa-opportunities/' +
|
||||
manifest['resources/css/app.css'].file,
|
||||
'utf8',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
'outputs/investor-intent-20261115/editor-preview.html',
|
||||
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz — prévia sintética de preparação</title><style>${css}</style><body><div class="mx-auto max-w-4xl p-4"><p class="rounded border p-3">QA sintético: editor renderizado, sem autenticação, gravação ou consultas. A cartografia foi substituída no ensaio. Esta prévia não demonstra o percurso autenticado.</p>${html}</div></body></html>`,
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('changing the consulted territory remounts its evidence and aborts a late response', async () => {
|
||||
const state = [],
|
||||
refs = [];
|
||||
let cursor = 0,
|
||||
refCursor = 0,
|
||||
cleanup;
|
||||
const hooks = {
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
if (!(index in state)) state[index] = initial;
|
||||
return [
|
||||
state[index],
|
||||
(next) => {
|
||||
state[index] = next;
|
||||
},
|
||||
];
|
||||
},
|
||||
useRef(initial) {
|
||||
const index = refCursor++;
|
||||
refs[index] ??= { current: initial };
|
||||
return refs[index];
|
||||
},
|
||||
useEffect(callback) {
|
||||
cleanup = callback();
|
||||
},
|
||||
};
|
||||
const Component = load('components/demographic-context.tsx', {
|
||||
react: hooks,
|
||||
}).default;
|
||||
const a = Component({ territoryId: 'synthetic-A' });
|
||||
const b = Component({ territoryId: 'synthetic-B' });
|
||||
assert.notEqual(a.key, b.key);
|
||||
assert.equal(Component({ territoryId: null }), null);
|
||||
const tree = a.type(a.props);
|
||||
const nodes = (n) =>
|
||||
!n || typeof n !== 'object'
|
||||
? []
|
||||
: Array.isArray(n)
|
||||
? n.flatMap(nodes)
|
||||
: [n, ...nodes(n.props?.children)];
|
||||
const button = nodes(tree).find((n) => n.type === 'button');
|
||||
const originalFetch = globalThis.fetch;
|
||||
let resolve, signal;
|
||||
globalThis.fetch = (url, options) => {
|
||||
assert.match(url, /synthetic-A/);
|
||||
signal = options.signal;
|
||||
return new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
};
|
||||
try {
|
||||
const pending = button.props.onClick();
|
||||
cleanup();
|
||||
assert.equal(signal.aborted, true);
|
||||
resolve({ ok: true, json: async () => ({ territories: ['old A'] }) });
|
||||
await pending;
|
||||
assert.equal(
|
||||
state[0],
|
||||
null,
|
||||
'late evidence must not be attached to another territory',
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test('shared evidence is closed by default, preserves content and wraps long references', () => {
|
||||
const html = render('components/evidence-details.tsx', {
|
||||
children: 'source-version-hash',
|
||||
title: 'Fonte',
|
||||
});
|
||||
assert.match(html, /<details[^>]*>/);
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen/);
|
||||
assert.match(html, /source-version-hash/);
|
||||
assert.match(html, /overflow-wrap:anywhere/);
|
||||
});
|
||||
test('public document keeps applicability, usage limitations and actions visible, with source metadata in detail', () => {
|
||||
const { PublicDocumentContent } = load(
|
||||
'components/public-document-content.tsx',
|
||||
);
|
||||
const resource = {
|
||||
id: 1,
|
||||
title: 'Diploma QA',
|
||||
description: 'Objecto documentado',
|
||||
issuer: null,
|
||||
document_number: null,
|
||||
document_date: null,
|
||||
applicable_from: '2025-01-01',
|
||||
applicable_until: null,
|
||||
source_url: null,
|
||||
source_confirmation: 'unknown',
|
||||
usage_notice: 'Confirmar o âmbito aplicável',
|
||||
view_url: null,
|
||||
download_url: '/documents/1',
|
||||
context_actions: [],
|
||||
};
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(PublicDocumentContent, { resource }),
|
||||
);
|
||||
assert.match(html, /2025-01-01/);
|
||||
assert.match(html, /Confirmar o âmbito aplicável/);
|
||||
assert.match(html, /href="\/documents\/1"/);
|
||||
assert.doesNotMatch(html, /Entidade emissora|Consultar ficha/);
|
||||
assert.ok(html.indexOf('Período indicado') > html.indexOf('</details>'));
|
||||
});
|
||||
test('territorial references retain exact citation and provenance without a primary internal-process block', () => {
|
||||
const source = {
|
||||
association: 'Corredor QA',
|
||||
role: 'Ligação',
|
||||
source_reference: 'Diploma QA §2',
|
||||
source_quote: 'Relação documentada',
|
||||
supports: '',
|
||||
traceability: 'original hash/version',
|
||||
official_source_accepted: true,
|
||||
existing_validation: 'validated',
|
||||
};
|
||||
const html = render('components/territorial-source-evidence.tsx', {
|
||||
sources: [source],
|
||||
});
|
||||
assert.match(html, /Diploma QA §2/);
|
||||
assert.match(html, /original hash\/version/);
|
||||
assert.doesNotMatch(
|
||||
html,
|
||||
/não retira a aceitação existente|campo específico/,
|
||||
);
|
||||
assert.equal(
|
||||
render('components/territorial-source-evidence.tsx', { sources: [] }),
|
||||
'',
|
||||
);
|
||||
});
|
||||
test('empty published catalogue does not claim absent companies, resources or economic potential', () => {
|
||||
const html = render('components/published-opportunities-empty.tsx', {
|
||||
href: '/oportunidades?sector=qa',
|
||||
});
|
||||
assert.match(html, /Sem anúncios publicados/);
|
||||
assert.match(
|
||||
html,
|
||||
/não indica ausência de empresas, recursos ou potencial/,
|
||||
);
|
||||
assert.match(html, /sector=qa/);
|
||||
});
|
||||
const value = (
|
||||
year,
|
||||
age_group = 'all',
|
||||
data_kind = 'projected',
|
||||
unit = 'pessoas',
|
||||
) => ({
|
||||
year,
|
||||
indicator: 'population',
|
||||
age_group,
|
||||
residence: 'all',
|
||||
value: '1234',
|
||||
original_value: '1 234',
|
||||
unit,
|
||||
data_kind,
|
||||
sheet: 'sheet',
|
||||
cell: 'B' + year,
|
||||
validation_status: 'valid',
|
||||
});
|
||||
test('demographic highlights never sum dimensions, mix units or silently replace a source/version', () => {
|
||||
const { demographicHighlights } = load(
|
||||
'components/demographic-evidence.tsx',
|
||||
);
|
||||
const values = [
|
||||
value(2024),
|
||||
value(2025),
|
||||
value(2026, '0-4'),
|
||||
value(2024, 'all', 'observed'),
|
||||
value(2023, 'all', 'projected', 'unspecified'),
|
||||
];
|
||||
assert.deepEqual(demographicHighlights(values), [
|
||||
values[1],
|
||||
values[3],
|
||||
values[4],
|
||||
]);
|
||||
assert.deepEqual(demographicHighlights([value(2025, '0-4')]), []);
|
||||
});
|
||||
test('demography shows original latest total, period, projection and decision warning; technical cells remain closed', () => {
|
||||
const evidence = {
|
||||
state: 'available',
|
||||
start_year: 2024,
|
||||
end_year: 2025,
|
||||
limitations: ['Não prova procura'],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'qa',
|
||||
name: 'Território QA',
|
||||
level: 'province',
|
||||
factors_to_assess: [],
|
||||
series: [
|
||||
{
|
||||
import_id: 'qa',
|
||||
source: 'Fonte QA',
|
||||
version: 'Edição QA',
|
||||
sha256: '123abc',
|
||||
file_name: 'QA.xlsx',
|
||||
missing_years: [],
|
||||
issue_counts: {},
|
||||
values: [value(2024), value(2025)],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const html = render('components/demographic-evidence.tsx', { evidence });
|
||||
assert.match(html, /1 234/);
|
||||
assert.match(html, /não demonstram procura ou rentabilidade/);
|
||||
assert.match(html, /Projecção/);
|
||||
assert.match(html, /SHA256/);
|
||||
assert.ok(html.indexOf('SHA256') > html.indexOf('<summary'));
|
||||
assert.doesNotMatch(html, /<details[^>]*\bopen/);
|
||||
});
|
||||
test('cluster analysis omits empty field blocks but keeps documented evidence and uncertainty', () => {
|
||||
const { forces } = load('lib/cluster-competitiveness.ts');
|
||||
const rows = Object.fromEntries(
|
||||
forces.map((f) => [
|
||||
f,
|
||||
{
|
||||
pressure: '',
|
||||
evidence: 'Facto QA',
|
||||
source: '',
|
||||
period: '',
|
||||
rationale: '',
|
||||
limitations: 'Por confirmar',
|
||||
opportunity: '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
const html = render('components/cluster-competitiveness-public.tsx', {
|
||||
analysis: {
|
||||
version: 1,
|
||||
at: '2026-11-15',
|
||||
draft: { sector: 'QA', region: 'Local QA', forces: rows },
|
||||
},
|
||||
});
|
||||
assert.match(html, /Facto QA/);
|
||||
assert.match(html, /Por confirmar/);
|
||||
assert.doesNotMatch(html, /<dt[^>]*>Fonte e referência/);
|
||||
});
|
||||
test('simulator keeps original calculation correspondence and source behind explicit details', () => {
|
||||
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(SimulationModeloA, { draft: {} }),
|
||||
);
|
||||
assert.match(html, /Modelo A/);
|
||||
assert.match(html, /SHA256/);
|
||||
assert.ok(
|
||||
html.indexOf('SHA256') >
|
||||
html.indexOf('Exemplar e integridade da fonte'),
|
||||
);
|
||||
assert.match(html, /não é imposto final/);
|
||||
});
|
||||
|
||||
// Optional visual fixture: the real components with explicit synthetic data,
|
||||
// not an authenticated application or an operational publication.
|
||||
if (process.env.INVESTMOZ_RECONCILIATION_PREVIEW === '1') {
|
||||
const population = (year, age, amount, residence = 'all') => ({
|
||||
...value(year, age, 'projected', 'pessoas'),
|
||||
residence,
|
||||
value: String(amount),
|
||||
original_value: String(amount),
|
||||
cell: `${year}-${age}-${residence}`,
|
||||
});
|
||||
const values = [
|
||||
population(2026, 'all', 1000),
|
||||
population(2028, 'all', 1200),
|
||||
population(2028, 'all', 480, 'urban'),
|
||||
population(2028, 'all', 720, 'rural'),
|
||||
];
|
||||
for (const age of ['0-4', '5-9', '10-14'])
|
||||
values.push(population(2028, age, 120));
|
||||
for (const age of [
|
||||
'15-19',
|
||||
'20-24',
|
||||
'25-29',
|
||||
'30-34',
|
||||
'35-39',
|
||||
'40-44',
|
||||
'45-49',
|
||||
'50-54',
|
||||
'55-59',
|
||||
'60-64',
|
||||
])
|
||||
values.push(population(2028, age, 60));
|
||||
const evidence = {
|
||||
state: 'available',
|
||||
start_year: 2026,
|
||||
end_year: 2028,
|
||||
sector: 'general',
|
||||
limitations: [
|
||||
'Exclusivamente dados sintéticos. Não representam população real.',
|
||||
],
|
||||
comparisons: [],
|
||||
differences: [],
|
||||
territories: [
|
||||
{
|
||||
id: 'synthetic-qa',
|
||||
name: 'Território sintético QA',
|
||||
level: 'district',
|
||||
factors_to_assess: [],
|
||||
series: [
|
||||
{
|
||||
import_id: 'qa',
|
||||
source: 'Fonte sintética de ensaio',
|
||||
version: 'QA 2026',
|
||||
sha256: 'a'.repeat(64),
|
||||
file_name: 'exemplo-sintetico.xlsx',
|
||||
missing_years: [2027],
|
||||
issue_counts: {},
|
||||
values,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const demographicHtml = render('components/demographic-evidence.tsx', {
|
||||
evidence,
|
||||
});
|
||||
const emptyHtml = render('components/published-opportunities-empty.tsx', {
|
||||
href: '#demografia',
|
||||
label: 'Estudar a localização',
|
||||
});
|
||||
const { PublicDocumentContent } = load(
|
||||
'components/public-document-content.tsx',
|
||||
);
|
||||
const documentHtml = renderToStaticMarkup(
|
||||
React.createElement(PublicDocumentContent, {
|
||||
resource: {
|
||||
id: 1,
|
||||
title: 'Guia sintético QA',
|
||||
description:
|
||||
'Documento de ensaio para conferir a apresentação.',
|
||||
issuer: 'Entidade sintética',
|
||||
document_number: 'QA-1',
|
||||
document_date: '2026-11-15',
|
||||
applicable_from: '2026-11-15',
|
||||
applicable_until: null,
|
||||
source_url: null,
|
||||
source_confirmation: 'unknown',
|
||||
usage_notice:
|
||||
'Exemplo de limitação relevante, conservada junto do documento.',
|
||||
view_url: null,
|
||||
download_url: '#documento',
|
||||
context_actions: [],
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sourceHtml = render('components/territorial-source-evidence.tsx', {
|
||||
sources: [
|
||||
{
|
||||
association: 'Relação territorial sintética',
|
||||
role: 'Contexto',
|
||||
source_reference: 'Fonte sintética §1',
|
||||
source_quote: 'Relação apenas para ensaio.',
|
||||
supports: '',
|
||||
traceability: 'Versão QA e original conservados',
|
||||
official_source_accepted: false,
|
||||
existing_validation: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
const { SimulationModeloA } = load('components/simulation-modelo-a.tsx');
|
||||
const simulatorHtml = renderToStaticMarkup(
|
||||
React.createElement(SimulationModeloA, { draft: {} }),
|
||||
);
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync('public/build-qa-opportunities/manifest.json', 'utf8'),
|
||||
);
|
||||
const css = fs.readFileSync(
|
||||
'public/build-qa-opportunities/' +
|
||||
manifest['resources/css/app.css'].file,
|
||||
'utf8',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
'outputs/demography-reconciliation-20261115/visual-components.html',
|
||||
`<!doctype html><html lang="pt"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>InvesteMoz QA — conferência de componentes</title><style>${css}</style><body class="bg-slate-50 text-slate-900"><main class="mx-auto max-w-5xl space-y-8 p-4"><header><h1 class="text-2xl font-bold">InvesteMoz — prévia QA</h1><p>Componentes reais com dados sintéticos. Não é uma sessão autenticada nem publicação no portal.</p><nav class="flex flex-wrap gap-4 py-4"><a href="#demografia">Demografia</a><a href="#catalogo">Catálogo</a><a href="#territorio">Território</a><a href="#documento">Biblioteca</a><a href="#simulador">Simulador</a></nav></header><section id="demografia">${demographicHtml}</section><section id="catalogo"><h2 class="text-xl font-semibold">Catálogo — sem anúncios publicados</h2>${emptyHtml}</section><section id="territorio"><h2 class="text-xl font-semibold">Contexto territorial</h2>${sourceHtml}</section><section id="documento">${documentHtml}</section><section id="simulador">${simulatorHtml}</section></main></body></html>`,
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
@@ -193,7 +193,7 @@ void test('small business exploratory draft includes idea and finance without ma
|
||||
assert.deepEqual(validateSimulationDraft(draft, 'opportunity'), {});
|
||||
});
|
||||
|
||||
void test('project investment evaluation opens a direct project, location, finance, tax and analysis journey', () => {
|
||||
void test('simple investment preparation separates initial investment and funding and retains the full advanced journey', () => {
|
||||
const selected = replaceSimulationValue({}, 'journey_type', 'investor');
|
||||
assert.equal(selected.purpose, 'simulate_only');
|
||||
const sections = getSimulationSections(selected).map(
|
||||
@@ -201,14 +201,29 @@ void test('project investment evaluation opens a direct project, location, finan
|
||||
);
|
||||
assert.deepEqual(sections, [
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'market',
|
||||
'investment',
|
||||
'financial',
|
||||
'operating',
|
||||
'cashflow',
|
||||
'tax',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
'review',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
getSimulationSections({ ...selected, detail_level: 'advanced' }).map(
|
||||
(section) => section.id,
|
||||
),
|
||||
[
|
||||
'purpose',
|
||||
'project',
|
||||
'location',
|
||||
'financial',
|
||||
'tax',
|
||||
'scenarios',
|
||||
'procedures',
|
||||
'review',
|
||||
],
|
||||
);
|
||||
for (const sectionId of [
|
||||
'project',
|
||||
'location',
|
||||
|
||||
Reference in New Issue
Block a user