@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
|
||||
if (Illuminate\Support\Facades\DB::connection()->getDatabaseName() !== 'investemoz') {
|
||||
fwrite(STDERR, "Refusing unexpected active database target.\n");
|
||||
exit(20);
|
||||
}
|
||||
|
||||
$config = config('database.connections.pgsql');
|
||||
$command = [
|
||||
'C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--host='.$config['host'], '--port='.$config['port'],
|
||||
'--username='.$config['username'], '--format=custom', '--no-owner', '--no-privileges', '--file='.$argv[1],
|
||||
$config['database'],
|
||||
];
|
||||
$environment = getenv();
|
||||
$environment['PGPASSWORD'] = $config['password'];
|
||||
$pipes = [];
|
||||
$process = proc_open($command, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes,
|
||||
dirname(__DIR__), $environment, ['bypass_shell' => true]);
|
||||
fclose($pipes[0]);
|
||||
$stdout = stream_get_contents($pipes[1]);
|
||||
fclose($pipes[1]);
|
||||
$stderr = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[2]);
|
||||
$exitCode = proc_close($process);
|
||||
|
||||
if ($exitCode !== 0) {
|
||||
fwrite(STDERR, "pg_dump failed: ".trim($stderr)."\n");
|
||||
exit($exitCode);
|
||||
}
|
||||
|
||||
echo "Backup completed for investemoz.\n";
|
||||
@@ -0,0 +1,28 @@
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require('C:/Users/macbook/AppData/Local/Temp/investmoz-visual-qa-tools-20261004/node_modules/playwright');
|
||||
const base = process.argv[2] ?? 'http://127.0.0.1:18089/documentos';
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const errors = [];
|
||||
const evidence = { base, testedAt: new Date().toISOString(), viewports: [], errors };
|
||||
|
||||
for (const viewport of [{ name: 'desktop', width: 1440, height: 1000 }, { name: 'mobile', width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport: { width: viewport.width, height: viewport.height } });
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
const response = await page.goto(base, { waitUntil: 'networkidle' });
|
||||
const heading = await page.getByRole('heading', { name: 'Documentos e Formulários' }).count();
|
||||
const overflow = await page.evaluate(() => ({ viewport: innerWidth, document: document.documentElement.scrollWidth, body: document.body.scrollWidth }));
|
||||
await page.keyboard.press('Tab');
|
||||
const focus = await page.evaluate(() => ({ tag: document.activeElement?.tagName, label: document.activeElement?.getAttribute('aria-label'), text: document.activeElement?.textContent?.trim().slice(0, 100) }));
|
||||
const screenshot = `docs/investmoz/document-library-${viewport.name}-2026-10-05.png`;
|
||||
await page.screenshot({ path: screenshot, fullPage: true });
|
||||
evidence.viewports.push({ ...viewport, status: response?.status(), heading, emptyState: await page.getByText(/N[aã]o existem documentos publicados para esta pesquisa/).count(), overflow, firstKeyboardFocus: focus, screenshot });
|
||||
await page.close();
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
const target = 'docs/investmoz/document-library-browser-2026-10-05.json';
|
||||
fs.writeFileSync(target, JSON.stringify(evidence, null, 2) + '\n');
|
||||
console.log(JSON.stringify(evidence, null, 2));
|
||||
@@ -0,0 +1,36 @@
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require('C:/Users/macbook/AppData/Local/Temp/investmoz-visual-qa-tools-20261004/node_modules/playwright');
|
||||
const base = process.argv[2] ?? 'http://127.0.0.1:8000/documentos';
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const evidence = { base, testedAt: new Date().toISOString(), targetDatabase: 'investemoz (confirmed by read-only Laravel connection query)', viewports: [], errors: [] };
|
||||
|
||||
for (const viewport of [{ name: 'desktop', width: 1440, height: 1000 }, { name: 'mobile', width: 390, height: 844 }]) {
|
||||
const page = await browser.newPage({ viewport: { width: viewport.width, height: viewport.height } });
|
||||
page.on('pageerror', (error) => evidence.errors.push(error.message));
|
||||
page.on('console', (message) => { if (message.type() === 'error') evidence.errors.push(message.text()); });
|
||||
const response = await page.goto(base, { waitUntil: 'networkidle' });
|
||||
const heading = await page.getByRole('heading', { name: 'Documentos e Formulários' }).count();
|
||||
const text = await page.locator('body').innerText();
|
||||
const overflow = await page.evaluate(() => ({ viewport: innerWidth, document: document.documentElement.scrollWidth, body: document.body.scrollWidth }));
|
||||
await page.keyboard.press('Tab');
|
||||
const focus = await page.evaluate(() => ({ tag: document.activeElement?.tagName, label: document.activeElement?.getAttribute('aria-label'), text: document.activeElement?.textContent?.trim().slice(0, 80) }));
|
||||
const screenshot = `docs/investmoz/document-library-completion-${viewport.name}-2026-10-06.png`;
|
||||
await page.screenshot({ path: screenshot, fullPage: true });
|
||||
await page.getByRole('textbox', { name: 'Pesquisar' }).fill('__sem_correspondencia_qa__');
|
||||
await page.getByRole('button', { name: 'Pesquisar' }).click();
|
||||
await page.waitForURL((url) => url.searchParams.get('q') === '__sem_correspondencia_qa__');
|
||||
const searchUrl = page.url();
|
||||
const noResults = await page.getByText(/Não existem documentos publicados para esta pesquisa/).count();
|
||||
const searchOverflow = await page.evaluate(() => document.documentElement.scrollWidth === innerWidth);
|
||||
evidence.viewports.push({ ...viewport, status: response?.status(), heading, publicResultsText: text.match(/\d+ documentos correspondem aos filtros activos/)?.[0] ?? null, emptyState: /Não existem documentos publicados para esta pesquisa/.test(text), overflow, firstKeyboardFocus: focus, noMatchSearch: { url: searchUrl, emptyState: noResults === 1, noHorizontalOverflow: searchOverflow }, screenshot });
|
||||
if (/SQLSTATE|select \* from|Database:|Host: 127\.0\.0\.1/.test(text)) evidence.errors.push(`${viewport.name}: página contém detalhe interno de erro`);
|
||||
await page.close();
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
fs.writeFileSync('docs/investmoz/document-library-completion-browser-2026-10-06.json', JSON.stringify(evidence, null, 2) + '\n');
|
||||
console.log(JSON.stringify(evidence, null, 2));
|
||||
if (evidence.errors.length || evidence.viewports.some((item) => item.status !== 200 || item.heading !== 1 || item.overflow.document !== item.width || !item.noMatchSearch.emptyState || !item.noMatchSearch.noHorizontalOverflow)) process.exit(1);
|
||||
@@ -52,7 +52,7 @@ for (const [key, field] of Object.entries(formSchema)) {
|
||||
...(field.options ? { enum: [...Object.keys(field.options), null] } : {}),
|
||||
...(field.type === 'date' ? { format: 'date' } : {}), description: field.en };
|
||||
}
|
||||
payload.properties.wizard_version = { type: ['string', 'null'], enum: ['1', null] };
|
||||
payload.properties.wizard_version = { type: ['string', 'null'], enum: ['1', '2', null] };
|
||||
payload.properties.wizard_step = { type: ['string', 'null'], pattern: '^[1-8]$' };
|
||||
input.properties.sector_id = { type: ['integer', 'null'], description: 'Existing active public.sectors identifier; required on wizard submission.' };
|
||||
document.paths['/listings/{id}'].put.requestBody.content['application/json'].schema.properties.sector_id = input.properties.sector_id;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
const require=createRequire(import.meta.url);
|
||||
const {chromium}=require('C:/Users/macbook/AppData/Local/Temp/investmoz-visual-qa-tools-20261004/node_modules/playwright');
|
||||
const base='http://127.0.0.1:8000'; const browser=await chromium.launch({headless:true}); const page=await browser.newPage({viewport:{width:1440,height:1000}}); const errors=[]; page.on('pageerror',e=>errors.push(e.message)); const evidence={base,testedAt:new Date().toISOString(),records:[],errors};
|
||||
for(const [route,key] of [['/oportunidades','all'],['/oportunidades?province=Nampula','province'],['/oportunidades?sector=agronegocio','sector']]){const r=await page.goto(base+route,{waitUntil:'networkidle'}); evidence.records.push({key,route,status:r.status(),cards:await page.locator('article').count(),unvalidatedNotice:await page.getByText(/não regista data de validação documental/i).count()});}
|
||||
const detail=await page.goto(base+'/oportunidades/inv-mz-agr-001-unidade-de-processamento-agricola-em-nampula',{waitUntil:'networkidle'}); evidence.detail={status:detail.status(),title:await page.title(),unvalidatedNotice:await page.getByText(/não regista data de validação documental/i).count()===1,publishedIntentActionRequiresLogin:false}; await page.getByRole('link',{name:'Entrar para preparar manifestação'}).click(); await page.waitForURL('**/login'); evidence.detail.publishedIntentActionRequiresLogin=new URL(page.url()).pathname==='/login'; evidence.pageErrors=errors; await browser.close(); const out='docs/investmoz/pilot/authorized-opportunity-filter-browser-2026-10-04.json'; fs.writeFileSync(out,JSON.stringify(evidence,null,2)+'\n'); console.log(JSON.stringify(evidence,null,2));
|
||||
@@ -0,0 +1,85 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require('C:/Users/macbook/AppData/Local/Temp/investmoz-visual-qa-tools-20261004/node_modules/playwright');
|
||||
const base = 'http://127.0.0.1:8000';
|
||||
const out = path.resolve('docs/investmoz/pilot');
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const evidence = { base, testedAt: new Date().toISOString(), pages: [], errors };
|
||||
async function visit(route, key) {
|
||||
const response = await page.goto(base + route, { waitUntil: 'networkidle' });
|
||||
evidence.pages.push({ key, status: response?.status(), title: await page.title(), bodyTextLength: (await page.locator('body').innerText()).length });
|
||||
if (!response?.ok()) throw new Error(`${route} returned ${response?.status()}`);
|
||||
}
|
||||
await visit('/oportunidades', 'catalogue');
|
||||
evidence.catalogueStatus = await page.getByText(/\d+ oportunidades publicadas/).innerText();
|
||||
evidence.navigationHasCatalogueGroup = await page.getByText('Catálogos territoriais e económicos').count() === 1;
|
||||
evidence.publishedOpportunityCount = await page.locator('article').count();
|
||||
await visit('/carteira?kind=cluster', 'clusters');
|
||||
evidence.clusterRecords = await page.locator('article').count();
|
||||
for (const [legacy, expected] of [['/clusters', '/carteira?kind=cluster'], ['/corredores', '/carteira?kind=corridor'], ['/projectos-ancora', '/carteira?kind=project']]) {
|
||||
await page.goto(base + legacy, { waitUntil: 'networkidle' });
|
||||
evidence[`legacy${legacy.replaceAll('/', '')}Redirect`] = new URL(page.url()).pathname + new URL(page.url()).search === expected;
|
||||
}
|
||||
await visit('/carteira?kind=cluster', 'clusters-again');
|
||||
const province = page.getByLabel('Província');
|
||||
await province.waitFor({ timeout: 5000 });
|
||||
const provinceValue = await province.locator('option').nth(1).getAttribute('value');
|
||||
if (provinceValue) {
|
||||
await province.selectOption(provinceValue);
|
||||
await page.getByRole('button', { name: 'Pesquisar' }).click();
|
||||
await page.waitForURL(url => url.searchParams.has('province_id'), { timeout: 5000 });
|
||||
evidence.locationFilterApplied = new URL(page.url()).searchParams.get('province_id') === provinceValue;
|
||||
evidence.locationFilteredResults = await page.locator('article').count();
|
||||
await visit('/carteira?kind=cluster', 'clusters-after-location-filter');
|
||||
} else {
|
||||
evidence.locationFilterApplied = false;
|
||||
}
|
||||
if (await page.locator('article a').count()) {
|
||||
const prior = page.url();
|
||||
const detailHref = await page.locator('article a').first().getAttribute('href');
|
||||
await page.locator('article a').first().click();
|
||||
await page.waitForURL(url => url.pathname.startsWith('/carteira/'), { timeout: 5000 });
|
||||
await page.waitForLoadState('networkidle');
|
||||
evidence.clusterDetailHref = detailHref;
|
||||
evidence.clusterDetailUrl = page.url();
|
||||
evidence.clusterDetailLoaded = page.url() !== prior && !/SQLSTATE|Undefined column|500 Server Error/.test(await page.locator('body').innerText());
|
||||
evidence.privateManifestationRequiresAccount = await page.getByText(/Para associar esta referência a uma manifestação privada, entre na sua conta/i).count() === 1;
|
||||
}
|
||||
await visit('/carteira?kind=cluster&q=__sem_resultado_qa__', 'clusters-no-results');
|
||||
evidence.usefulEmptyState = await page.getByText(/Ainda não existem fichas publicadas/).count() === 1;
|
||||
await visit('/carteira?kind=project', 'anchor-projects');
|
||||
evidence.anchorDossiers = await page.locator('article').count();
|
||||
if (await page.locator('article a').count()) {
|
||||
await page.locator('article a').first().click();
|
||||
await page.waitForURL(url => url.pathname.startsWith('/carteira/'), { timeout: 5000 });
|
||||
evidence.anchorReferenceVisible = await page.getByRole('heading', { name: 'Referência de projecto âncora' }).count() === 1;
|
||||
evidence.anchorDoesNotClaimOpenTender = await page.getByText(/(?:não representa|não significa) concurso aberto/i).count() === 1;
|
||||
}
|
||||
await visit('/zonas?category=zee', 'zee-catalogue');
|
||||
evidence.zoneCountText = await page.getByRole('status').first().innerText();
|
||||
await visit('/negocios', 'existing-business-marketplace');
|
||||
evidence.businessListingCount = await page.locator('article').count();
|
||||
await visit('/como-investir', 'investment-guide-desktop');
|
||||
evidence.guideHasBothPaths = await page.getByLabel('Tenho uma ideia').count() === 1 && await page.getByLabel('Tenho um projecto definido').count() === 1;
|
||||
await page.getByLabel('Tenho uma ideia').check();
|
||||
evidence.ideaPathRenders = await page.getByRole('heading', { name: '1. Ideia e problema' }).count() === 1;
|
||||
await page.getByLabel('Actividade (opcional)').fill('Panificação');
|
||||
evidence.activityContextShown = await page.getByText(/Actividade opcional: Panificação/).count() === 1;
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
await page.getByRole('button', { name: 'Abrir menu' }).click();
|
||||
evidence.mobileMenuExpanded = await page.getByRole('button', { name: 'Fechar menu' }).getAttribute('aria-expanded') === 'true';
|
||||
await page.keyboard.press('Tab');
|
||||
evidence.keyboardFocusVisible = await page.evaluate(() => document.activeElement?.tagName !== 'BODY');
|
||||
await page.screenshot({ path: path.join(out, 'investmoz-guide-mobile-2026-10-04.png'), fullPage: true });
|
||||
evidence.pageErrors = errors;
|
||||
await browser.close();
|
||||
fs.writeFileSync(path.join(out, 'investmoz-catalogue-guide-browser-2026-10-04.json'), JSON.stringify(evidence, null, 2) + '\n');
|
||||
console.log(JSON.stringify(evidence, null, 2));
|
||||
@@ -0,0 +1,44 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import fs from 'node:fs';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require('C:/Users/macbook/AppData/Local/Temp/investmoz-visual-qa-tools-20261004/node_modules/playwright');
|
||||
const base = process.env.INVESTMOZ_E2E_BASE ?? 'http://127.0.0.1:8011';
|
||||
const email = process.env.INVESTMOZ_E2E_EMAIL;
|
||||
const password = process.env.INVESTMOZ_E2E_PASSWORD;
|
||||
const dossierId = process.env.INVESTMOZ_E2E_DOSSIER_ID;
|
||||
const submissionId = process.env.INVESTMOZ_E2E_SUBMISSION_ID;
|
||||
if (![email, password, dossierId, submissionId].every(Boolean)) throw new Error('Set the isolated fixture credentials and IDs in INVESTMOZ_E2E_* environment variables.');
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
const errors = [];
|
||||
const posts = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
page.on('request', request => {
|
||||
if (request.method() === 'POST' && new URL(request.url()).pathname === '/investidor/manifestacoes') posts.push(request.url());
|
||||
});
|
||||
await page.goto(`${base}/login`, { waitUntil: 'networkidle' });
|
||||
await page.locator('input[type=email]').fill(email);
|
||||
await page.locator('input[type=password]').fill(password);
|
||||
await page.locator('button[type=submit]').click();
|
||||
await page.waitForURL('**/dashboard');
|
||||
const response = await page.goto(`${base}/carteira/${dossierId}`, { waitUntil: 'networkidle' });
|
||||
const evidence = {
|
||||
testedAt: new Date().toISOString(),
|
||||
loginSucceeded: true,
|
||||
dossierHttpStatus: response.status(),
|
||||
existingDraftVisible: await page.getByRole('link', { name: /Continuar rascunho/ }).count() === 1,
|
||||
};
|
||||
page.once('dialog', dialog => dialog.dismiss());
|
||||
await page.getByRole('button', { name: /Preparar manif/ }).click();
|
||||
await page.waitForTimeout(400);
|
||||
evidence.cancelledConfirmationKeepsDossierPage = new URL(page.url()).pathname === `/carteira/${dossierId}`;
|
||||
evidence.cancelledConfirmationSentNoCreateRequest = posts.length === 0;
|
||||
evidence.publicDossierRemainsVisible = await page.getByRole('heading', { name: 'Dossier sintetico de ensaio' }).count() === 1;
|
||||
await page.screenshot({ path: 'docs/investmoz/pilot/private-dossier-association-browser-2026-10-04.png', fullPage: true });
|
||||
await page.getByRole('link', { name: /Continuar rascunho/ }).click();
|
||||
await page.waitForURL(`**/investidor/manifestacoes/${submissionId}`);
|
||||
evidence.existingDraftContinues = new URL(page.url()).pathname.endsWith(submissionId);
|
||||
evidence.pageErrors = errors;
|
||||
await browser.close();
|
||||
fs.writeFileSync('docs/investmoz/pilot/private-dossier-association-browser-2026-10-04.json', JSON.stringify(evidence, null, 2) + '\n');
|
||||
console.log(JSON.stringify(evidence, null, 2));
|
||||
@@ -0,0 +1,263 @@
|
||||
// Read-only responsive/accessibility smoke test against an isolated local Laravel page and Edge CDP.
|
||||
import fs from 'node:fs';
|
||||
|
||||
const baseUrl = process.argv[2] ?? 'http://127.0.0.1:18082/simulador-fiscal';
|
||||
const outputPath =
|
||||
process.argv[3] ??
|
||||
'docs/investmoz/simulations/simulator-browser-audit-2026-10-03.json';
|
||||
const expectedQaTarget = process.argv[4] ?? null;
|
||||
const target = await (
|
||||
await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })
|
||||
).json();
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.addEventListener('open', resolve, { once: true });
|
||||
ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const errors = [];
|
||||
const apiResponses = [];
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown') {
|
||||
errors.push(message.params.exceptionDetails.text);
|
||||
}
|
||||
if (message.method === 'Network.responseReceived') {
|
||||
const response = message.params.response;
|
||||
const path = new URL(response.url).pathname;
|
||||
if (path.startsWith('/api/v1/')) {
|
||||
const targetHeader = Object.entries(response.headers ?? {}).find(
|
||||
([name]) => name.toLowerCase() === 'x-investmoz-qa-target',
|
||||
)?.[1];
|
||||
apiResponses.push({
|
||||
path,
|
||||
status: response.status,
|
||||
qaTarget: typeof targetHeader === 'string' ? targetHeader : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!message.id) return;
|
||||
const request = pending.get(message.id);
|
||||
pending.delete(message.id);
|
||||
if (message.error)
|
||||
request.reject(
|
||||
new Error(
|
||||
`CDP ${request.method}: ${message.error.message ?? 'request failed'}`,
|
||||
),
|
||||
);
|
||||
else request.resolve(message.result);
|
||||
});
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const requestId = ++id;
|
||||
pending.set(requestId, { resolve, reject, method });
|
||||
ws.send(JSON.stringify({ id: requestId, method, params }));
|
||||
});
|
||||
const evaluate = async (expression) => {
|
||||
let response;
|
||||
try {
|
||||
response = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Runtime.evaluate [${expression.slice(0, 120)}]: ${error.message}`,
|
||||
);
|
||||
}
|
||||
if (response.exceptionDetails) throw new Error('Page evaluation failed');
|
||||
return response.result?.value;
|
||||
};
|
||||
const waitFor = async (expression) => {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
if (await evaluate(`Boolean(${expression})`)) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${expression}`);
|
||||
};
|
||||
const waitForApiResponse = async () => {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
if (apiResponses.length > 0) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error('Timed out waiting for the public draft API response');
|
||||
};
|
||||
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Network.enable');
|
||||
await send('Page.navigate', { url: baseUrl });
|
||||
await waitFor("document.querySelector('main #simulator-step-title')");
|
||||
await waitForApiResponse();
|
||||
|
||||
const dimensions = [];
|
||||
for (const width of [390, 768, 1024, 1440]) {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
height: 900,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: width < 768,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
const result = await evaluate(`(() => {
|
||||
const controls = [...document.querySelectorAll('input:not([type="hidden"]), select, textarea, button')]
|
||||
.filter(e => e.getClientRects().length);
|
||||
const fixed = controls.filter(e => getComputedStyle(e).position === 'fixed');
|
||||
return {
|
||||
viewport: innerWidth,
|
||||
document: document.documentElement.clientWidth,
|
||||
documentScroll: document.documentElement.scrollWidth,
|
||||
bodyScroll: document.body.scrollWidth,
|
||||
fixedControls: fixed.length,
|
||||
controls: controls.length,
|
||||
};
|
||||
})()`);
|
||||
dimensions.push(result);
|
||||
}
|
||||
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width: 390,
|
||||
height: 900,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: true,
|
||||
});
|
||||
await evaluate("document.querySelector('#simulator-step-title').focus()");
|
||||
const keyboardFocusSequence = [];
|
||||
for (let index = 0; index < 12; index++) {
|
||||
await send('Input.dispatchKeyEvent', {
|
||||
type: 'keyDown',
|
||||
key: 'Tab',
|
||||
code: 'Tab',
|
||||
windowsVirtualKeyCode: 9,
|
||||
nativeVirtualKeyCode: 9,
|
||||
});
|
||||
await send('Input.dispatchKeyEvent', {
|
||||
type: 'keyUp',
|
||||
key: 'Tab',
|
||||
code: 'Tab',
|
||||
windowsVirtualKeyCode: 9,
|
||||
nativeVirtualKeyCode: 9,
|
||||
});
|
||||
keyboardFocusSequence.push(
|
||||
await evaluate(`(() => {
|
||||
const e = document.activeElement;
|
||||
return {
|
||||
tag: e?.tagName?.toLowerCase() ?? null,
|
||||
name: e?.getAttribute?.('aria-label') || e?.innerText?.trim() || e?.labels?.[0]?.innerText?.trim() || e?.title || null,
|
||||
visible: Boolean(e?.getClientRects?.().length),
|
||||
focusVisible: Boolean(e?.matches?.(':focus-visible')),
|
||||
};
|
||||
})()`),
|
||||
);
|
||||
}
|
||||
await send('Emulation.clearDeviceMetricsOverride');
|
||||
const domAudit = await evaluate(`(() => {
|
||||
const visible = e => e.getClientRects().length > 0 && getComputedStyle(e).visibility !== 'hidden';
|
||||
const controls = [...document.querySelectorAll('input:not([type="hidden"]), select, textarea')]
|
||||
.filter(visible).map(e => ({
|
||||
tag: e.tagName.toLowerCase(),
|
||||
type: e.type ?? null,
|
||||
name: e.name || null,
|
||||
label: e.labels?.[0]?.innerText?.trim() || e.getAttribute('aria-label') ||
|
||||
(e.getAttribute('aria-labelledby') ? document.getElementById(e.getAttribute('aria-labelledby'))?.innerText?.trim() : null),
|
||||
}));
|
||||
const buttons = [...document.querySelectorAll('button')].filter(visible).map(e => ({
|
||||
text: e.innerText.trim(),
|
||||
name: e.getAttribute('aria-label') || e.innerText.trim() || e.title || null,
|
||||
}));
|
||||
const links = [...document.querySelectorAll('a')].filter(visible).map(e => ({
|
||||
text: e.innerText.trim(),
|
||||
name: e.getAttribute('aria-label') || e.innerText.trim() || e.title || null,
|
||||
href: e.getAttribute('href'),
|
||||
}));
|
||||
return { title: document.title, controls, buttons, links };
|
||||
})()`);
|
||||
const axTree = await send('Accessibility.getFullAXTree');
|
||||
const controlRoles = new Set([
|
||||
'button',
|
||||
'textbox',
|
||||
'searchbox',
|
||||
'combobox',
|
||||
'checkbox',
|
||||
'radioButton',
|
||||
'link',
|
||||
'slider',
|
||||
'spinbutton',
|
||||
]);
|
||||
const unnamedAxControls = axTree.nodes
|
||||
.filter((node) => !node.ignored && controlRoles.has(node.role?.value))
|
||||
.filter((node) => !node.name?.value?.trim())
|
||||
.map((node) => node.role.value);
|
||||
const unlabeledControls = domAudit.controls.filter(
|
||||
(control) => !control.label,
|
||||
);
|
||||
const unnamedButtons = domAudit.buttons.filter((button) => !button.name);
|
||||
const unnamedLinks = domAudit.links.filter((link) => !link.name);
|
||||
const visibleAlerts =
|
||||
await evaluate(`[...document.querySelectorAll('[role="alert"]')]
|
||||
.filter(e => e.getClientRects().length > 0)
|
||||
.map(e => e.innerText.trim())
|
||||
.filter(Boolean)`);
|
||||
const noOverflow = dimensions.every(
|
||||
(item) =>
|
||||
item.documentScroll <= item.document + 1 &&
|
||||
item.bodyScroll <= item.document + 1,
|
||||
);
|
||||
const invalidKeyboardFocus = keyboardFocusSequence.filter(
|
||||
(item) => !item.name || !item.visible,
|
||||
);
|
||||
const apiFailures = apiResponses.filter(
|
||||
(response) => response.status < 200 || response.status >= 300,
|
||||
);
|
||||
const qaTargetVerified =
|
||||
expectedQaTarget === null ||
|
||||
(apiResponses.length > 0 &&
|
||||
apiResponses.every(
|
||||
(response) => response.qaTarget === expectedQaTarget,
|
||||
));
|
||||
const report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
scope: 'UI, foco e GET público de rascunho; sem cálculo, escrita ou validação de conteúdo persistido',
|
||||
title: domAudit.title,
|
||||
dimensions,
|
||||
keyboardFocusSequence,
|
||||
invalidKeyboardFocus,
|
||||
visibleControls: domAudit.controls.length,
|
||||
visibleButtons: domAudit.buttons.length,
|
||||
visibleLinks: domAudit.links.length,
|
||||
unlabeledControls,
|
||||
unnamedButtons,
|
||||
unnamedLinks,
|
||||
unnamedAxControls,
|
||||
visibleAlerts,
|
||||
javascriptExceptions: errors,
|
||||
apiResponses,
|
||||
apiFailures,
|
||||
expectedQaTarget,
|
||||
qaTargetVerified,
|
||||
passed:
|
||||
noOverflow &&
|
||||
invalidKeyboardFocus.length === 0 &&
|
||||
unlabeledControls.length === 0 &&
|
||||
unnamedButtons.length === 0 &&
|
||||
unnamedLinks.length === 0 &&
|
||||
unnamedAxControls.length === 0 &&
|
||||
visibleAlerts.length === 0 &&
|
||||
apiResponses.length > 0 &&
|
||||
qaTargetVerified &&
|
||||
apiFailures.length === 0 &&
|
||||
errors.length === 0,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
} finally {
|
||||
ws.close();
|
||||
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
// Browser smoke test with synthetic API failures; only page and current-draft GETs reach the isolated QA server.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const baseUrl = process.argv[2] ?? 'http://127.0.0.1:18088/simulador-fiscal';
|
||||
const outputPath =
|
||||
process.argv[3] ??
|
||||
path.join(os.tmpdir(), 'investmoz-simulator-api-errors-browser.json');
|
||||
const expectedTarget = process.argv[4] ?? 'investmoz_browser_e2e_test:55443';
|
||||
const target = await (
|
||||
await fetch('http://127.0.0.1:9225/json/new?about:blank', { method: 'PUT' })
|
||||
).json();
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.addEventListener('open', resolve, { once: true });
|
||||
ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const javascriptExceptions = [];
|
||||
const consoleErrors = [];
|
||||
const failedResources = [];
|
||||
const serverResponses = [];
|
||||
const apiResponses = [];
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown')
|
||||
javascriptExceptions.push(message.params.exceptionDetails.text);
|
||||
if (
|
||||
message.method === 'Runtime.consoleAPICalled' &&
|
||||
message.params.type === 'error'
|
||||
)
|
||||
consoleErrors.push(
|
||||
message.params.args
|
||||
.map((argument) => argument.value ?? argument.description ?? '')
|
||||
.join(' ')
|
||||
.slice(0, 500),
|
||||
);
|
||||
if (message.method === 'Network.loadingFailed')
|
||||
failedResources.push({ error: message.params.errorText });
|
||||
if (message.method === 'Network.responseReceived') {
|
||||
const response = message.params.response;
|
||||
const url = new URL(response.url);
|
||||
if (url.pathname.startsWith('/api/v1/'))
|
||||
apiResponses.push({ path: url.pathname, status: response.status });
|
||||
if (
|
||||
url.pathname === '/simulador-fiscal' ||
|
||||
url.pathname === '/api/v1/simulation-drafts/current'
|
||||
)
|
||||
serverResponses.push({
|
||||
path: url.pathname,
|
||||
status: response.status,
|
||||
qaTarget:
|
||||
response.headers['X-Investmoz-QA-Target'] ??
|
||||
response.headers['x-investmoz-qa-target'] ??
|
||||
null,
|
||||
});
|
||||
}
|
||||
if (!message.id) return;
|
||||
const request = pending.get(message.id);
|
||||
if (!request) return;
|
||||
pending.delete(message.id);
|
||||
if (message.error) request.reject(message.error);
|
||||
else request.resolve(message.result);
|
||||
});
|
||||
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const requestId = ++id;
|
||||
pending.set(requestId, { resolve, reject });
|
||||
ws.send(JSON.stringify({ id: requestId, method, params }));
|
||||
});
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
});
|
||||
if (response.exceptionDetails)
|
||||
throw new Error(
|
||||
response.exceptionDetails.exception?.description ??
|
||||
response.exceptionDetails.text,
|
||||
);
|
||||
return response.result?.value;
|
||||
};
|
||||
|
||||
const waitFor = async (expression, description) => {
|
||||
for (let attempt = 0; attempt < 120; attempt++) {
|
||||
if (await evaluate(expression)) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${description}`);
|
||||
};
|
||||
|
||||
const clickText = async (selector, text) => {
|
||||
const found = await evaluate(`(() => {
|
||||
const element = [...document.querySelectorAll(${JSON.stringify(selector)})]
|
||||
.find(node => node.innerText.trim().includes(${JSON.stringify(text)}));
|
||||
if (!element) return false;
|
||||
element.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!found) throw new Error(`Could not find ${selector}: ${text}`);
|
||||
};
|
||||
|
||||
const choose = async (labelText, query, optionText) => {
|
||||
const opened = await evaluate(`(() => {
|
||||
const label = [...document.querySelectorAll('label')]
|
||||
.find(node => node.innerText.includes(${JSON.stringify(labelText)}));
|
||||
const input = label && document.getElementById(label.htmlFor);
|
||||
if (!input) return false;
|
||||
input.focus();
|
||||
input.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!opened) throw new Error(`Could not open combobox: ${labelText}`);
|
||||
if (query) await send('Input.insertText', { text: query });
|
||||
await waitFor(
|
||||
`([...document.querySelectorAll('[role="option"]')]
|
||||
.some(node => node.innerText.trim().includes(${JSON.stringify(optionText)})))`,
|
||||
`option ${optionText}`,
|
||||
);
|
||||
await clickText('[role="option"]', optionText);
|
||||
};
|
||||
|
||||
const fillNumber = async (field, value) => {
|
||||
const found = await evaluate(`(() => {
|
||||
const input = document.getElementById(${JSON.stringify(`field-${field}`)});
|
||||
if (!input) return false;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||
setter.call(input, ${JSON.stringify(value)});
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return true;
|
||||
})()`);
|
||||
if (!found) throw new Error(`Could not fill numeric field: ${field}`);
|
||||
};
|
||||
|
||||
const mockApi = `(() => {
|
||||
window.__simApiUnhandled = [];
|
||||
window.addEventListener('unhandledrejection', event => {
|
||||
window.__simApiUnhandled.push(String(event.reason?.stack || event.reason || 'unknown').slice(0, 500));
|
||||
});
|
||||
const realFetch = window.fetch.bind(window);
|
||||
window.__simApiFailureTest = { catalog: 0, created: 0, poll: 0, draftWrites: 0 };
|
||||
window.fetch = async (input, init = {}) => {
|
||||
const rawUrl = input instanceof Request ? input.url : String(input);
|
||||
const method = init.method || (input instanceof Request ? input.method : 'GET');
|
||||
const url = new URL(rawUrl, location.href);
|
||||
if (url.pathname === '/api/v1/catalogs/jurisdictions' && url.searchParams.get('type') === 'country') {
|
||||
window.__simApiFailureTest.catalog += 1;
|
||||
if (window.__simApiFailureTest.catalog === 1)
|
||||
return new Response('<html>temporary gateway error</html>', {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'text/html' },
|
||||
});
|
||||
return new Response(JSON.stringify({ data: [{ id: 'qa-country', label: 'País de teste QA' }] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
if (url.pathname === '/api/v1/simulations' && method.toUpperCase() === 'POST') {
|
||||
window.__simApiFailureTest.created += 1;
|
||||
return new Response(JSON.stringify({
|
||||
data: { id: 'f7000000-0000-4000-8000-000000000001', status: 'queued', version_no: 1 },
|
||||
replayed: false,
|
||||
access_token: 'a'.repeat(64),
|
||||
}), { status: 202, headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
if (url.pathname === '/api/v1/simulations/f7000000-0000-4000-8000-000000000001') {
|
||||
window.__simApiFailureTest.poll += 1;
|
||||
return new Response(JSON.stringify({ message: 'Estado do cálculo temporariamente indisponível.' }), {
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
if (url.pathname === '/api/v1/simulation-drafts' && method.toUpperCase() === 'POST') {
|
||||
window.__simApiFailureTest.draftWrites += 1;
|
||||
return new Response(JSON.stringify({
|
||||
data: { id: 'f7000000-0000-4000-8000-000000000002', version_no: 1 },
|
||||
}), {
|
||||
status: 201,
|
||||
headers: { 'Content-Type': 'application/json', ETag: '"qa-draft-v1"' },
|
||||
});
|
||||
}
|
||||
if (
|
||||
url.pathname.startsWith('/api/v1/simulation-drafts/') &&
|
||||
url.pathname !== '/api/v1/simulation-drafts/current'
|
||||
) {
|
||||
if (method.toUpperCase() === 'PUT') {
|
||||
window.__simApiFailureTest.draftWrites += 1;
|
||||
return new Response(JSON.stringify({
|
||||
data: { id: 'f7000000-0000-4000-8000-000000000002', version_no: 2 },
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json', ETag: '"qa-draft-v2"' },
|
||||
});
|
||||
}
|
||||
if (method.toUpperCase() === 'DELETE') {
|
||||
window.__simApiFailureTest.draftWrites += 1;
|
||||
return new Response('', { status: 204 });
|
||||
}
|
||||
}
|
||||
return realFetch(input, init);
|
||||
};
|
||||
})()`;
|
||||
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Network.enable');
|
||||
await send('Log.enable');
|
||||
await send('Page.addScriptToEvaluateOnNewDocument', {
|
||||
source: mockApi,
|
||||
});
|
||||
await send('Page.navigate', { url: baseUrl });
|
||||
await waitFor(
|
||||
"Boolean(document.querySelector('#simulator-step-title'))",
|
||||
'simulator page',
|
||||
);
|
||||
await waitFor(
|
||||
"performance.getEntriesByType('resource').some(entry => entry.name.includes('/api/v1/simulation-drafts/current'))",
|
||||
'current-draft GET',
|
||||
);
|
||||
const realTargetConfirmed = serverResponses.some(
|
||||
(response) =>
|
||||
response.status === 200 &&
|
||||
response.qaTarget === expectedTarget &&
|
||||
response.path === '/simulador-fiscal',
|
||||
);
|
||||
if (!realTargetConfirmed)
|
||||
throw new Error(
|
||||
'The page response did not confirm the expected QA target.',
|
||||
);
|
||||
|
||||
await choose('Escolha o percurso', 'Particular', 'Particular');
|
||||
await choose('Nível de detalhe', 'Simples', 'Simples');
|
||||
await choose('O que pretende fazer?', 'Apenas simular', 'Apenas simular');
|
||||
await choose('Idioma preferido', 'Português', 'Português');
|
||||
await clickText('button', 'Operação fiscal');
|
||||
await choose('Ano do período fiscal', '', '2026');
|
||||
await choose('Periodicidade/período de referência', '', 'Anual');
|
||||
await choose('Componente que pretende explorar', '', 'IRPS');
|
||||
await choose('Categoria de rendimento', '', 'Trabalho');
|
||||
await choose(
|
||||
'Residência fiscal indicada pelo utilizador',
|
||||
'',
|
||||
'Indico que sou residente',
|
||||
);
|
||||
|
||||
const countryLabel = 'País que indica como residência fiscal';
|
||||
const countryOpen = await evaluate(`(() => {
|
||||
const label = [...document.querySelectorAll('label')]
|
||||
.find(node => node.innerText.includes(${JSON.stringify(countryLabel)}));
|
||||
const input = label && document.getElementById(label.htmlFor);
|
||||
if (!input) return false;
|
||||
input.focus();
|
||||
input.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!countryOpen)
|
||||
throw new Error(
|
||||
'Could not open the fiscal residency country combobox.',
|
||||
);
|
||||
await waitFor(
|
||||
'window.__simApiFailureTest?.catalog === 1',
|
||||
'first mocked catalog request',
|
||||
);
|
||||
await waitFor(
|
||||
"[...document.querySelectorAll('[role=alert]')].some(node => node.innerText.includes('Não foi possível carregar as opções'))",
|
||||
'catalog error alert',
|
||||
);
|
||||
const catalogErrorState = await evaluate(`(() => ({
|
||||
hasError: [...document.querySelectorAll('[role=alert]')].some(node => node.innerText.includes('Não foi possível carregar as opções')),
|
||||
hasEmptyMessage: document.body.innerText.includes('Sem opções correspondentes.'),
|
||||
retryVisible: [...document.querySelectorAll('button')].some(node => node.innerText.trim() === 'Tentar carregar novamente'),
|
||||
}))()`);
|
||||
if (
|
||||
!catalogErrorState.hasError ||
|
||||
catalogErrorState.hasEmptyMessage ||
|
||||
!catalogErrorState.retryVisible
|
||||
)
|
||||
throw new Error(
|
||||
'Catalog failure UI did not distinguish failure from an empty catalog or offer retry.',
|
||||
);
|
||||
await clickText('button', 'Tentar carregar novamente');
|
||||
await waitFor('window.__simApiFailureTest?.catalog === 2', 'catalog retry');
|
||||
await waitFor(
|
||||
"[...document.querySelectorAll('[role=option]')].some(node => node.innerText.includes('País de teste QA'))",
|
||||
'catalog option after retry',
|
||||
);
|
||||
await clickText('[role="option"]', 'País de teste QA');
|
||||
|
||||
await choose(
|
||||
'Que resultado de remuneração pretende explorar?',
|
||||
'',
|
||||
'Apuramento anual',
|
||||
);
|
||||
await choose('Estado da documentação de despesas', '', 'Documentada');
|
||||
await choose('Pretende calcular um cenário aritmético?', '', 'Sim');
|
||||
await fillNumber('base', '1000');
|
||||
await fillNumber('rate', '10');
|
||||
await fillNumber('reduction', '50');
|
||||
await clickText('button', 'Validar e calcular no servidor');
|
||||
await waitFor(
|
||||
"[...document.querySelectorAll('[role=alert]')].some(node => node.innerText.includes('Estado do cálculo temporariamente indisponível'))",
|
||||
'polling failure alert',
|
||||
);
|
||||
await waitFor(
|
||||
"document.body.innerText.includes('O cálculo continua pendente.')",
|
||||
'pending calculation message',
|
||||
);
|
||||
const result = await evaluate(`({
|
||||
mocks: window.__simApiFailureTest,
|
||||
catalogErrorAlert: [...document.querySelectorAll('[role=alert]')].some(node => node.innerText.includes('Não foi possível carregar as opções')),
|
||||
pollingErrorAlert: [...document.querySelectorAll('[role=alert]')].some(node => node.innerText.includes('Estado do cálculo temporariamente indisponível')),
|
||||
pendingStatusVisible: document.body.innerText.includes('O cálculo continua pendente.'),
|
||||
networkApiResponses: ${JSON.stringify(apiResponses)},
|
||||
})`);
|
||||
const report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
qaTarget: expectedTarget,
|
||||
scope: 'real public page/current-draft GET on isolated QA; catalog, calculation, polling and draft writes intercepted in browser',
|
||||
catalogErrorState,
|
||||
result,
|
||||
serverResponses,
|
||||
javascriptExceptions,
|
||||
consoleErrors,
|
||||
passed:
|
||||
realTargetConfirmed &&
|
||||
catalogErrorState.hasError &&
|
||||
!catalogErrorState.hasEmptyMessage &&
|
||||
catalogErrorState.retryVisible &&
|
||||
result.mocks.catalog === 2 &&
|
||||
result.mocks.created === 1 &&
|
||||
result.mocks.poll === 1 &&
|
||||
result.pollingErrorAlert &&
|
||||
result.pendingStatusVisible &&
|
||||
result.networkApiResponses.every(
|
||||
(response) =>
|
||||
response.path === '/api/v1/simulation-drafts/current',
|
||||
) &&
|
||||
javascriptExceptions.length === 0,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
} catch (cause) {
|
||||
const report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
qaTarget: expectedTarget,
|
||||
failure: cause instanceof Error ? cause.message : 'browser-test-failed',
|
||||
page: await evaluate(`(() => ({
|
||||
ready: document.readyState,
|
||||
title: document.title,
|
||||
url: location.href,
|
||||
appRoot: Boolean(document.querySelector('#app')),
|
||||
pageData: (() => {
|
||||
const script = document.querySelector('script[data-page]');
|
||||
try { return JSON.parse(script?.textContent || 'null')?.component ?? null; }
|
||||
catch { return 'invalid-page-json'; }
|
||||
})(),
|
||||
simulatorTitle: Boolean(document.querySelector('#simulator-step-title')),
|
||||
rootTextLength: document.querySelector('#app')?.innerText?.length ?? 0,
|
||||
rootChildren: document.querySelector('#app')?.children.length ?? 0,
|
||||
rootAttributes: [...(document.querySelector('#app')?.attributes ?? [])].map(attribute => attribute.name),
|
||||
scriptCount: document.scripts.length,
|
||||
moduleScripts: [...document.scripts].filter(script => script.type === 'module').length,
|
||||
resourceCount: performance.getEntriesByType('resource').length,
|
||||
resourceSamples: performance.getEntriesByType('resource').slice(0, 12).map(entry => new URL(entry.name).pathname),
|
||||
unhandledRejections: window.__simApiUnhandled ?? [],
|
||||
mockedApi: window.__simApiFailureTest ?? null,
|
||||
visibleAlerts: [...document.querySelectorAll('[role=alert]')]
|
||||
.filter(element => element.getClientRects().length)
|
||||
.map(element => element.innerText.trim()),
|
||||
submittedValues: ['base', 'rate', 'reduction'].map(field => ({
|
||||
field,
|
||||
value: document.getElementById('field-' + field)?.value ?? null,
|
||||
invalid: document.getElementById('field-' + field)?.getAttribute('aria-invalid') ?? null,
|
||||
})),
|
||||
}))()`).catch(() => null),
|
||||
serverResponses,
|
||||
javascriptExceptions,
|
||||
consoleErrors,
|
||||
failedResources: failedResources.slice(0, 20),
|
||||
passed: false,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.error(JSON.stringify(report, null, 2));
|
||||
throw cause;
|
||||
} finally {
|
||||
ws.close();
|
||||
await fetch(`http://127.0.0.1:9225/json/close/${target.id}`);
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
// Public anonymous calculation smoke test against an isolated QA Laravel DB.
|
||||
import fs from 'node:fs';
|
||||
|
||||
const baseUrl = process.argv[2] ?? 'http://127.0.0.1:18082/simulador-fiscal';
|
||||
const outputPath =
|
||||
process.argv[3] ??
|
||||
'docs/investmoz/simulations/simulator-calculation-responsive-browser-2026-10-03.json';
|
||||
const expectedQaTarget = process.argv[4] ?? null;
|
||||
const target = await (
|
||||
await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })
|
||||
).json();
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.addEventListener('open', resolve, { once: true });
|
||||
ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
const errors = [];
|
||||
const apiResponses = [];
|
||||
const simulationResponseShapes = [];
|
||||
const simulationRequestIds = new Map();
|
||||
const responseBodyCaptures = [];
|
||||
const responsiveStates = [];
|
||||
let clientValidation = null;
|
||||
let fiscalHeadingFocus = null;
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown')
|
||||
errors.push(message.params.exceptionDetails.text);
|
||||
if (message.method === 'Network.responseReceived') {
|
||||
const response = message.params.response;
|
||||
const path = new URL(response.url).pathname;
|
||||
if (path.startsWith('/api/v1/')) {
|
||||
const qaTarget = Object.entries(response.headers ?? {}).find(
|
||||
([name]) => name.toLowerCase() === 'x-investmoz-qa-target',
|
||||
)?.[1];
|
||||
apiResponses.push({
|
||||
path,
|
||||
status: response.status,
|
||||
qaTarget: typeof qaTarget === 'string' ? qaTarget : null,
|
||||
});
|
||||
if (path === '/api/v1/simulations')
|
||||
simulationRequestIds.set(message.params.requestId, {
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
message.method === 'Network.loadingFinished' &&
|
||||
simulationRequestIds.has(message.params.requestId)
|
||||
) {
|
||||
const response = simulationRequestIds.get(message.params.requestId);
|
||||
simulationRequestIds.delete(message.params.requestId);
|
||||
responseBodyCaptures.push(
|
||||
send('Network.getResponseBody', {
|
||||
requestId: message.params.requestId,
|
||||
})
|
||||
.then(({ body, base64Encoded }) => {
|
||||
const json = JSON.parse(
|
||||
base64Encoded
|
||||
? Buffer.from(body, 'base64').toString()
|
||||
: body,
|
||||
);
|
||||
const data = json?.data;
|
||||
simulationResponseShapes.push({
|
||||
httpStatus: response.status,
|
||||
outerKeys: Object.keys(json ?? {}).sort(),
|
||||
replayedType: typeof json?.replayed,
|
||||
replayed: json?.replayed === true,
|
||||
accessTokenLength:
|
||||
typeof json?.access_token === 'string'
|
||||
? json.access_token.length
|
||||
: null,
|
||||
data:
|
||||
data && typeof data === 'object'
|
||||
? {
|
||||
keys: Object.keys(data).sort(),
|
||||
idType: typeof data.id,
|
||||
status: data.status,
|
||||
versionNoType: typeof data.version_no,
|
||||
resultSnapshotType:
|
||||
data.result_snapshot === null
|
||||
? 'null'
|
||||
: Array.isArray(
|
||||
data.result_snapshot,
|
||||
)
|
||||
? 'array'
|
||||
: typeof data.result_snapshot,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
})
|
||||
.catch(() => {}),
|
||||
);
|
||||
}
|
||||
if (!message.id) return;
|
||||
const request = pending.get(message.id);
|
||||
pending.delete(message.id);
|
||||
if (!request) return;
|
||||
if (message.error) request.reject(message.error);
|
||||
else request.resolve(message.result);
|
||||
});
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const requestId = ++id;
|
||||
pending.set(requestId, { resolve, reject });
|
||||
ws.send(JSON.stringify({ id: requestId, method, params }));
|
||||
});
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
});
|
||||
if (response.exceptionDetails)
|
||||
throw new Error(
|
||||
response.exceptionDetails.exception?.description ??
|
||||
response.exceptionDetails.text,
|
||||
);
|
||||
return response.result?.value;
|
||||
};
|
||||
const waitFor = async (expression, description) => {
|
||||
for (let attempt = 0; attempt < 120; attempt++) {
|
||||
if (await evaluate(expression)) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${description}`);
|
||||
};
|
||||
const clickText = async (selector, text) => {
|
||||
const found = await evaluate(`(() => {
|
||||
const e = [...document.querySelectorAll(${JSON.stringify(selector)})]
|
||||
.find(node => node.innerText.trim().includes(${JSON.stringify(text)}));
|
||||
if (!e) return false;
|
||||
e.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!found) throw new Error(`Could not find ${selector}: ${text}`);
|
||||
};
|
||||
const choose = async (label, query, optionText) => {
|
||||
const opened = await evaluate(`(() => {
|
||||
const label = [...document.querySelectorAll('label')]
|
||||
.find(node => node.innerText.includes(${JSON.stringify(label)}));
|
||||
const input = label && document.getElementById(label.htmlFor);
|
||||
if (!input) return false;
|
||||
input.focus();
|
||||
input.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!opened) throw new Error(`Could not open combobox: ${label}`);
|
||||
await send('Input.insertText', { text: query });
|
||||
const optionSelector = `[role="option"]`;
|
||||
await waitFor(
|
||||
`([...document.querySelectorAll(${JSON.stringify(optionSelector)})]
|
||||
.some(node => node.innerText.trim().includes(${JSON.stringify(optionText)})))`,
|
||||
`option ${optionText}`,
|
||||
);
|
||||
await clickText(optionSelector, optionText);
|
||||
};
|
||||
const fillNumber = async (field, value) => {
|
||||
const found = await evaluate(`(() => {
|
||||
const input = document.getElementById(${JSON.stringify(`field-${field}`)});
|
||||
if (!input) return false;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||
setter.call(input, ${JSON.stringify(value)});
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return true;
|
||||
})()`);
|
||||
if (!found) throw new Error(`Could not fill numeric field: ${field}`);
|
||||
};
|
||||
|
||||
const auditResponsiveState = async (state) => {
|
||||
const widths = [320, 360, 390, 768, 1024, 1440];
|
||||
const viewports = [];
|
||||
for (const width of widths) {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
height: 900,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: width < 768,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 80));
|
||||
const layout = await evaluate(`(() => {
|
||||
const visible = e => e.getClientRects().length > 0 && getComputedStyle(e).visibility !== 'hidden';
|
||||
const name = e => e.getAttribute('aria-label') ||
|
||||
(e.getAttribute('aria-labelledby') ? document.getElementById(e.getAttribute('aria-labelledby'))?.innerText?.trim() : null) ||
|
||||
e.labels?.[0]?.innerText?.trim() || e.innerText?.trim() || e.title || null;
|
||||
const controls = [...document.querySelectorAll('input:not([type="hidden"]), select, textarea')]
|
||||
.filter(visible).map(e => ({ id: e.id || null, name: name(e) }));
|
||||
const buttons = [...document.querySelectorAll('button')].filter(visible).map(name);
|
||||
const links = [...document.querySelectorAll('a')].filter(visible).map(name);
|
||||
const overflowElements = [...document.querySelectorAll('body *')]
|
||||
.filter(visible).map(e => {
|
||||
const rect = e.getBoundingClientRect();
|
||||
return { tag: e.tagName, id: e.id || null, className: String(e.className || '').slice(0, 100),
|
||||
left: Math.round(rect.left), right: Math.round(rect.right), width: Math.round(rect.width),
|
||||
text: (e.innerText || '').trim().slice(0, 80) };
|
||||
}).filter(e => e.left < -1 || e.right > document.documentElement.clientWidth + 1)
|
||||
.sort((a, b) => (b.right - innerWidth) - (a.right - innerWidth)).slice(0, 8);
|
||||
return {
|
||||
requestedWidth: ${width}, viewport: innerWidth,
|
||||
layoutWidth: document.documentElement.clientWidth,
|
||||
documentScroll: document.documentElement.scrollWidth,
|
||||
bodyScroll: document.body.scrollWidth,
|
||||
unnamedControls: controls.filter(e => !e.name).map(e => e.id),
|
||||
unnamedButtons: buttons.filter(value => !value).length,
|
||||
unnamedLinks: links.filter(value => !value).length,
|
||||
visibleControls: controls.length,
|
||||
overflowElements,
|
||||
};
|
||||
})()`);
|
||||
const tree = await send('Accessibility.getFullAXTree');
|
||||
const namedRoles = new Set([
|
||||
'button',
|
||||
'textbox',
|
||||
'searchbox',
|
||||
'combobox',
|
||||
'checkbox',
|
||||
'radioButton',
|
||||
'link',
|
||||
'slider',
|
||||
'spinbutton',
|
||||
]);
|
||||
layout.unnamedAxControls = tree.nodes
|
||||
.filter((node) => !node.ignored && namedRoles.has(node.role?.value))
|
||||
.filter((node) => !node.name?.value?.trim())
|
||||
.map((node) => node.role.value);
|
||||
layout.passed =
|
||||
layout.documentScroll <= layout.layoutWidth + 1 &&
|
||||
layout.bodyScroll <= layout.layoutWidth + 1 &&
|
||||
layout.unnamedControls.length === 0 &&
|
||||
layout.unnamedButtons === 0 &&
|
||||
layout.unnamedLinks === 0 &&
|
||||
layout.unnamedAxControls.length === 0;
|
||||
viewports.push(layout);
|
||||
}
|
||||
await send('Emulation.clearDeviceMetricsOverride');
|
||||
responsiveStates.push({
|
||||
state,
|
||||
viewports,
|
||||
passed: viewports.every((item) => item.passed),
|
||||
});
|
||||
return viewports.every((item) => item.passed);
|
||||
};
|
||||
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Network.enable');
|
||||
await send('Page.navigate', { url: baseUrl });
|
||||
await waitFor(
|
||||
"Boolean(document.querySelector('main #simulator-step-title'))",
|
||||
'public simulator form',
|
||||
);
|
||||
const purposeResponsive = await auditResponsiveState('purpose');
|
||||
|
||||
await choose('Escolha o percurso', 'Particular', 'Particular');
|
||||
await choose('Nível de detalhe', 'Simples', 'Simples');
|
||||
await choose('O que pretende fazer?', 'Apenas simular', 'Apenas simular');
|
||||
await choose('Idioma preferido', 'Português', 'Português');
|
||||
await clickText('button', 'Operação fiscal');
|
||||
fiscalHeadingFocus = await evaluate(`(() => {
|
||||
const heading = document.querySelector('#simulator-step-title');
|
||||
const style = heading ? getComputedStyle(heading) : null;
|
||||
return {
|
||||
focused: document.activeElement === heading,
|
||||
outlineStyle: style?.outlineStyle ?? null,
|
||||
outlineWidth: style?.outlineWidth ?? null,
|
||||
visible: Boolean(heading?.getClientRects?.().length),
|
||||
};
|
||||
})()`);
|
||||
fiscalHeadingFocus.visibleIndicator =
|
||||
fiscalHeadingFocus.focused &&
|
||||
fiscalHeadingFocus.visible &&
|
||||
fiscalHeadingFocus.outlineStyle !== 'none' &&
|
||||
fiscalHeadingFocus.outlineWidth !== '0px';
|
||||
const fiscalResponsive = await auditResponsiveState('tax');
|
||||
await choose('Ano do período fiscal', '2026', '2026');
|
||||
await choose('Periodicidade/período de referência', 'Anual', 'Anual');
|
||||
await choose('Componente que pretende explorar', 'INSS', 'INSS');
|
||||
await choose(
|
||||
'Modo de exploração fiscal',
|
||||
'Cenário personalizado',
|
||||
'Cenário personalizado de planeamento',
|
||||
);
|
||||
|
||||
await clickText('button', 'Validar e calcular no servidor');
|
||||
await waitFor(
|
||||
"document.querySelector('#field-base')?.getAttribute('aria-invalid') === 'true'",
|
||||
'client-side missing-input validation',
|
||||
);
|
||||
const calculationRequestsBeforeCorrection = apiResponses.filter(
|
||||
(response) => response.path === '/api/v1/simulations',
|
||||
).length;
|
||||
clientValidation = await evaluate(`(() => {
|
||||
const input = document.querySelector('#field-base');
|
||||
const describedBy = (input?.getAttribute('aria-describedby') || '')
|
||||
.split(/\\s+/).filter(Boolean);
|
||||
const descriptions = describedBy.map(id => document.getElementById(id));
|
||||
return {
|
||||
inputInvalid: input?.getAttribute('aria-invalid') === 'true',
|
||||
inputDescribedBy: describedBy,
|
||||
descriptionsExist: descriptions.length > 0 && descriptions.every(Boolean),
|
||||
descriptionsAreAlerts: descriptions.length > 0 &&
|
||||
descriptions.every(node => node.getAttribute('role') === 'alert'),
|
||||
activeField: document.activeElement?.id || null,
|
||||
calculationRequestsBeforeCorrection: ${calculationRequestsBeforeCorrection},
|
||||
};
|
||||
})()`);
|
||||
clientValidation.accessibleErrors =
|
||||
clientValidation.inputInvalid &&
|
||||
clientValidation.descriptionsExist &&
|
||||
clientValidation.descriptionsAreAlerts &&
|
||||
clientValidation.activeField === 'field-base' &&
|
||||
clientValidation.calculationRequestsBeforeCorrection === 0;
|
||||
|
||||
await fillNumber('base', '1000');
|
||||
await fillNumber('rate', '10');
|
||||
await fillNumber('reduction', '50');
|
||||
await clickText('button', 'Validar e calcular no servidor');
|
||||
try {
|
||||
await waitFor(
|
||||
"document.body.innerText.includes('Simulação concluída') && document.body.innerText.includes('50')",
|
||||
'completed calculation result',
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
JSON.stringify(
|
||||
{
|
||||
visibleText: await evaluate('document.body.innerText'),
|
||||
clientValidation,
|
||||
apiResponses,
|
||||
simulationResponseShapes,
|
||||
javascriptExceptions: errors,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
await waitFor(
|
||||
"document.body.innerText.includes('não constitui cálculo nem conclusão fiscal') || document.body.innerText.includes('não determina taxas legais')",
|
||||
'non-tax disclaimer',
|
||||
);
|
||||
const resultResponsive = await auditResponsiveState('result');
|
||||
|
||||
const pageResult = await evaluate(`(() => ({
|
||||
title: document.title,
|
||||
resultText: [...document.querySelectorAll('strong')].map(node => node.innerText.trim()),
|
||||
completed: document.body.innerText.includes('Simulação concluída'),
|
||||
taxDisclaimer: document.body.innerText.includes('não determina taxas legais') ||
|
||||
document.body.innerText.includes('não constitui cálculo nem conclusão fiscal'),
|
||||
visibleAlerts: [...document.querySelectorAll('[role="alert"]')]
|
||||
.filter(node => node.getClientRects().length).map(node => node.innerText.trim()),
|
||||
anonymousIdentityNotice: document.body.innerText.includes('identidade e contactos não são enviados'),
|
||||
}))()`);
|
||||
await Promise.all(responseBodyCaptures);
|
||||
const calculationRequests = apiResponses.filter(
|
||||
(response) => response.path === '/api/v1/simulations',
|
||||
);
|
||||
const failedResponses = apiResponses.filter(
|
||||
(response) => response.status < 200 || response.status >= 300,
|
||||
);
|
||||
const qaTargetVerified =
|
||||
expectedQaTarget === null ||
|
||||
(apiResponses.length > 0 &&
|
||||
apiResponses.every(
|
||||
(response) => response.qaTarget === expectedQaTarget,
|
||||
));
|
||||
const report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
scope: 'submissão anónima, validação acessível e UI responsiva nos estados finalidade/fiscal/resultado; sem dados pessoais ou interpretação fiscal',
|
||||
expectedQaTarget,
|
||||
qaTargetVerified,
|
||||
inputs: {
|
||||
fiscalPeriod: '2026',
|
||||
componentContext: 'inss',
|
||||
base: '1000',
|
||||
rate: '10',
|
||||
reduction: '50',
|
||||
},
|
||||
clientValidation,
|
||||
fiscalHeadingFocus,
|
||||
responsiveStates,
|
||||
expectedArithmeticValue: '50',
|
||||
...pageResult,
|
||||
calculationRequests,
|
||||
apiResponses,
|
||||
simulationResponseShapes,
|
||||
failedResponses,
|
||||
javascriptExceptions: errors,
|
||||
passed:
|
||||
pageResult.completed &&
|
||||
pageResult.taxDisclaimer &&
|
||||
pageResult.anonymousIdentityNotice &&
|
||||
clientValidation.accessibleErrors &&
|
||||
fiscalHeadingFocus.visibleIndicator &&
|
||||
purposeResponsive &&
|
||||
fiscalResponsive &&
|
||||
resultResponsive &&
|
||||
qaTargetVerified &&
|
||||
pageResult.resultText.some(
|
||||
(value) => value === '50' || /^50\.0+$/.test(value),
|
||||
) &&
|
||||
calculationRequests.length === 1 &&
|
||||
calculationRequests[0].status === 202 &&
|
||||
failedResponses.length === 0 &&
|
||||
errors.length === 0 &&
|
||||
pageResult.visibleAlerts.length === 0,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
} catch (error) {
|
||||
const report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
scope: 'submissão anónima, validação acessÃvel e estado da execução; sem dados pessoais ou interpretação fiscal',
|
||||
clientValidation,
|
||||
fiscalHeadingFocus,
|
||||
responsiveStates,
|
||||
expectedQaTarget,
|
||||
calculationRequests: apiResponses.filter(
|
||||
(response) => response.path === '/api/v1/simulations',
|
||||
),
|
||||
apiResponses,
|
||||
simulationResponseShapes,
|
||||
completed: false,
|
||||
pendingStatus: simulationResponseShapes.at(-1)?.data?.status ?? null,
|
||||
failure:
|
||||
error instanceof Error ? error.message : 'browser-smoke-failed',
|
||||
passed: false,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.error(JSON.stringify(report, null, 2));
|
||||
throw error;
|
||||
} finally {
|
||||
ws.close();
|
||||
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
// Isolated React component browser test. Requires Vite and Edge CDP on localhost.
|
||||
import fs from 'node:fs';
|
||||
|
||||
const baseUrl =
|
||||
process.argv[2] ??
|
||||
'http://127.0.0.1:18117/tools/simulator-cashflow-preview.html';
|
||||
const outputPath =
|
||||
process.argv[3] ??
|
||||
'docs/investmoz/simulations/simulator-cashflow-browser-2026-10-03.json';
|
||||
const target = await (
|
||||
await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })
|
||||
).json();
|
||||
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.addEventListener('open', resolve, { once: true });
|
||||
ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
let nextId = 0;
|
||||
const pending = new Map();
|
||||
const exceptions = [];
|
||||
const network = [];
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.method === 'Runtime.exceptionThrown')
|
||||
exceptions.push(message.params.exceptionDetails.text);
|
||||
if (message.method === 'Network.responseReceived')
|
||||
network.push({
|
||||
url: message.params.response.url,
|
||||
status: message.params.response.status,
|
||||
});
|
||||
if (!message.id) return;
|
||||
const request = pending.get(message.id);
|
||||
pending.delete(message.id);
|
||||
if (!request) return;
|
||||
if (message.error) request.reject(message.error);
|
||||
else request.resolve(message.result);
|
||||
});
|
||||
const send = (method, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const id = ++nextId;
|
||||
pending.set(id, { resolve, reject });
|
||||
ws.send(JSON.stringify({ id, method, params }));
|
||||
});
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send('Runtime.evaluate', {
|
||||
expression,
|
||||
returnByValue: true,
|
||||
awaitPromise: true,
|
||||
});
|
||||
if (response.exceptionDetails)
|
||||
throw new Error(
|
||||
response.exceptionDetails.exception?.description ??
|
||||
response.exceptionDetails.text,
|
||||
);
|
||||
return response.result?.value;
|
||||
};
|
||||
const waitFor = async (expression, description) => {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
if (await evaluate(`Boolean(${expression})`)) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${description}`);
|
||||
};
|
||||
|
||||
let report;
|
||||
try {
|
||||
await send('Page.enable');
|
||||
await send('Runtime.enable');
|
||||
await send('Network.enable');
|
||||
await send('Page.navigate', { url: baseUrl });
|
||||
await waitFor(
|
||||
'document.querySelector(\'#cashflow-root section[aria-labelledby=\\"cashflow-title\\"]\')',
|
||||
'the rendered cashflow component',
|
||||
);
|
||||
|
||||
const fixedMode = await evaluate(`(() => {
|
||||
const fixed = [...document.querySelectorAll('label')].find(label => label.innerText.includes('Valor mensal fixo'))?.querySelector('input[type="radio"]');
|
||||
const note = [...document.querySelectorAll('[role="note"]')].map(node => node.innerText).find(text => text.includes('saldo total')) ?? null;
|
||||
return { selected: fixed?.checked ?? false, monthlyInputs: [...document.querySelectorAll('label')].filter(label => label.innerText.includes('Imposto assumido por mês')).length, incompleteNote: note };
|
||||
})()`);
|
||||
|
||||
const selectedSchedule = await evaluate(`(() => {
|
||||
const label = [...document.querySelectorAll('label')].find(item => item.innerText.includes('Calendário variável por mês'));
|
||||
const radio = label?.querySelector('input[type="radio"]');
|
||||
radio?.click();
|
||||
return Boolean(radio);
|
||||
})()`);
|
||||
if (!selectedSchedule)
|
||||
throw new Error('Monthly schedule option is missing.');
|
||||
await waitFor(
|
||||
"[...document.querySelectorAll('label')].filter(label => label.innerText.includes('Imposto assumido') && /mês \\d+/u.test(label.innerText)).length === 12",
|
||||
'12 labeled monthly assumption inputs',
|
||||
);
|
||||
|
||||
const setMonth = async (month, value) =>
|
||||
evaluate(`(() => {
|
||||
const label = [...document.querySelectorAll('label')].find(item => item.innerText.includes('Imposto assumido') && item.innerText.includes('mês ${month}'));
|
||||
const input = label?.querySelector('input');
|
||||
if (!input) return false;
|
||||
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||
setter.call(input, '${value}');
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
return true;
|
||||
})()`);
|
||||
for (const [month, value] of [
|
||||
[1, '250'],
|
||||
[2, '500'],
|
||||
]) {
|
||||
if (!(await setMonth(month, value)))
|
||||
throw new Error(`Could not update month ${month}.`);
|
||||
}
|
||||
await waitFor(
|
||||
"[...document.querySelectorAll('tbody tr')].some(row => row.querySelector('th')?.innerText.trim() === '1' && row.querySelectorAll('td')[4]?.innerText.trim() === '250.00')",
|
||||
'monthly assumption to affect the cash projection',
|
||||
);
|
||||
|
||||
const partialSchedule = await evaluate(`(() => {
|
||||
const rows = [...document.querySelectorAll('tbody tr')];
|
||||
const taxFor = month => rows.find(row => row.querySelector('th')?.innerText.trim() === String(month))?.querySelectorAll('td')[4]?.innerText.trim() ?? null;
|
||||
const note = [...document.querySelectorAll('[role="note"]')].map(node => node.innerText).find(text => text.includes('mês vazio')) ?? null;
|
||||
const status = document.body.innerText.includes('Caixa conhecida antes de imposto em falta');
|
||||
return { firstMonthTax: taxFor(1), secondMonthTax: taxFor(2), thirdMonthTax: taxFor(3), incompleteNote: note, incompleteSummary: status };
|
||||
})()`);
|
||||
|
||||
for (let month = 3; month <= 12; month++) {
|
||||
if (!(await setMonth(month, '0')))
|
||||
throw new Error(`Could not explicitly set month ${month} to zero.`);
|
||||
}
|
||||
await waitFor(
|
||||
"!document.body.innerText.includes('Há pelo menos um mês sem pressuposto de imposto')",
|
||||
'complete projection after explicit zero assumptions',
|
||||
);
|
||||
const completeSchedule = await evaluate(`(() => ({
|
||||
hasCompleteBalance: document.body.innerText.includes('Saldo projectado ao fim de 12 meses (MZN)'),
|
||||
zeroTaxMonths: [...document.querySelectorAll('tbody tr')].slice(2).every(row => row.querySelectorAll('td')[4]?.innerText.trim() === '0.00'),
|
||||
rowCount: document.querySelectorAll('tbody tr').length,
|
||||
}))()`);
|
||||
|
||||
const responsive = [];
|
||||
for (const width of [320, 360, 390, 768, 1024, 1440]) {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
height: 900,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: width < 768,
|
||||
});
|
||||
responsive.push(
|
||||
await evaluate(`(() => ({
|
||||
requested: ${width}, viewport: innerWidth,
|
||||
documentWidth: document.documentElement.clientWidth,
|
||||
documentScroll: document.documentElement.scrollWidth,
|
||||
bodyScroll: document.body.scrollWidth,
|
||||
hasHorizontalOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1 || document.body.scrollWidth > document.documentElement.clientWidth + 1,
|
||||
inputs: [...document.querySelectorAll('input:not([type="hidden"])')].filter(input => input.getClientRects().length).length,
|
||||
unnamedInputs: [...document.querySelectorAll('input:not([type="hidden"])')].filter(input => input.getClientRects().length && !(input.labels?.length || input.getAttribute('aria-label'))).length,
|
||||
}))()`),
|
||||
);
|
||||
}
|
||||
await send('Emulation.clearDeviceMetricsOverride');
|
||||
const ax = await send('Accessibility.getFullAXTree');
|
||||
const unnamedAxControls = ax.nodes
|
||||
.filter(
|
||||
(node) =>
|
||||
!node.ignored &&
|
||||
[
|
||||
'button',
|
||||
'textbox',
|
||||
'radioButton',
|
||||
'spinbutton',
|
||||
'link',
|
||||
].includes(node.role?.value),
|
||||
)
|
||||
.filter((node) => !node.name?.value?.trim())
|
||||
.map((node) => node.role.value);
|
||||
|
||||
report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
scope: 'React cashflow component only; no Laravel, API, database, or fiscal rules',
|
||||
fixedMode,
|
||||
partialSchedule,
|
||||
completeSchedule,
|
||||
responsive,
|
||||
unnamedAxControls,
|
||||
javascriptExceptions: exceptions,
|
||||
networkFailures: network.filter((item) => item.status >= 400),
|
||||
passed:
|
||||
fixedMode.selected &&
|
||||
fixedMode.monthlyInputs === 1 &&
|
||||
Boolean(fixedMode.incompleteNote) &&
|
||||
partialSchedule.firstMonthTax === '250.00' &&
|
||||
partialSchedule.secondMonthTax === '500.00' &&
|
||||
partialSchedule.thirdMonthTax === 'Indeterminado' &&
|
||||
Boolean(partialSchedule.incompleteNote) &&
|
||||
partialSchedule.incompleteSummary &&
|
||||
completeSchedule.hasCompleteBalance &&
|
||||
completeSchedule.zeroTaxMonths &&
|
||||
completeSchedule.rowCount === 12 &&
|
||||
responsive.every(
|
||||
(item) =>
|
||||
!item.hasHorizontalOverflow && item.unnamedInputs === 0,
|
||||
) &&
|
||||
unnamedAxControls.length === 0 &&
|
||||
exceptions.length === 0 &&
|
||||
network.every((item) => item.status < 400),
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
if (!report.passed) process.exitCode = 1;
|
||||
} catch (error) {
|
||||
report = {
|
||||
checkedAt: new Date().toISOString(),
|
||||
route: baseUrl,
|
||||
browser: 'Microsoft Edge headless via CDP',
|
||||
failure: error instanceof Error ? error.message : String(error),
|
||||
partialReport: report,
|
||||
passed: false,
|
||||
};
|
||||
fs.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.error(JSON.stringify(report, null, 2));
|
||||
throw error;
|
||||
} finally {
|
||||
ws.close();
|
||||
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<!doctype html>
|
||||
<html lang="pt">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>QA local — planeador de tesouraria</title>
|
||||
<link rel="icon" href="data:," />
|
||||
<link rel="stylesheet" href="/resources/css/app.css" />
|
||||
</head>
|
||||
<body>
|
||||
<main id="cashflow-root" class="mx-auto max-w-6xl p-4"></main>
|
||||
<script type="module">
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { SimulationCashflowPlanner } from '../resources/js/components/simulation-cashflow-planner.tsx';
|
||||
|
||||
createRoot(document.getElementById('cashflow-root')).render(
|
||||
React.createElement(SimulationCashflowPlanner, {
|
||||
currency: 'MZN',
|
||||
onCurrencyChange: () => {},
|
||||
}),
|
||||
);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Local smoke-test router. Its database target is intentionally fixed to the
|
||||
// disposable PHPUnit database; do not reuse it for development or production.
|
||||
$root = dirname(__DIR__);
|
||||
$qaEnvironment = [
|
||||
'APP_ENV' => 'testing',
|
||||
'APP_DEBUG' => 'true',
|
||||
'DB_CONNECTION' => 'pgsql',
|
||||
'DB_HOST' => '127.0.0.1',
|
||||
'DB_PORT' => '55441',
|
||||
'DB_DATABASE' => 'investmoz_test',
|
||||
'DB_USERNAME' => 'investmoz_test',
|
||||
'DB_PASSWORD' => '',
|
||||
'DB_URL' => '',
|
||||
'QUEUE_CONNECTION' => 'sync',
|
||||
'SESSION_DRIVER' => 'array',
|
||||
'CACHE_STORE' => 'array',
|
||||
];
|
||||
|
||||
foreach ($qaEnvironment as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $value;
|
||||
$_SERVER[$key] = $value;
|
||||
}
|
||||
|
||||
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
|
||||
$asset = $root.'/public'.$path;
|
||||
if ($path !== '/' && is_file($asset)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
require_once $root.'/vendor/autoload.php';
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
// Keep QA on the checked-in build manifest; the developer Vite server may be
|
||||
// stale or backed by a different working copy and is never the QA frontend.
|
||||
Illuminate\Support\Facades\Vite::useHotFile($root.'/storage/framework/investmoz-qa-hot-file');
|
||||
$configuration = $app->make('config');
|
||||
$connectionName = $configuration->get('database.default');
|
||||
$connection = $configuration->get('database.connections.'.$connectionName, []);
|
||||
|
||||
// Fail before opening a connection if cached config or .env changes the target.
|
||||
if ($connectionName !== 'pgsql'
|
||||
|| ($connection['host'] ?? null) !== '127.0.0.1'
|
||||
|| (string) ($connection['port'] ?? '') !== '55441'
|
||||
|| ($connection['database'] ?? null) !== 'investmoz_test'
|
||||
|| ! in_array($connection['url'] ?? null, [null, ''], true)) {
|
||||
http_response_code(503);
|
||||
exit('QA database configuration did not match the fixed target.');
|
||||
}
|
||||
|
||||
$identity = $app->make('db')->connection($connectionName)->selectOne(
|
||||
'select current_database() as database, host(inet_server_addr()) as host, inet_server_port() as port',
|
||||
);
|
||||
if ($identity->database !== 'investmoz_test' || $identity->host !== '127.0.0.1' || (int) $identity->port !== 55441) {
|
||||
http_response_code(503);
|
||||
exit('Connected database did not match the fixed QA target.');
|
||||
}
|
||||
|
||||
header('X-Investmoz-QA-Target: '.$identity->database.':'.$identity->port);
|
||||
$app->handleRequest(Illuminate\Http\Request::capture());
|
||||
+13
-5
@@ -10,7 +10,7 @@ const relation = {association_type: {type: 'string', enum: ['official','influenc
|
||||
const relationRequired=['association_type','role','source_reference','justification','valid_from'];
|
||||
const schemas = {
|
||||
Version: object({version_no:version},['version_no']),
|
||||
Zone: object({version_no:version,code:{type:'string',maxLength:80},category:{type:'string',enum:['zee','zfi','industrial_park','pending']},name:{type:'string',maxLength:255},name_en:nullable(string),description:nullable(string),description_en:nullable(string),province:nullable(string),district:nullable(string),operator_id:nullable(uuid),legal_source_id:nullable(uuid)},['code','category','name']),
|
||||
Zone: object({version_no:version,code:{type:'string',maxLength:80},category:{type:'string',enum:['zee','zfi','industrial_park','pending']},physical_category:{type:'string',enum:['economic_zone','industrial_park','agro_industrial_park','industrial_logistics_park','industrial_free_zone','integrated_tourism_area','other','unknown']},legal_regime:{type:'string',enum:['zee','zfi','general','pending','not_applicable']},development_status:{type:'string',enum:['announced','planned','in_development','partially_operational','operational','suspended','unknown']},availability_status:{type:'string',enum:['confirmed','unavailable','reported_unverified','not_informed']},area_components:{type:'array',items:{type:'object'}},source_evidence:{type:'array',items:{type:'object'}},name:{type:'string',maxLength:255},name_en:nullable(string),description:nullable(string),description_en:nullable(string),province:nullable(string),district:nullable(string),operator_id:nullable(uuid),legal_source_id:nullable(uuid)},['code','category','name']),
|
||||
LegalSource: object({title:string,url:{type:'string',format:'uri',description:'HTTPS reference only; no remote download.'},diploma:string,article:string,competent_entity:string,valid_from:date,valid_until:nullable(date)},['title','url','diploma','article','competent_entity','valid_from']),
|
||||
Link: object({opportunity_id:{type:'integer',minimum:1},...relation},['opportunity_id',...relationRequired]),
|
||||
Relation: object({cluster_id:nullable(uuid),corridor_id:nullable(uuid),project_id:nullable(uuid),...relation},relationRequired),
|
||||
@@ -23,14 +23,22 @@ schemas.Geometry.description='GeoJSON geometry in EPSG:4326, 2D, valid, nonempty
|
||||
const paths={}; let operations=0;
|
||||
for(const route of routes){
|
||||
const path='/'+route.uri; const method=route.method.split('|')[0].toLowerCase(); const admin=path.includes('/admin/');
|
||||
const parameters=[...path.matchAll(/\{([^}]+)\}/g)].map(match=>({name:match[1],in:'path',required:true,schema:match[1]==='action'?{type:'string',enum:path.includes('/admin/zones/')?['publish','suspend']:['validate','revoke']}:uuid}));
|
||||
if(method==='get' && path.endsWith('/zones')) parameters.push({name:'q',in:'query',schema:{type:'string',maxLength:120}},{name:'category',in:'query',schema:{type:'string',enum:['zee','zfi','industrial_park']}},{name:'page',in:'query',schema:version});
|
||||
const parameters=[...path.matchAll(/\{([^}]+)\}/g)].map(match=>({name:match[1],in:'path',required:true,schema:match[1]==='action'?{type:'string',enum:path.includes('zone-attachments')?['review','select-public','withdraw-public']:path.includes('/admin/zones/')?['publish','suspend']:['validate','revoke']}:uuid}));
|
||||
if(method==='get' && (path.endsWith('/zones') || path.endsWith('/zones/export.csv'))) parameters.push({name:'q',in:'query',schema:{type:'string',maxLength:120}},{name:'category',in:'query',schema:{type:'string',enum:['zee','zfi','industrial_park']}},{name:'physical_category',in:'query',schema:string},{name:'legal_regime',in:'query',schema:string},{name:'development_status',in:'query',schema:string},{name:'availability_status',in:'query',schema:string},{name:'activity',in:'query',schema:string},{name:'province_id',in:'query',schema:uuid},{name:'district_id',in:'query',schema:uuid},{name:'admin_post_id',in:'query',schema:uuid},{name:'locality_id',in:'query',schema:uuid},{name:'page',in:'query',schema:version});
|
||||
if(path.endsWith('/zone-map')) parameters.push({name:'zone_id',in:'query',schema:uuid},{name:'bbox[]',in:'query',style:'form',explode:true,schema:{type:'array',minItems:4,maxItems:4,items:{type:'number'}},description:'west,south,east,north; no antimeridian wrap.'});
|
||||
const creates=method==='post'&&!path.includes('{action}');
|
||||
const operation={operationId:route.action.split('\\').at(-1).replace('@','_')+'_'+operations++,summary:route.action.split('\\').at(-1),parameters,security:admin?[{laravelSession:[]}]:[],responses:{[creates?'201':'200']:{description:'Success. JSON; paginated lists. Private management responses use Cache-Control: private, no-store.',content:{'application/json':{schema:{type:'object'}}}},'403':{description:'Missing manager/MFA/designated role or self-review.'},'404':{description:'Not found or not publicly visible.'},'409':{description:'Stale version or duplicate relation.'},'419':{description:'Session/CSRF validation failed.'},'422':{description:'Invalid data, source, geometry, overlap or workflow.'},'429':{description:'Rate limit exceeded.'}}};
|
||||
const privateRoute=admin||path.includes('/management/');
|
||||
const operation={operationId:route.action.split('\\').at(-1).replace('@','_')+'_'+operations++,summary:route.action.split('\\').at(-1),parameters,security:privateRoute?[{laravelSession:[]}]:[],responses:{[creates?'201':'200']:{description:'Success. JSON; paginated lists. Private management responses use Cache-Control: private, no-store.',content:{'application/json':{schema:{type:'object'}}}},'403':{description:'Missing manager/MFA/designated role or self-review.'},'404':{description:'Not found or not publicly visible.'},'409':{description:'Stale version or duplicate relation.'},'419':{description:'Session/CSRF validation failed.'},'422':{description:'Invalid data, source, geometry, overlap or workflow.'},'429':{description:'Rate limit exceeded.'}}};
|
||||
if(path.endsWith('/zones/export.csv')) operation.responses['200']={description:'CSV filtered with the same server-side criteria as the public zone list.',content:{'text/csv':{schema:{type:'string',format:'binary'}}}};
|
||||
if(method!=='get'){
|
||||
const schema=path.includes('{action}')?'Version':path.endsWith('/legal-sources')?'LegalSource':path.endsWith('/links')?'Link':path.endsWith('/relations')?'Relation':path.endsWith('/geometries')?'Geometry':'Zone';
|
||||
operation.requestBody={required:true,content:{'application/json':{schema:{$ref:'#/components/schemas/'+schema}}}};
|
||||
if(path.endsWith('/attachments')){
|
||||
operation.requestBody={required:true,content:{'multipart/form-data':{schema:object({file:{type:'string',format:'binary'},kind:{type:'string',enum:['legal_instrument','map','photo','study','other']},caption:{type:'string',maxLength:255},source_reference:{type:'string',minLength:5,maxLength:2000},source_date:nullable(date),rights_status:{type:'string',enum:['pending','confirmed','restricted']},rights_basis:nullable(string)},['file','kind','caption','source_reference','rights_status'])}}};
|
||||
} else if(path.includes('zone-attachments/{id}/{action}')){
|
||||
operation.requestBody={required:true,content:{'application/json':{schema:object({version_no:version,decision:{type:'string',enum:['reviewed','rejected']},rights_status:{type:'string',enum:['pending','confirmed','restricted']},rights_basis:nullable(string),personal_data_status:{type:'string',enum:['none','present','unknown']}},path.endsWith('/review')?['version_no','decision','rights_status','personal_data_status']:['version_no'])}}};
|
||||
} else {
|
||||
operation.requestBody={required:true,content:{'application/json':{schema:{$ref:'#/components/schemas/'+schema}}}};
|
||||
}
|
||||
}
|
||||
(paths[path]??={})[method]=operation;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user