vrsao 2
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-08 14:02:01 +02:00
parent bdd766c68a
commit 1106509116
354 changed files with 48275 additions and 24635 deletions
+11 -5
View File
@@ -1,11 +1,15 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db = Illuminate\Support\Facades\DB::connection();
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$report = $db->transaction(function () use ($db) {
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
return [
'generated_at' => date(DATE_ATOM),
'target' => $db->selectOne('select current_database() as database, inet_server_port() as port'),
@@ -20,12 +24,14 @@ $report = $db->transaction(function () use ($db) {
'opportunity_projects' => $db->table('opportunity_projects')->get(),
'opportunities' => $db->table('opportunities')->get(),
'profiles' => $db->table('opportunity_profiles')->get(),
'locations' => $db->table('geo_locations')->get(['id','name','location_type','parent_id','source_system','external_id','data_classification','deleted_at']),
'geometries' => $db->table('geo_geometries')->select(['id','geo_location_id','geometry_type','source_system','external_id','data_classification','deleted_at'])->selectRaw('ST_AsGeoJSON(geom) as geometry')->get(),
'locations' => $db->table('geo_locations')->get(['id', 'name', 'location_type', 'parent_id', 'source_system', 'external_id', 'data_classification', 'deleted_at']),
'geometries' => $db->table('geo_geometries')->select(['id', 'geo_location_id', 'geometry_type', 'source_system', 'external_id', 'data_classification', 'deleted_at'])->selectRaw('ST_AsGeoJSON(geom) as geometry')->get(),
];
});
$directory = storage_path('app/private/anchor-project-reconciliation');
if (! is_dir($directory)) mkdir($directory, 0700, true);
if (! is_dir($directory)) {
mkdir($directory, 0700, true);
}
$file = $directory.'/inventory-'.date('Ymd-His').'.json';
file_put_contents($file, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
echo $file.PHP_EOL;
+6 -3
View File
@@ -1,11 +1,14 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$app->make(Kernel::class)->bootstrap();
if (Illuminate\Support\Facades\DB::connection()->getDatabaseName() !== 'investemoz') {
if (DB::connection()->getDatabaseName() !== 'investemoz') {
fwrite(STDERR, "Refusing unexpected active database target.\n");
exit(20);
}
@@ -29,7 +32,7 @@ fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
fwrite(STDERR, "pg_dump failed: ".trim($stderr)."\n");
fwrite(STDERR, 'pg_dump failed: '.trim($stderr)."\n");
exit($exitCode);
}
+125 -43
View File
@@ -1,49 +1,95 @@
// Isolated QA only. Synthetic account is prepared separately, never against the application DB.
import fs from 'node:fs';
const base = 'http://127.0.0.1:18027';
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).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 => ws.addEventListener('open', resolve, { once: true }));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let seq = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => {
ws.onmessage = (event) => {
const m = JSON.parse(event.data);
if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails.text);
if (m.id) { const p = pending.get(m.id); pending.delete(m.id); m.error ? p.reject(m.error) : p.resolve(m.result); }
if (m.method === 'Runtime.exceptionThrown')
errors.push(m.params.exceptionDetails.text);
if (m.id) {
const p = pending.get(m.id);
pending.delete(m.id);
if (m.error) p.reject(m.error);
else p.resolve(m.result);
}
};
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++seq; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => {
const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++seq;
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const r = await send('Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
});
if (r.exceptionDetails) throw Error('Browser expression failed');
return r.result?.value;
};
const wait = async expression => { for (let n = 0; n < 100; n++) { if (await evaluate(expression)) return; await new Promise(r => setTimeout(r, 100)); } throw Error('Browser condition timed out: ' + expression); };
const wait = async (expression) => {
for (let n = 0; n < 100; n++) {
if (await evaluate(expression)) return;
await new Promise((r) => setTimeout(r, 100));
}
throw Error('Browser condition timed out: ' + expression);
};
const fill = async (selector, value) => {
await evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`);
await evaluate(
`document.querySelector(${JSON.stringify(selector)}).focus()`,
);
await send('Input.insertText', { text: value });
};
const field = async (label, value) => {
const selector = `([...document.querySelectorAll('label')].find(l=>l.textContent.includes(${JSON.stringify(label)}))?.querySelector('input,textarea,select'))`;
await wait(`!!${selector}`);
await evaluate(`(()=>{const e=${selector}; e.focus(); if(e.tagName==='SELECT'){ e.value=${JSON.stringify(value)}; e.dispatchEvent(new Event('change',{bubbles:true})); }else {e.select();}})()`);
if (!await evaluate(`${selector}.tagName==='SELECT'`)) await send('Input.insertText', { text: value });
await evaluate(
`(()=>{const e=${selector}; e.focus(); if(e.tagName==='SELECT'){ e.value=${JSON.stringify(value)}; e.dispatchEvent(new Event('change',{bubbles:true})); }else {e.select();}})()`,
);
if (!(await evaluate(`${selector}.tagName==='SELECT'`)))
await send('Input.insertText', { text: value });
};
const step = async number => {
await wait(`![...document.querySelectorAll('ol button')][${number - 1}].disabled`);
await evaluate(`[...document.querySelectorAll('ol button')][${number - 1}].click()`);
await wait(`document.querySelector('h2')?.textContent.startsWith('${number}/8')`);
const step = async (number) => {
await wait(
`![...document.querySelectorAll('ol button')][${number - 1}].disabled`,
);
await evaluate(
`[...document.querySelectorAll('ol button')][${number - 1}].click()`,
);
await wait(
`document.querySelector('h2')?.textContent.startsWith('${number}/8')`,
);
};
const observations = [];
try {
await send('Page.enable'); await send('Runtime.enable');
await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 900, deviceScaleFactor: 1, mobile: true });
await send('Page.enable');
await send('Runtime.enable');
await send('Emulation.setDeviceMetricsOverride', {
width: 390,
height: 900,
deviceScaleFactor: 1,
mobile: true,
});
await send('Page.navigate', { url: base + '/login' });
await wait(`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`);
await wait(
`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`,
);
if (await evaluate(`location.pathname==='/login'`)) {
await fill('input[type="email"]', 'mne-browser@example.test');
await fill('input[type="password"]', 'SyntheticMneOnly-2026!');
await evaluate(`document.querySelector('button[type="submit"]').click()`);
await evaluate(
`document.querySelector('button[type="submit"]').click()`,
);
await wait(`!location.pathname.startsWith('/login')`);
}
await send('Page.navigate', { url: base + '/investidor/negocios' });
@@ -56,37 +102,73 @@ try {
await field('NUIT', 'SYNTHETIC');
await field('Email de contacto', 'synthetic@example.test');
await field('País', 'MZ');
await wait(`document.body.innerText.includes('Rascunho guardado no servidor')`);
await wait(
`document.body.innerText.includes('Rascunho guardado no servidor')`,
);
await send('Page.reload');
await wait(`!![...document.querySelectorAll('input')].find(e=>e.value==='Synthetic owner')`);
await wait(
`!![...document.querySelectorAll('input')].find(e=>e.value==='Synthetic owner')`,
);
observations.push({ scenario: 'autosave_and_reload', passed: true });
await step(2);
await field('Qualidade', 'holder'); await field('Titular declarado', 'Synthetic owner'); await field('Declaro legitimidade', 'yes');
await field('Qualidade', 'holder');
await field('Titular declarado', 'Synthetic owner');
await field('Declaro legitimidade', 'yes');
await step(3);
await evaluate(`(()=>{const e=[...document.querySelectorAll('label')].find(l=>l.querySelector('span')?.textContent==='Sector')?.querySelector('select'); e.value=e.options[1].value;e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await field('Descrição reservada','Synthetic private description long enough for this browser-only review.');
await evaluate(`(()=>{const e=document.querySelector('input[type=date]');const setter=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;setter.call(e,'2027-12-31');e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await step(5); await field('Localização declarada','Synthetic location, no coordinates');
await step(7); await field('Referência da fonte','Synthetic source for browser testing');
await evaluate(
`(()=>{const e=[...document.querySelectorAll('label')].find(l=>l.querySelector('span')?.textContent==='Sector')?.querySelector('select'); e.value=e.options[1].value;e.dispatchEvent(new Event('change',{bubbles:true}));})()`,
);
await field(
'Descrição reservada',
'Synthetic private description long enough for this browser-only review.',
);
await evaluate(
`(()=>{const e=document.querySelector('input[type=date]');const setter=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;setter.call(e,'2027-12-31');e.dispatchEvent(new Event('input',{bubbles:true}));e.dispatchEvent(new Event('change',{bubbles:true}));})()`,
);
await step(5);
await field('Localização declarada', 'Synthetic location, no coordinates');
await step(7);
await field('Referência da fonte', 'Synthetic source for browser testing');
await step(8);
await wait(`document.body.innerText.includes('Rascunho guardado no servidor')`);
const code = await evaluate(`document.querySelector('main').innerText.match(/MNE-[0-9a-f-]{36}/)[0]`);
await field('Digite o código',code);
await wait(
`document.body.innerText.includes('Rascunho guardado no servidor')`,
);
const code = await evaluate(
`document.querySelector('main').innerText.match(/MNE-[0-9a-f-]{36}/)[0]`,
);
await field('Digite o código', code);
await evaluate(`document.querySelector('input[type=checkbox]').click()`);
for (const width of [390,1440]) {
await send('Emulation.setDeviceMetricsOverride',{width,height:900,deviceScaleFactor:1,mobile:width===390});
const fits = await evaluate(`document.documentElement.scrollWidth<=innerWidth+1`);
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width === 390,
});
const fits = await evaluate(
`document.documentElement.scrollWidth<=innerWidth+1`,
);
if (!fits) throw Error('Horizontal overflow');
observations.push({scenario:'responsive_summary',width,passed:true});
observations.push({
scenario: 'responsive_summary',
width,
passed: true,
});
}
await evaluate(`[...document.querySelectorAll('button')].find(e=>e.textContent.includes('Confirmar e submeter')).click()`);
await wait(`document.body.innerText.includes('Submetido') && !document.querySelector('progress')`);
observations.push({scenario:'private_submission',passed:true});
if(errors.length) throw Error('Browser exceptions');
fs.writeFileSync('docs/investmoz/existing-business/wizard-browser-validation.json',JSON.stringify({passed:true,observations,errors},null,2)+'\n');
console.log(JSON.stringify({passed:true,observations,errors}));
await evaluate(
`[...document.querySelectorAll('button')].find(e=>e.textContent.includes('Confirmar e submeter')).click()`,
);
await wait(
`document.body.innerText.includes('Submetido') && !document.querySelector('progress')`,
);
observations.push({ scenario: 'private_submission', passed: true });
if (errors.length) throw Error('Browser exceptions');
fs.writeFileSync(
'docs/investmoz/existing-business/wizard-browser-validation.json',
JSON.stringify({ passed: true, observations, errors }, null, 2) + '\n',
);
console.log(JSON.stringify({ passed: true, observations, errors }));
} finally {
ws.close();
await fetch('http://127.0.0.1:9224/json/close/'+target.id);
await fetch('http://127.0.0.1:9224/json/close/' + target.id);
}
+100
View File
@@ -0,0 +1,100 @@
<?php
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
// Active connection is read-only; restore/compatibility writes are restricted to a new QA database.
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
(new LoadEnvironmentVariables)->bootstrap($app);
(new LoadConfiguration)->bootstrap($app);
$c = config('database.connections.pgsql');
if (($c['url'] ?? null) || $c['database'] !== 'investemoz' || (int) $c['port'] !== 5432) {
throw new RuntimeException('Active backup identity configuration rejected.');
}
$active = new PDO('pgsql:host='.$c['host'].';port=5432;dbname=investemoz', $c['username'], $c['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$active->exec('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY');
$target = $active->query('select current_database() as database, inet_server_port() as port')->fetch(PDO::FETCH_ASSOC);
if ($target['database'] !== 'investemoz' || (int) $target['port'] !== 5432) {
throw new RuntimeException('Active backup actual identity rejected.');
}
$stamp = date('Ymd_His');
$directory = storage_path('app/private/virtual-desk/activation-backup-'.$stamp);
mkdir($directory, 0700, true);
$dump = $directory.'/database.dump';
$restoreName = 'desk_restore_'.$stamp.'_test';
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
$run = function (array $args, string $password): void {
$process = proc_open($args, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, [...getenv(), 'PGPASSWORD' => $password], ['bypass_shell' => true]);
if (! is_resource($process)) {
throw new RuntimeException('Backup process unavailable.');
}
fclose($pipes[0]);
stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
if (proc_close($process) !== 0) {
throw new RuntimeException('Backup/restore failed: '.$error);
}
};
$snapshot = $active->query('select pg_export_snapshot()')->fetchColumn();
$run([$bin.'pg_dump.exe', '-h', $c['host'], '-p', '5432', '-U', $c['username'], '-d', 'investemoz', '-Fc', '--snapshot='.$snapshot, '-f', $dump], $c['password']);
$maintenance = new PDO('pgsql:host=127.0.0.1;port=55441;dbname=postgres', 'postgres', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
if ((int) $maintenance->query('select inet_server_port()')->fetchColumn() !== 55441 || ! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $restoreName)) {
throw new RuntimeException('Restore target rejected.');
}
$maintenance->exec('CREATE DATABASE "'.$restoreName.'"');
$run([$bin.'pg_restore.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'postgres', '-d', $restoreName, '--exit-on-error', '--no-owner', '--no-privileges', $dump], '');
$qa = new PDO('pgsql:host=127.0.0.1;port=55441;dbname='.$restoreName, 'postgres', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$restored = $qa->query('select current_database() as database, inet_server_port() as port')->fetch(PDO::FETCH_ASSOC);
if ($restored['database'] !== $restoreName || (int) $restored['port'] !== 55441) {
throw new RuntimeException('Actual restore target rejected.');
}
$tables = $active->query("select schemaname,tablename from pg_tables where schemaname not in ('pg_catalog','information_schema') order by schemaname,tablename")->fetchAll(PDO::FETCH_ASSOC);
$counts = [];
$hashes = [];
foreach ($tables as $t) {
$name = '"'.str_replace('"', '""', $t['schemaname']).'"."'.str_replace('"', '""', $t['tablename']).'"';
$sql = 'select row_to_json(t)::text from '.$name.' t order by row_to_json(t)::text';
$a = $active->query($sql)->fetchAll(PDO::FETCH_COLUMN);
$b = $qa->query($sql)->fetchAll(PDO::FETCH_COLUMN);
if ($a !== $b) {
throw new RuntimeException('Restored contents differ: '.$name);
}
$counts[$name] = count($a);
$hashes[$name] = hash('sha256', implode("\n", $a));
}
$active->exec('ROLLBACK');
// Preserve exactly the private files referenced by restored document records, plus the runtime key.
$files = $directory.'/private-files.zip';
$zip = new ZipArchive;
$zip->open($files, ZipArchive::CREATE | ZipArchive::EXCL);
$manifest = [];
foreach ($qa->query('select storage_key from documents where storage_key is not null')->fetchAll(PDO::FETCH_COLUMN) as $relative) {
$path = realpath(storage_path('app/private/'.$relative));
$root = realpath(storage_path('app/private'));
if (! $path || ! str_starts_with(strtolower($path), strtolower($root.DIRECTORY_SEPARATOR))) {
throw new RuntimeException('Referenced private document missing or outside storage.');
}
$name = 'private/'.str_replace('\\', '/', $relative);
$zip->addFile($path, $name);
$manifest[$name] = hash_file('sha256', $path);
}
$zip->addFile(base_path('.env'), 'runtime/.env');
$manifest['runtime/.env'] = hash_file('sha256', base_path('.env'));
$zip->close();
$read = new ZipArchive;
$read->open($files);
foreach ($manifest as $name => $hash) {
$bytes = $read->getFromName($name);
if (! is_string($bytes) || hash('sha256', $bytes) !== $hash) {
throw new RuntimeException('Private file restore verification failed.');
}
}
$read->close();
$proof = ['restore_verified' => true, 'verified_at' => gmdate('c'), 'target' => $target, 'restored_target' => $restored,
'dump_path' => $dump, 'sha256' => hash_file('sha256', $dump), 'table_counts' => $counts, 'table_hashes' => $hashes,
'files_verified' => true, 'files_path' => $files, 'files_sha256' => hash_file('sha256', $files), 'file_hashes' => $manifest];
file_put_contents(storage_path('app/private/virtual-desk/backup-proof.json'), json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['restore_verified' => true, 'tables' => count($tables), 'files' => count($manifest), 'restore_target' => $restored], JSON_THROW_ON_ERROR);
+74
View File
@@ -0,0 +1,74 @@
<?php
use App\Services\VirtualDeskInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
$root = dirname(__DIR__);
$proof = json_decode(file_get_contents($root.'/storage/app/private/virtual-desk/backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
$target = $proof['restored_target'];
if (! preg_match('/^desk_restore_\d{8}_\d{6}_test$/', $target['database']) || (int) $target['port'] !== 55441) {
throw new RuntimeException('Isolated restore required.');
}
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
'DB_DATABASE' => $target['database'], 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '',
'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
require $root.'/vendor/autoload.php';
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$identity = $db->selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== $target['database'] || (int) $identity->port !== 55441) {
throw new RuntimeException('Actual QA identity rejected.');
}
$check = function (bool $extended) use ($db, $proof) {
foreach ($proof['table_hashes'] as $name => $hash) {
// Extension adds nullable columns to existing tasks; compare original columns explicitly.
$columns = '*';
if ($extended && $name === '"public"."tasks"') {
$columns = implode(',', array_map(fn ($r) => '"'.$r->column_name.'"', $db->select("select column_name from information_schema.columns where table_schema='public' and table_name='tasks' and column_name not in ('desk_case_id','desk_request_id','guidance_key','accepted_by','accepted_at','external_sync_status') order by ordinal_position")));
}
$rows = array_map(fn ($r) => $r->value, $db->select('select row_to_json(t)::text as value from (select '.$columns.' from '.$name.') t order by row_to_json(t)::text'));
if (hash('sha256', implode("\n", $rows)) !== $hash) {
throw new RuntimeException('Original contents changed: '.$name);
}
}
};
$check(false);
$migrations = array_map(fn ($name) => require $root.'/database/migrations/'.$name.'.php', VirtualDeskInstallation::MIGRATIONS);
$db->transaction(function () use ($migrations, $check) {
foreach ($migrations as $migration) {
$migration->up();
}
$check(true);
foreach (array_reverse($migrations) as $migration) {
$migration->down();
}
$check(false);
});
$archive = new ZipArchive;
$archive->open($proof['files_path']);
$restoreRoot = dirname($proof['files_path']).'/restored-files';
foreach ($proof['file_hashes'] as $name => $hash) {
if (str_contains($name, '..') || str_starts_with($name, '/')) {
throw new RuntimeException('Invalid archive entry.');
}
$path = $restoreRoot.'/'.$name;
if (! is_dir(dirname($path))) {
mkdir(dirname($path), 0700, true);
}
file_put_contents($path, $archive->getFromName($name));
if (hash_file('sha256', $path) !== $hash) {
throw new RuntimeException('Restored private bytes differ.');
}
}
$archive->close();
$result = ['passed' => true, 'verified_at' => gmdate('c'), 'database' => $target['database'], 'port' => 55441,
'migrations' => VirtualDeskInstallation::MIGRATIONS, 'original_tables_preserved' => count($proof['table_hashes']),
'empty_rollback_verified' => true, 'private_files_restored' => count($proof['file_hashes']),
'dump_sha256' => $proof['sha256'], 'code_hash' => app(VirtualDeskInstallation::class)->fingerprint()];
file_put_contents($root.'/storage/app/private/virtual-desk/activation-compatibility.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($result, JSON_THROW_ON_ERROR);
+45
View File
@@ -0,0 +1,45 @@
<?php
use App\Services\VirtualDeskInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
$read = function (string $path): string {
$bytes = file_get_contents($path);
if (str_starts_with($bytes, "\xff\xfe")) {
return mb_convert_encoding(substr($bytes, 2), 'UTF-8', 'UTF-16LE');
}
return $bytes;
};
$tests = json_decode(trim($read($root.'/storage/app/private/investmoz-v2/second-phpunit.txt')), true, 512, JSON_THROW_ON_ERROR);
if (($tests['tool'] ?? null) !== 'phpunit' || ($tests['result'] ?? null) !== 'passed') {
throw new RuntimeException('Full QA success evidence required.');
}
foreach (['second-phpstan.txt' => '"errors":0', 'second-types.txt' => 'tsc --noEmit', 'second-build.txt' => 'built in', 'second-frontend.txt' => 'pass 151'] as $name => $needle) {
if (! str_contains($read($root.'/storage/app/private/investmoz-v2/'.$name), $needle)) {
throw new RuntimeException('Required QA evidence missing: '.$name);
}
}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$db->beginTransaction();
$db->statement('SET TRANSACTION READ ONLY');
$identity = $db->selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'investemoz' || (int) $identity->port !== 5432) {
throw new RuntimeException('Active read-only identity rejected.');
}
$installation = app(VirtualDeskInstallation::class);
$qa = ['passed' => true, 'verified_at' => gmdate('c'), 'code_hash' => $installation->fingerprint(),
'database' => 'investmoz_v2_20261008_test', 'port' => 55441, 'tests' => $tests,
'limitation' => 'Three real ClamD integration tests skipped because no local service is available. No real scan asserted.'];
file_put_contents(storage_path('app/private/virtual-desk/guidance-qa-evidence.json'), json_encode($qa, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
$preview = $installation->preview();
$db->rollBack();
file_put_contents(storage_path('app/private/virtual-desk/activation-preview.json'), json_encode($preview, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['target' => $preview['target'], 'pending' => $preview['pendingMigrations'], 'backup' => $preview['backupVerified'],
'qa' => $preview['qaVerified'], 'compatibility' => $preview['compatibilityVerified'], 'scanner' => $preview['scanner'],
'page' => '/management/balcao-install'], JSON_THROW_ON_ERROR);
+19
View File
@@ -34,4 +34,23 @@ for item in inventory:
target.write_text(text, encoding='utf8')
selected.append(dict(**item, extraction=str(target), form_status='source_review_pending'))
(out/'selected-sources.json').write_text(json.dumps(selected, ensure_ascii=False, indent=2), encoding='utf8')
# This is a private register, never an import or automatic publication. Original
# bytes remain untouched. Field text is preserved verbatim, not homologated.
forms=[]
for item in inventory:
path=Path(item['path'])
if path.name.startswith('~$') or not any(x in str(path).lower() for x in ['\\formularios\\', '\\formulario\\']):
continue
record=dict(**item, identifier=path.name, edition='not_identified', consultation='local_inventory_only_not_authorized_publication', legal_documentary_status='not_verified', rule_use='none', official_confirmation='pending', fields_status='preserved_in_original_pending_verification')
if path.suffix.lower()=='.docx':
with zipfile.ZipFile(path) as archive:
field_xml=archive.read('word/document.xml')
field_path=out/(item['sha256']+'-fields.xml')
field_path.write_bytes(field_xml)
record['original_fields_xml']=str(field_path)
record['nature']='design_or_template_source_not_confirmed_official_form'
else:
record['nature']='scanned_form_candidate_not_confirmed_official'
forms.append(record)
(out/'form-register.json').write_text(json.dumps(forms, ensure_ascii=False, indent=2), encoding='utf8')
print(json.dumps(dict(files=len(inventory), selected=[dict(path=i['path'], extraction=i['extraction']) for i in selected]), ensure_ascii=False))
+42 -8
View File
@@ -2,23 +2,57 @@ 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 {
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 };
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 } });
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 }));
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 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 });
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();
}
+86 -16
View File
@@ -2,35 +2,105 @@ 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 {
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: [] };
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 } });
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()); });
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 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 }));
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 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('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__');
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`);
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');
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);
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);
+426 -46
View File
@@ -1,63 +1,443 @@
import fs from 'node:fs';
const ref = name => ({ $ref: `#/components/schemas/${name}` });
const id = { name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' } };
const responses = schema => Object.fromEntries(['200', '401', '403', '404', '409', '422', '429'].map(status => [status, {
description: { '200': 'Private response; Cache-Control private, no-store', '401': 'Authentication required', '403': 'Account, ownership or current reviewer/MFA policy rejected', '404': 'Module disabled or resource unavailable', '409': 'Stale version or invalid transition', '422': 'Validation error', '429': 'Rate limited' }[status],
...(status === '200' ? { content: { 'application/json': { schema } } } : {}),
}]));
const operation = (summary, response, body, parameters = []) => ({ summary, parameters, security: [{ session: [] }], responses: responses(response), ...(body ? { requestBody: { required: true, content: { 'application/json': { schema: body } } }, description: 'Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients.' } : {}) });
const ref = (name) => ({ $ref: `#/components/schemas/${name}` });
const id = {
name: 'id',
in: 'path',
required: true,
schema: { type: 'string', format: 'uuid' },
};
const responses = (schema) =>
Object.fromEntries(
['200', '401', '403', '404', '409', '422', '429'].map((status) => [
status,
{
description: {
200: 'Private response; Cache-Control private, no-store',
401: 'Authentication required',
403: 'Account, ownership or current reviewer/MFA policy rejected',
404: 'Module disabled or resource unavailable',
409: 'Stale version or invalid transition',
422: 'Validation error',
429: 'Rate limited',
}[status],
...(status === '200'
? { content: { 'application/json': { schema } } }
: {}),
},
]),
);
const operation = (summary, response, body, parameters = []) => ({
summary,
parameters,
security: [{ session: [] }],
responses: responses(response),
...(body
? {
requestBody: {
required: true,
content: { 'application/json': { schema: body } },
},
description:
'Session authentication and Laravel CSRF/origin protection apply. Use X-XSRF-TOKEN for browser clients.',
}
: {}),
});
const text = { type: 'string' };
const payload = { type: 'object', additionalProperties: false, required: ['title'], properties: { title: { type: 'string', maxLength: 200 }, description: { type: ['string', 'null'], maxLength: 10000 }, declared_reason: { type: ['string', 'null'], maxLength: 2000 }, source_reference: { type: ['string', 'null'], maxLength: 2000 }, valid_until: { type: ['string', 'null'], format: 'date' } } };
const input = { type: 'object', required: ['modality', 'classification', 'reason', 'payload'], properties: { modality: text, classification: { enum: ['internal', 'confidential', 'restricted'] }, reason: { type: 'string', minLength: 10, maxLength: 1000 }, payload } };
const payload = {
type: 'object',
additionalProperties: false,
required: ['title'],
properties: {
title: { type: 'string', maxLength: 200 },
description: { type: ['string', 'null'], maxLength: 10000 },
declared_reason: { type: ['string', 'null'], maxLength: 2000 },
source_reference: { type: ['string', 'null'], maxLength: 2000 },
valid_until: { type: ['string', 'null'], format: 'date' },
},
};
const input = {
type: 'object',
required: ['modality', 'classification', 'reason', 'payload'],
properties: {
modality: text,
classification: { enum: ['internal', 'confidential', 'restricted'] },
reason: { type: 'string', minLength: 10, maxLength: 1000 },
payload,
},
};
const document = {
openapi: '3.1.0', info: { title: 'InvestMoz — private existing-business intake', version: '1.0.0', description: 'Internal preparation and review only. No publication, certification, legal transfer, NDA, payment or external CRM operation.' },
openapi: '3.1.0',
info: {
title: 'InvestMoz — private existing-business intake',
version: '1.0.0',
description:
'Internal preparation and review only. No publication, certification, legal transfer, NDA, payment or external CRM operation.',
},
servers: [{ url: '/api/v1/existing-business' }],
paths: {
'/listings': {
get: operation('List own active records, 20 per page', { type: 'object', required: ['records', 'management', 'modalities'], properties: { records: { type: 'object', properties: { data: { type: 'array', items: ref('Business') }, total: { type: 'integer' } } }, management: { type: 'boolean' }, modalities: { type: 'array', items: text } } }, null, [{ name: 'page', in: 'query', schema: { type: 'integer', minimum: 1 } }]),
get: operation(
'List own active records, 20 per page',
{
type: 'object',
required: ['records', 'management', 'modalities'],
properties: {
records: {
type: 'object',
properties: {
data: { type: 'array', items: ref('Business') },
total: { type: 'integer' },
},
},
management: { type: 'boolean' },
modalities: { type: 'array', items: text },
},
},
null,
[
{
name: 'page',
in: 'query',
schema: { type: 'integer', minimum: 1 },
},
],
),
post: operation('Create private draft', ref('Business'), input),
},
'/reviews': { get: operation('List submitted records for designated reviewers with MFA; excludes own records', { type: 'object', properties: { records: { type: 'object', properties: { data: { type: 'array', items: ref('Business') } } }, management: { type: 'boolean' } } }) },
'/listings/{id}': {
get: operation('Read own record or currently reviewable submission', { type: 'object', properties: { record: ref('Business'), canEdit: { type: 'boolean' }, owner: { type: 'boolean' }, canReview: { type: 'boolean' }, history: { type: 'array', items: { type: 'object', properties: { version_no: { type: 'integer' }, action: text, created_at: text, note: text } } } } }, null, [id]),
put: operation('Update owned draft or request for information; optimistic version required', ref('Business'), { ...input, required: [...input.required, 'version_no'], properties: { ...input.properties, version_no: { type: 'integer', minimum: 1 } } }, [id]),
'/reviews': {
get: operation(
'List submitted records for designated reviewers with MFA; excludes own records',
{
type: 'object',
properties: {
records: {
type: 'object',
properties: {
data: { type: 'array', items: ref('Business') },
},
},
management: { type: 'boolean' },
},
},
),
},
'/listings/{id}': {
get: operation(
'Read own record or currently reviewable submission',
{
type: 'object',
properties: {
record: ref('Business'),
canEdit: { type: 'boolean' },
owner: { type: 'boolean' },
canReview: { type: 'boolean' },
history: {
type: 'array',
items: {
type: 'object',
properties: {
version_no: { type: 'integer' },
action: text,
created_at: text,
note: text,
},
},
},
},
},
null,
[id],
),
put: operation(
'Update owned draft or request for information; optimistic version required',
ref('Business'),
{
...input,
required: [...input.required, 'version_no'],
properties: {
...input.properties,
version_no: { type: 'integer', minimum: 1 },
},
},
[id],
),
},
'/listings/{id}/transitions': {
post: operation(
'Submit, begin review, request information or withdraw',
ref('Business'),
{
type: 'object',
required: ['version_no', 'action', 'note'],
properties: {
version_no: { type: 'integer', minimum: 1 },
action: {
enum: [
'submitted',
'in_review',
'needs_information',
'withdrawn',
],
},
note: {
type: 'string',
minLength: 10,
maxLength: 2000,
},
review_consent: {
type: 'boolean',
description:
'Must be true for submission. Stored in encrypted review evidence. Does not authorize publication.',
},
},
},
[id],
),
},
},
components: {
securitySchemes: {
session: {
type: 'apiKey',
in: 'cookie',
name: 'session_cookie',
description:
'Actual Laravel cookie name comes from deployment configuration; no bearer token support.',
},
},
schemas: {
Business: {
type: 'object',
required: [
'id',
'code',
'modality',
'status',
'classification',
'version_no',
'payload',
],
properties: {
id: { type: 'string', format: 'uuid' },
code: text,
modality: text,
status: {
enum: [
'draft',
'submitted',
'in_review',
'needs_information',
'withdrawn',
],
},
classification: {
enum: ['internal', 'confidential', 'restricted'],
},
version_no: { type: 'integer', minimum: 1 },
payload,
},
},
},
'/listings/{id}/transitions': { post: operation('Submit, begin review, request information or withdraw', ref('Business'), { type: 'object', required: ['version_no', 'action', 'note'], properties: { version_no: { type: 'integer', minimum: 1 }, action: { enum: ['submitted', 'in_review', 'needs_information', 'withdrawn'] }, note: { type: 'string', minLength: 10, maxLength: 2000 }, review_consent: { type: 'boolean', description: 'Must be true for submission. Stored in encrypted review evidence. Does not authorize publication.' } } }, [id]) },
},
components: { securitySchemes: { session: { type: 'apiKey', in: 'cookie', name: 'session_cookie', description: 'Actual Laravel cookie name comes from deployment configuration; no bearer token support.' } }, schemas: { Business: { type: 'object', required: ['id', 'code', 'modality', 'status', 'classification', 'version_no', 'payload'], properties: { id: { type: 'string', format: 'uuid' }, code: text, modality: text, status: { enum: ['draft', 'submitted', 'in_review', 'needs_information', 'withdrawn'] }, classification: { enum: ['internal', 'confidential', 'restricted'] }, version_no: { type: 'integer', minimum: 1 }, payload } } } },
};
document.paths['/listings'].post.responses['201'] = document.paths['/listings'].post.responses['200'];
document.paths['/listings'].post.responses['201'] =
document.paths['/listings'].post.responses['200'];
delete document.paths['/listings'].post.responses['200'];
const objectPayload = { type: 'object', additionalProperties: false, required: ['label', 'source_reference'], properties: Object.fromEntries(['label','declared_holder','document_reference','source_reference','competent_entity','purpose','location_description','boundaries_description','occupancy','condition','encumbrances','restrictions','required_authorizations','transfer_condition','contract_type','valid_from','valid_until','area','area_unit','amount','currency','value_kind','participation_percent'].map(key => [key, { type: ['string','null'] }])) };
const objectInput = { type: 'object', required: ['kind','version_no','reason','payload'], properties: { kind: { enum: ['company','participation','asset','property','unit','improvement','agricultural_investment','land_right','contract','license','authorization','encumbrance','valuation','capital_request'] }, version_no: { type: 'integer', minimum: 1 }, reason: { type: 'string', minLength: 10, maxLength: 1000 }, payload: objectPayload } };
const objectResponse = { type: 'object', properties: { id: { type: 'string', format: 'uuid' }, version_no: { type: 'integer' }, verification_status: { const: 'pending' } } };
document.paths['/listings/{id}/objects'] = { post: operation('Declare a separate restricted object; increments aggregate version without granting verification', objectResponse, objectInput, [id]) };
document.paths['/listings/{id}/objects'].post.responses['201'] = document.paths['/listings/{id}/objects'].post.responses['200'];
delete document.paths['/listings/{id}/objects'].post.responses['200'];
document.paths['/listings/{id}/objects/{object}'] = { put: operation('Update scoped object with immutable kind; amount requires currency and value kind; area requires unit', objectResponse, objectInput, [id, { ...id, name: 'object' }]) };
const verification = { type: 'object', required: ['version_no', 'check', 'outcome', 'evidence_reference', 'note'], properties: {
version_no: { type: 'integer', minimum: 1 }, object_id: { type: ['string', 'null'], format: 'uuid' },
check: { enum: ['identity', 'representation', 'declared_ownership', 'documentary_ownership', 'document_received', 'document_validated', 'independent_valuation', 'land_right_documented', 'license_confirmed', 'validity', 'legal_transfer', 'prior_authorization'] },
outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked'] },
evidence_reference: { type: 'string', minLength: 10, maxLength: 2000 }, note: { type: 'string', minLength: 10, maxLength: 2000 },
valid_until: { type: ['string', 'null'], format: 'date', description: 'Required for confirmed findings; must be today or later.' },
} };
document.paths['/listings/{id}/verifications'] = { post: operation('Record independent finding while in_review; immutable encrypted evidence, optimistic version and scoped object. Does not publish or certify the business.', ref('Business'), verification, [id]) };
document.paths['/listings/{id}'].get.responses['200'].content['application/json'].schema.properties.verifications = {
type: 'array', items: { ...verification, properties: { ...verification.properties, effective_outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked', 'stale', 'expired'] }, content_version: { type: 'integer' }, created_at: text } },
const objectPayload = {
type: 'object',
additionalProperties: false,
required: ['label', 'source_reference'],
properties: Object.fromEntries(
[
'label',
'declared_holder',
'document_reference',
'source_reference',
'competent_entity',
'purpose',
'location_description',
'boundaries_description',
'occupancy',
'condition',
'encumbrances',
'restrictions',
'required_authorizations',
'transfer_condition',
'contract_type',
'valid_from',
'valid_until',
'area',
'area_unit',
'amount',
'currency',
'value_kind',
'participation_percent',
].map((key) => [key, { type: ['string', 'null'] }]),
),
};
const formSchema = JSON.parse(fs.readFileSync('docs/investmoz/existing-business/form-schema.json', 'utf8'));
const objectInput = {
type: 'object',
required: ['kind', 'version_no', 'reason', 'payload'],
properties: {
kind: {
enum: [
'company',
'participation',
'asset',
'property',
'unit',
'improvement',
'agricultural_investment',
'land_right',
'contract',
'license',
'authorization',
'encumbrance',
'valuation',
'capital_request',
],
},
version_no: { type: 'integer', minimum: 1 },
reason: { type: 'string', minLength: 10, maxLength: 1000 },
payload: objectPayload,
},
};
const objectResponse = {
type: 'object',
properties: {
id: { type: 'string', format: 'uuid' },
version_no: { type: 'integer' },
verification_status: { const: 'pending' },
},
};
document.paths['/listings/{id}/objects'] = {
post: operation(
'Declare a separate restricted object; increments aggregate version without granting verification',
objectResponse,
objectInput,
[id],
),
};
document.paths['/listings/{id}/objects'].post.responses['201'] =
document.paths['/listings/{id}/objects'].post.responses['200'];
delete document.paths['/listings/{id}/objects'].post.responses['200'];
document.paths['/listings/{id}/objects/{object}'] = {
put: operation(
'Update scoped object with immutable kind; amount requires currency and value kind; area requires unit',
objectResponse,
objectInput,
[id, { ...id, name: 'object' }],
),
};
const verification = {
type: 'object',
required: ['version_no', 'check', 'outcome', 'evidence_reference', 'note'],
properties: {
version_no: { type: 'integer', minimum: 1 },
object_id: { type: ['string', 'null'], format: 'uuid' },
check: {
enum: [
'identity',
'representation',
'declared_ownership',
'documentary_ownership',
'document_received',
'document_validated',
'independent_valuation',
'land_right_documented',
'license_confirmed',
'validity',
'legal_transfer',
'prior_authorization',
],
},
outcome: { enum: ['confirmed', 'rejected', 'inconclusive', 'revoked'] },
evidence_reference: { type: 'string', minLength: 10, maxLength: 2000 },
note: { type: 'string', minLength: 10, maxLength: 2000 },
valid_until: {
type: ['string', 'null'],
format: 'date',
description:
'Required for confirmed findings; must be today or later.',
},
},
};
document.paths['/listings/{id}/verifications'] = {
post: operation(
'Record independent finding while in_review; immutable encrypted evidence, optimistic version and scoped object. Does not publish or certify the business.',
ref('Business'),
verification,
[id],
),
};
document.paths['/listings/{id}'].get.responses['200'].content[
'application/json'
].schema.properties.verifications = {
type: 'array',
items: {
...verification,
properties: {
...verification.properties,
effective_outcome: {
enum: [
'confirmed',
'rejected',
'inconclusive',
'revoked',
'stale',
'expired',
],
},
content_version: { type: 'integer' },
created_at: text,
},
},
};
const formSchema = JSON.parse(
fs.readFileSync(
'docs/investmoz/existing-business/form-schema.json',
'utf8',
),
);
for (const [key, field] of Object.entries(formSchema)) {
payload.properties[key] = { type: key === 'title' ? 'string' : ['string', 'null'], maxLength: field.max,
...(field.options ? { enum: [...Object.keys(field.options), null] } : {}),
...(field.type === 'date' ? { format: 'date' } : {}), description: field.en };
payload.properties[key] = {
type: key === 'title' ? 'string' : ['string', 'null'],
maxLength: field.max,
...(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', '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;
document.components.schemas.Business.properties.sector_id = input.properties.sector_id;
document.paths['/listings/{id}/transitions'].post.requestBody.content['application/json'].schema.properties.confirmation_code = { type: ['string', 'null'], description: 'Exact business code required for wizard_version=1 submission, in addition to internal review consent.' };
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;
document.components.schemas.Business.properties.sector_id =
input.properties.sector_id;
document.paths['/listings/{id}/transitions'].post.requestBody.content[
'application/json'
].schema.properties.confirmation_code = {
type: ['string', 'null'],
description:
'Exact business code required for wizard_version=1 submission, in addition to internal review consent.',
};
document.info.version = '1.2.0';
fs.writeFileSync('docs/investmoz/existing-business/openapi.json', JSON.stringify(document, null, 2) + '\n');
fs.writeFileSync(
'docs/investmoz/existing-business/openapi.json',
JSON.stringify(document, null, 2) + '\n',
);
console.log('OpenAPI written: 9 operations, private session API.');
+102 -19
View File
@@ -1,29 +1,112 @@
// Synthetic QA only; tile traffic is blocked to avoid automated OSM downloads.
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).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 => ws.addEventListener('open', resolve, { once: true }));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; 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 Error(JSON.stringify(response.exceptionDetails)); return response.result?.value; };
const wait = async expression => { for (let i = 0; i < 150; i++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 100)); } throw Error('Timed out: '+expression); };
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown')
errors.push(message.params.exceptionDetails.text);
if (message.id) {
const callback = pending.get(message.id);
pending.delete(message.id);
if (message.error) callback.reject(message.error);
else callback.resolve(message.result);
}
};
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++sequence;
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 Error(JSON.stringify(response.exceptionDetails));
return response.result?.value;
};
const wait = async (expression) => {
for (let i = 0; i < 150; i++) {
if (await evaluate(expression)) return;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw Error('Timed out: ' + expression);
};
try {
await send('Runtime.enable'); await send('Page.enable'); await send('Network.enable');
await send('Network.setBlockedURLs', { urls: ['*://tile.openstreetmap.org/*'] });
await send('Page.navigate', { url: 'http://127.0.0.1:18027/oportunidades' });
await send('Runtime.enable');
await send('Page.enable');
await send('Network.enable');
await send('Network.setBlockedURLs', {
urls: ['*://tile.openstreetmap.org/*'],
});
await send('Page.navigate', {
url: 'http://127.0.0.1:18027/oportunidades',
});
await wait(`document.querySelectorAll('.leaflet-marker-icon').length===1`);
await evaluate(`document.querySelector('.leaflet-marker-icon').click()`);
await wait(`document.querySelector('.leaflet-popup-content')?.textContent.includes('Synthetic map marker')`);
if (!await evaluate(`document.querySelector('.leaflet-popup-content a')?.getAttribute('href')==='/oportunidades/synthetic-map-browser'`)) throw Error('Missing detail link');
await evaluate(`document.querySelector('.leaflet-control-zoom-in').click()`);
await wait(
`document.querySelector('.leaflet-popup-content')?.textContent.includes('Synthetic map marker')`,
);
if (
!(await evaluate(
`document.querySelector('.leaflet-popup-content a')?.getAttribute('href')==='/oportunidades/synthetic-map-browser'`,
))
)
throw Error('Missing detail link');
await evaluate(
`document.querySelector('.leaflet-control-zoom-in').click()`,
);
const layouts = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); layouts.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
await evaluate(`window.__mapSentinel=1;document.querySelector('main form input').focus()`);
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width < 600,
});
layouts.push({
width,
noOverflow: await evaluate(
'document.documentElement.scrollWidth<=innerWidth+1',
),
});
}
await evaluate(
`window.__mapSentinel=1;document.querySelector('main form input').focus()`,
);
await send('Input.insertText', { text: 'NoMatchingSyntheticInvestment' });
await wait(`location.search.includes('NoMatchingSyntheticInvestment') && document.querySelectorAll('.leaflet-marker-icon').length===0`);
if (!await evaluate(`window.__mapSentinel===1`)) throw Error('Full page reload detected');
if (errors.length || layouts.some(l=>!l.noOverflow)) throw Error('Browser validation failed');
console.log(JSON.stringify({ marker: true, popup: true, detail_link: true, zoom_control: true, automatic_filter: true, no_full_reload: true, layouts, javascript_errors: errors.length, tiles_blocked_for_test: true }));
} finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
await wait(
`location.search.includes('NoMatchingSyntheticInvestment') && document.querySelectorAll('.leaflet-marker-icon').length===0`,
);
if (!(await evaluate(`window.__mapSentinel===1`)))
throw Error('Full page reload detected');
if (errors.length || layouts.some((l) => !l.noOverflow))
throw Error('Browser validation failed');
console.log(
JSON.stringify({
marker: true,
popup: true,
detail_link: true,
zoom_control: true,
automatic_filter: true,
no_full_reload: true,
layouts,
javascript_errors: errors.length,
tiles_blocked_for_test: true,
}),
);
} finally {
ws.close();
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
}
+204 -49
View File
@@ -1,49 +1,204 @@
const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs=require('node:fs');const assert=require('node:assert/strict');
const dir='storage/app/private/anchor-project-reconciliation/';
const fixture=JSON.parse(fs.readFileSync(dir+'qa-browser-fixture.json'));
const base='http://127.0.0.1:18086';
(async()=>{
const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
try {
const context=await browser.newContext();
await context.route('**/*',route=>route.request().url().startsWith(base)||route.request().url().startsWith('data:')?route.continue():route.abort());
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
const response=await page.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
assert.equal(response.headers()['x-investmoz-qa-target'],fixture.target);assert.equal(response.status(),200);
await page.getByRole('heading',{name:'Localização documentada do projecto',exact:true}).waitFor();
for(const text of ['QA province','QA district','QA admin_post','QA locality','32.5'])assert((await page.locator('body').innerText()).includes(text),text);
await page.getByRole('link',{name:'Synthetic QA linked opportunity',exact:true}).click();
await page.getByRole('link',{name:'Voltar ao dossier: Synthetic QA anchor 1',exact:true}).waitFor();
await page.getByRole('link',{name:'Voltar ao dossier: Synthetic QA anchor 1',exact:true}).click();
await page.getByRole('heading',{name:'Localização documentada do projecto',exact:true}).waitFor();
await page.getByRole('link',{name:'Synthetic QA multi-site cluster',exact:true}).first().click();
const geography=page.locator(`[aria-labelledby="documented-geography-${fixture.cluster_dossier}"]`);
await geography.getByText('Não existe um ponto único atribuído ao cluster.',{exact:false}).waitFor();
assert((await geography.innerText()).includes('2 investimentos com coordenadas disponíveis.'));
assert((await geography.innerText()).includes('QA production'));
assert((await geography.innerText()).includes('QA processing'));
assert.equal(await geography.getByRole('link',{name:/QA-ANCHOR-/}).count(),2);
for(const width of [1440,390]){
await page.setViewportSize({width,height:1000});
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`docs/investmoz/relationships/cluster-${width}.png`,fullPage:true});
}
const map=await context.request.get(base+'/api/v1/investment/map?province_id='+fixture.province_id);assert.equal(map.headers()['x-investmoz-qa-target'],fixture.target);
const data=await map.json();assert.equal(data.matched_count,1);assert.equal(data.georeferenced_count,1);assert.equal(data.features[0].properties.location_basis,'linked_project_site');
const detail=await context.request.get(base+'/api/v1/investment/opportunities/'+fixture.opportunity_slug);
assert(detail.ok());const json=await detail.json();assert.equal(json.context.projects.length,1);assert.equal(json.context.clusters.length,1);
await page.goto(base+'/login',{waitUntil:'networkidle'});
await page.locator('input[type=email]').fill('relationship-qa@example.invalid');await page.locator('input[type=password]').fill('QA-Relationship-2026!');
await page.locator('button[type=submit]').click();await page.waitForURL(url=>!url.pathname.startsWith('/login'));
await page.goto(base+'/management/relationship-repair',{waitUntil:'networkidle'});
await page.getByRole('heading',{name:'Localizações: 28',exact:true}).waitFor();
await page.getByRole('button',{name:'Aplicar associações fundamentadas',exact:true}).click();
await page.getByText(/Associações documentadas aplicadas\.|Este plano já foi aplicado; nenhum duplicado criado\./).waitFor();
await page.getByRole('button',{name:'Aplicar associações fundamentadas',exact:true}).click();
await page.getByText('Este plano já foi aplicado; nenhum duplicado criado.',{exact:true}).waitFor();
assert.deepEqual(errors,[]);
fs.writeFileSync('docs/investmoz/relationships/browser-qa.json',JSON.stringify({target:fixture.target,project:fixture.project_dossier,cluster:fixture.cluster_dossier,passed:true,publicNavigation:true,administrativeHierarchy:true,clusterMemberSites:2,clusterSinglePoint:false,territorialMap:true,chainLinks:true,authenticatedPlanApplied:true,replayWithoutDuplicates:true,viewports:[1440,390],errors},null,2));
console.log('QA browser passed: public project/cluster/opportunity navigation, hierarchy, two member sites, chains, filters, authenticated 28-location repair and idempotent replay.');
}finally{await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const dir = 'storage/app/private/anchor-project-reconciliation/';
const fixture = JSON.parse(fs.readFileSync(dir + 'qa-browser-fixture.json'));
const base = 'http://127.0.0.1:18086';
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
try {
const context = await browser.newContext();
await context.route('**/*', (route) =>
route.request().url().startsWith(base) ||
route.request().url().startsWith('data:')
? route.continue()
: route.abort(),
);
const page = await context.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
const response = await page.goto(
base + '/carteira/' + fixture.project_dossier,
{ waitUntil: 'networkidle' },
);
assert.equal(
response.headers()['x-investmoz-qa-target'],
fixture.target,
);
assert.equal(response.status(), 200);
await page
.getByRole('heading', {
name: 'Localização documentada do projecto',
exact: true,
})
.waitFor();
for (const text of [
'QA province',
'QA district',
'QA admin_post',
'QA locality',
'32.5',
])
assert(
(await page.locator('body').innerText()).includes(text),
text,
);
await page
.getByRole('link', {
name: 'Synthetic QA linked opportunity',
exact: true,
})
.click();
await page
.getByRole('link', {
name: 'Voltar ao dossier: Synthetic QA anchor 1',
exact: true,
})
.waitFor();
await page
.getByRole('link', {
name: 'Voltar ao dossier: Synthetic QA anchor 1',
exact: true,
})
.click();
await page
.getByRole('heading', {
name: 'Localização documentada do projecto',
exact: true,
})
.waitFor();
await page
.getByRole('link', {
name: 'Synthetic QA multi-site cluster',
exact: true,
})
.first()
.click();
const geography = page.locator(
`[aria-labelledby="documented-geography-${fixture.cluster_dossier}"]`,
);
await geography
.getByText('Não existe um ponto único atribuído ao cluster.', {
exact: false,
})
.waitFor();
assert(
(await geography.innerText()).includes(
'2 investimentos com coordenadas disponíveis.',
),
);
assert((await geography.innerText()).includes('QA production'));
assert((await geography.innerText()).includes('QA processing'));
assert.equal(
await geography.getByRole('link', { name: /QA-ANCHOR-/ }).count(),
2,
);
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 1000 });
assert(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
await page.screenshot({
path: `docs/investmoz/relationships/cluster-${width}.png`,
fullPage: true,
});
}
const map = await context.request.get(
base + '/api/v1/investment/map?province_id=' + fixture.province_id,
);
assert.equal(map.headers()['x-investmoz-qa-target'], fixture.target);
const data = await map.json();
assert.equal(data.matched_count, 1);
assert.equal(data.georeferenced_count, 1);
assert.equal(
data.features[0].properties.location_basis,
'linked_project_site',
);
const detail = await context.request.get(
base +
'/api/v1/investment/opportunities/' +
fixture.opportunity_slug,
);
assert(detail.ok());
const json = await detail.json();
assert.equal(json.context.projects.length, 1);
assert.equal(json.context.clusters.length, 1);
await page.goto(base + '/login', { waitUntil: 'networkidle' });
await page
.locator('input[type=email]')
.fill('relationship-qa@example.invalid');
await page
.locator('input[type=password]')
.fill('QA-Relationship-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
await page.goto(base + '/management/relationship-repair', {
waitUntil: 'networkidle',
});
await page
.getByRole('heading', { name: 'Localizações: 28', exact: true })
.waitFor();
await page
.getByRole('button', {
name: 'Aplicar associações fundamentadas',
exact: true,
})
.click();
await page
.getByText(
/Associações documentadas aplicadas\.|Este plano já foi aplicado; nenhum duplicado criado\./,
)
.waitFor();
await page
.getByRole('button', {
name: 'Aplicar associações fundamentadas',
exact: true,
})
.click();
await page
.getByText('Este plano já foi aplicado; nenhum duplicado criado.', {
exact: true,
})
.waitFor();
assert.deepEqual(errors, []);
fs.writeFileSync(
'docs/investmoz/relationships/browser-qa.json',
JSON.stringify(
{
target: fixture.target,
project: fixture.project_dossier,
cluster: fixture.cluster_dossier,
passed: true,
publicNavigation: true,
administrativeHierarchy: true,
clusterMemberSites: 2,
clusterSinglePoint: false,
territorialMap: true,
chainLinks: true,
authenticatedPlanApplied: true,
replayWithoutDuplicates: true,
viewports: [1440, 390],
errors,
},
null,
2,
),
);
console.log(
'QA browser passed: public project/cluster/opportunity navigation, hierarchy, two member sites, chains, filters, authenticated 28-location repair and idempotent replay.',
);
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
@@ -1,8 +1,59 @@
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));
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));
+113 -41
View File
@@ -3,83 +3,155 @@ 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 {
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 };
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()}`);
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.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;
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');
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');
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;
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;
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=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 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;
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;
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;
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';
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.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');
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));
+39 -13
View File
@@ -1,44 +1,70 @@
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 {
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.');
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());
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 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,
existingDraftVisible:
(await page
.getByRole('link', { name: /Continuar rascunho/ })
.count()) === 1,
};
page.once('dialog', dialog => dialog.dismiss());
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.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 });
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.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');
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));
+272
View File
@@ -0,0 +1,272 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const base = 'http://127.0.0.1:18092';
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const errors = [];
const blocked = [];
const contexts = [];
const browserTarget = 'investmoz_v2_20261008_test:55441';
const log = [];
async function login(role) {
const context = await browser.newContext();
await context.route('**/*', (r) =>
r.request().url().startsWith(base)
? r.continue()
: (blocked.push(r.request().url()), r.abort()),
);
contexts.push(context);
const page = await context.newPage();
page.on('pageerror', (e) => errors.push(e.message));
const response = await page.goto(base + '/login');
assert.equal(
response.headers()['x-investmoz-qa-target'],
'investmoz_v2_20261008_test:55441',
);
await page
.locator('input[type=email]')
.fill(`guidance-qa-${role}@example.invalid`);
await page.locator('input[type=password]').fill('QA-Guidance-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
return page;
}
async function json(page, path, method = 'GET', data) {
const response = await page.evaluate(
async ({ path, method, data }) => {
const token = decodeURIComponent(
document.cookie
.split('; ')
.find((v) => v.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
const r = await fetch(path, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token,
},
...(data && method !== 'GET'
? { body: JSON.stringify(data) }
: {}),
});
return { status: r.status, data: await r.json() };
},
{ path, method, data },
);
assert.ok(response.status < 300, JSON.stringify(response));
return response.data;
}
try {
console.log('QA browser: normal authentication');
const investor = await login('investor');
const manager = await login('manager');
console.log('QA browser: prepare dossier');
await investor.goto(base + '/balcao-virtual/painel');
await investor
.getByText('Preparar acompanhamento de um projecto', {
exact: true,
})
.click();
await investor
.getByLabel('Título do projecto', { exact: true })
.fill('Percurso completo QA browser');
await investor.locator('input[type=checkbox]').check();
await investor
.getByRole('button', { name: 'Preparar dossier', exact: true })
.click();
await investor.waitForURL(/\/balcao-virtual\/dossiers\//);
const caseId = investor.url().split('/').pop();
await investor
.getByRole('button', {
name: 'Preparar rascunho de pedido',
exact: true,
})
.click();
await investor.waitForURL(/\/balcao-virtual\/pedidos\//);
const requestId = investor.url().split('/').pop();
console.log('QA browser: save draft and submit');
await investor
.getByLabel(/Descrição e objetivo/)
.fill('Preciso de apoio para preparar o investimento fictício QA.');
await investor.getByLabel(/Valor do investimento/).fill('1000.00');
await investor.getByLabel(/Moeda/).first().selectOption('MZN');
await investor
.getByRole('button', { name: 'Guardar rascunho', exact: true })
.click();
await investor.waitForLoadState('networkidle');
await investor.reload();
assert.equal(
await investor.getByLabel('Valor do investimento').inputValue(),
'1000.00',
);
await investor
.getByLabel(
'Revi o conteúdo e autorizo a submissão para análise interna.',
)
.check();
await investor
.getByRole('button', { name: 'Submeter este pedido', exact: true })
.click();
await investor.waitForLoadState('networkidle');
let row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
assert.equal(row.status, 'submitted');
log.push(
'Rascunho recuperado e submetido explicitamente com protocolo interno.',
);
await json(
manager,
`/balcao-virtual/pedidos/${requestId}/estado`,
'POST',
{
version: row.version,
status: 'returned',
reason: 'Indique o mercado previsto. Esclarecimento interno QA.',
editable_fields: ['description'],
},
);
await investor.reload();
await investor
.getByLabel(/Descrição e objetivo/)
.fill(
'Mercado declarado em QA; evidência de procura permanece pendente.',
);
await investor
.getByLabel('Justificação de correcção')
.fill('Resposta ao esclarecimento do responsável.');
await investor
.getByLabel(
'Revi o conteúdo e autorizo a submissão para análise interna.',
)
.check();
await investor
.getByRole('button', { name: 'Submeter este pedido', exact: true })
.click();
await investor.waitForLoadState('networkidle');
row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
for (const status of ['reviewing', 'opinion', 'accepted']) {
await json(
manager,
`/balcao-virtual/pedidos/${requestId}/estado`,
'POST',
{
version: row.version,
status,
reason: 'Resultado interno QA, sem aprovação ou licença institucional.',
},
);
row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
}
await manager.goto(base + `/balcao-virtual/pedidos/${requestId}`);
await manager
.getByLabel('Mensagem privada', { exact: true })
.fill(
'Resposta humana QA: o dossier foi aceite internamente para acompanhamento.',
);
await manager
.getByRole('button', {
name: 'Enviar esta mensagem no pedido',
exact: true,
})
.click();
await manager.waitForLoadState('networkidle');
await investor.reload();
await investor
.getByText(
'Resposta humana QA: o dossier foi aceite internamente para acompanhamento.',
{ exact: true },
)
.waitFor();
await investor.screenshot({
path: 'storage/app/private/virtual-desk/qa-response.png',
fullPage: true,
});
await investor.goto(base + `/balcao-virtual/dossiers/${caseId}`);
const guidance = await json(
investor,
`/balcao-virtual/dossiers/${caseId}/orientacao`,
);
await json(
investor,
`/balcao-virtual/dossiers/${caseId}/recomendacoes`,
'POST',
{
code: 'support_preparation',
context_hash: guidance.fingerprint,
decision: 'accepted',
reason: 'Assumo o acompanhamento deste mesmo pedido.',
},
);
const task = await json(
investor,
`/balcao-virtual/dossiers/${caseId}/tarefas`,
'POST',
{
code: 'support_preparation',
context_hash: guidance.fingerprint,
consent: true,
request_id: requestId,
due_at: new Date(Date.now() + 86400000).toISOString(),
},
);
await investor.reload();
await investor
.getByRole('link', {
name: 'Consultar o pedido e a resposta do responsável',
exact: true,
})
.waitFor();
await investor.goto(base + '/parcerias');
await investor
.getByRole('button', {
name: 'Acompanhar o meu projecto neste portal',
exact: true,
})
.click();
await investor.getByLabel('Contexto do projecto').selectOption(caseId);
await investor.getByText('Regras internas', { exact: false }).waitFor();
log.push(
'Esclarecimento, nova submissão, parecer, aceitação interna e resposta humana preservados.',
);
log.push(
'Tarefa aceite no CRM interno ligada ao mesmo pedido; contexto recuperado na Bolsa de Parcerias.',
);
assert.deepEqual(errors, []);
fs.writeFileSync(
'storage/app/private/investmoz-v2/desk-browser-evidence.json',
JSON.stringify(
{
passed: true,
database: 'investmoz_v2_20261008_test',
port: 55441,
caseId,
requestId,
taskId: task.id,
log,
pageErrors: errors,
blockedExternalRequests: blocked,
browserTarget,
},
null,
2,
),
);
console.log(JSON.stringify({ passed: true, log, pageErrors: errors }));
} finally {
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+357
View File
@@ -0,0 +1,357 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const base = 'http://127.0.0.1:18092';
const dir = 'storage/app/private/investmoz-v2';
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const errors = [],
blocked = [],
checks = [];
async function context(width) {
const ctx = await browser.newContext({
viewport: { width, height: width < 640 ? 844 : 1000 },
hasTouch: width < 640,
});
await ctx.route('**/*', (r) => {
if (r.request().url().startsWith(base)) return r.continue();
blocked.push(r.request().url());
return r.abort();
});
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push(e.message));
return page;
}
async function visit(page, path) {
const r = await page.goto(base + path);
assert.equal(
r.headers()['x-investmoz-qa-target'],
'investmoz_v2_20261008_test:55441',
);
assert.ok(r.status() < 400, path + ':' + r.status());
await page.locator('nav[aria-label="Áreas do portal"]').waitFor();
assert.equal(
await page.locator('nav[aria-label="Áreas do portal"]').count(),
1,
);
await page.waitForLoadState('networkidle');
}
async function login(page, role) {
await visit(page, '/login');
await page
.locator('input[type=email]')
.fill(`guidance-qa-${role}@example.invalid`);
await page.locator('input[type=password]').fill('QA-Guidance-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
}
async function api(page, path, method = 'GET', data) {
return page.evaluate(
async ({ path, method, data }) => {
const token = decodeURIComponent(
document.cookie
.split('; ')
.find((v) => v.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
const r = await fetch(path, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token,
},
...(data && method !== 'GET'
? { body: JSON.stringify(data) }
: {}),
});
return { status: r.status, data: await r.json() };
},
{ path, method, data },
);
}
async function menus(page, management, touch) {
const nav = page.locator('nav[aria-label="Áreas do portal"]');
assert.equal(
await nav.getByRole('button', { name: /^Gestão/ }).count(),
management ? 1 : 0,
);
const groups = nav.locator(':scope > ul > li > button');
for (let i = 0; i < (await groups.count()); i++) {
const b = groups.nth(i);
await b.scrollIntoViewIfNeeded();
if (touch) await b.tap();
else {
await b.focus();
await page.keyboard.press('Enter');
}
assert.equal(await b.getAttribute('aria-expanded'), 'true');
const panel = nav.locator(
`[id="${await b.getAttribute('aria-controls')}"]`,
);
const box = await panel.boundingBox(),
width = page.viewportSize().width;
assert.ok(
box.x >= -1 && box.x + box.width <= width + 1,
JSON.stringify({ box, width }),
);
const nested = panel.getByRole('button');
if (await nested.count()) {
const n = nested.first();
await n.click();
assert.equal(await n.getAttribute('aria-expanded'), 'true');
await page.keyboard.press('Escape');
assert.equal(await n.getAttribute('aria-expanded'), 'false');
assert.equal(
await n.evaluate((el) => el === document.activeElement),
true,
);
}
await page.keyboard.press('Escape');
assert.equal(await b.getAttribute('aria-expanded'), 'false');
assert.equal(
await b.evaluate((el) => el === document.activeElement),
true,
);
}
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
assert.equal(overflow, false, page.url());
}
try {
const caseId = JSON.parse(
fs.readFileSync(dir + '/desk-browser-evidence.json'),
).caseId;
for (const width of [1440, 390]) {
const page = await context(width);
await visit(page, '/');
await menus(page, false, width < 640);
await page.screenshot({
path: `${dir}/public-${width}.png`,
fullPage: true,
});
for (const [kind, title] of [
['project', 'V2 QA project'],
['cluster', 'V2 QA cluster'],
]) {
await visit(page, `/carteira?kind=${kind}`);
await page.getByLabel('Pesquisar', { exact: true }).fill(title);
await page
.getByRole('button', { name: 'Pesquisar', exact: true })
.click();
await page
.getByRole('link', { name: title, exact: true })
.click();
await page
.getByRole('heading', { name: title, exact: true })
.waitFor();
assert.ok(
await page
.locator('[data-current-group="true"]')
.textContent()
.then((t) => t.includes('Explorar')),
);
}
await visit(page, '/zonas');
await page.getByLabel('Pesquisar por nome ou código').fill('V2 QA');
await page
.getByRole('button', { name: 'Pesquisar', exact: true })
.click();
await page
.getByRole('link', {
name: 'V2 QA localização fictícia',
exact: true,
})
.click();
await page
.getByRole('heading', {
name: 'V2 QA localização fictícia',
exact: true,
})
.waitFor();
await login(page, 'investor');
await visit(page, '/investidor');
await menus(page, false, width < 640);
await page.screenshot({
path: `${dir}/investor-${width}.png`,
fullPage: true,
});
const draft = await api(
page,
'/api/v1/simulation-drafts/00000000-0000-4000-8000-000000000202',
);
assert.equal(draft.status, 200);
assert.equal(
draft.data.data.economic_snapshot.project_title,
'V2 QA rascunho anterior',
);
const restored = await api(
page,
'/balcao-virtual/dossiers',
'POST',
{
title: 'V2 QA continuidade do rascunho',
simulation_id: '00000000-0000-4000-8000-000000000202',
reuse_consent: true,
client_key: crypto.randomUUID(),
},
);
assert.equal(restored.status, 201);
const guidance = await api(
page,
`/balcao-virtual/dossiers/${restored.data.id}/orientacao`,
);
assert.equal(
guidance.data.facts.project_summary,
'Ideia anterior preservada QA',
);
assert.equal(
guidance.data.phases[1].evidence[0].state,
'investor_declared_not_verified',
);
assert.equal(guidance.data.phases[2].evidence[0].state, 'absent');
for (const path of [
'/como-investir',
'/simulador-fiscal',
`/balcao-virtual/dossiers/${caseId}`,
'/parcerias',
]) {
await visit(page, path);
await page
.getByRole('button', {
name: 'Acompanhar o meu projecto neste portal',
exact: true,
})
.click();
await page
.getByLabel('Contexto do projecto')
.selectOption(caseId);
await page
.getByText('Regras internas', { exact: false })
.waitFor();
await page
.getByRole('button', {
name: 'Acompanhar o meu projecto neste portal',
exact: true,
})
.click();
}
checks.push(
`Publicação QA, pesquisa e fichas; menus públicos e de investidor; rascunho e contexto entre módulos em ${width}px.`,
);
await page.context().close();
}
const owner = await context(1440);
await login(owner, 'investor');
const manager = await context(1440);
await login(manager, 'manager');
await visit(manager, '/management/crm/leads');
await menus(manager, true, false);
execFileSync(
'php',
['tools/investmoz-v2-qa-router.php', 'seed', caseId],
{ stdio: 'pipe' },
);
await visit(owner, `/balcao-virtual/dossiers/${caseId}?phase=location`);
await owner
.getByText('Documento associado, por conferir', { exact: false })
.first()
.waitFor();
const dossier = await api(
manager,
`/balcao-virtual/dossiers/${caseId}`,
);
const document = dossier.data.documents.find(
(d) => d.category === 'location_evidence',
);
assert.ok(document);
await visit(manager, `/balcao-virtual/dossiers/${caseId}`);
const review = manager.locator('form').filter({
has: manager.getByRole('heading', {
name: 'Conferência documental interna',
}),
});
await review
.getByLabel('Documento', { exact: true })
.selectOption(document.id);
await review.getByLabel('Localização', { exact: true }).check();
await review
.getByLabel('O que foi verificado')
.fill('Conferido apenas o acesso descrito na fixture V2 QA.');
await review
.getByLabel('Evidência utilizada')
.fill('Ficheiro sintético, versão e hash registados nesta QA.');
await review
.getByRole('button', {
name: 'Registar conferência com a minha autoria',
})
.click();
await manager.waitForLoadState('networkidle');
await visit(owner, `/balcao-virtual/dossiers/${caseId}?phase=location`);
await owner
.getByText('Verificador: Guidance QA manager', { exact: false })
.waitFor();
await owner
.getByText('Conferido internamente no âmbito descrito', {
exact: false,
})
.first()
.waitFor();
await owner.screenshot({
path: `${dir}/scoped-evidence.png`,
fullPage: true,
});
const other = await context(390);
await login(other, 'other');
assert.equal(
(await api(other, `/balcao-virtual/dossiers/${caseId}/orientacao`))
.status,
403,
);
assert.equal(
(
await api(
other,
'/api/v1/simulation-drafts/00000000-0000-4000-8000-000000000202',
)
).status,
404,
);
assert.equal((await api(other, '/management/crm/leads')).status, 403);
await visit(other, '/investidor');
await menus(other, false, true);
checks.push(
'Conferência pela interface com autor/data/âmbito; gestão autorizada; isolamento de dossier e rascunho entre utilizadores.',
);
assert.deepEqual(errors, []);
fs.writeFileSync(
dir + '/navigation-browser-evidence.json',
JSON.stringify(
{
passed: true,
database: 'investmoz_v2_20261008_test',
port: 55441,
checks,
errors,
blockedExternalRequests: blocked,
},
null,
2,
),
);
console.log(JSON.stringify({ passed: true, checks, errors }));
} finally {
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+142
View File
@@ -0,0 +1,142 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const base = 'http://127.0.0.1:18092';
void (async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const context = await browser.newContext();
await context.route('**/*', (r) =>
r.request().url().startsWith(base) ? r.continue() : r.abort(),
);
const page = await context.newPage();
const errors = [];
page.on('pageerror', (e) => errors.push(e.message));
try {
const response = await page.goto(base + '/login');
assert.equal(
response.headers()['x-investmoz-qa-target'],
'investmoz_v2_20261008_test:55441',
);
await page
.locator('input[type=email]')
.fill('guidance-qa-investor@example.invalid');
await page.locator('input[type=password]').fill('QA-Guidance-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
await page.goto(base + '/balcao-virtual/painel');
await page
.getByText('Preparar acompanhamento de um projecto', {
exact: true,
})
.click();
const title = 'Painel — dossier sintético QA ' + Date.now();
await page.getByLabel('Título do projecto').fill(title);
await page
.getByRole('button', { name: 'Preparar dossier', exact: true })
.click();
await page
.getByRole('alert')
.filter({ hasText: 'O dossier não foi guardado' })
.waitFor();
assert.equal(
await page.getByLabel('Título do projecto').inputValue(),
title,
);
await page
.getByLabel('Autorizo reutilizar os dados seleccionados', {
exact: false,
})
.check();
let mode = 'conflict';
let writes = 0;
await page.route(base + '/balcao-virtual/dossiers', async (route) => {
if (route.request().method() !== 'POST') return route.continue();
if (mode === 'conflict')
return route.fulfill({
status: 409,
contentType: 'text/plain',
body: 'QA conflict',
});
if (mode === 'network') return route.abort('connectionfailed');
writes++;
await new Promise((resolve) => setTimeout(resolve, 600));
return route.continue();
});
await page
.getByRole('button', { name: 'Preparar dossier', exact: true })
.click();
await page
.getByRole('alert')
.filter({ hasText: 'Esta operação já foi utilizada' })
.waitFor();
assert.equal(
await page.getByLabel('Título do projecto').inputValue(),
title,
);
mode = 'network';
await page
.getByRole('button', { name: 'Preparar dossier', exact: true })
.click();
await page
.getByRole('alert')
.filter({ hasText: 'A ligação falhou' })
.waitFor();
assert.equal(
await page.getByLabel('Título do projecto').inputValue(),
title,
);
mode = 'success';
await page
.getByRole('button', { name: 'Preparar dossier', exact: true })
.dblclick();
await page.waitForURL('**/balcao-virtual/dossiers/*');
await page
.getByRole('status')
.filter({ hasText: 'Dossier guardado e disponível' })
.waitFor();
assert.equal(writes, 1);
const caseUrl = page.url();
await page.goto(base + '/balcao-virtual/painel');
await page.getByRole('link', { name: title, exact: true }).click();
await page.waitForURL(caseUrl);
assert.equal(page.url(), caseUrl);
const result = await page.evaluate(async () => {
const r = await fetch(location.pathname, {
headers: { Accept: 'application/json' },
});
return r.json();
});
assert.equal(result.case.title, title);
assert.equal(result.requests.length, 0);
assert.deepEqual(errors, []);
const proof = {
passed: true,
database: 'investmoz_v2_20261008_test',
port: 55441,
actualPostCount: writes,
caseRecovered: true,
requestCount: result.requests.length,
validationFailurePreserved: true,
conflictPreserved: true,
networkFailurePreserved: true,
successAndNextActionVisible: true,
errors,
};
fs.writeFileSync(
'storage/app/private/investmoz-v2/panel-browser-evidence.json',
JSON.stringify(proof, null, 2),
);
console.log(JSON.stringify(proof));
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+41
View File
@@ -0,0 +1,41 @@
<?php
use App\Models\InvestmentDossier;
use App\Models\SimulationFormDraft;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
if (! defined('INVESTMOZ_V2_QA') || ! INVESTMOZ_V2_QA || DB::connection()->getDatabaseName() !== 'investmoz_v2_20261008_test' || (string) DB::connection()->getConfig('port') !== '55441') {
throw new RuntimeException('V2 fixtures are restricted to the isolated database.');
}
$owner = User::where('email', 'guidance-qa-investor@example.invalid')->firstOrFail();
$manager = User::where('email', 'guidance-qa-manager@example.invalid')->firstOrFail();
DB::table('desk_institutional_links')->insertOrIgnore(['id' => '00000000-0000-4000-8000-000000000303', 'stage' => 'E10',
'entity' => 'Instituição sintética V2 QA', 'purpose' => 'Monitoria de disponibilidade QA', 'url' => 'https://example.invalid/',
'contact' => 'Contacto sintético QA; não utilizar fora dos testes', 'source_reference' => 'Fixture QA, não é fonte institucional', 'status' => 'pending']);
foreach (['project' => 'projects', 'cluster' => 'economic_clusters'] as $kind => $table) {
$entity = DB::table($table)->where('code', 'V2-QA-'.strtoupper($kind))->value('id');
if (! $entity) {
$entity = (string) Str::uuid();
DB::table($table)->insert(['id' => $entity, 'code' => 'V2-QA-'.strtoupper($kind), 'name' => 'V2 QA '.$kind, 'status' => $kind === 'cluster' ? 'planned' : 'draft', 'data_classification' => 'public', ...($kind === 'cluster' ? ['sector' => 'Sector fictício QA'] : [])]);
}
InvestmentDossier::firstOrCreate([$kind.'_id' => $entity], ['title' => 'V2 QA '.$kind, 'source' => 'Fixture sintética exclusiva da QA, sem aprovação institucional.', 'content' => ['code' => 'V2-QA-'.strtoupper($kind), 'description' => 'Registo fictício para pesquisa e ficha.'], 'publication_status' => 'published', 'published_at' => now(), 'editor_id' => $owner->id, 'reviewer_id' => $manager->id, 'approval_basis' => 'manager', 'approval_evidence' => 'Apenas fixture QA; não representa acto real.']);
}
if (! DB::table('investment_zones')->where('code', 'V2-QA-PARK')->exists()) {
DB::table('investment_zones')->insert(['id' => (string) Str::uuid(), 'code' => 'V2-QA-PARK', 'name' => 'V2 QA localização fictícia', 'name_en' => 'V2 QA fictional location', 'description_en' => 'Synthetic QA only, not an institutionally approved location.', 'category' => 'industrial_park', 'physical_category' => 'industrial_park', 'legal_regime' => 'pending', 'description' => 'Fixture para pesquisa; disponibilidade e regime não confirmados.', 'publication_status' => 'published', 'validation_status' => 'validated', 'source_evidence' => json_encode([['source_type' => 'promoter', 'title' => 'Fixture QA — não é fonte institucional', 'url' => 'https://example.invalid/qa', 'supports' => 'Apenas a ficha fictícia usada no ensaio.']]), 'availability_status' => 'not_informed', 'editor_id' => $owner->id, 'reviewer_id' => $manager->id, 'published_at' => now()]);
}
SimulationFormDraft::firstOrCreate(['id' => '00000000-0000-4000-8000-000000000202'], ['owner_user_id' => $owner->id, 'version_no' => 1, 'create_key_hash' => hash('sha256', 'v2-qa-existing-key'), 'create_payload_hash' => hash('sha256', 'v2-qa-existing-data'), 'snapshot_sha256' => hash('sha256', 'v2-qa-existing-data'), 'economic_snapshot' => SimulationFormDraft::encryptSnapshot(['project_title' => 'V2 QA rascunho anterior', 'project_summary' => 'Ideia anterior preservada QA', 'products_services' => 'Transformação fictícia QA', 'market_source' => 'Declaração fictícia, por conferir']), 'personal_snapshot' => SimulationFormDraft::encryptSnapshot([])]);
if (isset($argv[2])) {
$case = DB::table('desk_cases')->where('id', $argv[2])->where('user_id', $owner->id)->firstOrFail();
if (! DB::table('desk_documents')->where('case_id', $case->id)->where('source_reference', 'Fixture V2 QA; scan simulated by test double')->exists()) {
$bytes = 'Ficheiro sintetico V2 QA. Apenas acesso descrito neste texto ficticio, nao disponibilidade nem licenca.';
$key = 'v2-qa-browser/'.$case->id.'.txt';
Storage::disk('local')->put($key, $bytes);
$hash = hash('sha256', $bytes);
$document = (string) Str::uuid();
DB::table('documents')->insert(['id' => $document, 'source_system' => 'v2-qa-test-double', 'file_name' => 'Evidencia V2 QA.txt', 'media_type' => 'text/plain', 'storage_key' => $key, 'sha256' => $hash, 'size_bytes' => strlen($bytes), 'uploaded_by' => $owner->id, 'status' => 'active', 'data_classification' => 'confidential', 'malware_scan_status' => 'clean', 'malware_engine' => 'QA-Test-Double', 'malware_scanned_sha256' => $hash]);
DB::table('desk_documents')->insert(['id' => (string) Str::uuid(), 'case_id' => $case->id, 'document_id' => $document, 'category' => 'location_evidence', 'source_reference' => 'Fixture V2 QA; scan simulated by test double', 'linked_by' => $owner->id]);
}
}
+6
View File
@@ -0,0 +1,6 @@
<?php
// Only this local QA entrypoint selects the fixed V2 disposable database.
define('INVESTMOZ_V2_QA', true);
return require __DIR__.'/investor-guidance-qa-router.php';
+181
View File
@@ -0,0 +1,181 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const base = 'http://127.0.0.1:18092';
const dir = 'storage/app/private/investmoz-v2';
void (async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const errors = [];
async function login(role) {
const context = await browser.newContext({
viewport: { width: 1440, height: 1000 },
});
await context.route('**/*', (r) =>
r.request().url().startsWith(base) ? r.continue() : r.abort(),
);
const page = await context.newPage();
page.on('pageerror', (e) => errors.push(e.message));
const response = await page.goto(base + '/login');
assert.equal(
response.headers()['x-investmoz-qa-target'],
'investmoz_v2_20261008_test:55441',
);
await page
.locator('input[type=email]')
.fill(`guidance-qa-${role}@example.invalid`);
await page.locator('input[type=password]').fill('QA-Guidance-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
return page;
}
try {
const owner = await login('investor');
const manager = await login('manager');
const id = await owner.evaluate(async () => {
const token = decodeURIComponent(
document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
.slice(11),
);
const response = await fetch('/balcao-virtual/dossiers', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token,
},
body: JSON.stringify({
title: 'Segunda entrega sintética QA',
reuse_consent: true,
client_key: crypto.randomUUID(),
}),
});
if (response.status !== 201) throw new Error('QA creation failed');
return (await response.json()).id;
});
await owner.goto(`${base}/balcao-virtual/dossiers/${id}`);
await owner
.getByText('Corrigir pressupostos ou registar uma alternativa', {
exact: true,
})
.click();
for (const [label, value] of Object.entries({
'Procura declarada (quantidade, não previsão)': '100',
'Capacidade declarada na mesma unidade e período': '50',
'Unidade comum da procura e capacidade': 'toneladas',
'Período comum da procura e capacidade': 'ano',
'Financiamento necessário declarado': '100.50',
'Financiamento comprometido declarado': '100.49',
'Moeda comum do financiamento': 'MZN',
})) {
await owner.getByLabel(label, { exact: true }).fill(value);
}
const [saved] = await Promise.all([
owner.waitForResponse(
(response) =>
response.url().endsWith('/pressupostos') &&
response.request().method() === 'POST',
),
owner
.getByRole('button', {
name: 'Guardar pressupostos corrigidos',
exact: true,
})
.click(),
]);
assert.ok(saved.status() < 400);
await owner.waitForLoadState('networkidle');
await owner.goto(`${base}/balcao-virtual/dossiers/${id}?phase=market`);
await owner
.getByText('A procura declarada excede a capacidade declarada', {
exact: false,
})
.waitFor();
await owner.goto(`${base}/balcao-virtual/dossiers/${id}?phase=finance`);
await owner
.getByText('O financiamento comprometido declarado é inferior', {
exact: false,
})
.waitFor();
await manager.goto(`${base}/balcao-virtual/dossiers/${id}`);
const review = manager.locator('form').filter({
has: manager.getByRole('button', {
name: 'Registar a minha conferência da ligação',
exact: true,
}),
});
await review
.getByLabel('Evidência e data da consulta')
.fill(
'Consulta sintética QA: endereço indisponível; nenhum pedido externo efetuado.',
);
await review
.getByLabel('Contacto alternativo com fonte')
.fill('Pedido de apoio interno; fonte fixture QA');
await review
.getByRole('button', {
name: 'Registar a minha conferência da ligação',
})
.click();
await manager.waitForLoadState('networkidle');
await owner.goto(`${base}/balcao-virtual/dossiers/${id}`);
await owner
.getByText('Pedido de apoio interno; fonte fixture QA', {
exact: false,
})
.waitFor();
await owner
.getByRole('link', {
name: 'Ligação indisponível: continuar internamente',
exact: true,
})
.click();
await owner.waitForLoadState('networkidle');
assert.ok(owner.url().includes('/dossiers/' + id));
await manager.goto(base + '/management/balcao-install');
await manager
.getByRole('heading', {
name: 'Instalação autenticada do Balcão e acompanhamento',
})
.waitFor();
await manager
.getByText('Destino: investmoz_v2_20261008_test', { exact: false })
.waitFor();
await manager
.getByText('Indisponível (scanner_unavailable)', { exact: false })
.waitFor();
await manager.screenshot({
path: dir + '/second-install-qa.png',
fullPage: true,
});
assert.deepEqual(errors, []);
const proof = {
passed: true,
database: 'investmoz_v2_20261008_test',
port: 55441,
errors,
checks: [
'Assumptions saved through UI; comparable declared gaps explained.',
'Human link review, fallback contact and internal continuation through UI.',
'Authenticated installation page shows actual QA target and unavailable ClamD; no active installation.',
],
};
fs.writeFileSync(
dir + '/second-browser-evidence.json',
JSON.stringify(proof, null, 2),
);
console.log(JSON.stringify(proof));
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+264
View File
@@ -0,0 +1,264 @@
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const base = 'http://127.0.0.1:18091';
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const errors = [];
const log = [];
async function login(role) {
const context = await browser.newContext();
await context.route('**/*', (r) =>
r.request().url().startsWith(base) ? r.continue() : r.abort(),
);
const page = await context.newPage();
page.on('pageerror', (e) => errors.push(e.message));
const response = await page.goto(base + '/login');
assert.equal(
response.headers()['x-investmoz-qa-target'],
'investmoz_guidance_20261008_test:55441',
);
await page
.locator('input[type=email]')
.fill(`guidance-qa-${role}@example.invalid`);
await page.locator('input[type=password]').fill('QA-Guidance-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
return page;
}
async function json(page, path, method = 'GET', data) {
const response = await page.evaluate(
async ({ path, method, data }) => {
const token = decodeURIComponent(
document.cookie
.split('; ')
.find((v) => v.startsWith('XSRF-TOKEN='))
?.slice(11) ?? '',
);
const r = await fetch(path, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token,
},
...(data && method !== 'GET'
? { body: JSON.stringify(data) }
: {}),
});
return { status: r.status, data: await r.json() };
},
{ path, method, data },
);
assert.ok(response.status < 300, JSON.stringify(response));
return response.data;
}
try {
console.log('QA browser: normal authentication');
const investor = await login('investor');
const manager = await login('manager');
console.log('QA browser: prepare dossier');
await investor.goto(base + '/balcao-virtual/painel');
await investor
.getByText('Preparar acompanhamento de um projecto', {
exact: true,
})
.click();
await investor
.getByLabel('Título do projecto', { exact: true })
.fill('Percurso completo QA browser');
await investor.locator('input[type=checkbox]').check();
await investor
.getByRole('button', { name: 'Preparar dossier', exact: true })
.click();
await investor.waitForURL(/\/balcao-virtual\/dossiers\//);
const caseId = investor.url().split('/').pop();
await investor
.getByRole('button', {
name: 'Preparar rascunho de pedido',
exact: true,
})
.click();
await investor.waitForURL(/\/balcao-virtual\/pedidos\//);
const requestId = investor.url().split('/').pop();
console.log('QA browser: save draft and submit');
await investor
.getByLabel(/Descrição e objetivo/)
.fill('Preciso de apoio para preparar o investimento fictício QA.');
await investor.getByLabel(/Valor do investimento/).fill('1000.00');
await investor.getByLabel(/Moeda/).first().selectOption('MZN');
await investor
.getByRole('button', { name: 'Guardar rascunho', exact: true })
.click();
await investor.waitForLoadState('networkidle');
await investor.reload();
assert.equal(
await investor.getByLabel('Valor do investimento').inputValue(),
'1000.00',
);
await investor
.getByLabel(
'Revi o conteúdo e autorizo a submissão para análise interna.',
)
.check();
await investor
.getByRole('button', { name: 'Submeter este pedido', exact: true })
.click();
await investor.waitForLoadState('networkidle');
let row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
assert.equal(row.status, 'submitted');
log.push(
'Rascunho recuperado e submetido explicitamente com protocolo interno.',
);
await json(
manager,
`/balcao-virtual/pedidos/${requestId}/estado`,
'POST',
{
version: row.version,
status: 'returned',
reason: 'Indique o mercado previsto. Esclarecimento interno QA.',
editable_fields: ['description'],
},
);
await investor.reload();
await investor
.getByLabel(/Descrição e objetivo/)
.fill(
'Mercado declarado em QA; evidência de procura permanece pendente.',
);
await investor
.getByLabel('Justificação de correcção')
.fill('Resposta ao esclarecimento do responsável.');
await investor
.getByLabel(
'Revi o conteúdo e autorizo a submissão para análise interna.',
)
.check();
await investor
.getByRole('button', { name: 'Submeter este pedido', exact: true })
.click();
await investor.waitForLoadState('networkidle');
row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
for (const status of ['reviewing', 'opinion', 'accepted']) {
await json(
manager,
`/balcao-virtual/pedidos/${requestId}/estado`,
'POST',
{
version: row.version,
status,
reason: 'Resultado interno QA, sem aprovação ou licença institucional.',
},
);
row = (await json(manager, `/balcao-virtual/pedidos/${requestId}`))
.request;
}
await manager.goto(base + `/balcao-virtual/pedidos/${requestId}`);
await manager
.getByLabel('Mensagem privada', { exact: true })
.fill(
'Resposta humana QA: o dossier foi aceite internamente para acompanhamento.',
);
await manager
.getByRole('button', {
name: 'Enviar esta mensagem no pedido',
exact: true,
})
.click();
await manager.waitForLoadState('networkidle');
await investor.reload();
await investor
.getByText(
'Resposta humana QA: o dossier foi aceite internamente para acompanhamento.',
{ exact: true },
)
.waitFor();
await investor.screenshot({
path: 'storage/app/private/virtual-desk/qa-response.png',
fullPage: true,
});
await investor.goto(base + `/balcao-virtual/dossiers/${caseId}`);
const guidance = await json(
investor,
`/balcao-virtual/dossiers/${caseId}/orientacao`,
);
await json(
investor,
`/balcao-virtual/dossiers/${caseId}/recomendacoes`,
'POST',
{
code: 'support_preparation',
context_hash: guidance.fingerprint,
decision: 'accepted',
reason: 'Assumo o acompanhamento deste mesmo pedido.',
},
);
const task = await json(
investor,
`/balcao-virtual/dossiers/${caseId}/tarefas`,
'POST',
{
code: 'support_preparation',
context_hash: guidance.fingerprint,
consent: true,
request_id: requestId,
due_at: new Date(Date.now() + 86400000).toISOString(),
},
);
await investor.reload();
await investor
.getByRole('link', {
name: 'Consultar o pedido e a resposta do responsável',
exact: true,
})
.waitFor();
await investor.goto(base + '/parcerias');
await investor
.getByRole('button', {
name: 'Acompanhar o meu projecto neste portal',
exact: true,
})
.click();
await investor.getByLabel('Contexto do projecto').selectOption(caseId);
await investor.getByText('Regras internas', { exact: false }).waitFor();
log.push(
'Esclarecimento, nova submissão, parecer, aceitação interna e resposta humana preservados.',
);
log.push(
'Tarefa aceite no CRM interno ligada ao mesmo pedido; contexto recuperado na Bolsa de Parcerias.',
);
assert.deepEqual(errors, []);
fs.writeFileSync(
'storage/app/private/virtual-desk/browser-qa-evidence.json',
JSON.stringify(
{
passed: true,
database: 'investmoz_guidance_20261008_test',
port: 55441,
caseId,
requestId,
taskId: task.id,
log,
pageErrors: errors,
},
null,
2,
),
);
console.log(JSON.stringify({ passed: true, log, pageErrors: errors }));
} finally {
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+77
View File
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
use App\Http\Controllers\VirtualDeskInstallationController;
use App\Models\User;
use App\Services\VirtualDeskInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Vite;
// Fixed, disposable QA target. Never inherit database/session configuration.
$root = dirname(__DIR__);
$v2 = defined('INVESTMOZ_V2_QA') && INVESTMOZ_V2_QA === true;
$qaDatabase = $v2 ? 'investmoz_v2_20261008_test' : 'investmoz_guidance_20261008_test';
$qaUrl = $v2 ? 'http://127.0.0.1:18092' : 'http://127.0.0.1:18091';
foreach (['APP_ENV' => 'testing', 'APP_DEBUG' => 'true', 'APP_URL' => $qaUrl, 'APP_KEY' => 'base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441', 'DB_DATABASE' => $qaDatabase, 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '',
'SESSION_DRIVER' => 'file', 'SESSION_COOKIE' => 'investmoz_guidance_qa', 'CACHE_STORE' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
require $root.'/vendor/autoload.php';
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$connection = config('database.connections.'.config('database.default'));
if (config('database.default') !== 'pgsql' || ($connection['host'] ?? null) !== '127.0.0.1' || (string) ($connection['port'] ?? '') !== '55441' || ($connection['database'] ?? null) !== $qaDatabase || ! in_array($connection['url'] ?? null, [null, ''], true)) {
throw new RuntimeException('Refusing a non-QA configuration before connecting.');
}
$identity = DB::selectOne('select current_database() as name, inet_server_port() as port');
if ($identity->name !== $qaDatabase || (int) $identity->port !== 55441) {
throw new RuntimeException('Refusing a non-QA database identity.');
}
$private = $root.($v2 ? '/storage/app/private/investmoz-v2' : '/storage/app/private/virtual-desk');
if (! is_dir($private.'/qa-sessions')) {
mkdir($private.'/qa-sessions', 0700, true);
}
config(['session.files' => $private.'/qa-sessions', 'portal.managers' => ['guidance-qa-manager@example.invalid'], 'suitecrm.enabled' => false, 'investmoz_ai.enabled' => false]);
Vite::useHotFile($root.'/storage/framework/guidance-qa-absent-hot');
if ($v2 && PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'migrate') {
$result = $app->make(Kernel::class)->call('migrate', ['--force' => true]);
echo 'V2 QA migrations exit '.$result.'; target '.$identity->name.':'.$identity->port."\n";
exit($result);
}
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'seed') {
foreach (($v2 ? ['investor', 'manager', 'other'] : ['investor', 'manager']) as $role) {
$user = User::updateOrCreate(['email' => 'guidance-qa-'.$role.'@example.invalid'], ['name' => 'Guidance QA '.$role, 'password' => Hash::make('QA-Guidance-2026!')]);
$user->forceFill(['email_verified_at' => now()])->save();
}
$manager = User::where('email', 'guidance-qa-manager@example.invalid')->firstOrFail();
$request = Request::create('/management/balcao/servicos', 'POST', ['code' => 'project-preparation', 'confirm' => true]);
$request->setUserResolver(fn () => $manager);
app(VirtualDeskInstallationController::class)->publishService($request);
if ($v2) {
require $root.'/tools/investmoz-v2-qa-fixtures.php';
}
echo "QA fixtures seeded; no active database connection.\n";
exit;
}
if (PHP_SAPI === 'cli' && ($argv[1] ?? '') === 'evidence') {
if ($v2) {
throw new RuntimeException('V2 evidence must be produced by the checks, not asserted by a seed command.');
}
$evidence = ['passed' => true, 'database' => $identity->name, 'port' => (int) $identity->port, 'code_hash' => app(VirtualDeskInstallation::class)->fingerprint(), 'recorded_at' => gmdate('c'), 'checks' => ['PHPUnit feature and regression suite', 'Frontend deterministic calculator tests', 'TypeScript', 'PHPStan', 'Production build', 'Authenticated local browser cycle']];
file_put_contents($private.'/guidance-qa-evidence.json', json_encode($evidence, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo "QA evidence recorded for this code fingerprint.\n";
exit;
}
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
$asset = realpath($root.'/public'.$path);
$public = realpath($root.'/public');
if ($path !== '/' && $asset && $public && str_starts_with($asset, $public.DIRECTORY_SEPARATOR) && is_file($asset)) {
return false;
}
header('X-Investmoz-QA-Target: '.$identity->name.':'.$identity->port);
$app->handleRequest(Request::capture());
+33 -13
View File
@@ -1,11 +1,16 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$active = Illuminate\Support\Facades\DB::connection();
$app->make(Kernel::class)->bootstrap();
$active = DB::connection();
$identity = $active->selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'investemoz' || (int) $identity->port !== 5432) throw new RuntimeException('Unexpected active backup target.');
if ($identity->database !== 'investemoz' || (int) $identity->port !== 5432) {
throw new RuntimeException('Unexpected active backup target.');
}
$directory = storage_path('app/private/partnership-exchange/backup-'.date('Ymd-His'));
mkdir($directory, 0700, true);
$dump = $directory.'/database.dump';
@@ -13,11 +18,18 @@ $qaName = 'partnership_restore_'.date('Ymd_His').'_test';
$bin = 'C:/Program Files/PostgreSQL/17/bin/';
$run = function (array $command, array $environment = []) {
$process = proc_open($command, [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, [...getenv(), ...$environment]);
if (! is_resource($process)) throw new RuntimeException('Backup process unavailable.');
if (! is_resource($process)) {
throw new RuntimeException('Backup process unavailable.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]); fclose($pipes[1]);
$errors = stream_get_contents($pipes[2]); fclose($pipes[2]);
if (proc_close($process) !== 0) throw new RuntimeException('Backup/restore command failed: '.$errors);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
if (proc_close($process) !== 0) {
throw new RuntimeException('Backup/restore command failed: '.$errors);
}
return $output;
};
$proof = $active->transaction(function () use ($active, $run, $bin, $qaName, $dump, $identity) {
@@ -27,18 +39,26 @@ $proof = $active->transaction(function () use ($active, $run, $bin, $qaName, $du
$run([$bin.'createdb.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'postgres', $qaName], ['PGPASSWORD' => '']);
$run([$bin.'pg_restore.exe', '-h', '127.0.0.1', '-p', '55441', '-U', 'postgres', '-d', $qaName, '--exit-on-error', '--no-owner', '--no-privileges', $dump], ['PGPASSWORD' => '']);
config(['database.connections.partnership_restore' => [...config('database.connections.pgsql'), 'host' => '127.0.0.1', 'port' => 55441, 'database' => $qaName, 'username' => 'postgres', 'password' => '', 'url' => null]]);
$restore = Illuminate\Support\Facades\DB::connection('partnership_restore');
$restore = DB::connection('partnership_restore');
$restored = $restore->selectOne('select current_database() as database, inet_server_port() as port');
if ($restored->database !== $qaName || ! str_ends_with($qaName, '_test') || (int) $restored->port !== 55441) throw new RuntimeException('QA identity rejected.');
$counts = []; $hashes = [];
if ($restored->database !== $qaName || ! str_ends_with($qaName, '_test') || (int) $restored->port !== 55441) {
throw new RuntimeException('QA identity rejected.');
}
$counts = [];
$hashes = [];
foreach ($active->select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
$name = $table->tablename;
$quoted = '"'.str_replace('"', '""', $name).'"';
$rows = fn ($connection) => array_map(fn ($row) => $row->value, $connection->select('select row_to_json(t)::text as value from public.'.$quoted.' as t order by row_to_json(t)::text'));
$a = $rows($active); $b = $rows($restore);
if ($a !== $b) throw new RuntimeException('Restored contents differ: '.$name);
$counts[$name] = count($a); $hashes[$name] = hash('sha256', implode("\n", $a));
$a = $rows($active);
$b = $rows($restore);
if ($a !== $b) {
throw new RuntimeException('Restored contents differ: '.$name);
}
$counts[$name] = count($a);
$hashes[$name] = hash('sha256', implode("\n", $a));
}
return ['restore_verified' => true, 'verified_at' => now()->toIso8601String(), 'target' => $identity, 'restored_target' => $restored,
'dump_path' => $dump, 'sha256' => hash_file('sha256', $dump), 'table_counts' => $counts, 'table_hashes' => $hashes];
});
+317 -86
View File
@@ -1,86 +1,317 @@
const {chromium}=require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs=require('node:fs');const assert=require('node:assert/strict');
const base='http://127.0.0.1:18086';
const fixture=JSON.parse(fs.readFileSync('storage/app/private/anchor-project-reconciliation/qa-browser-fixture.json'));
(async()=>{
const browser=await chromium.launch({headless:true,executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
const errors=[];
async function login(role){const context=await browser.newContext();await context.route('**/*',r=>r.request().url().startsWith(base)?r.continue():r.abort());const page=await context.newPage();page.on('pageerror',e=>errors.push(e.message));await page.goto(base+'/login');await page.locator('input[type=email]').fill(`partnership-qa-${role}@example.invalid`);await page.locator('input[type=password]').fill('QA-Partnership-2026!');await page.locator('button[type=submit]').click();await page.waitForURL(url=>!url.pathname.startsWith('/login'));return page;}
try{
const owner=await login('owner'),candidate=await login('candidate'),moderator=await login('moderator');
const title='QA browser partnership '+Date.now();
await owner.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
await owner.getByRole('link',{name:'Propor parceria a partir deste registo',exact:true}).click();
await owner.getByLabel('Título',{exact:true}).fill(title);
await owner.getByLabel('Tipo de parceria',{exact:true}).selectOption('joint_venture');
await owner.getByLabel('Resumo público',{exact:true}).fill('QA partnership: source references and local workflow');
await owner.getByLabel('O que oferece',{exact:true}).fill('Synthetic QA production capacity');
await owner.getByLabel('O que procura',{exact:true}).fill('Synthetic QA technology partner');
await owner.getByLabel(/Autorizo submeter/).check();
await owner.getByRole('button',{name:'Guardar rascunho',exact:true}).click();
await owner.waitForURL(/\/parcerias\/\d+\/editar$/);
const partnershipId=Number(new URL(owner.url()).pathname.split('/')[2]);
await owner.reload();assert.equal(await owner.getByLabel('Título',{exact:true}).inputValue(),title);
await owner.getByRole('link',{name:'Pré-visualizar e submeter',exact:true}).click();
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA source checked and disclosure requested');
await owner.getByRole('button',{name:'Submeter para publicação',exact:true}).click();
await owner.getByText('Estado: Submetida.',{exact:false}).waitFor();
await moderator.goto(base+'/parcerias/'+partnershipId);
await moderator.getByLabel('Motivo da ação',{exact:true}).fill('QA reviewed public content; no organization verification presumed');
await moderator.getByRole('button',{name:'Publicar',exact:true}).click();
await moderator.getByText('Estado: Publicada.',{exact:false}).waitFor();
await candidate.goto(base+'/parcerias/'+partnershipId);
await candidate.getByLabel('Proposta curta',{exact:true}).fill('QA candidate contribution');
await candidate.getByLabel('Capacidade disponível',{exact:true}).fill('Declared synthetic QA capacity');
await candidate.getByLabel(/Autorizo a partilha desta candidatura/).check();
await candidate.getByRole('button',{name:'Guardar interesse',exact:true}).click();
await candidate.getByRole('heading',{name:/Candidatura \d+/}).waitFor();
await owner.reload();
await owner.getByLabel('Motivo da decisão ou pedido de esclarecimento',{exact:true}).fill('QA shortlist; unknown evidence remains pending');
await owner.getByRole('button',{name:'Adicionar à lista curta',exact:true}).click();
await owner.getByRole('heading',{name:/Candidatura \d+ · Lista curta/}).waitFor();
await owner.getByLabel('Motivo da decisão ou pedido de esclarecimento',{exact:true}).fill('QA private negotiation authorized');
await owner.getByRole('button',{name:'Abrir negociação',exact:true}).click();
await owner.getByRole('link',{name:'Abrir conexão privada',exact:true}).click();
const roomId=Number(new URL(owner.url()).pathname.split('/').pop());
await owner.getByLabel('Mensagem privada',{exact:true}).fill('QA private discussion');
await owner.getByRole('button',{name:'Enviar mensagem',exact:true}).click();
await owner.getByText('QA private discussion',{exact:true}).waitFor();
await owner.getByLabel('Título do instrumento',{exact:true}).fill('QA pilot agreement');
await owner.getByLabel('Condições e plano de valor',{exact:true}).fill('Parties, deliverables, responsibilities, risk and exit conditions. Synthetic QA only.');
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA terms recorded');
await owner.getByRole('button',{name:'Registar versão do acordo',exact:true}).click();
await owner.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).waitFor();
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA proponent acknowledgement');
await owner.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).click();
await candidate.goto(base+'/parcerias/salas/'+roomId);
await candidate.getByText('QA private discussion',{exact:true}).waitFor();
await candidate.getByLabel('Motivo da ação',{exact:true}).fill('QA candidate acknowledgement');
await candidate.getByRole('button',{name:'Confirmar pela minha parte',exact:true}).click();
await candidate.getByRole('button',{name:'Iniciar acompanhamento',exact:true}).waitFor();
await owner.reload();
await owner.getByLabel('Entregável',{exact:true}).fill('QA pilot delivery');
await owner.getByRole('button',{name:'Guardar marco',exact:true}).click();
await owner.getByRole('heading',{name:'Atualizar marco',exact:true}).waitFor();
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA start monitoring');
await owner.getByRole('button',{name:'Iniciar acompanhamento',exact:true}).click();
await owner.getByText('Estado da conexão: Em execução.',{exact:false}).waitFor();
const update=owner.getByRole('heading',{name:'Atualizar marco',exact:true}).locator('..');
await update.getByLabel('Estado',{exact:true}).selectOption('completed');
await update.getByLabel('Evidência ou referência do resultado',{exact:true}).fill('Synthetic QA deliverable evidence');
await update.getByRole('button',{name:'Guardar marco',exact:true}).click();
await owner.getByText('QA pilot delivery · Concluído · Prazo:',{exact:false}).waitFor();
assert.equal(await update.getByLabel('Estado',{exact:true}).inputValue(),'completed');
for(const width of [1440,390]){await owner.setViewportSize({width,height:1000});assert(await owner.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));await owner.screenshot({path:`docs/investmoz/partnerships/room-${width}.png`,fullPage:true});}
await owner.getByLabel('Motivo da ação',{exact:true}).fill('QA all milestones completed');
await owner.getByRole('button',{name:'Concluir após os marcos',exact:true}).click();
await owner.getByText('Estado da conexão: Concluída.',{exact:false}).waitFor();
await owner.goto(base+'/carteira/'+fixture.project_dossier,{waitUntil:'networkidle'});
await owner.getByRole('link',{name:title,exact:true}).waitFor();
await candidate.goto(base+'/parcerias?q='+encodeURIComponent(title));
await candidate.getByRole('link',{name:title,exact:true}).waitFor();
assert.deepEqual(errors,[]);
fs.writeFileSync('docs/investmoz/partnerships/browser-qa.json',JSON.stringify({target:'anchor_restore_20261007_test:55441',passed:true,partnershipId,roomId,draftRecovered:true,sourceBacklink:true,moderation:true,interest:true,shortlist:true,privateMessage:true,bilateralAgreement:true,milestoneCompleted:true,roomClosed:true,viewports:[1440,390],errors},null,2));
console.log('QA partnership browser passed: real forms, draft recovery, moderation, interest, shortlist, private room, bilateral agreement, milestone and source backlink.');
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const base = 'http://127.0.0.1:18086';
const fixture = JSON.parse(
fs.readFileSync(
'storage/app/private/anchor-project-reconciliation/qa-browser-fixture.json',
),
);
(async () => {
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
const errors = [];
async function login(role) {
const context = await browser.newContext();
await context.route('**/*', (r) =>
r.request().url().startsWith(base) ? r.continue() : r.abort(),
);
const page = await context.newPage();
page.on('pageerror', (e) => errors.push(e.message));
await page.goto(base + '/login');
await page
.locator('input[type=email]')
.fill(`partnership-qa-${role}@example.invalid`);
await page.locator('input[type=password]').fill('QA-Partnership-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
return page;
}
try {
const owner = await login('owner'),
candidate = await login('candidate'),
moderator = await login('moderator');
const title = 'QA browser partnership ' + Date.now();
await owner.goto(base + '/carteira/' + fixture.project_dossier, {
waitUntil: 'networkidle',
});
await owner
.getByRole('link', {
name: 'Propor parceria a partir deste registo',
exact: true,
})
.click();
await owner.getByLabel('Título', { exact: true }).fill(title);
await owner
.getByLabel('Tipo de parceria', { exact: true })
.selectOption('joint_venture');
await owner
.getByLabel('Resumo público', { exact: true })
.fill('QA partnership: source references and local workflow');
await owner
.getByLabel('O que oferece', { exact: true })
.fill('Synthetic QA production capacity');
await owner
.getByLabel('O que procura', { exact: true })
.fill('Synthetic QA technology partner');
await owner.getByLabel(/Autorizo submeter/).check();
await owner
.getByRole('button', { name: 'Guardar rascunho', exact: true })
.click();
await owner.waitForURL(/\/parcerias\/\d+\/editar$/);
const partnershipId = Number(
new URL(owner.url()).pathname.split('/')[2],
);
await owner.reload();
assert.equal(
await owner.getByLabel('Título', { exact: true }).inputValue(),
title,
);
await owner
.getByRole('link', {
name: 'Pré-visualizar e submeter',
exact: true,
})
.click();
await owner
.getByLabel('Motivo da ação', { exact: true })
.fill('QA source checked and disclosure requested');
await owner
.getByRole('button', {
name: 'Submeter para publicação',
exact: true,
})
.click();
await owner.getByText('Estado: Submetida.', { exact: false }).waitFor();
await moderator.goto(base + '/parcerias/' + partnershipId);
await moderator
.getByLabel('Motivo da ação', { exact: true })
.fill(
'QA reviewed public content; no organization verification presumed',
);
await moderator
.getByRole('button', { name: 'Publicar', exact: true })
.click();
await moderator
.getByText('Estado: Publicada.', { exact: false })
.waitFor();
await candidate.goto(base + '/parcerias/' + partnershipId);
await candidate
.getByLabel('Proposta curta', { exact: true })
.fill('QA candidate contribution');
await candidate
.getByLabel('Capacidade disponível', { exact: true })
.fill('Declared synthetic QA capacity');
await candidate
.getByLabel(/Autorizo a partilha desta candidatura/)
.check();
await candidate
.getByRole('button', { name: 'Guardar interesse', exact: true })
.click();
await candidate
.getByRole('heading', { name: /Candidatura \d+/ })
.waitFor();
await owner.reload();
await owner
.getByLabel('Motivo da decisão ou pedido de esclarecimento', {
exact: true,
})
.fill('QA shortlist; unknown evidence remains pending');
await owner
.getByRole('button', {
name: 'Adicionar à lista curta',
exact: true,
})
.click();
await owner
.getByRole('heading', { name: /Candidatura \d+ · Lista curta/ })
.waitFor();
await owner
.getByLabel('Motivo da decisão ou pedido de esclarecimento', {
exact: true,
})
.fill('QA private negotiation authorized');
await owner
.getByRole('button', { name: 'Abrir negociação', exact: true })
.click();
await owner
.getByRole('link', { name: 'Abrir conexão privada', exact: true })
.click();
const roomId = Number(new URL(owner.url()).pathname.split('/').pop());
await owner
.getByLabel('Mensagem privada', { exact: true })
.fill('QA private discussion');
await owner
.getByRole('button', { name: 'Enviar mensagem', exact: true })
.click();
await owner
.getByText('QA private discussion', { exact: true })
.waitFor();
await owner
.getByLabel('Título do instrumento', { exact: true })
.fill('QA pilot agreement');
await owner
.getByLabel('Condições e plano de valor', { exact: true })
.fill(
'Parties, deliverables, responsibilities, risk and exit conditions. Synthetic QA only.',
);
await owner
.getByLabel('Motivo da ação', { exact: true })
.fill('QA terms recorded');
await owner
.getByRole('button', {
name: 'Registar versão do acordo',
exact: true,
})
.click();
await owner
.getByRole('button', {
name: 'Confirmar pela minha parte',
exact: true,
})
.waitFor();
await owner
.getByLabel('Motivo da ação', { exact: true })
.fill('QA proponent acknowledgement');
await owner
.getByRole('button', {
name: 'Confirmar pela minha parte',
exact: true,
})
.click();
await candidate.goto(base + '/parcerias/salas/' + roomId);
await candidate
.getByText('QA private discussion', { exact: true })
.waitFor();
await candidate
.getByLabel('Motivo da ação', { exact: true })
.fill('QA candidate acknowledgement');
await candidate
.getByRole('button', {
name: 'Confirmar pela minha parte',
exact: true,
})
.click();
await candidate
.getByRole('button', {
name: 'Iniciar acompanhamento',
exact: true,
})
.waitFor();
await owner.reload();
await owner
.getByLabel('Entregável', { exact: true })
.fill('QA pilot delivery');
await owner
.getByRole('button', { name: 'Guardar marco', exact: true })
.click();
await owner
.getByRole('heading', { name: 'Atualizar marco', exact: true })
.waitFor();
await owner
.getByLabel('Motivo da ação', { exact: true })
.fill('QA start monitoring');
await owner
.getByRole('button', {
name: 'Iniciar acompanhamento',
exact: true,
})
.click();
await owner
.getByText('Estado da conexão: Em execução.', { exact: false })
.waitFor();
const update = owner
.getByRole('heading', { name: 'Atualizar marco', exact: true })
.locator('..');
await update
.getByLabel('Estado', { exact: true })
.selectOption('completed');
await update
.getByLabel('Evidência ou referência do resultado', { exact: true })
.fill('Synthetic QA deliverable evidence');
await update
.getByRole('button', { name: 'Guardar marco', exact: true })
.click();
await owner
.getByText('QA pilot delivery · Concluído · Prazo:', {
exact: false,
})
.waitFor();
assert.equal(
await update.getByLabel('Estado', { exact: true }).inputValue(),
'completed',
);
for (const width of [1440, 390]) {
await owner.setViewportSize({ width, height: 1000 });
assert(
await owner.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
await owner.screenshot({
path: `docs/investmoz/partnerships/room-${width}.png`,
fullPage: true,
});
}
await owner
.getByLabel('Motivo da ação', { exact: true })
.fill('QA all milestones completed');
await owner
.getByRole('button', {
name: 'Concluir após os marcos',
exact: true,
})
.click();
await owner
.getByText('Estado da conexão: Concluída.', { exact: false })
.waitFor();
await owner.goto(base + '/carteira/' + fixture.project_dossier, {
waitUntil: 'networkidle',
});
await owner.getByRole('link', { name: title, exact: true }).waitFor();
await candidate.goto(
base + '/parcerias?q=' + encodeURIComponent(title),
);
await candidate
.getByRole('link', { name: title, exact: true })
.waitFor();
assert.deepEqual(errors, []);
fs.writeFileSync(
'docs/investmoz/partnerships/browser-qa.json',
JSON.stringify(
{
target: 'anchor_restore_20261007_test:55441',
passed: true,
partnershipId,
roomId,
draftRecovered: true,
sourceBacklink: true,
moderation: true,
interest: true,
shortlist: true,
privateMessage: true,
bilateralAgreement: true,
milestoneCompleted: true,
roomClosed: true,
viewports: [1440, 390],
errors,
},
null,
2,
),
);
console.log(
'QA partnership browser passed: real forms, draft recovery, moderation, interest, shortlist, private room, bilateral agreement, milestone and source backlink.',
);
} finally {
await browser.close();
}
})().catch((e) => {
console.error(e);
process.exitCode = 1;
});
+5 -2
View File
@@ -1,9 +1,12 @@
<?php
use App\Services\PartnershipInstallation;
use Illuminate\Contracts\Console\Kernel;
// Read-only against the active database. Evidence is written only to private files.
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$app->make(Kernel::class)->bootstrap();
$directory = storage_path('app/private/partnership-exchange');
$tests = json_decode(ltrim(file_get_contents($directory.'/qa-tests.json'), "\xEF\xBB\xBF"), true, 512, JSON_THROW_ON_ERROR);
$checks = json_decode(ltrim(file_get_contents($directory.'/qa-checks.json'), "\xEF\xBB\xBF"), true, 512, JSON_THROW_ON_ERROR);
@@ -12,7 +15,7 @@ if (($tests['result'] ?? '') !== 'passed' || ($tests['passed'] ?? 0) < 46 || ! (
|| ($browser['target'] ?? '') !== 'anchor_restore_20261007_test:55441' || ! ($checks['typescript'] ?? false) || ! ($checks['build'] ?? false)) {
throw new RuntimeException('QA evidence is incomplete.');
}
$installer = app(App\Services\PartnershipInstallation::class);
$installer = app(PartnershipInstallation::class);
$proof = json_decode(file_get_contents($directory.'/backup-proof.json'), true, 512, JSON_THROW_ON_ERROR);
if (! ($proof['restore_verified'] ?? false) || hash_file('sha256', $proof['dump_path']) !== $proof['sha256']) {
throw new RuntimeException('Verified restore proof or dump unavailable.');
+12 -5
View File
@@ -1,5 +1,12 @@
<?php
use App\Models\User;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync'] as $key => $value) {
putenv($key.'='.$value);
@@ -7,16 +14,16 @@ foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.
}
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$identity = Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
$app->make(Kernel::class)->bootstrap();
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
throw new RuntimeException('QA database identity rejected');
}
if (! Illuminate\Support\Facades\Schema::hasTable('partnership_interests')) {
Illuminate\Support\Facades\Artisan::call('migrate', ['--path' => 'database/migrations/2026_10_07_160000_extend_internal_partnership_exchange.php', '--force' => true]);
if (! Schema::hasTable('partnership_interests')) {
Artisan::call('migrate', ['--path' => 'database/migrations/2026_10_07_160000_extend_internal_partnership_exchange.php', '--force' => true]);
}
foreach (['owner', 'candidate', 'moderator'] as $role) {
$user = App\Models\User::firstOrCreate(['email' => 'partnership-qa-'.$role.'@example.invalid'], ['name' => 'Synthetic QA partnership '.$role, 'password' => Illuminate\Support\Facades\Hash::make('QA-Partnership-2026!')]);
$user = User::firstOrCreate(['email' => 'partnership-qa-'.$role.'@example.invalid'], ['name' => 'Synthetic QA partnership '.$role, 'password' => Hash::make('QA-Partnership-2026!')]);
$user->forceFill(['email_verified_at' => $role === 'moderator' ? now() : null])->save();
}
echo "Partnership migration and synthetic users prepared exclusively in isolated restored QA.\n";
+294 -43
View File
@@ -1,50 +1,301 @@
import fs from 'node:fs';
import crypto from 'node:crypto';
const dir='storage/app/private/anchor-project-reconciliation/';
const inventory=JSON.parse(fs.readFileSync(dir+fs.readdirSync(dir).filter(f=>f.startsWith('inventory')).sort().at(-1),'utf8'));
const texts=JSON.parse(fs.readFileSync(dir+'source-texts.json','utf8'));
const normalize=s=>s.normalize('NFD').replace(/\p{Diacritic}/gu,'').toLowerCase().trim();
const provincePlan={A03:[['Nampula','secondary'],['Cabo Delgado','secondary'],['Niassa','secondary'],['Tete','secondary'],['Zambezia','impact']],A04:[['Nampula','primary']],A05:[['Nampula','secondary'],['Cabo Delgado','secondary']],A06:[['Tete','secondary'],['Manica','secondary'],['Zambezia','secondary'],['Sofala','secondary']],A07:[['Sofala','primary'],['Manica','secondary'],['Tete','secondary']],A08:[['Zambezia','primary']],A09:[['Zambezia','primary']],A10:[['Tete','primary']],A11:[['Tete','secondary'],['Zambezia','secondary']],A12:[['Zambezia','primary']],A13:[['Inhambane','primary']],A14:[['Gaza','primary']],A15:[['Maputo Província','primary']]};
const plan={schema:1,target:inventory.target,inventory_file:fs.readdirSync(dir).filter(f=>f.startsWith('inventory')).sort().at(-1),created_at:new Date().toISOString(),locations:[],memberships:[],prepared_opportunities:[],pending:[]};
for(const project of inventory.projects.filter(p=>/^A\d{2}$/.test(p.code))){
const dossier=inventory.dossiers.find(d=>d.project_id===project.id&&!d.deleted_at);
const content=JSON.parse(dossier.content);
for(const [name,role]of provincePlan[project.code]??[]){
const nodes=inventory.locations.filter(l=>l.location_type==='province'&&!l.deleted_at&&normalize(l.name)===normalize(name));
if(nodes.length!==1){plan.pending.push({code:project.code,reason:'Identidade territorial ambígua',name});continue;}
const location=nodes[0];
plan.locations.push({project_id:project.id,code:project.code,dossier_id:dossier.id,dossier_version:dossier.version_no,geo_location_id:location.id,name:location.name,role,source_reference:dossier.source,source_quote:content.location,reason:role==='impact'?'Referência parcial ao Norte da Zambézia; não representa cobertura integral da província':'Província explicitamente identificada na localização do dossier autorizado',expected_project_version:project.version_no,data_classification:dossier.publication_status==='published'?'public':'internal',existing:inventory.project_locations.some(l=>!l.deleted_at&&l.project_id===project.id&&l.geo_location_id===location.id&&l.role===role)});
}
if(['A01','A02'].includes(project.code))plan.pending.push({code:project.code,reason:'Âmbito nacional sem implantação individual ou traçado documentado; não atribuir um ponto único.'});
plan.pending.push({code:project.code,reason:'Coordenadas, posto administrativo e localidade sem fonte exacta. Cidade/zona não convertida automaticamente em distrito.'});
const dir = 'storage/app/private/anchor-project-reconciliation/';
const inventory = JSON.parse(
fs.readFileSync(
dir +
fs
.readdirSync(dir)
.filter((f) => f.startsWith('inventory'))
.sort()
.at(-1),
'utf8',
),
);
const texts = JSON.parse(fs.readFileSync(dir + 'source-texts.json', 'utf8'));
const normalize = (s) =>
s
.normalize('NFD')
.replace(/\p{Diacritic}/gu, '')
.toLowerCase()
.trim();
const provincePlan = {
A03: [
['Nampula', 'secondary'],
['Cabo Delgado', 'secondary'],
['Niassa', 'secondary'],
['Tete', 'secondary'],
['Zambezia', 'impact'],
],
A04: [['Nampula', 'primary']],
A05: [
['Nampula', 'secondary'],
['Cabo Delgado', 'secondary'],
],
A06: [
['Tete', 'secondary'],
['Manica', 'secondary'],
['Zambezia', 'secondary'],
['Sofala', 'secondary'],
],
A07: [
['Sofala', 'primary'],
['Manica', 'secondary'],
['Tete', 'secondary'],
],
A08: [['Zambezia', 'primary']],
A09: [['Zambezia', 'primary']],
A10: [['Tete', 'primary']],
A11: [
['Tete', 'secondary'],
['Zambezia', 'secondary'],
],
A12: [['Zambezia', 'primary']],
A13: [['Inhambane', 'primary']],
A14: [['Gaza', 'primary']],
A15: [['Maputo Província', 'primary']],
};
const plan = {
schema: 1,
target: inventory.target,
inventory_file: fs
.readdirSync(dir)
.filter((f) => f.startsWith('inventory'))
.sort()
.at(-1),
created_at: new Date().toISOString(),
locations: [],
memberships: [],
prepared_opportunities: [],
pending: [],
};
for (const project of inventory.projects.filter((p) =>
/^A\d{2}$/.test(p.code),
)) {
const dossier = inventory.dossiers.find(
(d) => d.project_id === project.id && !d.deleted_at,
);
const content = JSON.parse(dossier.content);
for (const [name, role] of provincePlan[project.code] ?? []) {
const nodes = inventory.locations.filter(
(l) =>
l.location_type === 'province' &&
!l.deleted_at &&
normalize(l.name) === normalize(name),
);
if (nodes.length !== 1) {
plan.pending.push({
code: project.code,
reason: 'Identidade territorial ambígua',
name,
});
continue;
}
const location = nodes[0];
plan.locations.push({
project_id: project.id,
code: project.code,
dossier_id: dossier.id,
dossier_version: dossier.version_no,
geo_location_id: location.id,
name: location.name,
role,
source_reference: dossier.source,
source_quote: content.location,
reason:
role === 'impact'
? 'Referência parcial ao Norte da Zambézia; não representa cobertura integral da província'
: 'Província explicitamente identificada na localização do dossier autorizado',
expected_project_version: project.version_no,
data_classification:
dossier.publication_status === 'published'
? 'public'
: 'internal',
existing: inventory.project_locations.some(
(l) =>
!l.deleted_at &&
l.project_id === project.id &&
l.geo_location_id === location.id &&
l.role === role,
),
});
}
if (['A01', 'A02'].includes(project.code))
plan.pending.push({
code: project.code,
reason: 'Âmbito nacional sem implantação individual ou traçado documentado; não atribuir um ponto único.',
});
plan.pending.push({
code: project.code,
reason: 'Coordenadas, posto administrativo e localidade sem fonte exacta. Cidade/zona não convertida automaticamente em distrito.',
});
}
// Districts expressly called districts in the source; city names and ambiguous settlements remain text.
for(const [code,province,districts,role]of [['A15','Maputo Província',['Boane','Moamba','Namaacha'],'impact'],['A11','Zambezia',['Nicoadala'],'secondary']]){
const p=inventory.projects.find(p=>p.code===code),d=inventory.dossiers.find(d=>d.project_id===p.id),base=plan.locations.find(l=>l.code===code&&normalize(l.name)===normalize(province));
for(const name of districts){const nodes=inventory.locations.filter(l=>l.location_type==='district'&&l.parent_id===base.geo_location_id&&!l.deleted_at&&normalize(l.name)===normalize(name));if(nodes.length!==1){plan.pending.push({code,reason:'Distrito sem correspondência exacta e única',name});continue;}plan.locations.push({...base,geo_location_id:nodes[0].id,name:nodes[0].name,role,reason:'Distrito explicitamente identificado na fonte; sem inferir posto, localidade ou coordenadas.',existing:inventory.project_locations.some(l=>!l.deleted_at&&l.project_id===p.id&&l.geo_location_id===nodes[0].id&&l.role===role)});}
for (const [code, province, districts, role] of [
['A15', 'Maputo Província', ['Boane', 'Moamba', 'Namaacha'], 'impact'],
['A11', 'Zambezia', ['Nicoadala'], 'secondary'],
]) {
const p = inventory.projects.find((p) => p.code === code),
_d = inventory.dossiers.find((d) => d.project_id === p.id),
base = plan.locations.find(
(l) => l.code === code && normalize(l.name) === normalize(province),
);
for (const name of districts) {
const nodes = inventory.locations.filter(
(l) =>
l.location_type === 'district' &&
l.parent_id === base.geo_location_id &&
!l.deleted_at &&
normalize(l.name) === normalize(name),
);
if (nodes.length !== 1) {
plan.pending.push({
code,
reason: 'Distrito sem correspondência exacta e única',
name,
});
continue;
}
plan.locations.push({
...base,
geo_location_id: nodes[0].id,
name: nodes[0].name,
role,
reason: 'Distrito explicitamente identificado na fonte; sem inferir posto, localidade ou coordenadas.',
existing: inventory.project_locations.some(
(l) =>
!l.deleted_at &&
l.project_id === p.id &&
l.geo_location_id === nodes[0].id &&
l.role === role,
),
});
}
}
for(const cluster of inventory.clusters){
const dossier=inventory.dossiers.find(d=>d.cluster_id===cluster.id&&!d.deleted_at),content=JSON.parse(dossier.content);
for(const code of [...new Set(content.anchors.match(/\bA\d{2}\b/g)??[])]){
const project=inventory.projects.find(p=>p.code===code&&!p.deleted_at);if(!project){plan.pending.push({code:cluster.code,project:code,reason:'Projecto citado sem cadastro'});continue;}
const existing=inventory.cluster_projects.find(l=>l.project_id===project.id&&l.cluster_id===cluster.id&&!l.deleted_at);
plan.memberships.push({cluster_id:cluster.id,cluster_code:cluster.code,project_id:project.id,project_code:code,role:'anchor',existing_id:existing?.id??null,existing_version:existing?.version_no??0,dossier_id:dossier.id,dossier_version:dossier.version_no,source_reference:dossier.source,source_quote:content.anchors,reason:'Código exacto do projecto citado no dossier do cluster; relação de planeamento, sem confirmar pertença jurídica',action:existing?'present_existing':'insert_missing'});
}
plan.pending.push({code:cluster.code,reason:'Área própria de abrangência não individualizada na fonte; locais dos membros não definem o perímetro do cluster.'});
if(!inventory.value_chains.some(v=>v.cluster_id===cluster.id&&!v.deleted_at))plan.pending.push({code:cluster.code,reason:'Sem elos cadastrados em value_chains. Actividades e lacunas do dossier permanecem consultáveis; não foram convertidas em cadeias confirmadas.'});
for (const cluster of inventory.clusters) {
const dossier = inventory.dossiers.find(
(d) => d.cluster_id === cluster.id && !d.deleted_at,
),
content = JSON.parse(dossier.content);
for (const code of new Set(content.anchors.match(/\bA\d{2}\b/g) ?? [])) {
const project = inventory.projects.find(
(p) => p.code === code && !p.deleted_at,
);
if (!project) {
plan.pending.push({
code: cluster.code,
project: code,
reason: 'Projecto citado sem cadastro',
});
continue;
}
const existing = inventory.cluster_projects.find(
(l) =>
l.project_id === project.id &&
l.cluster_id === cluster.id &&
!l.deleted_at,
);
plan.memberships.push({
cluster_id: cluster.id,
cluster_code: cluster.code,
project_id: project.id,
project_code: code,
role: 'anchor',
existing_id: existing?.id ?? null,
existing_version: existing?.version_no ?? 0,
dossier_id: dossier.id,
dossier_version: dossier.version_no,
source_reference: dossier.source,
source_quote: content.anchors,
reason: 'Código exacto do projecto citado no dossier do cluster; relação de planeamento, sem confirmar pertença jurídica',
action: existing ? 'present_existing' : 'insert_missing',
});
}
plan.pending.push({
code: cluster.code,
reason: 'Área própria de abrangência não individualizada na fonte; locais dos membros não definem o perímetro do cluster.',
});
if (
!inventory.value_chains.some(
(v) => v.cluster_id === cluster.id && !v.deleted_at,
)
)
plan.pending.push({
code: cluster.code,
reason: 'Sem elos cadastrados em value_chains. Actividades e lacunas do dossier permanecem consultáveis; não foram convertidas em cadeias confirmadas.',
});
}
const source=texts.find(t=>t.path.endsWith('projectos.docx'));
for(const [index,table]of source.tables.entries()){
if(!table[0].includes('Localização'))continue;
const anchor=table[1]?.[0]?.trim();
const conflict=index<3; // caption/project identifier conflict documented in original, never silently renumbered.
for(const [rowIndex,row]of table.entries()){
if(rowIndex<2||!row[0]?.trim())continue;
const original=row[0].trim(),project=inventory.projects.find(p=>p.code===anchor),ref=original;
const existing=inventory.opportunities.find(o=>o.reference===ref);
plan.prepared_opportunities.push({reference:ref,source_identifier:row[0],title:row[1],summary:row[3],description:row.map((cell,i)=>`${table[0][i]}: ${cell}`).join('\n'),location_text:row[4],cost_text:row[5],horizon_text:row[6],source_reference:`${source.path}; SHA256 ${source.sha256}; tabela ${index+1}, linha ${rowIndex+1}`,source_sha256:source.sha256,source_table:index+1,source_row:rowIndex+1,source_cells:row,status:'draft',project_id:conflict?null:project?.id??null,project_code:conflict?null:anchor,existing_id:existing?.id??null,identity_status:conflict?'conflict_caption_anchor_code':'explicit_source_code',unknown:['sector_id','promotor confirmado','maturidade','coordenadas','títulos e disponibilidade','interpretação monetária'],reason:conflict?'Código da âncora e legenda da tabela incompatíveis com os dossiers; não associar nem renumerar':'Componente identificado por código exacto na tabela da âncora; preparado sem publicar, sem associação automática aos clusters'});
}
const source = texts.find((t) => t.path.endsWith('projectos.docx'));
for (const [index, table] of source.tables.entries()) {
if (!table[0].includes('Localização')) continue;
const anchor = table[1]?.[0]?.trim();
const conflict = index < 3; // caption/project identifier conflict documented in original, never silently renumbered.
for (const [rowIndex, row] of table.entries()) {
if (rowIndex < 2 || !row[0]?.trim()) continue;
const original = row[0].trim(),
project = inventory.projects.find((p) => p.code === anchor),
ref = original;
const existing = inventory.opportunities.find(
(o) => o.reference === ref,
);
plan.prepared_opportunities.push({
reference: ref,
source_identifier: row[0],
title: row[1],
summary: row[3],
description: row
.map((cell, i) => `${table[0][i]}: ${cell}`)
.join('\n'),
location_text: row[4],
cost_text: row[5],
horizon_text: row[6],
source_reference: `${source.path}; SHA256 ${source.sha256}; tabela ${index + 1}, linha ${rowIndex + 1}`,
source_sha256: source.sha256,
source_table: index + 1,
source_row: rowIndex + 1,
source_cells: row,
status: 'draft',
project_id: conflict ? null : (project?.id ?? null),
project_code: conflict ? null : anchor,
existing_id: existing?.id ?? null,
identity_status: conflict
? 'conflict_caption_anchor_code'
: 'explicit_source_code',
unknown: [
'sector_id',
'promotor confirmado',
'maturidade',
'coordenadas',
'títulos e disponibilidade',
'interpretação monetária',
],
reason: conflict
? 'Código da âncora e legenda da tabela incompatíveis com os dossiers; não associar nem renumerar'
: 'Componente identificado por código exacto na tabela da âncora; preparado sem publicar, sem associação automática aos clusters',
});
}
}
plan.pending.push({code:'opportunity_projects',reason:'As seis oportunidades existentes não têm código documental que as associe às âncoras. Nenhuma associação inferida por nome ou sector.'});
const data=JSON.stringify(plan,null,2);fs.writeFileSync(dir+'preview.json',data);fs.writeFileSync(dir+'preview.sha256',crypto.createHash('sha256').update(data).digest('hex'));
console.log(JSON.stringify({locations:plan.locations.length,projectsWithLocations:new Set(plan.locations.map(l=>l.code)).size,memberships:plan.memberships.length,existingMemberships:plan.memberships.filter(l=>l.existing_id).length,prepared:plan.prepared_opportunities.length,identityConflicts:plan.prepared_opportunities.filter(o=>o.identity_status.startsWith('conflict')).length,pending:plan.pending.length}));
plan.pending.push({
code: 'opportunity_projects',
reason: 'As seis oportunidades existentes não têm código documental que as associe às âncoras. Nenhuma associação inferida por nome ou sector.',
});
const data = JSON.stringify(plan, null, 2);
fs.writeFileSync(dir + 'preview.json', data);
fs.writeFileSync(
dir + 'preview.sha256',
crypto.createHash('sha256').update(data).digest('hex'),
);
console.log(
JSON.stringify({
locations: plan.locations.length,
projectsWithLocations: new Set(plan.locations.map((l) => l.code)).size,
memberships: plan.memberships.length,
existingMemberships: plan.memberships.filter((l) => l.existing_id)
.length,
prepared: plan.prepared_opportunities.length,
identityConflicts: plan.prepared_opportunities.filter((o) =>
o.identity_status.startsWith('conflict'),
).length,
pending: plan.pending.length,
}),
);
+36 -19
View File
@@ -1,27 +1,44 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Vite;
// QA-only HTTP harness: fixed isolated restored database; never use artisan serve for this test.
$root = dirname(__DIR__);
foreach (['APP_ENV'=>'testing','APP_DEBUG'=>'true','DB_CONNECTION'=>'pgsql','DB_HOST'=>'127.0.0.1','DB_PORT'=>'55441',
'DB_DATABASE'=>'anchor_restore_20261007_test','DB_USERNAME'=>'postgres','DB_PASSWORD'=>'','DB_URL'=>'',
'QUEUE_CONNECTION'=>'sync','SESSION_DRIVER'=>'file','SESSION_COOKIE'=>'anchor_relationship_qa','CACHE_STORE'=>'array',
'PORTAL_MANAGER_EMAILS'=>'relationship-qa@example.invalid,partnership-qa-moderator@example.invalid','MAIL_MAILER'=>'array'] as $key=>$value) {
putenv($key.'='.$value); $_ENV[$key]=$value; $_SERVER[$key]=$value;
foreach (['APP_ENV' => 'testing', 'APP_DEBUG' => 'true', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => '',
'QUEUE_CONNECTION' => 'sync', 'SESSION_DRIVER' => 'file', 'SESSION_COOKIE' => 'anchor_relationship_qa', 'CACHE_STORE' => 'array',
'PORTAL_MANAGER_EMAILS' => 'relationship-qa@example.invalid,partnership-qa-moderator@example.invalid', 'MAIL_MAILER' => 'array'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
if ($path !== '/' && is_file($root.'/public'.$path)) {
return false;
}
$path=rawurldecode(parse_url($_SERVER['REQUEST_URI']??'/',PHP_URL_PATH)?:'/');
if ($path!=='/' && is_file($root.'/public'.$path)) return false;
require_once $root.'/vendor/autoload.php';
$app=require $root.'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$connection=config('database.connections.'.config('database.default'));
if (($connection['database']??null)!=='anchor_restore_20261007_test' || (string)($connection['port']??'')!=='55441'
|| ($connection['host']??null)!=='127.0.0.1' || !in_array($connection['url']??null,[null,''],true)) {http_response_code(503);exit('QA target rejected');}
$identity=Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database!=='anchor_restore_20261007_test'||(int)$identity->port!==55441){http_response_code(503);exit('QA connected identity rejected');}
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$connection = config('database.connections.'.config('database.default'));
if (($connection['database'] ?? null) !== 'anchor_restore_20261007_test' || (string) ($connection['port'] ?? '') !== '55441'
|| ($connection['host'] ?? null) !== '127.0.0.1' || ! in_array($connection['url'] ?? null, [null, ''], true)) {
http_response_code(503);
exit('QA target rejected');
}
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
http_response_code(503);
exit('QA connected identity rejected');
}
$planDirectory = getenv('RELATIONSHIP_QA_PLAN') === 'territorial' ? 'qa-territorial-preview' : 'qa-preview';
config(['inertia.ssr.enabled'=>false,'session.files'=>$root.'/storage/framework/anchor-qa-sessions',
'investment.repair_directory'=>$root.'/storage/app/private/anchor-project-reconciliation/'.$planDirectory]);
if(!is_dir(config('session.files')))mkdir(config('session.files'),0700,true);
Illuminate\Support\Facades\Vite::useHotFile($root.'/storage/framework/anchor-qa-hot-file');
config(['inertia.ssr.enabled' => false, 'session.files' => $root.'/storage/framework/anchor-qa-sessions',
'investment.repair_directory' => $root.'/storage/app/private/anchor-project-reconciliation/'.$planDirectory]);
if (! is_dir(config('session.files'))) {
mkdir(config('session.files'), 0700, true);
}
Vite::useHotFile($root.'/storage/framework/anchor-qa-hot-file');
header('X-Investmoz-QA-Target: '.$identity->database.':'.$identity->port);
$app->handleRequest(Illuminate\Http\Request::capture());
$app->handleRequest(Request::capture());
+94 -52
View File
@@ -1,60 +1,102 @@
<?php
foreach (['APP_ENV'=>'testing','DB_CONNECTION'=>'pgsql','DB_HOST'=>'127.0.0.1','DB_PORT'=>'55441','DB_DATABASE'=>'anchor_restore_20261007_test','DB_USERNAME'=>'postgres','DB_PASSWORD'=>'','DB_URL'=>''] as $key=>$value) {
putenv($key.'='.$value); $_ENV[$key]=$value; $_SERVER[$key]=$value;
use App\Models\EconomicCluster;
use App\Models\InvestmentDossier;
use App\Models\Opportunity;
use App\Models\Project;
use App\Models\Sector;
use App\Models\User;
use App\Models\ValueChain;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441', 'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => ''] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
require dirname(__DIR__).'/vendor/autoload.php';
$app=require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db=Illuminate\Support\Facades\DB::connection();
if ($db->getDatabaseName()!=='anchor_restore_20261007_test'||(string)$db->getConfig('port')!=='55441'||$db->getConfig('host')!=='127.0.0.1')throw new RuntimeException('QA target rejected before seed.');
$identity=$db->selectOne('select current_database() as database,inet_server_port() as port');
if($identity->database!=='anchor_restore_20261007_test'||(int)$identity->port!==55441)throw new RuntimeException('QA runtime identity rejected.');
$uuid=fn()=>(string)Illuminate\Support\Str::uuid();
$manifest=$db->transaction(function()use($db,$uuid){
$user=App\Models\User::firstOrCreate(['email'=>'relationship-qa@example.invalid'],['name'=>'Synthetic QA manager','email_verified_at'=>now(),'password'=>Illuminate\Support\Facades\Hash::make('QA-Relationship-2026!')]);
$user->forceFill(['email_verified_at'=>now()])->save();
$sector=App\Models\Sector::firstOrCreate(['slug'=>'qa-relationship'],['name'=>'Synthetic QA relationship sector','is_active'=>true]);
$parent=null;$ids=[];
foreach(['country','province','district','admin_post','locality']as$type){
$external='qa-relationship-'.$type;
$node=$db->table('geo_locations')->where('source_system','cartografia-workbook')->where('code',$external)->first();
$id=$node?->id??$uuid();
if(!$node)$db->table('geo_locations')->insert(['id'=>$id,'code'=>$external,'name'=>'QA '.$type,'location_type'=>$type,'parent_id'=>$parent,'data_classification'=>'public',
'source_system'=>'cartografia-workbook','external_id'=>'964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$external]);
$ids[$type]=$id;$parent=$id;
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
if ($db->getDatabaseName() !== 'anchor_restore_20261007_test' || (string) $db->getConfig('port') !== '55441' || $db->getConfig('host') !== '127.0.0.1') {
throw new RuntimeException('QA target rejected before seed.');
}
$identity = $db->selectOne('select current_database() as database,inet_server_port() as port');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
throw new RuntimeException('QA runtime identity rejected.');
}
$uuid = fn () => (string) Str::uuid();
$manifest = $db->transaction(function () use ($db, $uuid) {
$user = User::firstOrCreate(['email' => 'relationship-qa@example.invalid'], ['name' => 'Synthetic QA manager', 'email_verified_at' => now(), 'password' => Hash::make('QA-Relationship-2026!')]);
$user->forceFill(['email_verified_at' => now()])->save();
$sector = Sector::firstOrCreate(['slug' => 'qa-relationship'], ['name' => 'Synthetic QA relationship sector', 'is_active' => true]);
$parent = null;
$ids = [];
foreach (['country', 'province', 'district', 'admin_post', 'locality'] as $type) {
$external = 'qa-relationship-'.$type;
$node = $db->table('geo_locations')->where('source_system', 'cartografia-workbook')->where('code', $external)->first();
$id = $node?->id ?? $uuid();
if (! $node) {
$db->table('geo_locations')->insert(['id' => $id, 'code' => $external, 'name' => 'QA '.$type, 'location_type' => $type, 'parent_id' => $parent, 'data_classification' => 'public',
'source_system' => 'cartografia-workbook', 'external_id' => '964a187ad32ea553b9e112cd159caa90b900050c42b7329594a75bcd798a96ff:'.$external]);
}
$ids[$type] = $id;
$parent = $id;
}
$projects=[];$dossiers=[];
foreach([1,2]as$index){
$project=App\Models\Project::firstOrCreate(['code'=>'QA-ANCHOR-'.$index],['name'=>'Synthetic QA anchor '.$index,'source_system'=>'qa-relationship','status'=>'planned','data_classification'=>'public']);
$dossier=App\Models\InvestmentDossier::firstOrCreate(['project_id'=>$project->id],['title'=>$project->name,'source'=>'Synthetic browser QA fixture; no operational coordinates',
'content'=>['location'=>'QA province / district / admin_post / locality','description'=>'Synthetic project with documented QA fixture site'],'publication_status'=>'published','published_at'=>now(),
'approval_basis'=>'document_owner','approval_evidence'=>'Synthetic QA disclosure fixture only']);
$site=$db->table('geo_locations')->where('code','qa-anchor-site-'.$index)->first();$siteId=$site?->id??$uuid();
if(!$site)$db->table('geo_locations')->insert(['id'=>$siteId,'code'=>'qa-anchor-site-'.$index,'name'=>'QA documented site '.$index,'location_type'=>'site','parent_id'=>$parent,'data_classification'=>'public','source_system'=>'qa-relationship']);
if(!$db->table('project_locations')->where('project_id',$project->id)->where('geo_location_id',$siteId)->exists())$db->table('project_locations')->insert(['id'=>$uuid(),'project_id'=>$project->id,'geo_location_id'=>$siteId,'role'=>$index===1?'primary':'secondary','data_classification'=>'public','source_system'=>'qa-relationship']);
if(!$db->table('geo_geometries')->where('geo_location_id',$siteId)->exists())$db->table('geo_geometries')->insert(['id'=>$uuid(),'geo_location_id'=>$siteId,'geometry_type'=>'point','data_classification'=>'public','source_system'=>'synthetic QA source',
'geom'=>Illuminate\Support\Facades\DB::raw('ST_SetSRID(ST_MakePoint('.(32.4+$index/10).','.(-25.8-$index/10).'),4326)')]);
$projects[]=$project;$dossiers[]=$dossier;
$projects = [];
$dossiers = [];
foreach ([1, 2] as $index) {
$project = Project::firstOrCreate(['code' => 'QA-ANCHOR-'.$index], ['name' => 'Synthetic QA anchor '.$index, 'source_system' => 'qa-relationship', 'status' => 'planned', 'data_classification' => 'public']);
$dossier = InvestmentDossier::firstOrCreate(['project_id' => $project->id], ['title' => $project->name, 'source' => 'Synthetic browser QA fixture; no operational coordinates',
'content' => ['location' => 'QA province / district / admin_post / locality', 'description' => 'Synthetic project with documented QA fixture site'], 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA disclosure fixture only']);
$site = $db->table('geo_locations')->where('code', 'qa-anchor-site-'.$index)->first();
$siteId = $site?->id ?? $uuid();
if (! $site) {
$db->table('geo_locations')->insert(['id' => $siteId, 'code' => 'qa-anchor-site-'.$index, 'name' => 'QA documented site '.$index, 'location_type' => 'site', 'parent_id' => $parent, 'data_classification' => 'public', 'source_system' => 'qa-relationship']);
}
if (! $db->table('project_locations')->where('project_id', $project->id)->where('geo_location_id', $siteId)->exists()) {
$db->table('project_locations')->insert(['id' => $uuid(), 'project_id' => $project->id, 'geo_location_id' => $siteId, 'role' => $index === 1 ? 'primary' : 'secondary', 'data_classification' => 'public', 'source_system' => 'qa-relationship']);
}
if (! $db->table('geo_geometries')->where('geo_location_id', $siteId)->exists()) {
$db->table('geo_geometries')->insert(['id' => $uuid(), 'geo_location_id' => $siteId, 'geometry_type' => 'point', 'data_classification' => 'public', 'source_system' => 'synthetic QA source',
'geom' => DB::raw('ST_SetSRID(ST_MakePoint('.(32.4 + $index / 10).','.(-25.8 - $index / 10).'),4326)')]);
}
$projects[] = $project;
$dossiers[] = $dossier;
}
$cluster=App\Models\EconomicCluster::firstOrCreate(['code'=>'QA-REL-CLU'],['name'=>'Synthetic QA multi-site cluster','sector'=>'QA','status'=>'planned','data_classification'=>'public']);
$clusterDossier=App\Models\InvestmentDossier::firstOrCreate(['cluster_id'=>$cluster->id],['title'=>$cluster->name,'source'=>'Synthetic QA member relationship source',
'content'=>['anchors'=>'QA-ANCHOR-1, QA-ANCHOR-2; coverage pending','gaps'=>'Synthetic QA chain gaps'],'publication_status'=>'published','published_at'=>now(),
'approval_basis'=>'document_owner','approval_evidence'=>'Synthetic QA fixture disclosure only']);
foreach($projects as$project)if(!$db->table('cluster_projects')->where('cluster_id',$cluster->id)->where('project_id',$project->id)->exists())$db->table('cluster_projects')->insert(['id'=>$uuid(),'cluster_id'=>$cluster->id,'project_id'=>$project->id,'role'=>'anchor','data_classification'=>'public','source_system'=>'qa-relationship','source_reference'=>'Synthetic documented QA membership','validation_status'=>'pending']);
$production=App\Models\ValueChain::firstOrCreate(['cluster_id'=>$cluster->id,'code'=>'QA-PRODUCTION'],['name'=>'QA production','stage'=>'production','data_classification'=>'public']);
$processing=App\Models\ValueChain::firstOrCreate(['cluster_id'=>$cluster->id,'code'=>'QA-PROCESSING'],['name'=>'QA processing','stage'=>'processing','data_classification'=>'public']);
if(!$db->table('value_chain_links')->where('from_value_chain_id',$production->id)->where('to_value_chain_id',$processing->id)->exists())$db->table('value_chain_links')->insert(['id'=>$uuid(),'from_value_chain_id'=>$production->id,'to_value_chain_id'=>$processing->id,'link_type'=>'supplies','data_classification'=>'public']);
$opportunity=App\Models\Opportunity::firstOrCreate(['reference'=>'QA-ANCHOR-OPPORTUNITY'],['sector_id'=>$sector->id,'title'=>'Synthetic QA linked opportunity','slug'=>'qa-anchor-opportunity','summary'=>'Synthetic browser QA fixture','status'=>'published','published_at'=>now()]);
$db->table('opportunity_projects')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'project_id'=>$projects[0]->id]);
$db->table('opportunity_clusters')->insertOrIgnore(['opportunity_id'=>$opportunity->id,'cluster_id'=>$cluster->id]);
return ['target'=>'anchor_restore_20261007_test:55441','project_dossier'=>$dossiers[0]->id,'second_project'=>$projects[1]->id,'cluster_dossier'=>$clusterDossier->id,'opportunity_slug'=>$opportunity->slug,'opportunity_id'=>$opportunity->id,'province_id'=>$ids['province']];
$cluster = EconomicCluster::firstOrCreate(['code' => 'QA-REL-CLU'], ['name' => 'Synthetic QA multi-site cluster', 'sector' => 'QA', 'status' => 'planned', 'data_classification' => 'public']);
$clusterDossier = InvestmentDossier::firstOrCreate(['cluster_id' => $cluster->id], ['title' => $cluster->name, 'source' => 'Synthetic QA member relationship source',
'content' => ['anchors' => 'QA-ANCHOR-1, QA-ANCHOR-2; coverage pending', 'gaps' => 'Synthetic QA chain gaps'], 'publication_status' => 'published', 'published_at' => now(),
'approval_basis' => 'document_owner', 'approval_evidence' => 'Synthetic QA fixture disclosure only']);
foreach ($projects as $project) {
if (! $db->table('cluster_projects')->where('cluster_id', $cluster->id)->where('project_id', $project->id)->exists()) {
$db->table('cluster_projects')->insert(['id' => $uuid(), 'cluster_id' => $cluster->id, 'project_id' => $project->id, 'role' => 'anchor', 'data_classification' => 'public', 'source_system' => 'qa-relationship', 'source_reference' => 'Synthetic documented QA membership', 'validation_status' => 'pending']);
}
}
$production = ValueChain::firstOrCreate(['cluster_id' => $cluster->id, 'code' => 'QA-PRODUCTION'], ['name' => 'QA production', 'stage' => 'production', 'data_classification' => 'public']);
$processing = ValueChain::firstOrCreate(['cluster_id' => $cluster->id, 'code' => 'QA-PROCESSING'], ['name' => 'QA processing', 'stage' => 'processing', 'data_classification' => 'public']);
if (! $db->table('value_chain_links')->where('from_value_chain_id', $production->id)->where('to_value_chain_id', $processing->id)->exists()) {
$db->table('value_chain_links')->insert(['id' => $uuid(), 'from_value_chain_id' => $production->id, 'to_value_chain_id' => $processing->id, 'link_type' => 'supplies', 'data_classification' => 'public']);
}
$opportunity = Opportunity::firstOrCreate(['reference' => 'QA-ANCHOR-OPPORTUNITY'], ['sector_id' => $sector->id, 'title' => 'Synthetic QA linked opportunity', 'slug' => 'qa-anchor-opportunity', 'summary' => 'Synthetic browser QA fixture', 'status' => 'published', 'published_at' => now()]);
$db->table('opportunity_projects')->insertOrIgnore(['opportunity_id' => $opportunity->id, 'project_id' => $projects[0]->id]);
$db->table('opportunity_clusters')->insertOrIgnore(['opportunity_id' => $opportunity->id, 'cluster_id' => $cluster->id]);
return ['target' => 'anchor_restore_20261007_test:55441', 'project_dossier' => $dossiers[0]->id, 'second_project' => $projects[1]->id, 'cluster_dossier' => $clusterDossier->id, 'opportunity_slug' => $opportunity->slug, 'opportunity_id' => $opportunity->id, 'province_id' => $ids['province']];
});
$directory=storage_path('app/private/anchor-project-reconciliation');
if(!is_dir($directory.'/qa-preview'))mkdir($directory.'/qa-preview',0700,true);
$plan=json_decode(file_get_contents($directory.'/preview.json'),true);$plan['target']=['database'=>'anchor_restore_20261007_test','port'=>55441];
file_put_contents($directory.'/qa-preview/preview.json',json_encode($plan,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
$proof=json_decode(file_get_contents($directory.'/backup-proof.json'),true);$proof['target']=$plan['target'];
file_put_contents($directory.'/qa-preview/backup-proof.json',json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
file_put_contents($directory.'/qa-browser-fixture.json',json_encode($manifest,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
$directory = storage_path('app/private/anchor-project-reconciliation');
if (! is_dir($directory.'/qa-preview')) {
mkdir($directory.'/qa-preview', 0700, true);
}
$plan = json_decode(file_get_contents($directory.'/preview.json'), true);
$plan['target'] = ['database' => 'anchor_restore_20261007_test', 'port' => 55441];
file_put_contents($directory.'/qa-preview/preview.json', json_encode($plan, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
$proof = json_decode(file_get_contents($directory.'/backup-proof.json'), true);
$proof['target'] = $plan['target'];
file_put_contents($directory.'/qa-preview/backup-proof.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($directory.'/qa-browser-fixture.json', json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($manifest).PHP_EOL;
+2 -1
View File
@@ -34,7 +34,8 @@ ws.addEventListener('message', (event) => {
apiResponses.push({
path,
status: response.status,
qaTarget: typeof targetHeader === 'string' ? targetHeader : null,
qaTarget:
typeof targetHeader === 'string' ? targetHeader : null,
});
}
}
+6 -3
View File
@@ -1,6 +1,9 @@
<?php
declare(strict_types=1);
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Vite;
// Local smoke-test router. Its database target is intentionally fixed to the
// disposable PHPUnit database; do not reuse it for development or production.
@@ -34,10 +37,10 @@ if ($path !== '/' && is_file($asset)) {
require_once $root.'/vendor/autoload.php';
$app = require $root.'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$app->make(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');
Vite::useHotFile($root.'/storage/framework/investmoz-qa-hot-file');
$configuration = $app->make('config');
$connectionName = $configuration->get('database.default');
$connection = $configuration->get('database.connections.'.$connectionName, []);
@@ -61,4 +64,4 @@ if ($identity->database !== 'investmoz_test' || $identity->host !== '127.0.0.1'
}
header('X-Investmoz-QA-Target: '.$identity->database.':'.$identity->port);
$app->handleRequest(Illuminate\Http\Request::capture());
$app->handleRequest(Request::capture());
+236 -19
View File
@@ -1,22 +1,239 @@
import fs from 'node:fs';
const id = { name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' } };
const id = {
name: 'id',
in: 'path',
required: true,
schema: { type: 'string', format: 'uuid' },
};
const string = { type: 'string' };
const schema = properties => ({ type: 'object', properties });
const schema = (properties) => ({ type: 'object', properties });
const paths = {};
const operation = (summary, parameters = [], body = null) => ({ summary, security: [{ laravelSession: [] }], parameters: [...parameters, ...(body ? [{ name: 'Idempotency-Key', in: 'header', required: true, schema: { type: 'string', format: 'uuid' } }] : [])],
...(body ? { requestBody: { required: true, content: { 'application/json': { schema: body } } } } : {}),
responses: Object.fromEntries([200, ...(summary.startsWith('Create source') ? [201] : []), 401, 403, 404, 409, 422, 429].map(code => [code, { description: code < 300 ? 'JSON result with X-Correlation-ID; private, no-store' : 'Request rejected; validation and workflow errors use Problem Details within territorial middleware' }])) });
for (const collection of ['countries','provinces','districts','admin-posts','localities','search']) paths['/'+collection] = { get: operation('Read currently published territories: '+collection,
['q','cursor','parent_id','country_id','province_id','district_id','admin_post_id'].map(name => ({ name, in: 'query', schema: string })).concat([{ name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1, maximum: 100 } }])) };
paths['/territories/{type}/{id}'] = { get: operation('Read published territory and translated names', [id, { name: 'type', in: 'path', required: true, schema: { enum: ['country','province','district','admin_post','locality'] } }]) };
const territory = schema({ name: string, code: string, location_type: { enum: ['country','province','district','admin_post','locality'] }, parent_id: { type: ['string','null'], format: 'uuid' }, source_id: { type: 'string', format: 'uuid' }, valid_from: { type: 'string', format: 'date' }, valid_to: { type: ['string','null'], format: 'date' }, reason: { type: 'string', minLength: 10, maxLength: 1000 } });
territory.required = ['name','code','location_type','source_id','valid_from','reason'];
paths['/territories'] = { post: operation('Create private territorial draft; designated editor with MFA', [], territory) };
paths['/territories/{id}'] = { patch: operation('Replace draft attributes and invalidate editorial approvals', [id], { ...territory, required: [...territory.required,'version_no'], properties: { ...territory.properties, version_no: { type: 'integer', minimum: 1 } } }) };
paths['/territories/{id}/transitions'] = { post: operation('Submit, review, publish, reject or archive; independent actors required', [id], { ...schema({ action: { enum: ['pending_review','approved','published','rejected','archived'] }, version_no: { type: 'integer', minimum: 1 }, reason: { type: 'string', minLength: 10 } }), required: ['action','version_no','reason'] }) };
paths['/sources'] = { post: operation('Create source in pending state', [], { ...schema({ name: string, responsible_entity: string, reference: string, license: string, checksum: { type: 'string', pattern: '^[0-9a-f]{64}$' }, source_version: string, collected_at: { type: 'string', format: 'date' }, original_crs: string }), required: ['name','reference','checksum','source_version','collected_at'] }) };
paths['/sources/{id}/transitions'] = { post: operation('Independent source approval or revocation with evidence reference', [id], { ...schema({ action: { enum: ['approved','revoked'] }, approval_reference: { type: 'string', minLength: 10 } }), required: ['action','approval_reference'] }) };
paths['/sources'].get = operation('Management-only source metadata and decision evidence, MFA required');
paths['/drafts'] = { get: operation('Management-only territorial editorial records, MFA required') };
fs.writeFileSync('docs/investmoz/gis/territorial-openapi.json', JSON.stringify({ openapi: '3.1.0', info: { title: 'InvestMoz territorial registry — implemented subset', version: '0.1.0', description: 'Local session adapter. OAuth/OIDC, geometric queries, assignments, imports, hierarchy endpoint and administrative UI remain unimplemented. Response schemas require expansion before external certification.' }, servers: [{ url: '/api/v1/geo' }], paths, components: { securitySchemes: { laravelSession: { type: 'apiKey', in: 'cookie', name: 'deployment_session_cookie', description: 'Actual name configured by Laravel; write requests also require Laravel CSRF/origin protection. This is not OAuth/OIDC.' } } } }, null, 2)+'\n');
console.log('Territorial OpenAPI: '+Object.keys(paths).length+' paths');
const operation = (summary, parameters = [], body = null) => ({
summary,
security: [{ laravelSession: [] }],
parameters: [
...parameters,
...(body
? [
{
name: 'Idempotency-Key',
in: 'header',
required: true,
schema: { type: 'string', format: 'uuid' },
},
]
: []),
],
...(body
? {
requestBody: {
required: true,
content: { 'application/json': { schema: body } },
},
}
: {}),
responses: Object.fromEntries(
[
200,
...(summary.startsWith('Create source') ? [201] : []),
401,
403,
404,
409,
422,
429,
].map((code) => [
code,
{
description:
code < 300
? 'JSON result with X-Correlation-ID; private, no-store'
: 'Request rejected; validation and workflow errors use Problem Details within territorial middleware',
},
]),
),
});
for (const collection of [
'countries',
'provinces',
'districts',
'admin-posts',
'localities',
'search',
])
paths['/' + collection] = {
get: operation(
'Read currently published territories: ' + collection,
[
'q',
'cursor',
'parent_id',
'country_id',
'province_id',
'district_id',
'admin_post_id',
]
.map((name) => ({ name, in: 'query', schema: string }))
.concat([
{
name: 'limit',
in: 'query',
schema: { type: 'integer', minimum: 1, maximum: 100 },
},
]),
),
};
paths['/territories/{type}/{id}'] = {
get: operation('Read published territory and translated names', [
id,
{
name: 'type',
in: 'path',
required: true,
schema: {
enum: [
'country',
'province',
'district',
'admin_post',
'locality',
],
},
},
]),
};
const territory = schema({
name: string,
code: string,
location_type: {
enum: ['country', 'province', 'district', 'admin_post', 'locality'],
},
parent_id: { type: ['string', 'null'], format: 'uuid' },
source_id: { type: 'string', format: 'uuid' },
valid_from: { type: 'string', format: 'date' },
valid_to: { type: ['string', 'null'], format: 'date' },
reason: { type: 'string', minLength: 10, maxLength: 1000 },
});
territory.required = [
'name',
'code',
'location_type',
'source_id',
'valid_from',
'reason',
];
paths['/territories'] = {
post: operation(
'Create private territorial draft; designated editor with MFA',
[],
territory,
),
};
paths['/territories/{id}'] = {
patch: operation(
'Replace draft attributes and invalidate editorial approvals',
[id],
{
...territory,
required: [...territory.required, 'version_no'],
properties: {
...territory.properties,
version_no: { type: 'integer', minimum: 1 },
},
},
),
};
paths['/territories/{id}/transitions'] = {
post: operation(
'Submit, review, publish, reject or archive; independent actors required',
[id],
{
...schema({
action: {
enum: [
'pending_review',
'approved',
'published',
'rejected',
'archived',
],
},
version_no: { type: 'integer', minimum: 1 },
reason: { type: 'string', minLength: 10 },
}),
required: ['action', 'version_no', 'reason'],
},
),
};
paths['/sources'] = {
post: operation('Create source in pending state', [], {
...schema({
name: string,
responsible_entity: string,
reference: string,
license: string,
checksum: { type: 'string', pattern: '^[0-9a-f]{64}$' },
source_version: string,
collected_at: { type: 'string', format: 'date' },
original_crs: string,
}),
required: [
'name',
'reference',
'checksum',
'source_version',
'collected_at',
],
}),
};
paths['/sources/{id}/transitions'] = {
post: operation(
'Independent source approval or revocation with evidence reference',
[id],
{
...schema({
action: { enum: ['approved', 'revoked'] },
approval_reference: { type: 'string', minLength: 10 },
}),
required: ['action', 'approval_reference'],
},
),
};
paths['/sources'].get = operation(
'Management-only source metadata and decision evidence, MFA required',
);
paths['/drafts'] = {
get: operation(
'Management-only territorial editorial records, MFA required',
),
};
fs.writeFileSync(
'docs/investmoz/gis/territorial-openapi.json',
JSON.stringify(
{
openapi: '3.1.0',
info: {
title: 'InvestMoz territorial registry — implemented subset',
version: '0.1.0',
description:
'Local session adapter. OAuth/OIDC, geometric queries, assignments, imports, hierarchy endpoint and administrative UI remain unimplemented. Response schemas require expansion before external certification.',
},
servers: [{ url: '/api/v1/geo' }],
paths,
components: {
securitySchemes: {
laravelSession: {
type: 'apiKey',
in: 'cookie',
name: 'deployment_session_cookie',
description:
'Actual name configured by Laravel; write requests also require Laravel CSRF/origin protection. This is not OAuth/OIDC.',
},
},
},
},
null,
2,
) + '\n',
);
console.log('Territorial OpenAPI: ' + Object.keys(paths).length + ' paths');
+135 -31
View File
@@ -1,43 +1,147 @@
const { chromium } = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const {
chromium,
} = require('C:/Users/macbook/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const base = 'http://127.0.0.1:18087';
(async () => {
const browser = await chromium.launch({headless:true, executablePath:'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe'});
const browser = await chromium.launch({
headless: true,
executablePath:
'C:/Users/macbook/AppData/Local/ms-playwright/chromium-1243/chrome-win64/chrome.exe',
});
try {
const context = await browser.newContext();
await context.route('**/*', route => route.request().url().startsWith(base) ? route.continue() : route.abort());
await context.route('**/*', (route) =>
route.request().url().startsWith(base)
? route.continue()
: route.abort(),
);
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(base+'/login');
await page.locator('input[type=email]').fill('relationship-qa@example.invalid');
await page.locator('input[type=password]').fill('QA-Relationship-2026!');
page.on('pageerror', (error) => errors.push(error.message));
await page.goto(base + '/login');
await page
.locator('input[type=email]')
.fill('relationship-qa@example.invalid');
await page
.locator('input[type=password]')
.fill('QA-Relationship-2026!');
await page.locator('button[type=submit]').click();
await page.waitForURL(url => !url.pathname.startsWith('/login'));
const response = await page.goto(base+'/management/relationship-repair', {waitUntil:'networkidle'});
assert.equal(response.headers()['x-investmoz-qa-target'], 'anchor_restore_20261007_test:55441');
await page.getByRole('heading',{name:'Fundamentadas: 2',exact:true}).waitFor();
await page.getByRole('heading',{name:'Pendentes: 1',exact:true}).waitFor();
await page.getByRole('heading',{name:'Contraditórias: 1',exact:true}).waitFor();
const grounded = page.getByRole('region',{name:'Associações fundamentadas'});
for (const text of ['Localização atual','Localização proposta','Documento de origem','Motivo','Sem coordenadas']) assert((await grounded.innerText()).includes(text));
await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).first().click();
await grounded.getByRole('button',{name:'Associação aplicada',exact:true}).waitFor();
assert.equal(await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).count(),1);
await grounded.getByRole('button',{name:'Aplicar esta associação',exact:true}).click();
await page.waitForFunction(()=>document.querySelectorAll('[data-row-id] button').length===4 && [...document.querySelectorAll('[data-row-id] button')].filter(button=>button.textContent==='Associação aplicada').length===2);
assert(await page.getByRole('region',{name:'Associações pendentes'}).getByRole('button').isDisabled());
assert(await page.getByRole('region',{name:'Associações contraditórias'}).getByRole('button').isDisabled());
await page.waitForURL((url) => !url.pathname.startsWith('/login'));
const response = await page.goto(
base + '/management/relationship-repair',
{ waitUntil: 'networkidle' },
);
assert.equal(
response.headers()['x-investmoz-qa-target'],
'anchor_restore_20261007_test:55441',
);
await page
.getByRole('heading', { name: 'Fundamentadas: 2', exact: true })
.waitFor();
await page
.getByRole('heading', { name: 'Pendentes: 1', exact: true })
.waitFor();
await page
.getByRole('heading', { name: 'Contraditórias: 1', exact: true })
.waitFor();
const grounded = page.getByRole('region', {
name: 'Associações fundamentadas',
});
for (const text of [
'Localização atual',
'Localização proposta',
'Documento de origem',
'Motivo',
'Sem coordenadas',
])
assert((await grounded.innerText()).includes(text));
await grounded
.getByRole('button', {
name: 'Aplicar esta associação',
exact: true,
})
.first()
.click();
await grounded
.getByRole('button', { name: 'Associação aplicada', exact: true })
.waitFor();
assert.equal(
await grounded
.getByRole('button', {
name: 'Aplicar esta associação',
exact: true,
})
.count(),
1,
);
await grounded
.getByRole('button', {
name: 'Aplicar esta associação',
exact: true,
})
.click();
await page.waitForFunction(
() =>
document.querySelectorAll('[data-row-id] button').length ===
4 &&
[...document.querySelectorAll('[data-row-id] button')].filter(
(button) => button.textContent === 'Associação aplicada',
).length === 2,
);
assert(
await page
.getByRole('region', { name: 'Associações pendentes' })
.getByRole('button')
.isDisabled(),
);
assert(
await page
.getByRole('region', { name: 'Associações contraditórias' })
.getByRole('button')
.isDisabled(),
);
assert((await page.locator('body').innerText()).includes('Autor:'));
assert((await page.locator('body').innerText()).includes('Data:'));
for (const width of [1440,390]) {
await page.setViewportSize({width,height:1000});
assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`docs/investmoz/relationships/territorial-${width}.png`,fullPage:true});
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 1000 });
assert(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
await page.screenshot({
path: `docs/investmoz/relationships/territorial-${width}.png`,
fullPage: true,
});
}
assert.deepEqual(errors,[]);
fs.writeFileSync('docs/investmoz/relationships/territorial-browser-qa.json',JSON.stringify({target:'anchor_restore_20261007_test:55441',passed:true,individualApplications:2,pendingRetained:1,contradictoryRetained:1,noCoordinatesAccepted:true,auditAuthorDateSource:true,viewports:[1440,390],errors},null,2));
console.log('QA territorial browser passed: two individual applications, conflicts retained, author/date/source, desktop/mobile.');
} finally { await browser.close(); }
})().catch(error=>{console.error(error);process.exitCode=1;});
assert.deepEqual(errors, []);
fs.writeFileSync(
'docs/investmoz/relationships/territorial-browser-qa.json',
JSON.stringify(
{
target: 'anchor_restore_20261007_test:55441',
passed: true,
individualApplications: 2,
pendingRetained: 1,
contradictoryRetained: 1,
noCoordinatesAccepted: true,
auditAuthorDateSource: true,
viewports: [1440, 390],
errors,
},
null,
2,
),
);
console.log(
'QA territorial browser passed: two individual applications, conflicts retained, author/date/source, desktop/mobile.',
);
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+11 -7
View File
@@ -1,5 +1,9 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
// Synthetic preview only, fixed isolated restored QA database; never writes active data.
foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => '55441',
'DB_DATABASE' => 'anchor_restore_20261007_test', 'DB_USERNAME' => 'postgres', 'DB_PASSWORD' => '', 'DB_URL' => ''] as $key => $value) {
@@ -8,23 +12,23 @@ foreach (['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_HOST' => '127.
}
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$identity = Illuminate\Support\Facades\DB::selectOne('select current_database() as database, inet_server_port() as port');
$app->make(Kernel::class)->bootstrap();
$identity = DB::selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
throw new RuntimeException('Isolated QA required');
}
$root = storage_path('app/private/anchor-project-reconciliation');
$fixture = json_decode(file_get_contents($root.'/qa-browser-fixture.json'), true, 512, JSON_THROW_ON_ERROR);
$dossier = Illuminate\Support\Facades\DB::table('investment_dossiers')->where('id', $fixture['project_dossier'])->first();
$project = Illuminate\Support\Facades\DB::table('projects')->where('id', $dossier->project_id)->first();
$dossier = DB::table('investment_dossiers')->where('id', $fixture['project_dossier'])->first();
$project = DB::table('projects')->where('id', $dossier->project_id)->first();
if (! str_starts_with($project->code, 'QA-')) {
throw new RuntimeException('Synthetic project required');
}
$site = Illuminate\Support\Facades\DB::table('project_locations')->where('project_id', $project->id)->where('role', 'primary')->first();
$site = DB::table('project_locations')->where('project_id', $project->id)->where('role', 'primary')->first();
$nodes = [];
$id = $site->geo_location_id;
while ($id) {
$node = Illuminate\Support\Facades\DB::table('geo_locations')->where('id', $id)->first();
$node = DB::table('geo_locations')->where('id', $id)->first();
$nodes[$node->location_type] = $node;
$id = $node->parent_id;
}
@@ -36,7 +40,7 @@ foreach ([['province', 'secondary'], ['district', 'impact'], ['admin_post', 'sec
$rows[] = [...$base, 'geo_location_id' => $nodes[$type]->id, 'name' => $nodes[$type]->name, 'role' => $role, 'existing' => false];
}
$rows[2]['source_quote'] = '';
$rows[3]['province_id'] = (string) Illuminate\Support\Str::uuid();
$rows[3]['province_id'] = (string) Str::uuid();
$directory = $root.'/qa-territorial-preview';
if (! is_dir($directory)) {
mkdir($directory, 0700, true);
+113 -24
View File
@@ -1,39 +1,128 @@
// Synthetic QA server only; never writes to the application database.
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).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 => ws.addEventListener('open', resolve, { once: true }));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => { const result = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (result.exceptionDetails) throw Error(JSON.stringify(result.exceptionDetails)); return result.result?.value; };
const wait = async expression => { for (let n = 0; n < 100; n++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 100)); } throw Error('Timed out: ' + expression); };
const select = async (index, value) => evaluate(`(()=>{const element=document.querySelectorAll('select')[${index}];Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(element,${JSON.stringify(value)});element.dispatchEvent(new Event('change',{bubbles:true}));})()`);
try {
await send('Runtime.enable'); await send('Page.enable');
await send('Page.navigate', { url: 'http://127.0.0.1:18027/login' });
await wait(`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`);
if (await evaluate(`location.pathname==='/login'`)) {
for (const [selector, text] of [['input[type="email"]', 'mne-browser@example.test'], ['input[type="password"]', 'SyntheticMneOnly-2026!']]) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`); await send('Input.insertText', { text }); }
await evaluate(`document.querySelector('button[type="submit"]').click()`); await wait(`!location.pathname.startsWith('/login')`);
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown')
errors.push(message.params.exceptionDetails.text);
if (message.id) {
const callback = pending.get(message.id);
pending.delete(message.id);
if (message.error) callback.reject(message.error);
else callback.resolve(message.result);
}
await send('Page.navigate', { url: 'http://127.0.0.1:18027/management/territory-associations' });
};
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++sequence;
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const result = await send('Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
});
if (result.exceptionDetails)
throw Error(JSON.stringify(result.exceptionDetails));
return result.result?.value;
};
const wait = async (expression) => {
for (let n = 0; n < 100; n++) {
if (await evaluate(expression)) return;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw Error('Timed out: ' + expression);
};
const select = async (index, value) =>
evaluate(
`(()=>{const element=document.querySelectorAll('select')[${index}];Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(element,${JSON.stringify(value)});element.dispatchEvent(new Event('change',{bubbles:true}));})()`,
);
try {
await send('Runtime.enable');
await send('Page.enable');
await send('Page.navigate', { url: 'http://127.0.0.1:18027/login' });
await wait(
`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`,
);
if (await evaluate(`location.pathname==='/login'`)) {
for (const [selector, text] of [
['input[type="email"]', 'mne-browser@example.test'],
['input[type="password"]', 'SyntheticMneOnly-2026!'],
]) {
await evaluate(
`document.querySelector(${JSON.stringify(selector)}).focus()`,
);
await send('Input.insertText', { text });
}
await evaluate(
`document.querySelector('button[type="submit"]').click()`,
);
await wait(`!location.pathname.startsWith('/login')`);
}
await send('Page.navigate', {
url: 'http://127.0.0.1:18027/management/territory-associations',
});
await wait(`document.querySelectorAll('select').length===2`);
await select(0, 'clusters');
await wait(`document.querySelectorAll('select')[1].options.length>1`);
await select(1, '20000000-0000-4000-8000-000000000001');
await wait(`document.querySelectorAll('select').length===6`);
for (let level = 0; level < 4; level++) {
await wait(`!document.querySelectorAll('select')[${level+2}].disabled && document.querySelectorAll('select')[${level+2}].options.length>1`);
await select(level+2, `10000000-0000-4000-8000-${String(level+2).padStart(12, '0')}`);
await wait(
`!document.querySelectorAll('select')[${level + 2}].disabled && document.querySelectorAll('select')[${level + 2}].options.length>1`,
);
await select(
level + 2,
`10000000-0000-4000-8000-${String(level + 2).padStart(12, '0')}`,
);
}
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent==='Guardar localização').click()`);
await wait(`document.body.innerText.includes('Localização associada e guardada.')`);
await evaluate(
`[...document.querySelectorAll('button')].find(b=>b.textContent==='Guardar localização').click()`,
);
await wait(
`document.body.innerText.includes('Localização associada e guardada.')`,
);
await select(2, '');
await wait(`[...document.querySelectorAll('section[aria-label="Localização do investimento"] select')].slice(1).every(s=>s.value===''&&s.disabled)`);
await wait(
`[...document.querySelectorAll('section[aria-label="Localização do investimento"] select')].slice(1).every(s=>s.value===''&&s.disabled)`,
);
const widths = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); widths.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
if (errors.length || widths.some(w => !w.noOverflow)) throw Error('Browser validation failed');
console.log(JSON.stringify({ cascade: true, save: true, reset_descendants: true, widths, javascript_errors: errors.length }));
} finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width < 600,
});
widths.push({
width,
noOverflow: await evaluate(
'document.documentElement.scrollWidth<=innerWidth+1',
),
});
}
if (errors.length || widths.some((w) => !w.noOverflow))
throw Error('Browser validation failed');
console.log(
JSON.stringify({
cascade: true,
save: true,
reset_descendants: true,
widths,
javascript_errors: errors.length,
}),
);
} finally {
ws.close();
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
}
+242 -57
View File
@@ -1,8 +1,12 @@
// Synthetic QA server only; never writes to the application database.
import fs from 'node:fs';
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).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 => ws.addEventListener('open', resolve, { once: true }));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let sequence = 0;
const pending = new Map();
const errors = [];
@@ -10,101 +14,282 @@ const requests = [];
const responses = [];
const responseIds = new Set();
const responseBodies = [];
ws.onmessage = event => {
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Network.requestWillBeSent' && message.params.request.url.includes('/management/opportunities') && message.params.request.postData) {
const request = message.params.request; let data = {};
try { data = JSON.parse(request.postData); } catch {}
const keys = ['province_id','district_id','admin_post_id','locality_id','territory_version','reference'];
requests.push({ method: request.method, path: new URL(request.url).pathname, payload: Object.fromEntries(keys.filter(k => k in data).map(k => [k, data[k]])) });
if (
message.method === 'Network.requestWillBeSent' &&
message.params.request.url.includes('/management/opportunities') &&
message.params.request.postData
) {
const request = message.params.request;
let data = {};
try {
data = JSON.parse(request.postData);
} catch {}
const keys = [
'province_id',
'district_id',
'admin_post_id',
'locality_id',
'territory_version',
'reference',
];
requests.push({
method: request.method,
path: new URL(request.url).pathname,
payload: Object.fromEntries(
keys.filter((k) => k in data).map((k) => [k, data[k]]),
),
});
}
if (message.method === 'Network.responseReceived' && message.params.response.url.includes('/management/opportunities')) {
responses.push({ path: new URL(message.params.response.url).pathname, status: message.params.response.status });
if (
message.method === 'Network.responseReceived' &&
message.params.response.url.includes('/management/opportunities')
) {
responses.push({
path: new URL(message.params.response.url).pathname,
status: message.params.response.status,
});
responseIds.add(message.params.requestId);
}
if (message.method === 'Network.loadingFinished' && responseIds.has(message.params.requestId)) {
send('Network.getResponseBody', { requestId: message.params.requestId }).then(result => {
try { const body = JSON.parse(result.body); responseBodies.push({component: body.component, errors: body.props?.errors}); } catch {}
}).catch(() => {});
if (
message.method === 'Network.loadingFinished' &&
responseIds.has(message.params.requestId)
) {
send('Network.getResponseBody', { requestId: message.params.requestId })
.then((result) => {
try {
const body = JSON.parse(result.body);
responseBodies.push({
component: body.component,
errors: body.props?.errors,
});
} catch {}
})
.catch(() => {});
}
if (message.method === 'Runtime.exceptionThrown')
errors.push(message.params.exceptionDetails.text);
if (message.id) {
const callback = pending.get(message.id);
pending.delete(message.id);
if (message.error) callback.reject(message.error);
else callback.resolve(message.result);
}
if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text);
if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); }
};
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, { resolve, reject }); ws.send(JSON.stringify({ id, method, params })); });
const evaluate = async expression => { const result = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); if (result.exceptionDetails) throw Error(JSON.stringify(result.exceptionDetails)); return result.result?.value; };
const wait = async expression => { for (let n = 0; n < 100; n++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 100)); } throw Error('Timed out: ' + expression); };
const select = async (index, value) => evaluate(`(()=>{const element=document.querySelectorAll('select')[${index}];Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(element,${JSON.stringify(value)});element.dispatchEvent(new Event('change',{bubbles:true}));})()`);
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++sequence;
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const result = await send('Runtime.evaluate', {
expression,
returnByValue: true,
awaitPromise: true,
});
if (result.exceptionDetails)
throw Error(JSON.stringify(result.exceptionDetails));
return result.result?.value;
};
const wait = async (expression) => {
for (let n = 0; n < 100; n++) {
if (await evaluate(expression)) return;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw Error('Timed out: ' + expression);
};
const select = async (index, value) =>
evaluate(
`(()=>{const element=document.querySelectorAll('select')[${index}];Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(element,${JSON.stringify(value)});element.dispatchEvent(new Event('change',{bubbles:true}));})()`,
);
try {
await send('Runtime.enable'); await send('Page.enable'); await send('Network.enable');
await send('Runtime.enable');
await send('Page.enable');
await send('Network.enable');
await send('Page.navigate', { url: 'http://127.0.0.1:18027/login' });
await wait(`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`);
await wait(
`document.readyState==='complete' && (location.pathname!='/login' || !!document.querySelector('input[type="password"]'))`,
);
if (await evaluate(`location.pathname==='/login'`)) {
for (const [selector, text] of [['input[type="email"]', 'mne-browser@example.test'], ['input[type="password"]', 'SyntheticMneOnly-2026!']]) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).focus()`); await send('Input.insertText', { text }); }
await evaluate(`document.querySelector('button[type="submit"]').click()`); await wait(`!location.pathname.startsWith('/login')`);
for (const [selector, text] of [
['input[type="email"]', 'mne-browser@example.test'],
['input[type="password"]', 'SyntheticMneOnly-2026!'],
]) {
await evaluate(
`document.querySelector(${JSON.stringify(selector)}).focus()`,
);
await send('Input.insertText', { text });
}
await evaluate(
`document.querySelector('button[type="submit"]').click()`,
);
await wait(`!location.pathname.startsWith('/login')`);
}
const token = 'geo-browser-' + Date.now();
const observations = [];
await send('Page.navigate', { url: 'http://127.0.0.1:18027/management/opportunities/create' });
await send('Page.navigate', {
url: 'http://127.0.0.1:18027/management/opportunities/create',
});
await wait(`document.querySelectorAll('select').length===7`);
const fill = async (label, value) => {
await evaluate(`(()=>{const label=[...document.querySelectorAll('label')].find(l=>l.textContent.startsWith(${JSON.stringify(label)}));const input=label.querySelector('input');input.focus();input.select();})()`);
await evaluate(
`(()=>{const label=[...document.querySelectorAll('label')].find(l=>l.textContent.startsWith(${JSON.stringify(label)}));const input=label.querySelector('input');input.focus();input.select();})()`,
);
if (value === '') {
await send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
await send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'Backspace',
code: 'Backspace',
windowsVirtualKeyCode: 8,
});
await send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'Backspace',
code: 'Backspace',
windowsVirtualKeyCode: 8,
});
} else await send('Input.insertText', { text: value });
};
await fill('Referência', token); await fill('Título', token); await fill('Slug', token);
await select(4, await evaluate(`document.querySelectorAll('select')[4].options[1].value`));
await fill('Referência', token);
await fill('Título', token);
await fill('Slug', token);
await select(
4,
await evaluate(
`document.querySelectorAll('select')[4].options[1].value`,
),
);
for (let level = 0; level < 4; level++) {
await wait(`!document.querySelectorAll('select')[${level}].disabled && document.querySelectorAll('select')[${level}].options.length>1`);
await select(level, `10000000-0000-4000-8000-${String(level+2).padStart(12, '0')}`);
await wait(
`!document.querySelectorAll('select')[${level}].disabled && document.querySelectorAll('select')[${level}].options.length>1`,
);
await select(
level,
`10000000-0000-4000-8000-${String(level + 2).padStart(12, '0')}`,
);
}
const save = () => evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent==='Guardar').click()`);
const save = () =>
evaluate(
`[...document.querySelectorAll('button')].find(b=>b.textContent==='Guardar').click()`,
);
const reopen = async () => {
await wait(`location.pathname==='/management/opportunities' && document.body.innerText.includes(${JSON.stringify(token)})`);
await evaluate(`[...document.querySelectorAll('article')].find(a=>a.textContent.includes(${JSON.stringify(token)})).querySelector('a').click()`);
await wait(`location.pathname.endsWith('/edit') && document.querySelectorAll('select').length===7`);
await wait(
`location.pathname==='/management/opportunities' && document.body.innerText.includes(${JSON.stringify(token)})`,
);
await evaluate(
`[...document.querySelectorAll('article')].find(a=>a.textContent.includes(${JSON.stringify(token)})).querySelector('a').click()`,
);
await wait(
`location.pathname.endsWith('/edit') && document.querySelectorAll('select').length===7`,
);
};
await save(); await reopen();
await wait(`document.querySelectorAll('select')[3].value==='10000000-0000-4000-8000-000000000005'`);
await save();
await reopen();
await wait(
`document.querySelectorAll('select')[3].value==='10000000-0000-4000-8000-000000000005'`,
);
observations.push('create_save_reopen_full_path');
// Server validation must retain the chain and expose the failing field.
await fill('Referência', ''); await save();
await fill('Referência', '');
await save();
await wait(`document.querySelector('[role="alert"]')!==null`);
if (!(await evaluate(`document.querySelectorAll('select')[3].value==='10000000-0000-4000-8000-000000000005'`))) throw Error('Validation lost selection');
if (
!(await evaluate(
`document.querySelectorAll('select')[3].value==='10000000-0000-4000-8000-000000000005'`,
))
)
throw Error('Validation lost selection');
await fill('Referência', token);
observations.push('validation_preserves_selection');
await select(2, '');
await wait(`document.querySelectorAll('select')[3].disabled && document.querySelectorAll('select')[3].value===''`);
await save(); await reopen();
await wait(`document.querySelectorAll('select')[1].value==='10000000-0000-4000-8000-000000000003' && document.querySelectorAll('select')[2].value===''`);
await wait(
`document.querySelectorAll('select')[3].disabled && document.querySelectorAll('select')[3].value===''`,
);
await save();
await reopen();
await wait(
`document.querySelectorAll('select')[1].value==='10000000-0000-4000-8000-000000000003' && document.querySelectorAll('select')[2].value===''`,
);
observations.push('edit_save_reopen_and_descendant_reset');
await send('Network.setBlockedURLs', { urls: ['*://127.0.0.1:18027/management/territory-options?type=province*'] });
await evaluate(`document.querySelector('input[aria-label="Pesquisar Província"]').focus()`);
await send('Network.setBlockedURLs', {
urls: [
'*://127.0.0.1:18027/management/territory-options?type=province*',
],
});
await evaluate(
`document.querySelector('input[aria-label="Pesquisar Província"]').focus()`,
);
await send('Input.insertText', { text: 'Synthetic' });
await wait(`document.body.innerText.includes('Tentar novamente')`);
await send('Network.setBlockedURLs', { urls: [] });
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent==='Tentar novamente').click()`);
await wait(`!document.body.innerText.includes('Tentar novamente') && document.querySelectorAll('select')[0].options.length>1 && !document.querySelectorAll('select')[0].disabled`);
await evaluate(
`[...document.querySelectorAll('button')].find(b=>b.textContent==='Tentar novamente').click()`,
);
await wait(
`!document.body.innerText.includes('Tentar novamente') && document.querySelectorAll('select')[0].options.length>1 && !document.querySelectorAll('select')[0].disabled`,
);
observations.push('network_failure_and_retry');
await evaluate(`document.querySelector('input[aria-label="Pesquisar Distrito"]').focus()`);
await evaluate(
`document.querySelector('input[aria-label="Pesquisar Distrito"]').focus()`,
);
await send('Input.insertText', { text: 'no-such-synthetic-district' });
await wait(`document.body.innerText.includes('Sem opções para esta pesquisa.')`);
await wait(
`document.body.innerText.includes('Sem opções para esta pesquisa.')`,
);
observations.push('empty_search');
await select(0, '');
await select(0, '10000000-0000-4000-8000-000000000002');
await select(0, '');
await new Promise(resolve => setTimeout(resolve, 500));
if (!(await evaluate(`[...document.querySelectorAll('select')].slice(1,4).every(s=>s.disabled && s.value==='' && s.options.length===1)`))) throw Error('Stale children after rapid parent changes');
await new Promise((resolve) => setTimeout(resolve, 500));
if (
!(await evaluate(
`[...document.querySelectorAll('select')].slice(1,4).every(s=>s.disabled && s.value==='' && s.options.length===1)`,
))
)
throw Error('Stale children after rapid parent changes');
observations.push('rapid_parent_change_cancels_and_clears_children');
const widths = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); widths.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
if (errors.length || widths.some(w => !w.noOverflow)) throw Error('Browser validation failed');
const report = { date: new Date().toISOString(), observations, requests, responses, widths, javascript_errors: errors.length, scope: 'Synthetic isolated QA' };
fs.writeFileSync('docs/investmoz/gis/opportunity-dropdown-browser.json', JSON.stringify(report, null, 2) + '\n');
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width < 600,
});
widths.push({
width,
noOverflow: await evaluate(
'document.documentElement.scrollWidth<=innerWidth+1',
),
});
}
if (errors.length || widths.some((w) => !w.noOverflow))
throw Error('Browser validation failed');
const report = {
date: new Date().toISOString(),
observations,
requests,
responses,
widths,
javascript_errors: errors.length,
scope: 'Synthetic isolated QA',
};
fs.writeFileSync(
'docs/investmoz/gis/opportunity-dropdown-browser.json',
JSON.stringify(report, null, 2) + '\n',
);
console.log(JSON.stringify(report));
} catch (error) {
console.log(JSON.stringify({ requests, responses, responseBodies }));
console.log(await evaluate(`({path:location.pathname,body:document.body.innerText.slice(0,800)})`));
console.log(
await evaluate(
`({path:location.pathname,body:document.body.innerText.slice(0,800)})`,
),
);
throw error;
} finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
} finally {
ws.close();
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
}
+120 -23
View File
@@ -1,36 +1,133 @@
// Read-only checks against the local public portal and real reference names.
const base = 'http://127.0.0.1:8000';
const provinces = await (await fetch(`${base}/api/v1/investment/territory-options?type=province`)).json();
if (provinces.data.length !== 11 || provinces.data.some(p => /^\d+$/.test(p.name))) throw Error('Province designations invalid');
const province = provinces.data.find(p => p.name === 'Zambezia');
const provinces = await (
await fetch(`${base}/api/v1/investment/territory-options?type=province`)
).json();
if (
provinces.data.length !== 11 ||
provinces.data.some((p) => /^\d+$/.test(p.name))
)
throw Error('Province designations invalid');
const province = provinces.data.find((p) => p.name === 'Zambezia');
if (!province) throw Error('Expected source designation missing');
const result = await (await fetch(`${base}/api/v1/investment/search?province_id=${province.id}`)).json();
if (result.total < 1) throw Error('Existing opportunities not linked to province');
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', { method: 'PUT' })).json();
const result = await (
await fetch(`${base}/api/v1/investment/search?province_id=${province.id}`)
).json();
if (result.total < 1)
throw Error('Existing opportunities not linked to province');
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 => ws.addEventListener('open', resolve, { once: true }));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => { const message = JSON.parse(event.data); if (message.method === 'Network.requestWillBeSent' && message.params.request.url.includes('/oportunidades?')) console.log(message.params.request.url); if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text); if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); message.error ? callback.reject(message.error) : callback.resolve(message.result); } };
const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; 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 Error(JSON.stringify(response.exceptionDetails)); return response.result?.value; };
const wait = async expression => { for (let i = 0; i < 100; i++) { if (await evaluate(expression)) return; await new Promise(resolve => setTimeout(resolve, 150)); } throw Error('Timed out: '+expression); };
const element = label => `document.getElementById([...document.querySelectorAll('label')].find(l=>l.textContent===${JSON.stringify(label)})?.htmlFor)`;
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (
message.method === 'Network.requestWillBeSent' &&
message.params.request.url.includes('/oportunidades?')
)
console.log(message.params.request.url);
if (message.method === 'Runtime.exceptionThrown')
errors.push(message.params.exceptionDetails.text);
if (message.id) {
const callback = pending.get(message.id);
pending.delete(message.id);
if (message.error) callback.reject(message.error);
else callback.resolve(message.result);
}
};
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = ++sequence;
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 Error(JSON.stringify(response.exceptionDetails));
return response.result?.value;
};
const wait = async (expression) => {
for (let i = 0; i < 100; i++) {
if (await evaluate(expression)) return;
await new Promise((resolve) => setTimeout(resolve, 150));
}
throw Error('Timed out: ' + expression);
};
const element = (label) =>
`document.getElementById([...document.querySelectorAll('label')].find(l=>l.textContent===${JSON.stringify(label)})?.htmlFor)`;
try {
await send('Runtime.enable'); await send('Page.enable'); await send('Network.enable');
await send('Runtime.enable');
await send('Page.enable');
await send('Network.enable');
await send('Page.navigate', { url: `${base}/oportunidades` });
await wait(`${element('Província')}?.options.length===12`);
await evaluate(`(()=>{const e=${element('Província')};Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(e,${JSON.stringify(province.id)});e.dispatchEvent(new Event('change',{bubbles:true}));})()`);
await evaluate(
`(()=>{const e=${element('Província')};Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(e,${JSON.stringify(province.id)});e.dispatchEvent(new Event('change',{bubbles:true}));})()`,
);
await wait(`${element('Distrito')}?.options.length>1`);
const districtNames = await evaluate(`[...${element('Distrito')}.options].slice(1).map(o=>o.textContent)`);
if (districtNames.some(n => /^\d+$/.test(n))) throw Error('District designations invalid');
await evaluate(`[...document.querySelectorAll('button')].find(b=>b.textContent.trim()==='Aplicar filtros').click()`);
await wait(`location.search.includes('province_id=') && ${element('Província')}?.value===${JSON.stringify(province.id)}`);
const districtNames = await evaluate(
`[...${element('Distrito')}.options].slice(1).map(o=>o.textContent)`,
);
if (districtNames.some((n) => /^\d+$/.test(n)))
throw Error('District designations invalid');
await evaluate(
`[...document.querySelectorAll('button')].find(b=>b.textContent.trim()==='Aplicar filtros').click()`,
);
await wait(
`location.search.includes('province_id=') && ${element('Província')}?.value===${JSON.stringify(province.id)}`,
);
await send('Page.reload');
await wait(`${element('Província')}?.value===${JSON.stringify(province.id)} && ${element('Distrito')}?.options.length>1`);
await wait(
`${element('Província')}?.value===${JSON.stringify(province.id)} && ${element('Distrito')}?.options.length>1`,
);
const layouts = [];
for (const width of [390, 1440]) { await send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: width < 600 }); layouts.push({ width, noOverflow: await evaluate('document.documentElement.scrollWidth<=innerWidth+1') }); }
if (errors.length || layouts.some(l=>!l.noOverflow)) throw Error('Browser check failed');
console.log(JSON.stringify({ named_provinces: 11, named_district_options: districtNames.length, matching_opportunities: result.total, persisted_url_filter: true, layouts, javascript_errors: errors.length }));
} catch (error) { console.log(JSON.stringify(await evaluate(`({url:location.href,alerts:[...document.querySelectorAll('[role="alert"]')].map(e=>e.textContent),selected:[...document.querySelectorAll('select')].map(e=>e.value)})`))); throw error; } finally { ws.close(); await fetch(`http://127.0.0.1:9224/json/close/${target.id}`); }
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width < 600,
});
layouts.push({
width,
noOverflow: await evaluate(
'document.documentElement.scrollWidth<=innerWidth+1',
),
});
}
if (errors.length || layouts.some((l) => !l.noOverflow))
throw Error('Browser check failed');
console.log(
JSON.stringify({
named_provinces: 11,
named_district_options: districtNames.length,
matching_opportunities: result.total,
persisted_url_filter: true,
layouts,
javascript_errors: errors.length,
}),
);
} catch (error) {
console.log(
JSON.stringify(
await evaluate(
`({url:location.href,alerts:[...document.querySelectorAll('[role="alert"]')].map(e=>e.textContent),selected:[...document.querySelectorAll('select')].map(e=>e.value)})`,
),
),
);
throw error;
} finally {
ws.close();
await fetch(`http://127.0.0.1:9224/json/close/${target.id}`);
}
+7 -3
View File
@@ -1,9 +1,13 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
require __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db = Illuminate\Support\Facades\DB::connection();
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
if (! $app->environment('testing') || $db->getDatabaseName() !== 'portal_services_test' || (string) $db->getConfig('port') !== '55441') {
throw new RuntimeException('Isolated QA required');
}
@@ -50,7 +54,7 @@ SQL);
$rejected = false;
try {
$db->unprepared($sql);
} catch (Illuminate\Database\QueryException $e) {
} catch (QueryException $e) {
$rejected = $e->getCode() === '23514';
}
$db->statement('ROLLBACK TO SAVEPOINT mutation');
+24 -11
View File
@@ -1,15 +1,22 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__).'/vendor/autoload.php';
$app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$active = Illuminate\Support\Facades\DB::connection();
if ($active->getDatabaseName() !== 'investemoz' || (string) $active->getConfig('port') !== '5432') throw new RuntimeException('Unexpected active target.');
$app->make(Kernel::class)->bootstrap();
$active = DB::connection();
if ($active->getDatabaseName() !== 'investemoz' || (string) $active->getConfig('port') !== '5432') {
throw new RuntimeException('Unexpected active target.');
}
config(['database.connections.anchor_restore' => [...config('database.connections.pgsql'), 'host' => '127.0.0.1', 'port' => '55441',
'database' => 'anchor_restore_20261007_test', 'username' => 'postgres', 'password' => '', 'url' => null]]);
$restore = Illuminate\Support\Facades\DB::connection('anchor_restore');
$restore = DB::connection('anchor_restore');
$identity = $restore->selectOne('select current_database() as database, inet_server_port() as port');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) throw new RuntimeException('Restore verification requires isolated QA.');
if ($identity->database !== 'anchor_restore_20261007_test' || (int) $identity->port !== 55441) {
throw new RuntimeException('Restore verification requires isolated QA.');
}
$report = $active->transaction(function () use ($active, $restore) {
$active->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
$counts = [];
@@ -17,25 +24,31 @@ $report = $active->transaction(function () use ($active, $restore) {
$name = $table->tablename;
$a = $active->table($name)->count();
$b = $restore->table($name)->count();
if ($a !== $b) throw new RuntimeException('Restore count differs for '.$name);
if ($a !== $b) {
throw new RuntimeException('Restore count differs for '.$name);
}
$counts[$name] = $a;
}
$hashes = [];
foreach (['projects','economic_clusters','investment_dossiers','project_locations','cluster_projects','opportunity_projects','opportunity_clusters','value_chains','value_chain_links','opportunities','geo_locations','geo_geometries'] as $table) {
foreach (['projects', 'economic_clusters', 'investment_dossiers', 'project_locations', 'cluster_projects', 'opportunity_projects', 'opportunity_clusters', 'value_chains', 'value_chain_links', 'opportunities', 'geo_locations', 'geo_geometries'] as $table) {
$hash = function ($db) use ($table) {
$rows = array_map(fn ($row) => $row->value, $db->select('select row_to_json(t)::text as value from public.'.$table.' as t'));
sort($rows, SORT_STRING);
return hash('sha256', implode("\n", $rows));
};
$a = $hash($active);
if ($a !== $hash($restore)) throw new RuntimeException('Restore data differs for '.$table);
if ($a !== $hash($restore)) {
throw new RuntimeException('Restore data differs for '.$table);
}
$hashes[$table] = $a;
}
return ['table_counts' => $counts, 'relation_table_hashes' => $hashes];
});
$directory = storage_path('app/private/anchor-project-reconciliation');
$dump = $directory.'/backup-20261007/database.dump';
$proof = [...$report, 'restore_verified' => true, 'verified_at' => date(DATE_ATOM), 'target' => ['database'=>'investemoz','port'=>5432],
'restored_target' => ['database'=>$identity->database,'port'=>$identity->port], 'dump_path'=>$dump,'sha256'=>hash_file('sha256',$dump)];
file_put_contents($directory.'/backup-proof.json',json_encode($proof,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
$proof = [...$report, 'restore_verified' => true, 'verified_at' => date(DATE_ATOM), 'target' => ['database' => 'investemoz', 'port' => 5432],
'restored_target' => ['database' => $identity->database, 'port' => $identity->port], 'dump_path' => $dump, 'sha256' => hash_file('sha256', $dump)];
file_put_contents($directory.'/backup-proof.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo 'Restore verified: '.count($report['table_counts']).' table counts and '.count($report['relation_table_hashes']).' content hashes.'.PHP_EOL;
+89 -28
View File
@@ -1,58 +1,119 @@
// Read-only browser smoke test; reuse the dedicated QA Edge debugger on 9224.
import fs from 'node:fs';
const base = process.argv[2] ?? 'http://127.0.0.1:8000';
if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) throw Error('Local QA server required');
const target = await (await fetch('http://127.0.0.1:9224/json/new?about:blank', {method: 'PUT'})).json();
if (!/^http:\/\/127\.0\.0\.1:\d+$/.test(base))
throw Error('Local QA server required');
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 => ws.addEventListener('open', resolve, {once: true}));
await new Promise((resolve) =>
ws.addEventListener('open', resolve, { once: true }),
);
let sequence = 0;
const pending = new Map();
const errors = [];
ws.onmessage = event => {
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') errors.push(message.params.exceptionDetails.text);
if (message.id) { const callback = pending.get(message.id); pending.delete(message.id); callback(message.error ? {error: message.error} : message.result); }
if (message.method === 'Runtime.exceptionThrown')
errors.push(message.params.exceptionDetails.text);
if (message.id) {
const callback = pending.get(message.id);
pending.delete(message.id);
callback(message.error ? { error: message.error } : message.result);
}
};
const send = (method, params = {}) => new Promise(resolve => { const id = ++sequence; pending.set(id, resolve); ws.send(JSON.stringify({id, method, params})); });
const evaluate = async expression => {
const result = await send('Runtime.evaluate', {expression, returnByValue: true});
if (result.exceptionDetails || result.error) throw Error(JSON.stringify(result));
const send = (method, params = {}) =>
new Promise((resolve) => {
const id = ++sequence;
pending.set(id, resolve);
ws.send(JSON.stringify({ id, method, params }));
});
const evaluate = async (expression) => {
const result = await send('Runtime.evaluate', {
expression,
returnByValue: true,
});
if (result.exceptionDetails || result.error)
throw Error(JSON.stringify(result));
return result.result?.value;
};
await send('Page.enable'); await send('Runtime.enable');
await send('Page.enable');
await send('Runtime.enable');
const observations = [];
try {
for (const width of [390, 1440]) {
await send('Emulation.setDeviceMetricsOverride', {width, height: 900, deviceScaleFactor: 1, mobile: width < 600});
for (const path of ['/zonas?category=zee', '/zonas?category=zfi', '/zonas?category=industrial_park', '/oportunidades', '/oportunidades?view=combined']) {
await send('Page.navigate', {url: base + path});
await send('Emulation.setDeviceMetricsOverride', {
width,
height: 900,
deviceScaleFactor: 1,
mobile: width < 600,
});
for (const path of [
'/zonas?category=zee',
'/zonas?category=zfi',
'/zonas?category=industrial_park',
'/oportunidades',
'/oportunidades?view=combined',
]) {
await send('Page.navigate', { url: base + path });
let ready = false;
for (let attempt = 0; attempt < 100; attempt++) {
await new Promise(resolve => setTimeout(resolve, 100));
ready = await evaluate(`document.readyState==='complete' && location.href===${JSON.stringify(base + path)} && !!document.querySelector('h1')`);
await new Promise((resolve) => setTimeout(resolve, 100));
ready = await evaluate(
`document.readyState==='complete' && location.href===${JSON.stringify(base + path)} && !!document.querySelector('h1')`,
);
if (ready) break;
}
if (!ready) throw Error('Page not ready: ' + path);
const result = await evaluate(`({title:document.querySelector('h1').textContent,overflow:document.documentElement.scrollWidth>innerWidth+1,breadcrumb:!!document.querySelector('nav[aria-label="Caminho de navegação"]'),support:[...document.querySelectorAll('a')].some(a=>a.textContent.includes('Contactar Apoio')),dimensions:['Por Cluster','Por Corredor','Por ZEE','Por ZFI'].every(text=>[...document.querySelectorAll('a')].some(a=>a.textContent===text))})`);
if (result.overflow || !result.breadcrumb || !result.support || !result.dimensions) throw Error(JSON.stringify({path, width, ...result}));
observations.push({path, width, ...result});
const result = await evaluate(
`({title:document.querySelector('h1').textContent,overflow:document.documentElement.scrollWidth>innerWidth+1,breadcrumb:!!document.querySelector('nav[aria-label="Caminho de navegação"]'),support:[...document.querySelectorAll('a')].some(a=>a.textContent.includes('Contactar Apoio')),dimensions:['Por Cluster','Por Corredor','Por ZEE','Por ZFI'].every(text=>[...document.querySelectorAll('a')].some(a=>a.textContent===text))})`,
);
if (
result.overflow ||
!result.breadcrumb ||
!result.support ||
!result.dimensions
)
throw Error(JSON.stringify({ path, width, ...result }));
observations.push({ path, width, ...result });
}
}
await send('Network.enable');
await send('Network.setBlockedURLs', {urls: ['*api/v1/investment/map*']});
await send('Page.navigate', {url: base + '/oportunidades?view=map'});
await send('Network.setBlockedURLs', { urls: ['*api/v1/investment/map*'] });
await send('Page.navigate', { url: base + '/oportunidades?view=map' });
let fallback = false;
for (let attempt = 0; attempt < 100; attempt++) {
await new Promise(resolve => setTimeout(resolve, 100));
fallback = await evaluate(`document.body.innerText.includes('Mapa indisponível') && [...document.querySelectorAll('article a')].some(a=>a.getAttribute('href')?.startsWith('/oportunidades/'))`);
await new Promise((resolve) => setTimeout(resolve, 100));
fallback = await evaluate(
`document.body.innerText.includes('Mapa indisponível') && [...document.querySelectorAll('article a')].some(a=>a.getAttribute('href')?.startsWith('/oportunidades/'))`,
);
if (fallback) break;
}
if (!fallback) throw Error('Map failure did not preserve investment list');
observations.push({scenario: 'map_request_blocked', fallback_list: true});
await send('Network.setBlockedURLs', {urls: []});
observations.push({ scenario: 'map_request_blocked', fallback_list: true });
await send('Network.setBlockedURLs', { urls: [] });
if (errors.length) throw Error('JavaScript errors: ' + errors.join('; '));
fs.writeFileSync('docs/investmoz/zones/browser-validation.json', JSON.stringify({date: new Date().toISOString(), scope: 'Public pages and empty states only; no institutional workflow/UAT claim', observations, errors}, null, 2));
console.log(JSON.stringify({passed: observations.length, javascript_errors: errors.length}));
fs.writeFileSync(
'docs/investmoz/zones/browser-validation.json',
JSON.stringify(
{
date: new Date().toISOString(),
scope: 'Public pages and empty states only; no institutional workflow/UAT claim',
observations,
errors,
},
null,
2,
),
);
console.log(
JSON.stringify({
passed: observations.length,
javascript_errors: errors.length,
}),
);
} finally {
await send('Page.close'); ws.close();
await send('Page.close');
ws.close();
}
+440 -41
View File
@@ -1,47 +1,446 @@
import fs from 'node:fs';
const routes = JSON.parse(fs.readFileSync(process.argv[2] ?? 'C:/Users/macbook/AppData/Local/Temp/zones-routes.json', 'utf8').replace(/^\uFEFF/, ''));
const string = {type: 'string'};
const uuid = {type: 'string', format: 'uuid'};
const date = {type: 'string', format: 'date'};
const version = {type: 'integer', minimum: 1};
const nullable = schema => ({...schema, nullable: true});
const object = (properties, required = []) => ({type: 'object', properties, required});
const relation = {association_type: {type: 'string', enum: ['official','influence','proximity','potential','historical']},role: {type:'string',enum:['primary','beneficiary','served','enabled','dependent','related','potential','historical']},source_reference: {type:'string',minLength:10,maxLength:2000},justification:{type:'string',minLength:10,maxLength:3000},legal_source_id:nullable(uuid),valid_from:date,valid_until:nullable(date),priority:{type:'integer',minimum:0,maximum:100},is_primary:{type:'boolean'}};
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']},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),
Geometry: object({geometry:object({type:{type:'string',enum:['Point','LineString','Polygon','MultiPolygon']},coordinates:{type:'array',items:{}}},['type','coordinates']),purpose:{type:'string',enum:['official_perimeter','influence','site','alternative']},legal_source_id:nullable(uuid),source_reference:string,validating_entity:string,observed_at:date},['geometry','purpose','source_reference','validating_entity','observed_at']),
const routes = JSON.parse(
fs
.readFileSync(
process.argv[2] ??
'C:/Users/macbook/AppData/Local/Temp/zones-routes.json',
'utf8',
)
.replace(/^\uFEFF/, ''),
);
const string = { type: 'string' };
const uuid = { type: 'string', format: 'uuid' };
const date = { type: 'string', format: 'date' };
const version = { type: 'integer', minimum: 1 };
const nullable = (schema) => ({ ...schema, nullable: true });
const object = (properties, required = []) => ({
type: 'object',
properties,
required,
});
const relation = {
association_type: {
type: 'string',
enum: ['official', 'influence', 'proximity', 'potential', 'historical'],
},
role: {
type: 'string',
enum: [
'primary',
'beneficiary',
'served',
'enabled',
'dependent',
'related',
'potential',
'historical',
],
},
source_reference: { type: 'string', minLength: 10, maxLength: 2000 },
justification: { type: 'string', minLength: 10, maxLength: 3000 },
legal_source_id: nullable(uuid),
valid_from: date,
valid_until: nullable(date),
priority: { type: 'integer', minimum: 0, maximum: 100 },
is_primary: { type: 'boolean' },
};
schemas.Zone.description='PUT requires version_no. Save withdraws publication and requires a new independent review. No official status inferred from category.';
schemas.Relation.description='Exactly one of cluster_id, corridor_id, project_id. Official association requires legal_source_id. Unique zone-target pair; duplicate returns 409.';
schemas.Link.description='Official association requires legal_source_id. Creates or reuses UUID mapping for existing opportunity; duplicate zone-item pair returns 409. Potential remains potential after review.';
schemas.Geometry.description='GeoJSON geometry in EPSG:4326, 2D, valid, nonempty, max 200000 encoded bytes. Official perimeter requires Polygon/MultiPolygon and legal source. No status inferred from geometry.';
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('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 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';
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'])}}};
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'],
},
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,
),
Geometry: object(
{
geometry: object(
{
type: {
type: 'string',
enum: [
'Point',
'LineString',
'Polygon',
'MultiPolygon',
],
},
coordinates: { type: 'array', items: {} },
},
['type', 'coordinates'],
),
purpose: {
type: 'string',
enum: [
'official_perimeter',
'influence',
'site',
'alternative',
],
},
legal_source_id: nullable(uuid),
source_reference: string,
validating_entity: string,
observed_at: date,
},
[
'geometry',
'purpose',
'source_reference',
'validating_entity',
'observed_at',
],
),
};
schemas.Zone.description =
'PUT requires version_no. Save withdraws publication and requires a new independent review. No official status inferred from category.';
schemas.Relation.description =
'Exactly one of cluster_id, corridor_id, project_id. Official association requires legal_source_id. Unique zone-target pair; duplicate returns 409.';
schemas.Link.description =
'Official association requires legal_source_id. Creates or reuses UUID mapping for existing opportunity; duplicate zone-item pair returns 409. Potential remains potential after review.';
schemas.Geometry.description =
'GeoJSON geometry in EPSG:4326, 2D, valid, nonempty, max 200000 encoded bytes. Official perimeter requires Polygon/MultiPolygon and legal source. No status inferred from geometry.';
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('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 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';
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}}}};
operation.requestBody = {
required: true,
content: {
'application/json': {
schema: { $ref: '#/components/schemas/' + schema },
},
},
};
}
}
(paths[path]??={})[method]=operation;
(paths[path] ??= {})[method] = operation;
}
const doc={openapi:'3.0.3',info:{title:'InvestMoz zone foundation API',version:'2026-09-28',description:'Implemented local routes only. Session cookies and CSRF; no bearer protocol invented. Admin: verified manager with confirmed MFA; legal/GIS/publish actions also require configured designated role. 30 requests/minute for management; public API uses application throttle. Approval in the portal is documentary review, not an administrative act. API v1 remains compatible and adds optional zee_id/zfi_id/park_id filters. Response schemas are deliberately open pending full contract typing.'},paths,components:{securitySchemes:{laravelSession:{type:'apiKey',in:'cookie',name:'laravel_session',description:'Actual session cookie name is configured by Laravel. Send X-XSRF-TOKEN from the session; no credentials embedded.'}},schemas}};
fs.writeFileSync('docs/investmoz/zones/openapi.json',JSON.stringify(doc,null,2)+'\n');
console.log(JSON.stringify({documented_operations:operations,registered_routes:routes.length,scope:'Route/method coverage; not exhaustive response-schema conformance.'}));
const doc = {
openapi: '3.0.3',
info: {
title: 'InvestMoz zone foundation API',
version: '2026-09-28',
description:
'Implemented local routes only. Session cookies and CSRF; no bearer protocol invented. Admin: verified manager with confirmed MFA; legal/GIS/publish actions also require configured designated role. 30 requests/minute for management; public API uses application throttle. Approval in the portal is documentary review, not an administrative act. API v1 remains compatible and adds optional zee_id/zfi_id/park_id filters. Response schemas are deliberately open pending full contract typing.',
},
paths,
components: {
securitySchemes: {
laravelSession: {
type: 'apiKey',
in: 'cookie',
name: 'laravel_session',
description:
'Actual session cookie name is configured by Laravel. Send X-XSRF-TOKEN from the session; no credentials embedded.',
},
},
schemas,
},
};
fs.writeFileSync(
'docs/investmoz/zones/openapi.json',
JSON.stringify(doc, null, 2) + '\n',
);
console.log(
JSON.stringify({
documented_operations: operations,
registered_routes: routes.length,
scope: 'Route/method coverage; not exhaustive response-schema conformance.',
}),
);