Juntar fase5-producao ao main (inclui c9bd6db da máquina Windows)
Conflito em docs/historico/decisoes-do-proprietario.md resolvido mantendo
as decisões de 01/12 da fase 5 e as notas de 30/11 de c9bd6db.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Binary file not shown.
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot access and required source scope; positive old source selection tested in disposable databases.'},null,2));
|
||||
console.log('Escolha de acordos conferida em leitura no piloto.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Live synthetic scope has no technical alternatives or specific execution grants; technical review, independence and source changes tested in disposable databases.'},null,2));
|
||||
console.log('Alternativas tecnicas e tarefas conferidas, preservando competencias especificas.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer = client(); await viewer.enter('admin');
|
||||
const dashboard = await viewer.request('/dashboard');
|
||||
if (dashboard.page?.props.context?.enforced) await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
|
||||
@@ -43,4 +54,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/approval-routing-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,profile_task_catalogue:'passed',workflow_notices:'ready',existing_requisition_routing:detail,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2));
|
||||
console.log('Profile task catalogue and existing requisition routing verified.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/approval-search-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -24,4 +35,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot facts and authorised CSV; populated overlap, registered expired proposals and pagination tested in disposable databases.'},null,2));
|
||||
console.log('Consultas de aprovadas conferidas sem novas decisões no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -15,4 +26,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/audit-metadata-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,pilot_grants_changed:false,business_commands:false,visual_review:false,coverage:'Denial before explicit permission; positive access exercised in disposable databases.'},null,2));
|
||||
console.log('Auditoria recusa acesso no piloto sem nova competência explícita.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='))
|
||||
.replace('async function request(path, method = \'GET\', data, inertia = true)', 'async function request(path, method = \'GET\', data, inertia = true, extraHeaders = {})')
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source
|
||||
.slice(source.indexOf('const base ='), source.indexOf('const author ='))
|
||||
.replace(
|
||||
"async function request(path, method = 'GET', data, inertia = true)",
|
||||
"async function request(path, method = 'GET', data, inertia = true, extraHeaders = {})",
|
||||
)
|
||||
.replace('headers: {', 'headers: { ...extraHeaders,');
|
||||
assert.ok(common.includes('extraHeaders = {}'));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -30,4 +42,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing synthetic requisition 2: scoped detail, partial audit pagination and full CSV access.'},null,2));
|
||||
console.log('Paginação parcial do histórico conferida sem comandos de negócio no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes = [];
|
||||
for (const role of ['procurement', 'department_head', 'finance']) {
|
||||
const viewer = client();
|
||||
@@ -33,4 +44,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
note: 'Only current first-page tasks are followed; disposable tests cover pending approval and issuance.'
|
||||
}, null, 2));
|
||||
console.log('Encaminhamento de adjudicacoes conferido com o ambito actual dos perfis existentes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -26,4 +37,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/benchmark-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -2,12 +2,29 @@ import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const installation = JSON.parse(
|
||||
await fs.readFile('docs/proofs/rq01-distribution-pilot-installation.json', 'utf8'),
|
||||
await fs.readFile(
|
||||
'docs/proofs/rq01-distribution-pilot-installation.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(installation.status, 'installed_and_capability_enabled_no_business_operations');
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
assert.equal(
|
||||
installation.status,
|
||||
'installed_and_capability_enabled_no_business_operations',
|
||||
);
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['requester','admin','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -30,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/rq01-distribution-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -6,43 +6,118 @@ import assert from 'node:assert/strict';
|
||||
|
||||
const frontend = process.argv[2];
|
||||
assert.ok(frontend, 'Provide the verified frontend build directory.');
|
||||
const roots = ['app', 'bootstrap', 'config', 'database', 'resources', 'routes', 'integrations', 'packages', 'public',
|
||||
'composer.json', 'composer.lock', 'package.json', 'package-lock.json', 'artisan', '.gitattributes', '.env.example',
|
||||
'scripts/verify-compras-release.php', 'scripts/build-compras-release.mjs', 'scripts/archive-compras-release.py', 'scripts/deployment/compras-tempo-deploy.sh'];
|
||||
const roots = [
|
||||
'app',
|
||||
'bootstrap',
|
||||
'config',
|
||||
'database',
|
||||
'resources',
|
||||
'routes',
|
||||
'integrations',
|
||||
'packages',
|
||||
'public',
|
||||
'composer.json',
|
||||
'composer.lock',
|
||||
'package.json',
|
||||
'package-lock.json',
|
||||
'artisan',
|
||||
'.gitattributes',
|
||||
'.env.example',
|
||||
'scripts/verify-compras-release.php',
|
||||
'scripts/build-compras-release.mjs',
|
||||
'scripts/archive-compras-release.py',
|
||||
'scripts/deployment/compras-tempo-deploy.sh',
|
||||
];
|
||||
const listed = ['git', 'ls-files'];
|
||||
const tracked = execFileSync(listed[0], [...listed.slice(1), '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const added = execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const tracked = execFileSync(
|
||||
listed[0],
|
||||
[...listed.slice(1), '-z', '--', ...roots],
|
||||
{ encoding: 'utf8' },
|
||||
).split('\0');
|
||||
const added = execFileSync(
|
||||
'git',
|
||||
['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots],
|
||||
{ encoding: 'utf8' },
|
||||
).split('\0');
|
||||
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const source = {};
|
||||
const exact = [];
|
||||
for (const file of [...new Set([...tracked, ...added])].filter(Boolean).sort()) {
|
||||
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/')) continue;
|
||||
for (const file of [...new Set([...tracked, ...added])]
|
||||
.filter(Boolean)
|
||||
.sort()) {
|
||||
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/'))
|
||||
continue;
|
||||
const info = await fs.lstat(file);
|
||||
if (!info.isFile() || info.isSymbolicLink()) continue;
|
||||
const bytes = await fs.readFile(file);
|
||||
const pinned = file.startsWith('packages/budget-control/') || file.startsWith('packages/payables/')
|
||||
|| file === 'resources/data/geography/cartografia-moz.json' || bytes.includes(0);
|
||||
const pinned =
|
||||
file.startsWith('packages/budget-control/') ||
|
||||
file.startsWith('packages/payables/') ||
|
||||
file === 'resources/data/geography/cartografia-moz.json' ||
|
||||
bytes.includes(0);
|
||||
if (pinned) exact.push(file);
|
||||
source[file] = hash(pinned ? bytes : Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n')));
|
||||
source[file] = hash(
|
||||
pinned
|
||||
? bytes
|
||||
: Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n')),
|
||||
);
|
||||
}
|
||||
const buildBytes = await fs.readFile(path.join(frontend, 'manifest.json'));
|
||||
const build = JSON.parse(buildBytes);
|
||||
const assets = {};
|
||||
for (const entry of Object.values(build)) {
|
||||
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
|
||||
for (const file of [
|
||||
entry.file,
|
||||
...(entry.css ?? []),
|
||||
...(entry.assets ?? []),
|
||||
]) {
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..'));
|
||||
assets[file] = hash(await fs.readFile(path.join(frontend, file)));
|
||||
}
|
||||
}
|
||||
const manifest = { contract: 'compras.release.v1', product: 'compras', source_eol: 'lf', exact_source_files: exact,
|
||||
source_files: source, frontend: { manifest_sha256: hash(buildBytes), entry: build['resources/js/app.tsx'].file,
|
||||
fonts_manifest_sha256: hash(await fs.readFile(path.join(frontend, 'fonts-manifest.json'))),
|
||||
files: Object.fromEntries(Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en'))) },
|
||||
const manifest = {
|
||||
contract: 'compras.release.v1',
|
||||
product: 'compras',
|
||||
source_eol: 'lf',
|
||||
exact_source_files: exact,
|
||||
source_files: source,
|
||||
frontend: {
|
||||
manifest_sha256: hash(buildBytes),
|
||||
entry: build['resources/js/app.tsx'].file,
|
||||
fonts_manifest_sha256: hash(
|
||||
await fs.readFile(path.join(frontend, 'fonts-manifest.json')),
|
||||
),
|
||||
files: Object.fromEntries(
|
||||
Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en')),
|
||||
),
|
||||
},
|
||||
components: [
|
||||
{ setting: 'COMPRAS_RUNTIME_ROOT', manifest_sha256: '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7' },
|
||||
{ setting: 'COMPRAS_INVENTORY_ROOT', manifest_sha256: '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd' },
|
||||
{ setting: 'COMPRAS_ORDER_CANCELLATION_ROOT', manifest_sha256: '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f' },
|
||||
] };
|
||||
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile('compras-release.json', JSON.stringify(manifest, null, 2)+'\n');
|
||||
console.log(JSON.stringify({ release_id: manifest.release_id, source_files: Object.keys(source).length, asset_files: Object.keys(assets).length }));
|
||||
{
|
||||
setting: 'COMPRAS_RUNTIME_ROOT',
|
||||
manifest_sha256:
|
||||
'80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7',
|
||||
},
|
||||
{
|
||||
setting: 'COMPRAS_INVENTORY_ROOT',
|
||||
manifest_sha256:
|
||||
'8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd',
|
||||
},
|
||||
{
|
||||
setting: 'COMPRAS_ORDER_CANCELLATION_ROOT',
|
||||
manifest_sha256:
|
||||
'52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f',
|
||||
},
|
||||
],
|
||||
};
|
||||
manifest.release_id = 'compras-' + hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile(
|
||||
'compras-release.json',
|
||||
JSON.stringify(manifest, null, 2) + '\n',
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
release_id: manifest.release_id,
|
||||
source_files: Object.keys(source).length,
|
||||
asset_files: Object.keys(assets).length,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -52,7 +52,7 @@ foreach ($runtime + $verification as $file => $expected) {
|
||||
throw new RuntimeException('Candidata imutável divergente.');
|
||||
}
|
||||
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
if (! is_dir(dirname($target))) {
|
||||
mkdir(dirname($target), 0700, true);
|
||||
@@ -94,5 +94,5 @@ if (! $rejected) {
|
||||
throw new RuntimeException('A candidata não deve ser instalável pelo updater de código.');
|
||||
}
|
||||
$result = ['candidate_id' => $id, 'directory' => $destination, 'manifest_sha256' => hash('sha256', $manifestText), 'archives' => $archives, 'standard_updater_refuses_candidate' => true, 'activation_performed' => false];
|
||||
file_put_contents($root.'/docs/proofs/internal-requisitions-candidate.json', json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
|
||||
file_put_contents($root.'/docs/proofs/internal-requisitions-candidate.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const proofName = process.argv.includes('--additional') ? 'candidate-additional-geography-http.json' : 'candidate-geography-http.json';
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const proofName = process.argv.includes('--additional')
|
||||
? 'candidate-additional-geography-http.json'
|
||||
: 'candidate-geography-http.json';
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const guest=await fetch(base+'/candidaturas/1/divisao-administrativa',{headers:{Accept:'application/json'},redirect:'manual'}); assert.equal(guest.status,401);
|
||||
const staff=client(); await staff.enter('admin'); assert.equal((await staff.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302); const denied=await staff.request('/candidaturas/1/divisao-administrativa','GET',undefined,false); assert.equal(denied.status,401);
|
||||
const catalogue=await staff.request('/api/divisao-administrativa'); assert.equal(catalogue.status,200); assert.equal(catalogue.page.data.length,11);
|
||||
await fs.writeFile('docs/proofs/${proofName}',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',guest_status:401,staff_without_candidate_status:401,existing_staff_catalogue_status:200,registration_commands:false,profile_commands:false,portal_configuration_commands:false,business_commands:false,mfa_activation:false,positive_candidate_session_coverage:'disposable tests only',visual_review:false},null,2));
|
||||
console.log('Candidate catalogue denied to guests and staff-only sessions; no candidate registration or profile changes.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer=client(); await viewer.enter('admin');
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
|
||||
const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
|
||||
@@ -11,4 +22,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
let inboxes=0; for(const record of index.page.props.processes.data.slice(0,2)) { const page=await viewer.request('/pessoas/'+record.id+'/recebidas'); if(page.status===200) { assert.equal(page.page.props.geographyEnabled,true); inboxes++; } else { assert.equal(page.status,403); } }
|
||||
await fs.writeFile('docs/proofs/candidate-territory-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',people_index_status:200,unknown_process_catalogue_status:404,procurement_catalogue_in_people_context_status:403,visible_inboxes_checked:inboxes,business_commands:false,process_or_portal_created:false,profile_commands:false,triage_commands:false,visual_review:false,positive_process_filter_coverage:'disposable tests'},null,2));
|
||||
console.log('People access remains scoped; no new processes, profiles or triage decisions.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -4,35 +4,72 @@ import assert from 'node:assert/strict';
|
||||
|
||||
const release = JSON.parse(await fs.readFile('compras-release.json', 'utf8'));
|
||||
const base = 'https://compras.tempo.co.mz';
|
||||
const entry = await fetch(base+'/', { redirect: 'manual', signal: AbortSignal.timeout(15000) });
|
||||
const entry = await fetch(base + '/', {
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
assert.equal(entry.status, 302);
|
||||
assert.equal(new URL(entry.headers.get('location'), base).pathname, '/login');
|
||||
const queue = Object.entries(release.frontend.files);
|
||||
let checked = 0;
|
||||
await Promise.all(Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, expected] = entry;
|
||||
const response = await fetch(base+'/build/'+name, { signal: AbortSignal.timeout(20000) });
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), expected, name);
|
||||
checked++;
|
||||
}
|
||||
}));
|
||||
for (const [path, component] of [['/', 'auth/login'], ['/login', 'auth/login'], ['/apresentacao', 'home']]) {
|
||||
const response = await fetch(base+path, { signal: AbortSignal.timeout(15000) });
|
||||
await Promise.all(
|
||||
Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, expected] = entry;
|
||||
const response = await fetch(base + '/build/' + name, {
|
||||
signal: AbortSignal.timeout(20000),
|
||||
});
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(
|
||||
crypto
|
||||
.createHash('sha256')
|
||||
.update(new Uint8Array(await response.arrayBuffer()))
|
||||
.digest('hex'),
|
||||
expected,
|
||||
name,
|
||||
);
|
||||
checked++;
|
||||
}
|
||||
}),
|
||||
);
|
||||
for (const [path, component] of [
|
||||
['/', 'auth/login'],
|
||||
['/login', 'auth/login'],
|
||||
['/apresentacao', 'home'],
|
||||
]) {
|
||||
const response = await fetch(base + path, {
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
const html = await response.text();
|
||||
assert.ok(html.includes(release.frontend.entry));
|
||||
const bootstrap = html.match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/);
|
||||
const bootstrap = html.match(
|
||||
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
|
||||
);
|
||||
assert.ok(bootstrap);
|
||||
const page = JSON.parse(bootstrap[1]);
|
||||
assert.equal(page.component, component);
|
||||
assert.equal(page.props.auth.user, null);
|
||||
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
|
||||
assert.deepEqual(page.props.commonFinanceNavigation, {
|
||||
payments: false,
|
||||
ledger: false,
|
||||
configuration: false,
|
||||
});
|
||||
}
|
||||
const proof = { state: 'passed', product: 'compras', release_id: release.release_id, public_url: base,
|
||||
assets_verified: checked, real_product_entry: true, login_entry: true, anonymous_private_identity_or_financial_access: false };
|
||||
await fs.writeFile('docs/proofs/compras-release-http.json', JSON.stringify(proof, null, 2)+'\n');
|
||||
const proof = {
|
||||
state: 'passed',
|
||||
product: 'compras',
|
||||
release_id: release.release_id,
|
||||
public_url: base,
|
||||
assets_verified: checked,
|
||||
real_product_entry: true,
|
||||
login_entry: true,
|
||||
anonymous_private_identity_or_financial_access: false,
|
||||
};
|
||||
await fs.writeFile(
|
||||
'docs/proofs/compras-release-http.json',
|
||||
JSON.stringify(proof, null, 2) + '\n',
|
||||
);
|
||||
console.log(JSON.stringify(proof));
|
||||
|
||||
@@ -6,25 +6,58 @@ const file = 'docs/proofs/public-demonstration-frontend.json';
|
||||
const proof = JSON.parse(await fs.readFile(file, 'utf8'));
|
||||
const queue = Object.entries(proof.files);
|
||||
let checked = 0;
|
||||
await Promise.all(Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, hash] = entry;
|
||||
const response = await fetch('https://compras.tempo.co.mz/build/' + name, { signal: AbortSignal.timeout(20000) });
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), hash, name);
|
||||
checked++;
|
||||
}
|
||||
}));
|
||||
Object.assign(proof, { state: 'assets_passed_banner_pending', public_assets_responses_and_hashes: checked });
|
||||
await Promise.all(
|
||||
Array.from({ length: 4 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [name, hash] = entry;
|
||||
const response = await fetch(
|
||||
'https://compras.tempo.co.mz/build/' + name,
|
||||
{ signal: AbortSignal.timeout(20000) },
|
||||
);
|
||||
assert.equal(response.status, 200, name);
|
||||
assert.equal(
|
||||
crypto
|
||||
.createHash('sha256')
|
||||
.update(new Uint8Array(await response.arrayBuffer()))
|
||||
.digest('hex'),
|
||||
hash,
|
||||
name,
|
||||
);
|
||||
checked++;
|
||||
}
|
||||
}),
|
||||
);
|
||||
Object.assign(proof, {
|
||||
state: 'assets_passed_banner_pending',
|
||||
public_assets_responses_and_hashes: checked,
|
||||
});
|
||||
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
|
||||
const response = await fetch('https://compras.tempo.co.mz/login', { signal: AbortSignal.timeout(15000) });
|
||||
const response = await fetch('https://compras.tempo.co.mz/login', {
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
const html = await response.text();
|
||||
const manifest = JSON.parse(await fs.readFile('storage/framework/testing/compras-presentation-final-ui-20261129/manifest.json', 'utf8'));
|
||||
const manifest = JSON.parse(
|
||||
await fs.readFile(
|
||||
'storage/framework/testing/compras-presentation-final-ui-20261129/manifest.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.ok(html.includes(manifest['resources/js/app.tsx'].file));
|
||||
assert.ok(html.includes('Empresa e dados fictícios'));
|
||||
Object.assign(proof, { state: 'passed', date: new Date().toISOString(), public_entry_current: true, demonstration_banner_present: true });
|
||||
Object.assign(proof, {
|
||||
state: 'passed',
|
||||
date: new Date().toISOString(),
|
||||
public_entry_current: true,
|
||||
demonstration_banner_present: true,
|
||||
});
|
||||
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
|
||||
console.log(JSON.stringify({ state: proof.state, public_assets_responses_and_hashes: checked, public_entry_current: true }));
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
state: proof.state,
|
||||
public_assets_responses_and_hashes: checked,
|
||||
public_entry_current: true,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -2,53 +2,115 @@ import fs from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
let plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8'));
|
||||
let plan = JSON.parse(
|
||||
await fs.readFile(
|
||||
'docs/proofs/compras-standalone-pilot-activation-proposal.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
let interfaceDelta = false;
|
||||
try {
|
||||
const result = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication.json', 'utf8'));
|
||||
const bytes = await fs.readFile('docs/proofs/analytics-print-publication-proposal.json');
|
||||
const result = JSON.parse(
|
||||
await fs.readFile(
|
||||
'docs/proofs/analytics-print-publication.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const bytes = await fs.readFile(
|
||||
'docs/proofs/analytics-print-publication-proposal.json',
|
||||
);
|
||||
const proposal = JSON.parse(bytes);
|
||||
const approval = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication-authorization.json', 'utf8'));
|
||||
const approval = JSON.parse(
|
||||
await fs.readFile(
|
||||
'docs/proofs/analytics-print-publication-authorization.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(result.pilot_state ?? result.state, 'passed');
|
||||
assert.equal(approval.state, 'approved');
|
||||
assert.equal(approval.proposal_sha256, crypto.createHash('sha256').update(bytes).digest('hex'));
|
||||
assert.equal(
|
||||
approval.proposal_sha256,
|
||||
crypto.createHash('sha256').update(bytes).digest('hex'),
|
||||
);
|
||||
assert.equal(result.manifest_sha256, proposal.manifest_sha256);
|
||||
assert.equal(proposal.previous_manifest_sha256, plan.frontend.manifest_sha256);
|
||||
assert.equal(
|
||||
proposal.previous_manifest_sha256,
|
||||
plan.frontend.manifest_sha256,
|
||||
);
|
||||
plan = { ...plan, frontend: proposal };
|
||||
interfaceDelta = true;
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
}
|
||||
const activation = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation.json', 'utf8'));
|
||||
const activation = JSON.parse(
|
||||
await fs.readFile(
|
||||
'docs/proofs/compras-standalone-pilot-activation.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(activation.state, 'passed');
|
||||
assert.equal(plan.target, 'http://127.0.0.1:8005');
|
||||
let verified = 0;
|
||||
const queue = Object.entries(plan.frontend.files);
|
||||
await Promise.all(Array.from({ length: 3 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [file, hash] = entry;
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..'));
|
||||
const response = await fetch(`${plan.target}/build/${file}`, { signal: AbortSignal.timeout(10000) });
|
||||
assert.equal(response.status, 200, file);
|
||||
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), hash, file);
|
||||
verified++;
|
||||
}
|
||||
}));
|
||||
const response = await fetch('https://compras.tempo.co.mz/dashboard', { signal: AbortSignal.timeout(15000) });
|
||||
await Promise.all(
|
||||
Array.from({ length: 3 }, async () => {
|
||||
for (;;) {
|
||||
const entry = queue.shift();
|
||||
if (!entry) return;
|
||||
const [file, hash] = entry;
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..'));
|
||||
const response = await fetch(`${plan.target}/build/${file}`, {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
assert.equal(response.status, 200, file);
|
||||
assert.equal(
|
||||
crypto
|
||||
.createHash('sha256')
|
||||
.update(new Uint8Array(await response.arrayBuffer()))
|
||||
.digest('hex'),
|
||||
hash,
|
||||
file,
|
||||
);
|
||||
verified++;
|
||||
}
|
||||
}),
|
||||
);
|
||||
const response = await fetch('https://compras.tempo.co.mz/dashboard', {
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
const html = await response.text();
|
||||
const bootstrap = html.match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/);
|
||||
const bootstrap = html.match(
|
||||
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
|
||||
);
|
||||
assert.ok(bootstrap, 'Expected public Inertia bootstrap');
|
||||
const page = JSON.parse(bootstrap[1]);
|
||||
assert.equal(page.props.auth.user, null);
|
||||
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
|
||||
const manifest = JSON.parse(await fs.readFile('public/build/manifest.json', 'utf8'));
|
||||
assert.deepEqual(page.props.commonFinanceNavigation, {
|
||||
payments: false,
|
||||
ledger: false,
|
||||
configuration: false,
|
||||
});
|
||||
const manifest = JSON.parse(
|
||||
await fs.readFile('public/build/manifest.json', 'utf8'),
|
||||
);
|
||||
const publicCurrent = html.includes(manifest['resources/js/app.tsx'].file);
|
||||
const proof = { date: new Date().toISOString(), state: publicCurrent ? 'passed' : 'pilot_passed_public_installation_pending', pilot_asset_responses_and_hashes: verified,
|
||||
public_domain_html_delivers_new_entry: publicCurrent, public_anonymous_identity_preserved: true,
|
||||
private_finance_navigation_not_exposed_publicly: true, new_grants_or_business_operations: false };
|
||||
await fs.writeFile(interfaceDelta ? 'docs/proofs/analytics-print-publication-http.json' : 'docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n');
|
||||
const proof = {
|
||||
date: new Date().toISOString(),
|
||||
state: publicCurrent
|
||||
? 'passed'
|
||||
: 'pilot_passed_public_installation_pending',
|
||||
pilot_asset_responses_and_hashes: verified,
|
||||
public_domain_html_delivers_new_entry: publicCurrent,
|
||||
public_anonymous_identity_preserved: true,
|
||||
private_finance_navigation_not_exposed_publicly: true,
|
||||
new_grants_or_business_operations: false,
|
||||
};
|
||||
await fs.writeFile(
|
||||
interfaceDelta
|
||||
? 'docs/proofs/analytics-print-publication-http.json'
|
||||
: 'docs/proofs/compras-standalone-published-assets.json',
|
||||
JSON.stringify(proof, null, 2) + '\n',
|
||||
);
|
||||
console.log(JSON.stringify(proof));
|
||||
if (!publicCurrent) process.exitCode = 1;
|
||||
|
||||
@@ -2,9 +2,20 @@ import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
// Reuse the established isolated-host session client; do not copy credentials or bypass normal routes.
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results = [];
|
||||
for (const role of ['admin', 'procurement', 'finance']) {
|
||||
const viewer = client();
|
||||
@@ -41,4 +52,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/commercial-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<?php
|
||||
|
||||
use App\Services\StandaloneRuntime;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
require $root.'/vendor/autoload.php';
|
||||
@@ -55,9 +57,9 @@ $collectFlags(config()->all());
|
||||
ksort($flags);
|
||||
echo json_encode(['state' => 'passed', 'runtime_enabled' => $runtime->enabled(), 'features' => $features,
|
||||
'deployment_flags' => $flags,
|
||||
'history_schema' => ['pa_history_imports' => Illuminate\Support\Facades\Schema::hasTable('pa_history_imports'), 'pa_imported_payments' => Illuminate\Support\Facades\Schema::hasTable('pa_imported_payments')],
|
||||
'history_schema' => ['pa_history_imports' => Schema::hasTable('pa_history_imports'), 'pa_imported_payments' => Schema::hasTable('pa_imported_payments')],
|
||||
'pending_application_migrations' => array_values(array_diff(array_map(fn ($file) => basename($file, '.php'), glob($root.'/database/migrations/*.php')), DB::table('migrations')->pluck('migration')->all())),
|
||||
'routes' => $routes, 'component_flags' => $components, 'company_context_policies' => $tenants,
|
||||
'context_entitlements_configured' => count(config('work_context.entitlements', [])) > 0,
|
||||
'operational_contexts' => array_combine(array_keys(App\Services\WorkContext::OPTIONS), array_map(fn ($key) => App\Services\WorkContext::operational($key), array_keys(App\Services\WorkContext::OPTIONS))),
|
||||
'operational_contexts' => array_combine(array_keys(WorkContext::OPTIONS), array_map(fn ($key) => WorkContext::operational($key), array_keys(WorkContext::OPTIONS))),
|
||||
'business_data_changed' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -23,4 +34,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot export access; populated exports and native quantities tested in disposable databases.'},null,2));
|
||||
console.log('Exportação conferida sem comandos de negócio no piloto.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -25,4 +36,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot access and validation; positive record filtering verified in disposable databases.'},null,2));
|
||||
console.log('Consulta filtrada conferida no piloto sem comandos de negócio.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse','procurement','finance']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -28,4 +39,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Read-only pilot access; partial/full receipts, allocations and corrections exercised in disposable databases.'},null,2));
|
||||
console.log('Acompanhamento e paginação conferidos sem criar previsões, reservas ou movimentos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot read rights; positive old origins and native reversals tested in disposable databases.'},null,2));
|
||||
console.log('Pesquisa de origens de correcção conferida sem decisões, concessões ou movimentos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/draft-preparation-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/equipment-integration-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,grants_changed:false,visual_review:false,coverage:'Existing equipment only; complete native journeys exercised in disposable databases.'},null,2));
|
||||
console.log('Equipamentos consultados no piloto; sem novas compras ou movimentos.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','outputFile','return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'outputFile',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const rows=[], prints=new Set();
|
||||
const paths=['/ordens','/recepcoes','/stock','/stock/requisicoes','/equipamentos','/orcamentos','/facturas','/pagamentos','/planeamento','/revisao-compras','/relatorios','/relatorios/medidas-fornecedores','/compras/fornecimento?view=calendar','/compras/fornecimento?view=imports','/compras/acordos/vigencia'];
|
||||
for(const role of ['admin','procurement','finance','warehouse']){
|
||||
@@ -27,4 +39,6 @@ await new Function('fs','assert','outputFile','return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile(outputFile,JSON.stringify({environment:base,scope:'existing authorised records only',rows,print_paths:[...prints],business_commands:false,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({routes_checked:rows.length,print_paths:[...prints],statuses:rows.reduce((a,r)=>(a[r.status]=(a[r.status]??0)+1,a),{})}));
|
||||
`+'})()')(fs,assert,process.argv[2]??'docs/proofs/final-review-inventory.json');
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert, process.argv[2] ?? 'docs/proofs/final-review-inventory.json');
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes = [];
|
||||
for (const role of ['admin', 'finance']) {
|
||||
const viewer = client();
|
||||
@@ -36,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
note: 'Payment consultation retains its existing access audit; no financial decision is executed.'
|
||||
}, null, 2));
|
||||
console.log('Facturas, pagamentos e tarefas financeiras conferidos com as contas existentes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes = [];
|
||||
for (const role of ['procurement', 'finance', 'department_head']) {
|
||||
const viewer = client();
|
||||
@@ -38,4 +49,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
visual_review: false, coverage: 'Existing current scope and first-page tasks only; pending decisions tested in disposable databases.'
|
||||
}, null, 2));
|
||||
console.log('Analise documental, admissao, recomendacao e tarefas conferidas nos ambitos existentes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -18,4 +29,6 @@ for(const role of ['admin','procurement','finance']) {
|
||||
}
|
||||
await fs.writeFile('docs/proofs/administrative-geography-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
|
||||
console.log('Geographic selection available in company and supplier pages; no classification submitted.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
const admin=client(); await admin.enter('admin');
|
||||
assert.equal((await admin.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
@@ -14,4 +25,6 @@ records.push({role:'admin',pendingRecords:10729,firstPage:50,blankDesignations:9
|
||||
records.push({role:'procurement',reviewStatus:403});
|
||||
await fs.writeFile('docs/proofs/administrative-geography-review-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
|
||||
console.log('Administrative review and filtered CSV checked read-only; no geography or entity changes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','procurement','finance']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -18,4 +29,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot scope and lookup validation; approved historical periods and suspensions tested in disposable databases.'},null,2));
|
||||
console.log('Pesquisa de análises conferida sem criar origens, decisões ou acessos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes=[];
|
||||
for (const [role, expected] of [['admin',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -28,4 +39,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Existing current scope has no historical analysis and no historical execution grants; pending historical reviews tested only in disposable databases.'},null,2));
|
||||
console.log('Historico, competencias especificas, tarefas e diagnostico da instalacao conferidos.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer = client();
|
||||
await viewer.enter('admin');
|
||||
const dashboard = await viewer.request('/dashboard');
|
||||
@@ -27,4 +38,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
accounts_or_grants_changed: false, sgf_installation_changed: false, visual_review: false
|
||||
}, null, 2));
|
||||
console.log('Consulta da integração interna conferida; detalhes existentes verificados: ' + checkedDetails);
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -27,4 +38,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Pilot access and empty paginated/filtered lists; pending processes, native corrections and old sources tested in disposable databases.'},null,2));
|
||||
console.log('Ocorrências e estornos paginados conferidos sem decisões ou movimentos novos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'No persistent stock dispositions or reversals exist; pending decisions and physical movements tested in disposable databases only.'},null,2));
|
||||
console.log('Ocorrencias, estornos e tarefas conferidos nos perfis existentes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,19 +1,37 @@
|
||||
// Native Fortify, CSRF and Inertia protocol for owned loopback QA only.
|
||||
export function createNativeInertiaClient(origin, check) {
|
||||
const base = new URL(origin);
|
||||
if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname) || !base.port) throw Error("Owned loopback client required");
|
||||
if (
|
||||
base.protocol !== 'http:' ||
|
||||
!['localhost', '127.0.0.1'].includes(base.hostname) ||
|
||||
!base.port
|
||||
)
|
||||
throw Error('Owned loopback client required');
|
||||
const cookies = new Map();
|
||||
let version = '';
|
||||
const request = async (route, options = {}) => {
|
||||
if (!route.startsWith('/') || new URL(route, base).origin !== base.origin) throw Error('External HTTP destination refused');
|
||||
const response = await fetch(new URL(route, base), { ...options, redirect: 'manual', headers: {
|
||||
Accept: 'application/json', Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '),
|
||||
...(options.headers?.['X-Inertia'] === 'true' ? { 'X-Inertia-Version': version } : {}), ...options.headers,
|
||||
} });
|
||||
if (
|
||||
!route.startsWith('/') ||
|
||||
new URL(route, base).origin !== base.origin
|
||||
)
|
||||
throw Error('External HTTP destination refused');
|
||||
const response = await fetch(new URL(route, base), {
|
||||
...options,
|
||||
redirect: 'manual',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '),
|
||||
...(options.headers?.['X-Inertia'] === 'true'
|
||||
? { 'X-Inertia-Version': version }
|
||||
: {}),
|
||||
...options.headers,
|
||||
},
|
||||
});
|
||||
for (const header of response.headers.getSetCookie()) {
|
||||
const pair = header.split(';', 1)[0];
|
||||
const index = pair.indexOf('=');
|
||||
if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1));
|
||||
if (index > 0)
|
||||
cookies.set(pair.slice(0, index), pair.slice(index + 1));
|
||||
}
|
||||
// A checker may inspect only status/headers. Drain the network body before
|
||||
// a closed PHP socket can leave Undici paused, retaining a readable clone.
|
||||
@@ -21,55 +39,135 @@ export function createNativeInertiaClient(origin, check) {
|
||||
await response.arrayBuffer();
|
||||
return buffered;
|
||||
};
|
||||
const csrf = () => ({ 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? '') });
|
||||
const login = async email => {
|
||||
const initial = await request('/login', { headers: { Accept: 'text/html' } });
|
||||
const csrf = () => ({
|
||||
'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? ''),
|
||||
});
|
||||
const login = async (email) => {
|
||||
const initial = await request('/login', {
|
||||
headers: { Accept: 'text/html' },
|
||||
});
|
||||
check(initial.status === 200, 'native login page');
|
||||
const initialPage = (await initial.text()).match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/);
|
||||
const initialPage = (await initial.text()).match(
|
||||
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
|
||||
);
|
||||
check(initialPage !== null, 'native initial page protocol');
|
||||
version = JSON.parse(initialPage[1]).version;
|
||||
check(typeof version === 'string' && version.length > 0, 'native asset version');
|
||||
const payload = JSON.stringify({ email, password: 'password', remember: false });
|
||||
const invalid = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload });
|
||||
check(
|
||||
typeof version === 'string' && version.length > 0,
|
||||
'native asset version',
|
||||
);
|
||||
const payload = JSON.stringify({
|
||||
email,
|
||||
password: 'password',
|
||||
remember: false,
|
||||
});
|
||||
const invalid = await request('/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: payload,
|
||||
});
|
||||
check(invalid.status === 419, 'missing CSRF refused before login');
|
||||
const response = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: payload });
|
||||
check([200, 302].includes(response.status), 'native Fortify credentials accepted');
|
||||
const stale = await request('/dashboard', { headers: { 'X-Inertia': 'true', 'X-Inertia-Version': 'deliberately-stale-synthetic-version' } });
|
||||
check(stale.status === 409 && stale.headers.has('X-Inertia-Location'), 'stale asset protocol refused without changing access rules');
|
||||
const dashboard = await request('/dashboard', { headers: { 'X-Inertia': 'true' } });
|
||||
check(dashboard.status === 200, `authenticated dashboard status ${dashboard.status}`);
|
||||
const response = await request('/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...csrf() },
|
||||
body: payload,
|
||||
});
|
||||
check(
|
||||
[200, 302].includes(response.status),
|
||||
'native Fortify credentials accepted',
|
||||
);
|
||||
const stale = await request('/dashboard', {
|
||||
headers: {
|
||||
'X-Inertia': 'true',
|
||||
'X-Inertia-Version': 'deliberately-stale-synthetic-version',
|
||||
},
|
||||
});
|
||||
check(
|
||||
stale.status === 409 && stale.headers.has('X-Inertia-Location'),
|
||||
'stale asset protocol refused without changing access rules',
|
||||
);
|
||||
const dashboard = await request('/dashboard', {
|
||||
headers: { 'X-Inertia': 'true' },
|
||||
});
|
||||
check(
|
||||
dashboard.status === 200,
|
||||
`authenticated dashboard status ${dashboard.status}`,
|
||||
);
|
||||
const state = await dashboard.json();
|
||||
check(state.props.auth?.user?.email === email, 'session retains the exact native actor');
|
||||
check(
|
||||
state.props.auth?.user?.email === email,
|
||||
'session retains the exact native actor',
|
||||
);
|
||||
};
|
||||
const page = async (route, component) => {
|
||||
const response = await request(route, { headers: { 'X-Inertia': 'true' } });
|
||||
const response = await request(route, {
|
||||
headers: { 'X-Inertia': 'true' },
|
||||
});
|
||||
let error = '';
|
||||
if (response.status !== 200) {
|
||||
try { error = String((await response.clone().json()).message ?? '').slice(0, 180); } catch { /* status remains diagnostic */ }
|
||||
try {
|
||||
error = String(
|
||||
(await response.clone().json()).message ?? '',
|
||||
).slice(0, 180);
|
||||
} catch {
|
||||
/* status remains diagnostic */
|
||||
}
|
||||
}
|
||||
check(response.status === 200, `${component} native route status ${response.status} ${error}`);
|
||||
check(response.headers.get('X-Inertia') === 'true', `${component} native Inertia response`);
|
||||
check(
|
||||
response.status === 200,
|
||||
`${component} native route status ${response.status} ${error}`,
|
||||
);
|
||||
check(
|
||||
response.headers.get('X-Inertia') === 'true',
|
||||
`${component} native Inertia response`,
|
||||
);
|
||||
const page = await response.json();
|
||||
check(page.component === component, `${component} component`);
|
||||
check(page.encryptHistory === true, `${component} encrypted history`);
|
||||
if (component.startsWith('purchase-controls/')) check(response.headers.get('Cache-Control')?.includes('private') && response.headers.get('Cache-Control')?.includes('no-store'), 'purchase controls private response');
|
||||
if (component.startsWith('purchase-controls/'))
|
||||
check(
|
||||
response.headers.get('Cache-Control')?.includes('private') &&
|
||||
response.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'purchase controls private response',
|
||||
);
|
||||
return page;
|
||||
};
|
||||
const logout = async () => {
|
||||
check([200, 204, 302].includes((await request('/logout', { method: 'POST', headers: csrf() })).status), 'native logout');
|
||||
check((await request('/auditoria/eventos')).status === 401, 'closed session cannot read metadata');
|
||||
check(
|
||||
[200, 204, 302].includes(
|
||||
(await request('/logout', { method: 'POST', headers: csrf() }))
|
||||
.status,
|
||||
),
|
||||
'native logout',
|
||||
);
|
||||
check(
|
||||
(await request('/auditoria/eventos')).status === 401,
|
||||
'closed session cannot read metadata',
|
||||
);
|
||||
};
|
||||
const post = async (route, payload, expected = 302) => {
|
||||
const response = await request(route, { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: JSON.stringify(payload) });
|
||||
const response = await request(route, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...csrf() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const allowed = Array.isArray(expected) ? expected : [expected];
|
||||
let detail = '';
|
||||
if (!allowed.includes(response.status)) {
|
||||
try {
|
||||
const error = await response.clone().json();
|
||||
detail = String(error.message ?? '').slice(0, 180) + ' fields=' + Object.keys(error.errors ?? {}).join(',');
|
||||
} catch { /* status is still diagnostic */ }
|
||||
detail =
|
||||
String(error.message ?? '').slice(0, 180) +
|
||||
' fields=' +
|
||||
Object.keys(error.errors ?? {}).join(',');
|
||||
} catch {
|
||||
/* status is still diagnostic */
|
||||
}
|
||||
}
|
||||
check(allowed.includes(response.status), `native command ${route} status ${response.status} ${detail}`);
|
||||
check(
|
||||
allowed.includes(response.status),
|
||||
`native command ${route} status ${response.status} ${detail}`,
|
||||
);
|
||||
return response;
|
||||
};
|
||||
return { request, login, page, logout, post };
|
||||
|
||||
@@ -1,22 +1,44 @@
|
||||
// Prepare a source overlay only; keep the host's existing feature and permission guards.
|
||||
export function purchasingHomeOverlay(source) {
|
||||
const once = (old, value) => {
|
||||
if (source.split(old).length !== 2) throw Error('Purchasing home baseline changed: ' + old);
|
||||
if (source.split(old).length !== 2)
|
||||
throw Error('Purchasing home baseline changed: ' + old);
|
||||
source = source.replace(old, value);
|
||||
};
|
||||
const declarations = source.match(/\bconst\s+requisitions\s*=/g) ?? [];
|
||||
if (declarations.length > 1) throw Error('Ambiguous requisition capability declaration.');
|
||||
if (declarations.length > 1)
|
||||
throw Error('Ambiguous requisition capability declaration.');
|
||||
if (declarations.length === 0) {
|
||||
once("const payables=unit!==null&&can('supplier_payables.view',unit);", "const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);");
|
||||
} else if (!/const\s+requisitions\s*=\s*unit\s*!==\s*null\s*&&\s*(?:context\.purchasing\?\.internal_requisitions\s*===\s*true\s*&&\s*)?can\(['"]purchasing_requisitions\.view['"],\s*unit\);/.test(source)) {
|
||||
throw Error('Unknown requisition capability guard; reconcile before preparing.');
|
||||
once(
|
||||
"const payables=unit!==null&&can('supplier_payables.view',unit);",
|
||||
"const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);",
|
||||
);
|
||||
} else if (
|
||||
!/const\s+requisitions\s*=\s*unit\s*!==\s*null\s*&&\s*(?:context\.purchasing\?\.internal_requisitions\s*===\s*true\s*&&\s*)?can\(['"]purchasing_requisitions\.view['"],\s*unit\);/.test(
|
||||
source,
|
||||
)
|
||||
) {
|
||||
throw Error(
|
||||
'Unknown requisition capability guard; reconcile before preparing.',
|
||||
);
|
||||
}
|
||||
if (!source.includes('href="/purchasing/internal-requisitions"')) {
|
||||
once('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}');
|
||||
once(
|
||||
'<div className="actions">',
|
||||
'<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}',
|
||||
);
|
||||
}
|
||||
if (!source.includes('href="/purchasing/internal-requisitions/budget-setup"')) {
|
||||
once('<div className="actions">', '<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}');
|
||||
if (
|
||||
!source.includes(
|
||||
'href="/purchasing/internal-requisitions/budget-setup"',
|
||||
)
|
||||
) {
|
||||
once(
|
||||
'<div className="actions">',
|
||||
'<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}',
|
||||
);
|
||||
}
|
||||
if (!/!requisitions\s*&&/.test(source)) once('!budget&&!payables&&', '!budget&&!payables&&!requisitions&&');
|
||||
if (!/!requisitions\s*&&/.test(source))
|
||||
once('!budget&&!payables&&', '!budget&&!payables&&!requisitions&&');
|
||||
return source;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Read-only pilot access and empty pagination; 210 controls/history and pending-active pairs tested in disposable databases.'},null,2));
|
||||
console.log('Paginação de lotes conferida no piloto, sem novos dados ou permissões.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -23,4 +34,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Pilot has no active lot controls or operational quality grants; pending decisions and lot links exercised in disposable databases.'},null,2));
|
||||
console.log('Consulta e restrições de qualidade conferidas sem alterar lotes, decisões ou direitos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Live pilot has no lot setups or operational lot grants; pending configuration review tested only in disposable databases.'},null,2));
|
||||
console.log('Controlo por lotes e tarefas conferidos sem novas concessoes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -147,12 +147,41 @@ assert.equal(
|
||||
configuredMulti.some((e) => e.id === 'new_request'),
|
||||
true,
|
||||
);
|
||||
const capitalReaders = ['admin', 'procurement', 'finance', 'department_head', 'warehouse'];
|
||||
assert.ok(routes.some((route) => route.uri === 'projectos-imobilizado' && route.method.split('|').includes('GET')));
|
||||
const capitalReaders = [
|
||||
'admin',
|
||||
'procurement',
|
||||
'finance',
|
||||
'department_head',
|
||||
'warehouse',
|
||||
];
|
||||
assert.ok(
|
||||
routes.some(
|
||||
(route) =>
|
||||
route.uri === 'projectos-imobilizado' &&
|
||||
route.method.split('|').includes('GET'),
|
||||
),
|
||||
);
|
||||
for (const role of [...capitalReaders, 'requester']) {
|
||||
const groups = procurementNavigation([role], false, undefined, false, false, false, true);
|
||||
assert.equal(groups.flatMap((group) => group.entries).some((entry) => entry.id === 'capital_register'), capitalReaders.includes(role));
|
||||
if (capitalReaders.includes(role)) assert.equal(activeProcurementEntry(groups, '/projectos-imobilizado?history=qa'), 'capital_register');
|
||||
const groups = procurementNavigation(
|
||||
[role],
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
groups
|
||||
.flatMap((group) => group.entries)
|
||||
.some((entry) => entry.id === 'capital_register'),
|
||||
capitalReaders.includes(role),
|
||||
);
|
||||
if (capitalReaders.includes(role))
|
||||
assert.equal(
|
||||
activeProcurementEntry(groups, '/projectos-imobilizado?history=qa'),
|
||||
'capital_register',
|
||||
);
|
||||
}
|
||||
const proof = {
|
||||
checked_at: new Date().toISOString(),
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -16,4 +27,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
await fs.writeFile('docs/proofs/mfa-foundation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,pilot_migration_applied:false,sgf_changed:false,visual_review:false},null,2));
|
||||
console.log('Base de confirmação conferida; MFA do piloto continua desactivado.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,migration_status_not_inferred_from_http:true,sgf_changed:false,visual_review:false,
|
||||
coverage:'Pilot remains disabled; enabled native management flows tested in disposable databases.'},null,2));
|
||||
console.log('Interface de segurança conferida; adesão MFA do piloto permanece desactivada.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -27,4 +38,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot report scopes; populated dates, pagination and revoked streaming access tested in disposable databases.'},null,2));
|
||||
console.log('Filtro de necessidades por aprovar conferido em leitura no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -23,4 +34,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
read_commands:false,business_decisions:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing synthetic profiles in read-only consultation; populated notice and mark-read flows tested in disposable databases.'},null,2));
|
||||
console.log('Consulta dos avisos conferida sem marcar avisos do piloto como lidos.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -15,4 +26,6 @@ for(const role of ['admin','warehouse','procurement','finance']) {
|
||||
}
|
||||
await fs.writeFile('docs/proofs/operational-geography-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
|
||||
console.log('Operational controls remain hidden pending schema approval; current geography catalogue remains available.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -4,11 +4,19 @@ import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
if (process.argv.length !== 3 || process.argv[2] !== '--read-only') {
|
||||
throw new Error('Use --read-only for in-process GET checks with existing pilot actors.');
|
||||
throw new Error(
|
||||
'Use --read-only for in-process GET checks with existing pilot actors.',
|
||||
);
|
||||
}
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const result = spawnSync('php', ['scripts/check-standalone-pilot-profiles.php', '--read-only'], {
|
||||
cwd: root, stdio: 'inherit', windowsHide: true,
|
||||
});
|
||||
const result = spawnSync(
|
||||
'php',
|
||||
['scripts/check-standalone-pilot-profiles.php', '--read-only'],
|
||||
{
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
if (result.error) throw result.error;
|
||||
process.exitCode = result.status ?? 1;
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer = client();
|
||||
await viewer.enter('admin');
|
||||
const response = await viewer.request('/administracao/parametrizacao');
|
||||
@@ -31,4 +42,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('storage/app/pilot-access-source.json', JSON.stringify(snapshot, null, 2));
|
||||
console.log(JSON.stringify({ ...proof, current_rules: props.companyRules,
|
||||
registered: snapshot.users.map(person => ({ id: person.id, name: person.name, department_id: person.department_id, functions: person.current_permissions, contexts: person.current_contexts })) }, null, 2));
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -12,8 +12,9 @@ foreach ($settings as $key => $value) {
|
||||
}
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
|
||||
use App\Models\ExternalPayment;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Supplier;
|
||||
@@ -21,6 +22,7 @@ use App\Models\User;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use App\Services\SupplierPayables;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Events\QueryExecuted;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -147,7 +149,7 @@ if ($job === 'setup') {
|
||||
} elseif (in_array($job, ['decision_fault', 'decision_confirm', 'decision_inspect'], true)) {
|
||||
config(['common-payables.history_decisions_enabled' => true]);
|
||||
auth()->guard()->setUser($validator);
|
||||
$payment = \App\Models\ExternalPayment::query()->where('amount_minor', 100000)->sole();
|
||||
$payment = ExternalPayment::query()->where('amount_minor', 100000)->sole();
|
||||
$frozen = fn () => hash('sha256', Payables::canonical(['imports' => DB::table('pa_history_imports')->get()->toArray(), 'links' => DB::table('pa_imported_payments')->get()->toArray()]));
|
||||
$original = $frozen();
|
||||
if ($job === 'decision_fault') {
|
||||
@@ -192,4 +194,4 @@ if ($job === 'setup') {
|
||||
} else {
|
||||
throw new LogicException('Unknown proof job.');
|
||||
}
|
||||
echo json_encode($result,JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE).PHP_EOL;
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -19,4 +30,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/payable-insights-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({http_checks:results.length*2,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer=client(); await viewer.enter('admin');
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
|
||||
const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
|
||||
@@ -18,4 +29,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/people-dossier-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,business_commands:false,visual_review:false,coverage:'Existing visible processes only; service and staff journeys exercised in disposable databases.'},null,2));
|
||||
console.log('Consulta de Pessoas conferida; sem decisões ou novos registos.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
const code = common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
const code =
|
||||
common +
|
||||
`
|
||||
const viewer = client(); await viewer.enter('admin');
|
||||
const dashboard = await viewer.request('/dashboard');
|
||||
if (dashboard.page?.props.context?.enforced) {
|
||||
@@ -57,4 +65,7 @@ await fs.writeFile('docs/proofs/people-reports-http.json',JSON.stringify({
|
||||
},null,2));
|
||||
console.log('People report and CSV verified in local evaluation.');
|
||||
`;
|
||||
await new Function('fs', 'assert', 'return (async()=>{'+code+'})()')(fs, assert);
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + code + '})()')(
|
||||
fs,
|
||||
assert,
|
||||
);
|
||||
|
||||
@@ -1,12 +1,29 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const proposal = JSON.parse(await fs.readFile('docs/proofs/pilot-access-proposal.json', 'utf8'));
|
||||
const applied = JSON.parse(await fs.readFile('docs/proofs/pilot-access-activation.json', 'utf8'));
|
||||
const proposal = JSON.parse(
|
||||
await fs.readFile('docs/proofs/pilot-access-proposal.json', 'utf8'),
|
||||
);
|
||||
const applied = JSON.parse(
|
||||
await fs.readFile('docs/proofs/pilot-access-activation.json', 'utf8'),
|
||||
);
|
||||
assert.equal(applied.result, 'applied');
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'proposal', 'applied', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'proposal',
|
||||
'applied',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer = client();
|
||||
await viewer.enter('admin');
|
||||
const parameters = await viewer.request('/administracao/parametrizacao');
|
||||
@@ -83,4 +100,6 @@ await new Function('fs', 'assert', 'proposal', 'applied', 'return (async()=>{' +
|
||||
};
|
||||
await fs.writeFile('docs/proofs/pilot-access-activation-http.json', JSON.stringify(proof, null, 2));
|
||||
console.log(JSON.stringify(proof, null, 2));
|
||||
` + '})()')(fs, assert, proposal, applied);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert, proposal, applied);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['department_head','procurement','requester']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('docs/proofs/pilot-approval-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
quantity:'2.000',total_minor_mzn:2320,approved_by:10,business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
|
||||
console.log('Aprovacao unica e encaminhamento para consulta ao mercado confirmados.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['procurement','finance','department_head']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -26,4 +37,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/pilot-evaluation-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,supplier_selection_or_order:false,visual_review:false},null,2));
|
||||
console.log('Seis avaliações neutras e encaminhamento para comparação conferidos por HTTP.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,12 +1,25 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer=client();await viewer.enter('admin');const dashboard=await viewer.request('/dashboard');
|
||||
if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
|
||||
const response=await viewer.request('/stock/piloto.csv','GET',undefined,false);
|
||||
assert.equal(response.status,200);assert.ok(response.text.includes('Conferido em'));assert.ok(response.text.includes('SGC autónomo'));assert.ok(response.text.includes('A preparar'));assert.ok(!response.text.includes('Solicitante — avaliação local'));
|
||||
await fs.writeFile('docs/proofs/pilot-export-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,csv:'passed',dated_configuration_checks:true,account_register_exported:false,business_commands:false,accounts_or_grants_changed:false,visual_print_review:false},null,2));
|
||||
console.log('Exportação administrativa do diagnóstico conferida em HTTP.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
const proof = JSON.parse(await fs.readFile('docs/proofs/pilot-market-activation.json', 'utf8'));
|
||||
await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
const proof = JSON.parse(
|
||||
await fs.readFile('docs/proofs/pilot-market-activation.json', 'utf8'),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'proof',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['procurement','finance','department_head']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -29,4 +43,6 @@ await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('docs/proofs/pilot-market-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
totals_minor_mzn:[2320,2552,2784],business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
|
||||
console.log('Cadastros independentes, tres propostas e encaminhamento conferidos sem avaliar.');
|
||||
` + '})()')(fs, assert, proof);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert, proof);
|
||||
|
||||
@@ -1,10 +1,27 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
const proof = JSON.parse(await fs.readFile('docs/proofs/pilot-replenishment-activation.json', 'utf8'));
|
||||
await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
const proof = JSON.parse(
|
||||
await fs.readFile(
|
||||
'docs/proofs/pilot-replenishment-activation.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'proof',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
assert.equal(proof.result, 'applied');
|
||||
const requester = client(); await requester.enter('requester');
|
||||
assert.equal((await requester.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
@@ -32,4 +49,6 @@ await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
|
||||
automatic_source_reused:true,physical_milli:row.physical_milli,free_milli:row.free_milli,checks,
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
|
||||
console.log('Rascunho, origem da reposicao, tarefas, competencias e saldo confirmados por HTTP.');
|
||||
` + '})()')(fs, assert, proof);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert, proof);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['requester','department_head']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('docs/proofs/pilot-submission-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
quantity:'2.000',total_minor_mzn:2320,all_approval_steps_pending:true,business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
|
||||
console.log('Submissao e encaminhamento confirmados, sem aprovar a compra.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot access and lookup validation; positive source choices and suspensions tested in disposable databases.'},null,2));
|
||||
console.log('Pesquisa de políticas conferida sem criar sugestões, compras ou competências no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -126,5 +126,5 @@ try {
|
||||
}
|
||||
}
|
||||
$result['restore_database_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/audit-access-preparation.json',json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
file_put_contents($root.'/docs/proofs/audit-access-preparation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
echo 'Audit access proposal rehearsed only in restored disposable backup; pilot grants unchanged.'.PHP_EOL;
|
||||
|
||||
@@ -3,49 +3,147 @@ import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
assert.ok(process.argv.includes('--apply-qa-preview'), 'Explicit QA preview switch required.');
|
||||
assert.ok(
|
||||
process.argv.includes('--apply-qa-preview'),
|
||||
'Explicit QA preview switch required.',
|
||||
);
|
||||
const root = await fs.realpath(process.cwd());
|
||||
const settings = JSON.parse(await fs.readFile('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json', 'utf8'));
|
||||
const settings = JSON.parse(
|
||||
await fs.readFile(
|
||||
'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(settings.APP_ENV, 'payable-testing');
|
||||
assert.equal(settings.DB_HOST, '127.0.0.1');
|
||||
assert.equal(await fs.realpath(settings.HOST_ROOT), root);
|
||||
const authorization = JSON.parse(await fs.readFile('docs/proofs/rq01-source-authorization.json', 'utf8'));
|
||||
const authorization = JSON.parse(
|
||||
await fs.readFile('docs/proofs/rq01-source-authorization.json', 'utf8'),
|
||||
);
|
||||
assert.equal(authorization.owner_decision, 'autorizo as melhorias propostas');
|
||||
const sha = async file => createHash('sha256').update(await fs.readFile(file)).digest('hex');
|
||||
const sha = async (file) =>
|
||||
createHash('sha256')
|
||||
.update(await fs.readFile(file))
|
||||
.digest('hex');
|
||||
const definitions = {
|
||||
'--product-review': ['ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93', 'sgc-product-review-candidate-20261122', 'product-review', 'QA product presentation and order compatibility correction'],
|
||||
'--history-review': ['9bbca2dc15b40c05f268b118e4f16178a3120ae19329fdbe19403178e22cf251', 'sgc-history-candidate-20261122', 'history-review', 'Requisition preparation in native encrypted browser history'],
|
||||
'--financial-review': ['4b4801f658ef0cbbc3f83311afbb610add0c7985916ba25c21af2a8b77cf683f', 'sgc-payable-insights-candidate-20261122', 'financial-review', 'Read-only native payable positions and CSV for existing financial viewers'],
|
||||
'--history-clean-review': ['aad78d2d79f03e3d95ca880875e331973bb2f2702288945852a818837a259057', 'sgc-history-clean-candidate-20261122', 'history-clean-review', 'Correct false dirty state caused by restored technical identities; preserve protection of edited preparation'],
|
||||
'--product-review': [
|
||||
'ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93',
|
||||
'sgc-product-review-candidate-20261122',
|
||||
'product-review',
|
||||
'QA product presentation and order compatibility correction',
|
||||
],
|
||||
'--history-review': [
|
||||
'9bbca2dc15b40c05f268b118e4f16178a3120ae19329fdbe19403178e22cf251',
|
||||
'sgc-history-candidate-20261122',
|
||||
'history-review',
|
||||
'Requisition preparation in native encrypted browser history',
|
||||
],
|
||||
'--financial-review': [
|
||||
'4b4801f658ef0cbbc3f83311afbb610add0c7985916ba25c21af2a8b77cf683f',
|
||||
'sgc-payable-insights-candidate-20261122',
|
||||
'financial-review',
|
||||
'Read-only native payable positions and CSV for existing financial viewers',
|
||||
],
|
||||
'--history-clean-review': [
|
||||
'aad78d2d79f03e3d95ca880875e331973bb2f2702288945852a818837a259057',
|
||||
'sgc-history-clean-candidate-20261122',
|
||||
'history-clean-review',
|
||||
'Correct false dirty state caused by restored technical identities; preserve protection of edited preparation',
|
||||
],
|
||||
};
|
||||
const selected = Object.keys(definitions).filter(flag => process.argv.includes(flag));
|
||||
const selected = Object.keys(definitions).filter((flag) =>
|
||||
process.argv.includes(flag),
|
||||
);
|
||||
assert.ok(selected.length <= 1, 'Select exactly one reviewed delta.');
|
||||
const [previous, directory, label, scope] = selected.length ? definitions[selected[0]] : ['c2203372527050e083f6cc0aab47a1e08534015d692b3a8781a26ddf65109c23', 'rq01-production-candidate-20261122', 'rq01-production', 'QA presentation of approved production destination increment'];
|
||||
const proofNames = { 'product-review': 'product-review', 'history-review': 'requisition-history', 'financial-review': 'payable-insights', 'history-clean-review': 'requisition-history-clean', 'rq01-production': 'production-destination' };
|
||||
const [previous, directory, label, scope] = selected.length
|
||||
? definitions[selected[0]]
|
||||
: [
|
||||
'c2203372527050e083f6cc0aab47a1e08534015d692b3a8781a26ddf65109c23',
|
||||
'rq01-production-candidate-20261122',
|
||||
'rq01-production',
|
||||
'QA presentation of approved production destination increment',
|
||||
];
|
||||
const proofNames = {
|
||||
'product-review': 'product-review',
|
||||
'history-review': 'requisition-history',
|
||||
'financial-review': 'payable-insights',
|
||||
'history-clean-review': 'requisition-history-clean',
|
||||
'rq01-production': 'production-destination',
|
||||
};
|
||||
const currentManifest = path.join(root, 'public/build/manifest.json');
|
||||
assert.equal(await sha(currentManifest), previous, 'Preview target changed; review before updating.');
|
||||
assert.equal(
|
||||
await sha(currentManifest),
|
||||
previous,
|
||||
'Preview target changed; review before updating.',
|
||||
);
|
||||
const candidate = path.join(root, 'storage/framework/testing', directory);
|
||||
const manifest = JSON.parse(await fs.readFile(path.join(candidate, 'manifest.json'), 'utf8'));
|
||||
const manifest = JSON.parse(
|
||||
await fs.readFile(path.join(candidate, 'manifest.json'), 'utf8'),
|
||||
);
|
||||
const files = new Map();
|
||||
for (const entry of Object.values(manifest)) {
|
||||
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..') && !path.isAbsolute(file));
|
||||
for (const file of [
|
||||
entry.file,
|
||||
...(entry.css ?? []),
|
||||
...(entry.assets ?? []),
|
||||
]) {
|
||||
assert.ok(
|
||||
file.startsWith('assets/') &&
|
||||
!file.includes('..') &&
|
||||
!path.isAbsolute(file),
|
||||
);
|
||||
files.set(file, await sha(path.join(candidate, file)));
|
||||
}
|
||||
}
|
||||
const backup = path.join(root, `storage/framework/testing/manifest-before-${label}-20261122.json`);
|
||||
const backup = path.join(
|
||||
root,
|
||||
`storage/framework/testing/manifest-before-${label}-20261122.json`,
|
||||
);
|
||||
await fs.copyFile(currentManifest, backup, fs.constants.COPYFILE_EXCL);
|
||||
for (const [file, expected] of files) {
|
||||
const target = path.join(root, 'public/build', file);
|
||||
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||
try { await fs.copyFile(path.join(candidate, file), target, fs.constants.COPYFILE_EXCL); }
|
||||
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
||||
assert.equal(await sha(target), expected, 'Never replace an existing divergent chunk.');
|
||||
try {
|
||||
await fs.copyFile(
|
||||
path.join(candidate, file),
|
||||
target,
|
||||
fs.constants.COPYFILE_EXCL,
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
}
|
||||
assert.equal(
|
||||
await sha(target),
|
||||
expected,
|
||||
'Never replace an existing divergent chunk.',
|
||||
);
|
||||
}
|
||||
assert.equal(await sha(currentManifest), previous);
|
||||
const temporary = path.join(root, 'public/build/manifest.rq01-preview.tmp');
|
||||
await fs.copyFile(path.join(candidate, 'manifest.json'), temporary);
|
||||
await fs.rename(temporary, currentManifest);
|
||||
const proof = { environment: 'http://127.0.0.1:8005', scope, authorization: 'rq01-source-authorization.json', assets_verified: files.size, previous_manifest_sha256: previous, manifest_sha256: await sha(currentManifest), previous_manifest_backup: backup, schemas_changed: false, business_commands: false, capability_settings_changed: false, visual_review: false };
|
||||
await fs.writeFile(`docs/proofs/${proofNames[label]}-preview.json`, JSON.stringify(proof, null, 2) + '\n');
|
||||
console.log(JSON.stringify({ result: 'passed', assets_verified: files.size, manifest_sha256: proof.manifest_sha256, business_commands: false }));
|
||||
const proof = {
|
||||
environment: 'http://127.0.0.1:8005',
|
||||
scope,
|
||||
authorization: 'rq01-source-authorization.json',
|
||||
assets_verified: files.size,
|
||||
previous_manifest_sha256: previous,
|
||||
manifest_sha256: await sha(currentManifest),
|
||||
previous_manifest_backup: backup,
|
||||
schemas_changed: false,
|
||||
business_commands: false,
|
||||
capability_settings_changed: false,
|
||||
visual_review: false,
|
||||
};
|
||||
await fs.writeFile(
|
||||
`docs/proofs/${proofNames[label]}-preview.json`,
|
||||
JSON.stringify(proof, null, 2) + '\n',
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
result: 'passed',
|
||||
assets_verified: files.size,
|
||||
manifest_sha256: proof.manifest_sha256,
|
||||
business_commands: false,
|
||||
}),
|
||||
);
|
||||
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# Cópia de segurança completa: base de dados (pg_dump -Fc), ficheiros privados (storage/app)
|
||||
# e manifesto com hashes e contagens. Não copia o .env (guardar à parte, cifrado).
|
||||
# Uso: scripts/producao/backup.sh [pasta-destino] (por omissão BACKUP_DIR ou /var/backups/compras)
|
||||
# Retenção: apaga cópias com mais de BACKUP_RETENTION_DAYS dias (omissão 30).
|
||||
source "$(dirname "$0")/lib.sh"
|
||||
|
||||
ROOT="${1:-${BACKUP_DIR:-/var/backups/compras}}"
|
||||
RETENTION="${BACKUP_RETENTION_DAYS:-30}"
|
||||
STAMP="$(date -u +%Y%m%d-%H%M%S)"
|
||||
TARGET="$ROOT/$STAMP"
|
||||
|
||||
umask 0077
|
||||
load_database
|
||||
mkdir -p "$ROOT"
|
||||
mkdir "$TARGET" || fail "Destino já existe: $TARGET"
|
||||
trap 'log "Cópia interrompida; a remover $TARGET incompleto."; rm -rf "$TARGET"' ERR
|
||||
|
||||
log "Base de dados $PGDATABASE → $TARGET/database.dump"
|
||||
pg_dump -Fc --no-owner --no-acl -f "$TARGET/database.dump"
|
||||
pg_restore --list "$TARGET/database.dump" >/dev/null
|
||||
|
||||
log "Ficheiros privados → $TARGET/storage-app.tar.gz"
|
||||
tar -czf "$TARGET/storage-app.tar.gz" -C "$APP_DIR/storage" app
|
||||
|
||||
table_counts "$PGDATABASE" > "$TARGET/counts.txt"
|
||||
git -C "$APP_DIR" rev-parse HEAD > "$TARGET/commit.txt" 2>/dev/null || echo "desconhecido" > "$TARGET/commit.txt"
|
||||
(cd "$TARGET" && sha256 database.dump storage-app.tar.gz counts.txt commit.txt > SHA256SUMS)
|
||||
trap - ERR
|
||||
|
||||
if [ "$RETENTION" -gt 0 ]; then
|
||||
find "$ROOT" -mindepth 1 -maxdepth 1 -type d -name '20*' -mtime +"$RETENTION" -print -exec rm -rf {} + | sed 's/^/[retenção] removida /'
|
||||
fi
|
||||
log "Cópia concluída: $TARGET ($(du -sh "$TARGET" | cut -f1))"
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
# Funções comuns dos scripts de produção. Lê a ligação PostgreSQL da configuração Laravel
|
||||
# (sem a imprimir) e exporta-a para as variáveis PG* que pg_dump/psql/pg_restore usam.
|
||||
set -Eeuo pipefail
|
||||
|
||||
APP_DIR="${APP_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
|
||||
PHP_BIN="${PHP_BIN:-php}"
|
||||
KEY_TABLES="tenants users requisitions purchase_orders goods_receipts invoices external_payments budgets budget_entries audit_logs"
|
||||
|
||||
log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*"; }
|
||||
fail() { log "ERRO: $*"; exit 1; }
|
||||
|
||||
sha256() { if command -v sha256sum >/dev/null; then sha256sum "$@"; else shasum -a 256 "$@"; fi; }
|
||||
|
||||
load_database() {
|
||||
local values
|
||||
values="$(cd "$APP_DIR" && "$PHP_BIN" -r '
|
||||
require "vendor/autoload.php";
|
||||
$app = require "bootstrap/app.php";
|
||||
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$name = config("database.default");
|
||||
$c = config("database.connections.".$name);
|
||||
if (($c["driver"] ?? "") !== "pgsql") { fwrite(STDERR, "A ligação por omissão não é PostgreSQL.\n"); exit(1); }
|
||||
foreach (["host" => "PGHOST", "port" => "PGPORT", "database" => "PGDATABASE", "username" => "PGUSER", "password" => "PGPASSWORD"] as $k => $v) {
|
||||
echo $v, " ", base64_encode((string) ($c[$k] ?? "")), "\n";
|
||||
}')" || fail "Configuração da base de dados indisponível."
|
||||
while read -r name value; do
|
||||
export "$name=$(printf '%s' "$value" | base64 --decode)"
|
||||
done <<< "$values"
|
||||
[ -n "$PGDATABASE" ] || fail "Nome da base de dados vazio."
|
||||
}
|
||||
|
||||
# Comandos PostgreSQL. Com RESTORE_AS=<utilizador do sistema> (ex.: postgres) correm por esse
|
||||
# utilizador e pelo socket local, para o ensaio de restauro não exigir CREATEDB ao utilizador da aplicação.
|
||||
pg() {
|
||||
if [ -n "${RESTORE_AS:-}" ]; then
|
||||
runuser -u "$RESTORE_AS" -- env -u PGHOST -u PGPORT -u PGUSER -u PGPASSWORD -u PGDATABASE "$@"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
|
||||
# Contagem de linhas das tabelas principais, uma por linha: "tabela contagem".
|
||||
table_counts() {
|
||||
local database="$1" table
|
||||
for table in $KEY_TABLES; do
|
||||
if [ "$(pg psql -X -At -d "$database" -c "select to_regclass('public.$table') is not null")" = "t" ]; then
|
||||
printf '%s %s\n' "$table" "$(pg psql -X -At -d "$database" -c "select count(*) from public.$table")"
|
||||
fi
|
||||
done
|
||||
}
|
||||
Executable
+31
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# Ensaio de restauro: confere os hashes da cópia, restaura a base numa base temporária,
|
||||
# compara as contagens das tabelas principais e confere o arquivo de ficheiros.
|
||||
# Não toca na base de produção nem nos ficheiros da aplicação. Apaga a base temporária no fim.
|
||||
# Uso: scripts/producao/restore-check.sh <pasta-da-cópia>
|
||||
# Sem CREATEDB para o utilizador da aplicação: RESTORE_AS=postgres (como root) usa o superutilizador local.
|
||||
source "$(dirname "$0")/lib.sh"
|
||||
|
||||
SOURCE="${1:?Indique a pasta da cópia}"
|
||||
[ -f "$SOURCE/SHA256SUMS" ] || fail "Cópia sem manifesto: $SOURCE"
|
||||
load_database
|
||||
TEMP_DB="compras_restore_check_$(date -u +%Y%m%d%H%M%S)_$$"
|
||||
WORK="$(mktemp -d)"
|
||||
cleanup() { pg dropdb --if-exists "$TEMP_DB" 2>/dev/null || true; rm -rf "$WORK"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
log "Conferir hashes"
|
||||
(cd "$SOURCE" && sha256 -c SHA256SUMS >/dev/null) || fail "Hashes não conferem."
|
||||
|
||||
log "Restaurar em $TEMP_DB"
|
||||
pg createdb "$TEMP_DB"
|
||||
pg pg_restore --no-owner --no-acl --exit-on-error -d "$TEMP_DB" < "$SOURCE/database.dump"
|
||||
|
||||
table_counts "$TEMP_DB" > "$WORK/counts.txt"
|
||||
diff -u "$SOURCE/counts.txt" "$WORK/counts.txt" || fail "As contagens restauradas diferem das registadas na cópia."
|
||||
log "Contagens iguais: $(tr '\n' ' ' < "$WORK/counts.txt")"
|
||||
|
||||
tar -xzf "$SOURCE/storage-app.tar.gz" -C "$WORK"
|
||||
log "Ficheiros no arquivo: $(find "$WORK/app" -type f | wc -l | tr -d ' ')"
|
||||
|
||||
log "Restauro verificado: $SOURCE"
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes = [];
|
||||
for (const role of ['procurement', 'finance', 'department_head']) {
|
||||
const viewer = client();
|
||||
@@ -36,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
visual_review: false, coverage: 'Current first-page tasks only; complete pending journeys covered by disposable tests.'
|
||||
}, null, 2));
|
||||
console.log('Consulta ao mercado e ligacoes das tarefas conferidas com os perfis existentes.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse','procurement']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -20,4 +31,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
}
|
||||
await fs.writeFile('docs/proofs/receipt-block-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,documents_uploaded:false,visual_review:false},null,2));
|
||||
console.log('Recepções consultadas no piloto; sem comandos de negócio.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','warehouse','procurement']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -20,4 +31,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/receipt-print-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,visual_review:false},null,2));
|
||||
console.log('Reprodução imprimível consultada; sem movimentos ou decisões.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer=client(); await viewer.enter('admin');
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
|
||||
const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/received-availability-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,availabilityRows,business_commands:false,visual_review:false,coverage:'Existing visible processes only; positive received-availability cases exercised in disposable tests.'},null,2));
|
||||
console.log('People page/dossier availability projection checked for existing visible sources only.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -39,6 +39,7 @@ $result = DB::transaction(function () use ($backup): array {
|
||||
'reason' => 'Corrigir apenas a codificacao dos rotulos sinteticos gerados, reutilizando o nome existente do titular.']);
|
||||
$repaired++;
|
||||
}
|
||||
|
||||
return ['state' => 'passed', 'generated_profile_labels_repaired' => $repaired, 'permissions_contexts_users_and_credentials_changed' => false];
|
||||
});
|
||||
$path = '/root/compras-demo-access.json';
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403]]) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
pilot_health_command_executed:false,business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Existing tenant-scoped diagnostic UI and rights preserved; CLI health executed only in disposable databases.'},null,2));
|
||||
console.log('Diagnóstico do piloto conferido em leitura, sem executar reposições.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const viewer=client(); await viewer.enter('admin');
|
||||
const dashboard=await viewer.request('/dashboard');
|
||||
if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
|
||||
@@ -15,4 +26,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
assert.ok(Date.now()-Date.parse(p.schedulerStatus.finished_at)<120000);
|
||||
await fs.writeFile('docs/proofs/replenishment-pilot-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,component:'stock/replenishment',recovery_installed:true,pagination:['rules','needs','history','workItems'],filter:'pending',scheduler:p.schedulerStatus,administrator_read_only:true,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2));
|
||||
console.log('Reposição: paginação, filtro, recuperação e passagem recente do serviço confirmados por HTTP.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,8 +1,19 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
|
||||
coverage:'Read-only metadata export of existing synthetic requisition 2, compared with native detail visibility.'},null,2));
|
||||
console.log('Metadados do histórico conferidos no piloto sem decisões ou alterações de dados.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
+1919
-392
File diff suppressed because it is too large
Load Diff
@@ -6,45 +6,91 @@ import crypto from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const workspace = 'C:/laragon/www/compras';
|
||||
if (path.resolve(process.cwd()) !== path.resolve(workspace)) throw Error('Compras workspace required');
|
||||
if (path.resolve(process.cwd()) !== path.resolve(workspace))
|
||||
throw Error('Compras workspace required');
|
||||
const canonical = 'C:/laragon/www/sgf-tempo/packages';
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const sources = ['finance-bundle/Bundle.php'];
|
||||
for (const name of ['payables', 'general-ledger']) {
|
||||
for (const file of ['bootstrap.php', 'README.md']) {
|
||||
if (fs.existsSync(path.join(canonical, name, file))) sources.push(`${name}/${file}`);
|
||||
if (fs.existsSync(path.join(canonical, name, file)))
|
||||
sources.push(`${name}/${file}`);
|
||||
}
|
||||
for (const dir of ['src', 'ui']) {
|
||||
for (const file of fs.readdirSync(path.join(canonical, name, dir)).sort()) {
|
||||
if (!/^[A-Za-z0-9_-]+\.php$/.test(file)) throw Error('Unexpected runtime source');
|
||||
for (const file of fs
|
||||
.readdirSync(path.join(canonical, name, dir))
|
||||
.sort()) {
|
||||
if (!/^[A-Za-z0-9_-]+\.php$/.test(file))
|
||||
throw Error('Unexpected runtime source');
|
||||
sources.push(`${name}/${dir}/${file}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const content = sources.map(source => {
|
||||
const actual = path.join(canonical, source);
|
||||
if (!fs.lstatSync(actual).isFile() || fs.lstatSync(actual).isSymbolicLink()) throw Error('Regular runtime files required');
|
||||
return { file: source === 'finance-bundle/Bundle.php' ? 'Bundle.php' : source, bytes: fs.readFileSync(actual) };
|
||||
}).sort((a, b) => a.file.localeCompare(b.file));
|
||||
const content = sources
|
||||
.map((source) => {
|
||||
const actual = path.join(canonical, source);
|
||||
if (
|
||||
!fs.lstatSync(actual).isFile() ||
|
||||
fs.lstatSync(actual).isSymbolicLink()
|
||||
)
|
||||
throw Error('Regular runtime files required');
|
||||
return {
|
||||
file:
|
||||
source === 'finance-bundle/Bundle.php' ? 'Bundle.php' : source,
|
||||
bytes: fs.readFileSync(actual),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.file.localeCompare(b.file));
|
||||
const files = content.map(({ file, bytes }) => ({ file, sha256: hash(bytes) }));
|
||||
const manifest = JSON.stringify({ contract: 'COMMON-FINANCE-BUNDLE-v1', synthetic_only: true, files }, null, 2) + '\n';
|
||||
const manifest =
|
||||
JSON.stringify(
|
||||
{ contract: 'COMMON-FINANCE-BUNDLE-v1', synthetic_only: true, files },
|
||||
null,
|
||||
2,
|
||||
) + '\n';
|
||||
const pin = hash(manifest);
|
||||
const root = path.join(workspace, 'storage/framework/testing', `requisition-ledger-runtime-qa-${pin.slice(0, 16)}`);
|
||||
const root = path.join(
|
||||
workspace,
|
||||
'storage/framework/testing',
|
||||
`requisition-ledger-runtime-qa-${pin.slice(0, 16)}`,
|
||||
);
|
||||
if (!fs.existsSync(root)) {
|
||||
fs.mkdirSync(root);
|
||||
for (const { file, bytes } of content) {
|
||||
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, file), bytes, { flag: 'wx' });
|
||||
}
|
||||
fs.writeFileSync(path.join(root, 'manifest.json'), manifest, { flag: 'wx' });
|
||||
fs.writeFileSync(path.join(root, 'manifest.json'), manifest, {
|
||||
flag: 'wx',
|
||||
});
|
||||
}
|
||||
if (hash(fs.readFileSync(path.join(root, 'manifest.json'))) !== pin) throw Error('Existing artefact differs; never overwrite');
|
||||
if (hash(fs.readFileSync(path.join(root, 'manifest.json'))) !== pin)
|
||||
throw Error('Existing artefact differs; never overwrite');
|
||||
// The caller fixes this manifest and loader hash before loading any executable.
|
||||
for (const { file, sha256 } of files) {
|
||||
const target = path.join(root, file);
|
||||
if (!fs.lstatSync(target).isFile() || fs.lstatSync(target).isSymbolicLink() || hash(fs.readFileSync(target)) !== sha256) throw Error('Artefact byte mismatch');
|
||||
if (
|
||||
!fs.lstatSync(target).isFile() ||
|
||||
fs.lstatSync(target).isSymbolicLink() ||
|
||||
hash(fs.readFileSync(target)) !== sha256
|
||||
)
|
||||
throw Error('Artefact byte mismatch');
|
||||
}
|
||||
const code = 'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);';
|
||||
const checked = spawnSync('php', ['-r', code, root, pin], { windowsHide: true, encoding: 'utf8' });
|
||||
if (checked.status !== 0) throw Error('Existing common bundle verifier refused the private artefact');
|
||||
console.log(JSON.stringify({ root, manifest_sha256: pin, files: files.length, verified: true, synthetic_only: true, installed_or_activated: false }));
|
||||
const code =
|
||||
'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);';
|
||||
const checked = spawnSync('php', ['-r', code, root, pin], {
|
||||
windowsHide: true,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
if (checked.status !== 0)
|
||||
throw Error('Existing common bundle verifier refused the private artefact');
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
root,
|
||||
manifest_sha256: pin,
|
||||
files: files.length,
|
||||
verified: true,
|
||||
synthetic_only: true,
|
||||
installed_or_activated: false,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -2,19 +2,45 @@ import crypto from 'node:crypto';
|
||||
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
|
||||
|
||||
/** Exercise native Fortify sessions and read routes, without business commands or a browser claim. */
|
||||
export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot }) {
|
||||
export async function verifyNativeReviewHttp(
|
||||
origin,
|
||||
fixture,
|
||||
{ assets, snapshot },
|
||||
) {
|
||||
const base = new URL(origin);
|
||||
if (base.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(base.hostname) || !base.port || typeof snapshot !== 'function') throw Error('Owned loopback review required');
|
||||
if (
|
||||
base.protocol !== 'http:' ||
|
||||
!['localhost', '127.0.0.1'].includes(base.hostname) ||
|
||||
!base.port ||
|
||||
typeof snapshot !== 'function'
|
||||
)
|
||||
throw Error('Owned loopback review required');
|
||||
let checks = 0;
|
||||
const check = (condition, label) => { if (!condition) throw Error(`Native HTTP verification failed: ${label}`); checks++; };
|
||||
const check = (condition, label) => {
|
||||
if (!condition)
|
||||
throw Error(`Native HTTP verification failed: ${label}`);
|
||||
checks++;
|
||||
};
|
||||
const client = () => createNativeInertiaClient(base.href, check);
|
||||
const guest = client();
|
||||
check((await guest.request('/auditoria/eventos')).status === 401, 'anonymous metadata access refused');
|
||||
check(Array.isArray(assets) && assets.length > 0, 'private candidate assets supplied');
|
||||
check(
|
||||
(await guest.request('/auditoria/eventos')).status === 401,
|
||||
'anonymous metadata access refused',
|
||||
);
|
||||
check(
|
||||
Array.isArray(assets) && assets.length > 0,
|
||||
'private candidate assets supplied',
|
||||
);
|
||||
for (const asset of assets) {
|
||||
const file = await guest.request(`/build/${asset.file}`);
|
||||
check(file.status === 200, 'private candidate asset served');
|
||||
check(crypto.createHash('sha256').update(Buffer.from(await file.arrayBuffer())).digest('hex') === asset.sha256, 'HTTP asset bytes match private build');
|
||||
check(
|
||||
crypto
|
||||
.createHash('sha256')
|
||||
.update(Buffer.from(await file.arrayBuffer()))
|
||||
.digest('hex') === asset.sha256,
|
||||
'HTTP asset bytes match private build',
|
||||
);
|
||||
}
|
||||
const reviewer = client();
|
||||
const auditor = client();
|
||||
@@ -26,105 +52,360 @@ export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot
|
||||
await privateAuditor.login(fixture.synthetic_private_audit_login);
|
||||
// Login/logout may legitimately rotate native authentication fields. Compare the read window only.
|
||||
const before = await snapshot();
|
||||
const privateAudit = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||
check(privateAudit.props.families.length === 4 && privateAudit.props.exports.data.length === 0, 'dedicated private authority opens approved families without generating a package');
|
||||
for (const actor of [reviewer, auditor, requester]) check((await actor.request('/auditoria/privada')).status === 403, 'other authorities cannot open private audit');
|
||||
check((await privateAuditor.request('/orcamentos')).status === 403, 'private audit never grants native financial workspace');
|
||||
const operationalOrders = await reviewer.page('/ordens-operacionais', 'requisitions/operational-orders');
|
||||
check((await auditor.request('/ordens-operacionais')).status === 403, 'metadata authority never grants operational order register access');
|
||||
check(operationalOrders.props.canConfigure === true && operationalOrders.props.policy === null, 'native admin can configure origin but a GET does not select an origin');
|
||||
const ownOperationalOrders = await requester.page('/ordens-operacionais', 'requisitions/operational-orders');
|
||||
check(ownOperationalOrders.props.canConfigure === false && ownOperationalOrders.props.allowedTypes.length === 0, 'requester receives no production workshop or procurement order creation grant');
|
||||
const urgentStock = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`, 'requisitions/urgent-stock');
|
||||
check(urgentStock.props.eligible.length === 0, 'ordinary historical source receives no implicit urgent reduction');
|
||||
check((await requester.request(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`)).status === 403, 'request ownership does not grant stock threshold preparation or quotation oversight');
|
||||
const privateAudit = await privateAuditor.page(
|
||||
'/auditoria/privada',
|
||||
'audit/private',
|
||||
);
|
||||
check(
|
||||
privateAudit.props.families.length === 4 &&
|
||||
privateAudit.props.exports.data.length === 0,
|
||||
'dedicated private authority opens approved families without generating a package',
|
||||
);
|
||||
for (const actor of [reviewer, auditor, requester])
|
||||
check(
|
||||
(await actor.request('/auditoria/privada')).status === 403,
|
||||
'other authorities cannot open private audit',
|
||||
);
|
||||
check(
|
||||
(await privateAuditor.request('/orcamentos')).status === 403,
|
||||
'private audit never grants native financial workspace',
|
||||
);
|
||||
const operationalOrders = await reviewer.page(
|
||||
'/ordens-operacionais',
|
||||
'requisitions/operational-orders',
|
||||
);
|
||||
check(
|
||||
(await auditor.request('/ordens-operacionais')).status === 403,
|
||||
'metadata authority never grants operational order register access',
|
||||
);
|
||||
check(
|
||||
operationalOrders.props.canConfigure === true &&
|
||||
operationalOrders.props.policy === null,
|
||||
'native admin can configure origin but a GET does not select an origin',
|
||||
);
|
||||
const ownOperationalOrders = await requester.page(
|
||||
'/ordens-operacionais',
|
||||
'requisitions/operational-orders',
|
||||
);
|
||||
check(
|
||||
ownOperationalOrders.props.canConfigure === false &&
|
||||
ownOperationalOrders.props.allowedTypes.length === 0,
|
||||
'requester receives no production workshop or procurement order creation grant',
|
||||
);
|
||||
const urgentStock = await reviewer.page(
|
||||
`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`,
|
||||
'requisitions/urgent-stock',
|
||||
);
|
||||
check(
|
||||
urgentStock.props.eligible.length === 0,
|
||||
'ordinary historical source receives no implicit urgent reduction',
|
||||
);
|
||||
check(
|
||||
(
|
||||
await requester.request(
|
||||
`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`,
|
||||
)
|
||||
).status === 403,
|
||||
'request ownership does not grant stock threshold preparation or quotation oversight',
|
||||
);
|
||||
const budgets = await reviewer.page('/orcamentos', 'budgets/index');
|
||||
check(budgets.props.budgets.length > 0, 'native synthetic budget is visible to its authorised reader');
|
||||
check(
|
||||
budgets.props.budgets.length > 0,
|
||||
'native synthetic budget is visible to its authorised reader',
|
||||
);
|
||||
const budgetHeaders = await reviewer.request('/orcamentos');
|
||||
check(budgetHeaders.headers.get('Cache-Control')?.includes('no-store'), 'private budget response not cacheable');
|
||||
check((await requester.request('/orcamentos')).status === 403, 'requester cannot read operational budget preparations');
|
||||
check(
|
||||
budgetHeaders.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'private budget response not cacheable',
|
||||
);
|
||||
check(
|
||||
(await requester.request('/orcamentos')).status === 403,
|
||||
'requester cannot read operational budget preparations',
|
||||
);
|
||||
for (const actor of [reviewer, requester]) {
|
||||
await actor.page('/conflitos', 'conflicts/index');
|
||||
const response = await actor.request('/conflitos');
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'personal conflicts not cacheable');
|
||||
check(
|
||||
response.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'personal conflicts not cacheable',
|
||||
);
|
||||
}
|
||||
for (const [route, component] of [['/stock', 'stock/index'], ['/stock/operacoes', 'stock/operations']]) {
|
||||
for (const [route, component] of [
|
||||
['/stock', 'stock/index'],
|
||||
['/stock/operacoes', 'stock/operations'],
|
||||
]) {
|
||||
await reviewer.page(route, component);
|
||||
const response = await reviewer.request(route);
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'stock workspace not cacheable');
|
||||
check((await requester.request(route)).status === 403, 'requester cannot read operational stock workspace');
|
||||
check(
|
||||
response.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'stock workspace not cacheable',
|
||||
);
|
||||
check(
|
||||
(await requester.request(route)).status === 403,
|
||||
'requester cannot read operational stock workspace',
|
||||
);
|
||||
}
|
||||
for (const [route, component] of [['/equipamentos', 'equipment/index'], ['/regras-investimento', 'investment/index']]) {
|
||||
for (const [route, component] of [
|
||||
['/equipamentos', 'equipment/index'],
|
||||
['/regras-investimento', 'investment/index'],
|
||||
]) {
|
||||
const page = await reviewer.page(route, component);
|
||||
check(page.props.canManage === true, 'native administrative preparation scope retained');
|
||||
check(
|
||||
page.props.canManage === true,
|
||||
'native administrative preparation scope retained',
|
||||
);
|
||||
const response = await reviewer.request(route);
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'equipment and investment preparation not cacheable');
|
||||
check((await requester.request(route)).status === 403, 'requester cannot inherit equipment or investment administration');
|
||||
check(
|
||||
response.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'equipment and investment preparation not cacheable',
|
||||
);
|
||||
check(
|
||||
(await requester.request(route)).status === 403,
|
||||
'requester cannot inherit equipment or investment administration',
|
||||
);
|
||||
}
|
||||
const companyConfiguration = await reviewer.page('/administracao/parametrizacao', 'company/parameters');
|
||||
check(companyConfiguration.props.ready === true && Array.isArray(companyConfiguration.props.profiles) && companyConfiguration.props.profiles.length > 0, 'existing synthetic company configuration remains consultable');
|
||||
const companyResponse = await reviewer.request('/administracao/parametrizacao');
|
||||
check(companyResponse.headers.get('Cache-Control')?.includes('no-store'), 'company configuration not cacheable');
|
||||
check((await requester.request('/administracao/parametrizacao')).status === 403, 'requester cannot inherit configuration administration');
|
||||
const detail = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show');
|
||||
check(detail.props.canReadAuditMetadata === true, 'native request audit navigation permission');
|
||||
const history = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/prazos`, 'requisitions/expiry');
|
||||
check(history.props.history.data[0].request.total_minor === 10000, 'original cycle amount survives native HTTP');
|
||||
const query = new URLSearchParams({ request_reference: fixture.audit_request_reference });
|
||||
const metadata = await reviewer.page(`/auditoria/eventos?${query}`, 'audit/metadata');
|
||||
check(metadata.props.requestContext?.number === fixture.audit_request_reference, 'authorised native context locator');
|
||||
const minimalEvents = page => {
|
||||
check(page.props.events.data.length > 0, 'filtered native events present');
|
||||
check(page.props.events.data.every(e => JSON.stringify(Object.keys(e).sort()) === JSON.stringify(['action', 'created_at', 'id', 'user_id'])), 'events contain only four metadata fields');
|
||||
const companyConfiguration = await reviewer.page(
|
||||
'/administracao/parametrizacao',
|
||||
'company/parameters',
|
||||
);
|
||||
check(
|
||||
companyConfiguration.props.ready === true &&
|
||||
Array.isArray(companyConfiguration.props.profiles) &&
|
||||
companyConfiguration.props.profiles.length > 0,
|
||||
'existing synthetic company configuration remains consultable',
|
||||
);
|
||||
const companyResponse = await reviewer.request(
|
||||
'/administracao/parametrizacao',
|
||||
);
|
||||
check(
|
||||
companyResponse.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'company configuration not cacheable',
|
||||
);
|
||||
check(
|
||||
(await requester.request('/administracao/parametrizacao')).status ===
|
||||
403,
|
||||
'requester cannot inherit configuration administration',
|
||||
);
|
||||
const detail = await reviewer.page(
|
||||
`/requisicoes/${fixture.historical_decision_request}`,
|
||||
'requisitions/show',
|
||||
);
|
||||
check(
|
||||
detail.props.canReadAuditMetadata === true,
|
||||
'native request audit navigation permission',
|
||||
);
|
||||
const history = await reviewer.page(
|
||||
`/requisicoes/${fixture.historical_decision_request}/prazos`,
|
||||
'requisitions/expiry',
|
||||
);
|
||||
check(
|
||||
history.props.history.data[0].request.total_minor === 10000,
|
||||
'original cycle amount survives native HTTP',
|
||||
);
|
||||
const query = new URLSearchParams({
|
||||
request_reference: fixture.audit_request_reference,
|
||||
});
|
||||
const metadata = await reviewer.page(
|
||||
`/auditoria/eventos?${query}`,
|
||||
'audit/metadata',
|
||||
);
|
||||
check(
|
||||
metadata.props.requestContext?.number ===
|
||||
fixture.audit_request_reference,
|
||||
'authorised native context locator',
|
||||
);
|
||||
const minimalEvents = (page) => {
|
||||
check(
|
||||
page.props.events.data.length > 0,
|
||||
'filtered native events present',
|
||||
);
|
||||
check(
|
||||
page.props.events.data.every(
|
||||
(e) =>
|
||||
JSON.stringify(Object.keys(e).sort()) ===
|
||||
JSON.stringify(['action', 'created_at', 'id', 'user_id']),
|
||||
),
|
||||
'events contain only four metadata fields',
|
||||
);
|
||||
};
|
||||
minimalEvents(metadata);
|
||||
for (const [view, component] of [['agreements', 'supply/index'], ['contracts', 'supply/index'], ['calendar', 'supply/index'], ['imports', 'supply/index'],
|
||||
['history', 'supply/history'], ['suggestions', 'supply/suggestions'], ['reservations', 'supply/coordination'], ['deliveries', 'supply/coordination'], ['alternatives', 'supply/coordination']]) {
|
||||
const page = await reviewer.page(`/compras/fornecimento?view=${view}`, component);
|
||||
if (['imports', 'reservations', 'deliveries', 'alternatives'].includes(view)) check(page.props.canPrepare === false, `${view} read does not grant preparation`);
|
||||
for (const [view, component] of [
|
||||
['agreements', 'supply/index'],
|
||||
['contracts', 'supply/index'],
|
||||
['calendar', 'supply/index'],
|
||||
['imports', 'supply/index'],
|
||||
['history', 'supply/history'],
|
||||
['suggestions', 'supply/suggestions'],
|
||||
['reservations', 'supply/coordination'],
|
||||
['deliveries', 'supply/coordination'],
|
||||
['alternatives', 'supply/coordination'],
|
||||
]) {
|
||||
const page = await reviewer.page(
|
||||
`/compras/fornecimento?view=${view}`,
|
||||
component,
|
||||
);
|
||||
if (
|
||||
['imports', 'reservations', 'deliveries', 'alternatives'].includes(
|
||||
view,
|
||||
)
|
||||
)
|
||||
check(
|
||||
page.props.canPrepare === false,
|
||||
`${view} read does not grant preparation`,
|
||||
);
|
||||
}
|
||||
const operationalControls = await reviewer.page('/revisao-compras', 'purchase-controls/index');
|
||||
check(operationalControls.props.policies.length === 1 && operationalControls.props.policies[0].status === 'pending' && operationalControls.props.policies[0].enabled === false, 'existing synthetic policy remains pending and disabled in operational view');
|
||||
const operationalControls = await reviewer.page(
|
||||
'/revisao-compras',
|
||||
'purchase-controls/index',
|
||||
);
|
||||
check(
|
||||
operationalControls.props.policies.length === 1 &&
|
||||
operationalControls.props.policies[0].status === 'pending' &&
|
||||
operationalControls.props.policies[0].enabled === false,
|
||||
'existing synthetic policy remains pending and disabled in operational view',
|
||||
);
|
||||
await reviewer.page('/ordens/cancelamentos', 'purchase-controls/orders');
|
||||
const ownControls = await requester.page('/revisao-compras', 'purchase-controls/index');
|
||||
check(ownControls.props.policies.length === 0 && ownControls.props.awards.length === 0 && ownControls.props.cancellations.length === 0, 'requester does not inherit operational policy or cancellation data');
|
||||
const ownRequest = await requester.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show');
|
||||
check(ownRequest.props.canReadAuditMetadata === false, 'request ownership does not grant metadata audit');
|
||||
check((await requester.request('/auditoria/eventos')).status === 403, 'requester audit route refuses absent capability');
|
||||
const limited = await auditor.page(`/auditoria/eventos?${query}`, 'audit/metadata');
|
||||
const ownControls = await requester.page(
|
||||
'/revisao-compras',
|
||||
'purchase-controls/index',
|
||||
);
|
||||
check(
|
||||
ownControls.props.policies.length === 0 &&
|
||||
ownControls.props.awards.length === 0 &&
|
||||
ownControls.props.cancellations.length === 0,
|
||||
'requester does not inherit operational policy or cancellation data',
|
||||
);
|
||||
const ownRequest = await requester.page(
|
||||
`/requisicoes/${fixture.historical_decision_request}`,
|
||||
'requisitions/show',
|
||||
);
|
||||
check(
|
||||
ownRequest.props.canReadAuditMetadata === false,
|
||||
'request ownership does not grant metadata audit',
|
||||
);
|
||||
check(
|
||||
(await requester.request('/auditoria/eventos')).status === 403,
|
||||
'requester audit route refuses absent capability',
|
||||
);
|
||||
const limited = await auditor.page(
|
||||
`/auditoria/eventos?${query}`,
|
||||
'audit/metadata',
|
||||
);
|
||||
minimalEvents(limited);
|
||||
check(limited.props.requestContext === null, 'metadata-only actor receives no private process locator');
|
||||
check((await auditor.request(`/requisicoes/${fixture.historical_decision_request}`)).status === 404, 'metadata-only actor cannot read private request');
|
||||
check((await auditor.request('/compras/fornecimento?view=agreements')).status === 403, 'metadata grant does not grant supply access');
|
||||
const csv = async actor => {
|
||||
check(
|
||||
limited.props.requestContext === null,
|
||||
'metadata-only actor receives no private process locator',
|
||||
);
|
||||
check(
|
||||
(
|
||||
await auditor.request(
|
||||
`/requisicoes/${fixture.historical_decision_request}`,
|
||||
)
|
||||
).status === 404,
|
||||
'metadata-only actor cannot read private request',
|
||||
);
|
||||
check(
|
||||
(await auditor.request('/compras/fornecimento?view=agreements'))
|
||||
.status === 403,
|
||||
'metadata grant does not grant supply access',
|
||||
);
|
||||
const csv = async (actor) => {
|
||||
const response = await actor.request(`/auditoria/eventos.csv?${query}`);
|
||||
check(response.status === 200 && response.headers.get('Content-Type')?.includes('text/csv'), 'native metadata CSV');
|
||||
check(response.headers.get('Cache-Control')?.includes('no-store'), 'private CSV not cacheable');
|
||||
check(
|
||||
response.status === 200 &&
|
||||
response.headers.get('Content-Type')?.includes('text/csv'),
|
||||
'native metadata CSV',
|
||||
);
|
||||
check(
|
||||
response.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'private CSV not cacheable',
|
||||
);
|
||||
const body = await response.text();
|
||||
check(body.includes(fixture.audit_request_reference), 'CSV preserves exact criteria');
|
||||
check(
|
||||
body.includes(fixture.audit_request_reference),
|
||||
'CSV preserves exact criteria',
|
||||
);
|
||||
return body;
|
||||
};
|
||||
check(await csv(reviewer) === await csv(auditor), 'both metadata grants export the same scoped metadata without private context');
|
||||
check(
|
||||
(await csv(reviewer)) === (await csv(auditor)),
|
||||
'both metadata grants export the same scoped metadata without private context',
|
||||
);
|
||||
const after = await snapshot();
|
||||
check(JSON.stringify(before) === JSON.stringify(after), 'all native table rows and columns unchanged during read window');
|
||||
const auditInput = {operation_key: crypto.randomUUID(), families: ['purchasing', 'stock', 'finance', 'configuration'], purpose: 'Owned synthetic native QA export'};
|
||||
check(
|
||||
JSON.stringify(before) === JSON.stringify(after),
|
||||
'all native table rows and columns unchanged during read window',
|
||||
);
|
||||
const auditInput = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
families: ['purchasing', 'stock', 'finance', 'configuration'],
|
||||
purpose: 'Owned synthetic native QA export',
|
||||
};
|
||||
await privateAuditor.post('/auditoria/privada', auditInput);
|
||||
const prepared = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||
check(prepared.props.exports.data.length === 1, 'one private package prepared after the unchanged read window');
|
||||
const prepared = await privateAuditor.page(
|
||||
'/auditoria/privada',
|
||||
'audit/private',
|
||||
);
|
||||
check(
|
||||
prepared.props.exports.data.length === 1,
|
||||
'one private package prepared after the unchanged read window',
|
||||
);
|
||||
const packageRow = prepared.props.exports.data[0];
|
||||
const download = await privateAuditor.request(packageRow.download_url);
|
||||
check(download.status === 200 && download.headers.get('Cache-Control')?.includes('no-store'), 'authenticated private package download');
|
||||
check(
|
||||
download.status === 200 &&
|
||||
download.headers.get('Cache-Control')?.includes('no-store'),
|
||||
'authenticated private package download',
|
||||
);
|
||||
const bytes = Buffer.from(await download.arrayBuffer());
|
||||
check(bytes.length === packageRow.size && crypto.createHash('sha256').update(bytes).digest('hex') === packageRow.sha256, 'native download bytes match immutable package size and SHA256');
|
||||
check(
|
||||
bytes.length === packageRow.size &&
|
||||
crypto.createHash('sha256').update(bytes).digest('hex') ===
|
||||
packageRow.sha256,
|
||||
'native download bytes match immutable package size and SHA256',
|
||||
);
|
||||
await privateAuditor.post('/auditoria/privada', auditInput);
|
||||
const replay = await privateAuditor.page('/auditoria/privada', 'audit/private');
|
||||
check(replay.props.exports.data.length === 1 && replay.props.exports.data[0].sha256 === packageRow.sha256, 'replay preserves the same archive');
|
||||
check((await auditor.request(packageRow.download_url)).status === 403, 'metadata cannot download private package');
|
||||
const replay = await privateAuditor.page(
|
||||
'/auditoria/privada',
|
||||
'audit/private',
|
||||
);
|
||||
check(
|
||||
replay.props.exports.data.length === 1 &&
|
||||
replay.props.exports.data[0].sha256 === packageRow.sha256,
|
||||
'replay preserves the same archive',
|
||||
);
|
||||
check(
|
||||
(await auditor.request(packageRow.download_url)).status === 403,
|
||||
'metadata cannot download private package',
|
||||
);
|
||||
await reviewer.logout();
|
||||
await auditor.logout();
|
||||
await requester.logout();
|
||||
await privateAuditor.logout();
|
||||
return { checks, fortify_sessions: 4, missing_csrf_refused: true, stale_inertia_version_refused: true, supply_views: 9, purchase_control_views: 2, requester_scope_verified: true, encrypted_history_verified: true,
|
||||
budget_view_verified: true, conflict_index_verified: true, stock_views_verified: 2, equipment_view_verified: true, investment_view_verified: true, company_configuration_verified: true, operational_orders_verified: true, urgent_stock_verified: true, metadata_scope_isolation_verified: true, readonly_tables_equal: Object.keys(before).length,
|
||||
private_asset_verified: true, private_assets_verified: assets.length, business_commands_sent: 0, audit_export_commands_sent: 2, private_audit_download_verified: true, browser_visual_acceptance: false };
|
||||
return {
|
||||
checks,
|
||||
fortify_sessions: 4,
|
||||
missing_csrf_refused: true,
|
||||
stale_inertia_version_refused: true,
|
||||
supply_views: 9,
|
||||
purchase_control_views: 2,
|
||||
requester_scope_verified: true,
|
||||
encrypted_history_verified: true,
|
||||
budget_view_verified: true,
|
||||
conflict_index_verified: true,
|
||||
stock_views_verified: 2,
|
||||
equipment_view_verified: true,
|
||||
investment_view_verified: true,
|
||||
company_configuration_verified: true,
|
||||
operational_orders_verified: true,
|
||||
urgent_stock_verified: true,
|
||||
metadata_scope_isolation_verified: true,
|
||||
readonly_tables_equal: Object.keys(before).length,
|
||||
private_asset_verified: true,
|
||||
private_assets_verified: assets.length,
|
||||
business_commands_sent: 0,
|
||||
audit_export_commands_sent: 2,
|
||||
private_audit_download_verified: true,
|
||||
browser_visual_acceptance: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,145 +2,393 @@ import crypto from 'node:crypto';
|
||||
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
|
||||
|
||||
/** Same 100 MZN illustrative office scenario as the native Pest journey, through real HTTP sessions. */
|
||||
export async function verifyOfficePurchaseHttp(origin, fixture, readState, progress) {
|
||||
export async function verifyOfficePurchaseHttp(
|
||||
origin,
|
||||
fixture,
|
||||
readState,
|
||||
progress,
|
||||
) {
|
||||
const office = fixture.office_journey;
|
||||
if (!office || fixture.synthetic_only !== true || typeof readState !== 'function') throw Error('Dedicated synthetic office HTTP fixture required');
|
||||
if (
|
||||
!office ||
|
||||
fixture.synthetic_only !== true ||
|
||||
typeof readState !== 'function'
|
||||
)
|
||||
throw Error('Dedicated synthetic office HTTP fixture required');
|
||||
let checks = 0;
|
||||
let commands = 0;
|
||||
let phase = 'login';
|
||||
const check = (condition, label) => { if (!condition) throw Error(`Office HTTP verification failed [${phase}]: ${label}`); checks++; };
|
||||
const stage = name => { phase = name; progress?.({ office_http_phase: name, checks }); };
|
||||
const check = (condition, label) => {
|
||||
if (!condition)
|
||||
throw Error(`Office HTTP verification failed [${phase}]: ${label}`);
|
||||
checks++;
|
||||
};
|
||||
const stage = (name) => {
|
||||
phase = name;
|
||||
progress?.({ office_http_phase: name, checks });
|
||||
};
|
||||
const clients = {};
|
||||
for (const [name, actor] of Object.entries(office.actors)) {
|
||||
clients[name] = createNativeInertiaClient(origin, check);
|
||||
await clients[name].login(actor.email);
|
||||
}
|
||||
const { owner, buyer, head, finance, reviewer, warehouse, procurement_reviewer: procurementReviewer } = clients;
|
||||
const {
|
||||
owner,
|
||||
buyer,
|
||||
head,
|
||||
finance,
|
||||
reviewer,
|
||||
warehouse,
|
||||
procurement_reviewer: procurementReviewer,
|
||||
} = clients;
|
||||
const state = async () => {
|
||||
const source = await readState();
|
||||
if (source.budget !== null) {
|
||||
// The common balance contract takes a lock. Use its native authorised endpoint, never a second calculator.
|
||||
const page = await finance.page('/orcamentos', 'budgets/index');
|
||||
const budget = page.props.budgets.find(row => Number(row.id) === Number(source.budget.id));
|
||||
const fields = ['approved_total_minor', 'reinforced_minor', 'reserved_minor', 'committed_minor', 'consumed_minor', 'available_minor'];
|
||||
check(budget !== undefined && fields.every(field => Object.hasOwn(budget, field)), 'native authoritative budget balance fields');
|
||||
const budget = page.props.budgets.find(
|
||||
(row) => Number(row.id) === Number(source.budget.id),
|
||||
);
|
||||
const fields = [
|
||||
'approved_total_minor',
|
||||
'reinforced_minor',
|
||||
'reserved_minor',
|
||||
'committed_minor',
|
||||
'consumed_minor',
|
||||
'available_minor',
|
||||
];
|
||||
check(
|
||||
budget !== undefined &&
|
||||
fields.every((field) => Object.hasOwn(budget, field)),
|
||||
'native authoritative budget balance fields',
|
||||
);
|
||||
const after = await readState();
|
||||
check(after.financial_fingerprint === source.financial_fingerprint, 'native balance consultation has no financial effects');
|
||||
after.budget.balance = Object.fromEntries(fields.map(field => [field, budget[field]]));
|
||||
check(
|
||||
after.financial_fingerprint === source.financial_fingerprint,
|
||||
'native balance consultation has no financial effects',
|
||||
);
|
||||
after.budget.balance = Object.fromEntries(
|
||||
fields.map((field) => [field, budget[field]]),
|
||||
);
|
||||
return after;
|
||||
}
|
||||
return source;
|
||||
};
|
||||
const post = async (client, route, data, expected = 302) => { commands++; return client.post(route, data, expected); };
|
||||
const date = days => new Date(Date.parse(fixture.clock) + days * 86400000).toISOString().slice(0, 10);
|
||||
const roles = { department_head: head, procurement: buyer, finance: reviewer };
|
||||
const post = async (client, route, data, expected = 302) => {
|
||||
commands++;
|
||||
return client.post(route, data, expected);
|
||||
};
|
||||
const date = (days) =>
|
||||
new Date(Date.parse(fixture.clock) + days * 86400000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
const roles = {
|
||||
department_head: head,
|
||||
procurement: buyer,
|
||||
finance: reviewer,
|
||||
};
|
||||
const awardRoles = { ...roles, procurement: procurementReviewer };
|
||||
let selectorRefused = false;
|
||||
let current = await state();
|
||||
check(current.request === null && current.budget === null && current.stock === null, 'dedicated purchase references are initially unused');
|
||||
check(
|
||||
current.request === null &&
|
||||
current.budget === null &&
|
||||
current.stock === null,
|
||||
'dedicated purchase references are initially unused',
|
||||
);
|
||||
|
||||
stage('budget');
|
||||
check((await owner.request('/orcamentos')).status === 403, 'requester cannot read company budget data');
|
||||
await post(finance, '/orcamentos', { cost_center_id: office.cost_center_id, year: Number(date(0).slice(0, 4)),
|
||||
kind: 'operating', includes_tax: true, amount: '1000.00', reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais' });
|
||||
check(
|
||||
(await owner.request('/orcamentos')).status === 403,
|
||||
'requester cannot read company budget data',
|
||||
);
|
||||
await post(finance, '/orcamentos', {
|
||||
cost_center_id: office.cost_center_id,
|
||||
year: Number(date(0).slice(0, 4)),
|
||||
kind: 'operating',
|
||||
includes_tax: true,
|
||||
amount: '1000.00',
|
||||
reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais',
|
||||
});
|
||||
current = await state();
|
||||
check(current.budget !== null && Number(current.budget.created_by) === office.actors.finance.id, 'native budget issuer');
|
||||
check(
|
||||
current.budget !== null &&
|
||||
Number(current.budget.created_by) === office.actors.finance.id,
|
||||
'native budget issuer',
|
||||
);
|
||||
await post(finance, `/orcamentos/${current.budget.id}/aprovar`, {}, 403);
|
||||
check((await state()).budget.approved_by === null, 'budget issuer cannot approve their own allocation');
|
||||
check(
|
||||
(await state()).budget.approved_by === null,
|
||||
'budget issuer cannot approve their own allocation',
|
||||
);
|
||||
await post(reviewer, `/orcamentos/${current.budget.id}/aprovar`, {});
|
||||
current = await state();
|
||||
check(Number(current.budget.approved_by) === office.actors.reviewer.id && Number(current.budget.balance.available_minor) === 100000, 'independent native budget approval');
|
||||
check(
|
||||
Number(current.budget.approved_by) === office.actors.reviewer.id &&
|
||||
Number(current.budget.balance.available_minor) === 100000,
|
||||
'independent native budget approval',
|
||||
);
|
||||
|
||||
stage('request_and_accounts');
|
||||
await post(owner, '/requisicoes', { operation_key: crypto.randomUUID(), cost_center_id: office.cost_center_id,
|
||||
priority: 'normal', needed_by: date(7), justification: 'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real',
|
||||
items: [{ description: 'Material de escritório HTTP QA', category: office.category, purchase_type: 'consumable',
|
||||
production_area: null, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00',
|
||||
procurement_category: 'office_equipment', category_reason: 'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP' }] });
|
||||
await post(owner, '/requisicoes', {
|
||||
operation_key: crypto.randomUUID(),
|
||||
cost_center_id: office.cost_center_id,
|
||||
priority: 'normal',
|
||||
needed_by: date(7),
|
||||
justification:
|
||||
'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real',
|
||||
items: [
|
||||
{
|
||||
description: 'Material de escritório HTTP QA',
|
||||
category: office.category,
|
||||
purchase_type: 'consumable',
|
||||
production_area: null,
|
||||
quantity: '1.000',
|
||||
unit: 'un',
|
||||
unit_price: '100.00',
|
||||
tax_rate: '0.00',
|
||||
procurement_category: 'office_equipment',
|
||||
category_reason:
|
||||
'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP',
|
||||
},
|
||||
],
|
||||
});
|
||||
current = await state();
|
||||
const requestId = current.request.id;
|
||||
const lineId = current.request.items[0].id;
|
||||
let capital = null;
|
||||
if (office.capital_register) {
|
||||
await post(buyer, '/projectos-imobilizado', { operation_key: crypto.randomUUID(), record_key: null, version: 0,
|
||||
type: 'project', code: office.capital_register.code, name: 'Projecto exclusivamente sintético do percurso HTTP',
|
||||
department_id: office.capital_register.department_id, equipment_id: null, reference: 'Origem documental fictícia de ensaio',
|
||||
state: 'active', reason: 'Cadastro próprio de Compras para conferir rastreabilidade sem dados reais' });
|
||||
const register = await buyer.page('/projectos-imobilizado', 'equipment/capital-register');
|
||||
capital = register.props.records.data.find(row => row.data.code === office.capital_register.code);
|
||||
check(capital !== undefined && capital.version === 1, 'own project created through native HTTP');
|
||||
const choices = await owner.page(`/requisicoes/${requestId}/projectos-imobilizado`, 'requisitions/capital-assignments');
|
||||
check(choices.props.canWrite && choices.props.choices.data.some(row => row.id === capital.id), 'request owner sees the native capital destination');
|
||||
await post(owner, `/requisicoes/${requestId}/projectos-imobilizado`, { operation_key: crypto.randomUUID(), version: 0,
|
||||
item_id: lineId, capital_id: capital.id, reason: 'Destino explícito da linha para o projecto estritamente sintético' });
|
||||
check((await owner.request('/projectos-imobilizado')).status === 403, 'assignment visibility does not grant the requester access to the register');
|
||||
await post(buyer, '/projectos-imobilizado', {
|
||||
operation_key: crypto.randomUUID(),
|
||||
record_key: null,
|
||||
version: 0,
|
||||
type: 'project',
|
||||
code: office.capital_register.code,
|
||||
name: 'Projecto exclusivamente sintético do percurso HTTP',
|
||||
department_id: office.capital_register.department_id,
|
||||
equipment_id: null,
|
||||
reference: 'Origem documental fictícia de ensaio',
|
||||
state: 'active',
|
||||
reason: 'Cadastro próprio de Compras para conferir rastreabilidade sem dados reais',
|
||||
});
|
||||
const register = await buyer.page(
|
||||
'/projectos-imobilizado',
|
||||
'equipment/capital-register',
|
||||
);
|
||||
capital = register.props.records.data.find(
|
||||
(row) => row.data.code === office.capital_register.code,
|
||||
);
|
||||
check(
|
||||
capital !== undefined && capital.version === 1,
|
||||
'own project created through native HTTP',
|
||||
);
|
||||
const choices = await owner.page(
|
||||
`/requisicoes/${requestId}/projectos-imobilizado`,
|
||||
'requisitions/capital-assignments',
|
||||
);
|
||||
check(
|
||||
choices.props.canWrite &&
|
||||
choices.props.choices.data.some((row) => row.id === capital.id),
|
||||
'request owner sees the native capital destination',
|
||||
);
|
||||
await post(owner, `/requisicoes/${requestId}/projectos-imobilizado`, {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: 0,
|
||||
item_id: lineId,
|
||||
capital_id: capital.id,
|
||||
reason: 'Destino explícito da linha para o projecto estritamente sintético',
|
||||
});
|
||||
check(
|
||||
(await owner.request('/projectos-imobilizado')).status === 403,
|
||||
'assignment visibility does not grant the requester access to the register',
|
||||
);
|
||||
}
|
||||
const accountPage = await owner.page(`/requisicoes/${requestId}/contas`, 'requisitions/accounts');
|
||||
const accountPage = await owner.page(
|
||||
`/requisicoes/${requestId}/contas`,
|
||||
'requisitions/accounts',
|
||||
);
|
||||
const account = accountPage.props.accounts.data[0];
|
||||
check(account !== undefined, 'actual common movement account available');
|
||||
await post(owner, `/requisicoes/${requestId}/contas`, { operation_key: crypto.randomUUID(), version: 0, item_id: lineId,
|
||||
basis_hash: accountPage.props.items[0].basis_hash, reason: 'Imputação documental explícita na base própria do percurso HTTP QA',
|
||||
allocations: [{ account_id: account.id, source_hash: account.source_hash, subtotal: '100.00', total: '100.00' }] });
|
||||
await post(owner, `/requisicoes/${requestId}/contas`, {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: 0,
|
||||
item_id: lineId,
|
||||
basis_hash: accountPage.props.items[0].basis_hash,
|
||||
reason: 'Imputação documental explícita na base própria do percurso HTTP QA',
|
||||
allocations: [
|
||||
{
|
||||
account_id: account.id,
|
||||
source_hash: account.source_hash,
|
||||
subtotal: '100.00',
|
||||
total: '100.00',
|
||||
},
|
||||
],
|
||||
});
|
||||
current = await state();
|
||||
const submit = { operation_key: crypto.randomUUID(), process_version: current.request.process_version };
|
||||
const submit = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
process_version: current.request.process_version,
|
||||
};
|
||||
await post(owner, `/requisicoes/${requestId}/submeter`, submit);
|
||||
await post(owner, `/requisicoes/${requestId}/submeter`, submit);
|
||||
current = await state();
|
||||
check(current.request.status === 'pending' && Number(current.budget.balance.reserved_minor) === 10000, 'submission replay preserves one native reserve');
|
||||
await post(owner, `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), process_version: current.request.process_version,
|
||||
decision: 'approved', comment: 'Tentativa própria exclusivamente sintética, que deve ser recusada' }, 403);
|
||||
for (let level = 0; current.request.status === 'pending' && level < 8; level++) {
|
||||
const step = current.request.steps.find(s => s.decision === 'pending');
|
||||
check(step !== undefined && roles[step.role] !== undefined, 'frozen request level has a native eligible actor');
|
||||
await post(roles[step.role], `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(),
|
||||
process_version: current.request.process_version, decision: 'approved', comment: 'Conferência independente do pedido HTTP exclusivamente sintético' });
|
||||
check(
|
||||
current.request.status === 'pending' &&
|
||||
Number(current.budget.balance.reserved_minor) === 10000,
|
||||
'submission replay preserves one native reserve',
|
||||
);
|
||||
await post(
|
||||
owner,
|
||||
`/requisicoes/${requestId}/decidir`,
|
||||
{
|
||||
operation_key: crypto.randomUUID(),
|
||||
process_version: current.request.process_version,
|
||||
decision: 'approved',
|
||||
comment:
|
||||
'Tentativa própria exclusivamente sintética, que deve ser recusada',
|
||||
},
|
||||
403,
|
||||
);
|
||||
for (
|
||||
let level = 0;
|
||||
current.request.status === 'pending' && level < 8;
|
||||
level++
|
||||
) {
|
||||
const step = current.request.steps.find(
|
||||
(s) => s.decision === 'pending',
|
||||
);
|
||||
check(
|
||||
step !== undefined && roles[step.role] !== undefined,
|
||||
'frozen request level has a native eligible actor',
|
||||
);
|
||||
await post(roles[step.role], `/requisicoes/${requestId}/decidir`, {
|
||||
operation_key: crypto.randomUUID(),
|
||||
process_version: current.request.process_version,
|
||||
decision: 'approved',
|
||||
comment:
|
||||
'Conferência independente do pedido HTTP exclusivamente sintético',
|
||||
});
|
||||
current = await state();
|
||||
}
|
||||
check(current.request.status === 'approved', 'native request circuit completed');
|
||||
check(
|
||||
current.request.status === 'approved',
|
||||
'native request circuit completed',
|
||||
);
|
||||
|
||||
stage('suppliers_and_quotes');
|
||||
for (let index = 0; index < 3; index++) {
|
||||
const nuit = String(300000001 + index);
|
||||
await post(buyer, '/fornecedores', { name: `Fornecedor HTTP QA ${index + 1}`, nuit, contact: 'Contacto sintético',
|
||||
email: `office-http-${index}@example.invalid`, phone: '123456789', address: 'Morada exclusivamente sintética',
|
||||
category: office.category, beneficiaries: 'Beneficiário exclusivamente sintético', document_references: 'Referências fictícias de ensaio',
|
||||
diligence_notes: 'Preparação de dados sintéticos sem fornecedor real', blocked: false, next_review: date(365) });
|
||||
await post(buyer, '/fornecedores', {
|
||||
name: `Fornecedor HTTP QA ${index + 1}`,
|
||||
nuit,
|
||||
contact: 'Contacto sintético',
|
||||
email: `office-http-${index}@example.invalid`,
|
||||
phone: '123456789',
|
||||
address: 'Morada exclusivamente sintética',
|
||||
category: office.category,
|
||||
beneficiaries: 'Beneficiário exclusivamente sintético',
|
||||
document_references: 'Referências fictícias de ensaio',
|
||||
diligence_notes:
|
||||
'Preparação de dados sintéticos sem fornecedor real',
|
||||
blocked: false,
|
||||
next_review: date(365),
|
||||
});
|
||||
current = await state();
|
||||
const supplier = current.suppliers.find(s => s.nuit === nuit);
|
||||
const supplier = current.suppliers.find((s) => s.nuit === nuit);
|
||||
check(supplier !== undefined, 'native supplier created');
|
||||
await post(finance, `/fornecedores/${supplier.id}/validar`, { version: supplier.version, status: 'active', comment: 'Conferência financeira independente de dados exclusivamente sintéticos' });
|
||||
await post(buyer, `/requisicoes/${requestId}/cotacoes`, { currency: 'MZN', supplier_id: supplier.id,
|
||||
reference: `HTTP-OFFICE-QUOTE-${index + 1}`, delivery_days: 5, valid_until: date(30),
|
||||
payment_terms: 'Condições exclusivamente sintéticas de trinta dias', no_conflict: true,
|
||||
items: [{ requisition_item_id: lineId, unit_price: `${100 + index * 10}.00`, discount_type: 'none', discount_value: '0.00' }] });
|
||||
await post(finance, `/fornecedores/${supplier.id}/validar`, {
|
||||
version: supplier.version,
|
||||
status: 'active',
|
||||
comment:
|
||||
'Conferência financeira independente de dados exclusivamente sintéticos',
|
||||
});
|
||||
await post(buyer, `/requisicoes/${requestId}/cotacoes`, {
|
||||
currency: 'MZN',
|
||||
supplier_id: supplier.id,
|
||||
reference: `HTTP-OFFICE-QUOTE-${index + 1}`,
|
||||
delivery_days: 5,
|
||||
valid_until: date(30),
|
||||
payment_terms: 'Condições exclusivamente sintéticas de trinta dias',
|
||||
no_conflict: true,
|
||||
items: [
|
||||
{
|
||||
requisition_item_id: lineId,
|
||||
unit_price: `${100 + index * 10}.00`,
|
||||
discount_type: 'none',
|
||||
discount_value: '0.00',
|
||||
},
|
||||
],
|
||||
});
|
||||
current = await state();
|
||||
const quote = current.quotes.find(q => q.supplier_id === supplier.id);
|
||||
const quote = current.quotes.find((q) => q.supplier_id === supplier.id);
|
||||
check(quote !== undefined, 'native quote created');
|
||||
for (const evaluator of [head, reviewer]) await post(evaluator, `/cotacoes/${quote.id}/avaliar`, {
|
||||
quality: '5', history: '5', payment: '5', comment: 'Avaliação independente exclusivamente sintética do percurso HTTP', no_conflict: true });
|
||||
for (const evaluator of [head, reviewer])
|
||||
await post(evaluator, `/cotacoes/${quote.id}/avaliar`, {
|
||||
quality: '5',
|
||||
history: '5',
|
||||
payment: '5',
|
||||
comment:
|
||||
'Avaliação independente exclusivamente sintética do percurso HTTP',
|
||||
no_conflict: true,
|
||||
});
|
||||
}
|
||||
current = await state();
|
||||
check(current.quotes.length === 3 && Number(current.quotes[0].total_minor) === 10000, 'three independently evaluated native quotations');
|
||||
check(
|
||||
current.quotes.length === 3 &&
|
||||
Number(current.quotes[0].total_minor) === 10000,
|
||||
'three independently evaluated native quotations',
|
||||
);
|
||||
|
||||
stage('award_and_order');
|
||||
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, { quotation_id: current.quotes[0].id,
|
||||
justification: 'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo',
|
||||
delivery_date: date(7), delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP' });
|
||||
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, {
|
||||
quotation_id: current.quotes[0].id,
|
||||
justification:
|
||||
'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo',
|
||||
delivery_date: date(7),
|
||||
delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP',
|
||||
});
|
||||
current = await state();
|
||||
const awardId = current.award.id;
|
||||
for (let level = 0; current.award.status !== 'approved' && level < 8; level++) {
|
||||
const step = current.award.steps.find(s => s.decision === 'pending');
|
||||
check(step !== undefined && awardRoles[step.role] !== undefined, 'final-value level has a native eligible actor');
|
||||
for (
|
||||
let level = 0;
|
||||
current.award.status !== 'approved' && level < 8;
|
||||
level++
|
||||
) {
|
||||
const step = current.award.steps.find((s) => s.decision === 'pending');
|
||||
check(
|
||||
step !== undefined && awardRoles[step.role] !== undefined,
|
||||
'final-value level has a native eligible actor',
|
||||
);
|
||||
if (step.role === 'procurement') {
|
||||
await post(buyer, `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada' }, 403);
|
||||
await post(
|
||||
buyer,
|
||||
`/adjudicacoes/${awardId}/decidir`,
|
||||
{
|
||||
decision: 'approved',
|
||||
comment:
|
||||
'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada',
|
||||
},
|
||||
403,
|
||||
);
|
||||
current = await state();
|
||||
check(current.award.steps.find(row => row.id === step.id)?.decision === 'pending', 'selector refusal preserves the pending independent decision');
|
||||
check(
|
||||
current.award.steps.find((row) => row.id === step.id)
|
||||
?.decision === 'pending',
|
||||
'selector refusal preserves the pending independent decision',
|
||||
);
|
||||
selectorRefused = true;
|
||||
}
|
||||
await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Conferência independente do valor final exclusivamente sintético HTTP' });
|
||||
await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, {
|
||||
decision: 'approved',
|
||||
comment:
|
||||
'Conferência independente do valor final exclusivamente sintético HTTP',
|
||||
});
|
||||
current = await state();
|
||||
}
|
||||
check(current.award.status === 'approved' && selectorRefused, 'native final-value approvals completed by an independent buyer');
|
||||
check(
|
||||
current.award.status === 'approved' && selectorRefused,
|
||||
'native final-value approvals completed by an independent buyer',
|
||||
);
|
||||
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
|
||||
current = await state();
|
||||
const orderId = current.order.id;
|
||||
@@ -148,147 +396,434 @@ export async function verifyOfficePurchaseHttp(origin, fixture, readState, progr
|
||||
const issued = current.financial_fingerprint;
|
||||
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
|
||||
current = await state();
|
||||
check(current.order.id === orderId && current.financial_fingerprint === issued, 'order replay has no financial or document effect');
|
||||
check(Number(current.order.total_minor) === 10000 && current.order.account_assignments[lineId].data.allocations[0].account.id === account.id, 'order preserves exact amount and native chart attribution');
|
||||
check(current.order.budget_checked === true, 'new order preserves the budget authority confirmation already returned at issuance');
|
||||
if (capital) check(current.order.capital_assignments[lineId].snapshot.source.record_key === capital.record_key
|
||||
&& current.order.capital_assignments[lineId].snapshot.source.version === 1, 'issued order preserves the exact native project version');
|
||||
check(
|
||||
current.order.id === orderId &&
|
||||
current.financial_fingerprint === issued,
|
||||
'order replay has no financial or document effect',
|
||||
);
|
||||
check(
|
||||
Number(current.order.total_minor) === 10000 &&
|
||||
current.order.account_assignments[lineId].data.allocations[0]
|
||||
.account.id === account.id,
|
||||
'order preserves exact amount and native chart attribution',
|
||||
);
|
||||
check(
|
||||
current.order.budget_checked === true,
|
||||
'new order preserves the budget authority confirmation already returned at issuance',
|
||||
);
|
||||
if (capital)
|
||||
check(
|
||||
current.order.capital_assignments[lineId].snapshot.source
|
||||
.record_key === capital.record_key &&
|
||||
current.order.capital_assignments[lineId].snapshot.source
|
||||
.version === 1,
|
||||
'issued order preserves the exact native project version',
|
||||
);
|
||||
const financialDocumentsHref = `/facturas?purchase_order_id=${orderId}#invoice-documents`;
|
||||
const financeOrder = await finance.page(`/ordens/${orderId}`, 'purchases/show');
|
||||
check(financeOrder.props.financialDocumentsHref === financialDocumentsHref
|
||||
&& financeOrder.props.relatedProcesses.some(source => source.id === requestId && source.href === `/requisicoes/${requestId}/processo`), 'order navigation preserves exact financial and process context');
|
||||
const financeOrder = await finance.page(
|
||||
`/ordens/${orderId}`,
|
||||
'purchases/show',
|
||||
);
|
||||
check(
|
||||
financeOrder.props.financialDocumentsHref === financialDocumentsHref &&
|
||||
financeOrder.props.relatedProcesses.some(
|
||||
(source) =>
|
||||
source.id === requestId &&
|
||||
source.href === `/requisicoes/${requestId}/processo`,
|
||||
),
|
||||
'order navigation preserves exact financial and process context',
|
||||
);
|
||||
const printRoute = `/ordens/${orderId}/imprimir`;
|
||||
const printHeaders = { 'X-Inertia': 'true', ...(financeOrder.version === null ? {} : { 'X-Inertia-Version': financeOrder.version }) };
|
||||
const printNavigation = await finance.request(printRoute, { headers: printHeaders });
|
||||
check(printNavigation.status === 409 && printNavigation.headers.get('x-inertia-location') === printRoute, 'authorised print navigation requests the complete HTML document');
|
||||
const printHeaders = {
|
||||
'X-Inertia': 'true',
|
||||
...(financeOrder.version === null
|
||||
? {}
|
||||
: { 'X-Inertia-Version': financeOrder.version }),
|
||||
};
|
||||
const printNavigation = await finance.request(printRoute, {
|
||||
headers: printHeaders,
|
||||
});
|
||||
check(
|
||||
printNavigation.status === 409 &&
|
||||
printNavigation.headers.get('x-inertia-location') === printRoute,
|
||||
'authorised print navigation requests the complete HTML document',
|
||||
);
|
||||
const printDocument = await finance.request(printRoute);
|
||||
check(printDocument.status === 200 && (await printDocument.text()).includes('Controlo orçamental registado na emissão.'), 'native controlled print preserves the actual budget confirmation');
|
||||
const privatePrint = await owner.request(printRoute, { headers: printHeaders });
|
||||
check(privatePrint.status === 403 && !privatePrint.headers.has('x-inertia-location'), 'requester receives no print redirect without native order access');
|
||||
check(
|
||||
printDocument.status === 200 &&
|
||||
(await printDocument.text()).includes(
|
||||
'Controlo orçamental registado na emissão.',
|
||||
),
|
||||
'native controlled print preserves the actual budget confirmation',
|
||||
);
|
||||
const privatePrint = await owner.request(printRoute, {
|
||||
headers: printHeaders,
|
||||
});
|
||||
check(
|
||||
privatePrint.status === 403 &&
|
||||
!privatePrint.headers.has('x-inertia-location'),
|
||||
'requester receives no print redirect without native order access',
|
||||
);
|
||||
const buyerOrder = await buyer.page(`/ordens/${orderId}`, 'purchases/show');
|
||||
// This synthetic buyer also has Admin; use the independent Procurement-only reviewer to test redaction.
|
||||
const independentOrder = await procurementReviewer.page(`/ordens/${orderId}`, 'purchases/show');
|
||||
check(buyerOrder.props.financialDocumentsHref === financialDocumentsHref && independentOrder.props.financialDocumentsHref === null,
|
||||
'order financial link follows native Admin/Finance access without Procurement inheritance');
|
||||
const independentOrder = await procurementReviewer.page(
|
||||
`/ordens/${orderId}`,
|
||||
'purchases/show',
|
||||
);
|
||||
check(
|
||||
buyerOrder.props.financialDocumentsHref === financialDocumentsHref &&
|
||||
independentOrder.props.financialDocumentsHref === null,
|
||||
'order financial link follows native Admin/Finance access without Procurement inheritance',
|
||||
);
|
||||
|
||||
stage('receipt_and_invoice');
|
||||
const financeReceipt = await finance.page(`/ordens/${orderId}/recepcoes`, 'receipts/order');
|
||||
const warehouseReceipt = await warehouse.page(`/ordens/${orderId}/recepcoes`, 'receipts/order');
|
||||
check(financeReceipt.props.financialDocumentsHref === financialDocumentsHref && warehouseReceipt.props.financialDocumentsHref === null,
|
||||
'receipt navigation exposes financial context only to the native reader');
|
||||
await post(warehouse, '/stock/artigos', { code: 'HTTP-OFFICE-QA', name: 'Material de escritório HTTP QA', unit: 'un' });
|
||||
const financeReceipt = await finance.page(
|
||||
`/ordens/${orderId}/recepcoes`,
|
||||
'receipts/order',
|
||||
);
|
||||
const warehouseReceipt = await warehouse.page(
|
||||
`/ordens/${orderId}/recepcoes`,
|
||||
'receipts/order',
|
||||
);
|
||||
check(
|
||||
financeReceipt.props.financialDocumentsHref ===
|
||||
financialDocumentsHref &&
|
||||
warehouseReceipt.props.financialDocumentsHref === null,
|
||||
'receipt navigation exposes financial context only to the native reader',
|
||||
);
|
||||
await post(warehouse, '/stock/artigos', {
|
||||
code: 'HTTP-OFFICE-QA',
|
||||
name: 'Material de escritório HTTP QA',
|
||||
unit: 'un',
|
||||
});
|
||||
current = await state();
|
||||
const receipt = { idempotency_key: crypto.randomUUID(), delivery_note: 'HTTP-OFFICE-DELIVERY-QA', received_on: date(0),
|
||||
warehouse_id: office.warehouse_id, items: [{ purchase_order_item_id: orderLineId, received_quantity: '1.000', accepted_quantity: '1.000',
|
||||
quality_status: 'compliant', stock_item_id: current.stock.id }] };
|
||||
const receipt = {
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
delivery_note: 'HTTP-OFFICE-DELIVERY-QA',
|
||||
received_on: date(0),
|
||||
warehouse_id: office.warehouse_id,
|
||||
items: [
|
||||
{
|
||||
purchase_order_item_id: orderLineId,
|
||||
received_quantity: '1.000',
|
||||
accepted_quantity: '1.000',
|
||||
quality_status: 'compliant',
|
||||
stock_item_id: current.stock.id,
|
||||
},
|
||||
],
|
||||
};
|
||||
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 201);
|
||||
current = await state();
|
||||
const received = current.financial_fingerprint;
|
||||
const confirmedReceiptId = current.order.receipts[0].id;
|
||||
const financialReceiptDetail = await finance.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show');
|
||||
const warehouseReceiptDetail = await warehouse.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show');
|
||||
check(financialReceiptDetail.props.financialDocumentsHref === financialDocumentsHref
|
||||
&& warehouseReceiptDetail.props.financialDocumentsHref === null,
|
||||
'confirmed receipt detail offers the exact financial context only to its native reader');
|
||||
const financialReceiptDetail = await finance.page(
|
||||
`/recepcoes/${confirmedReceiptId}`,
|
||||
'receipts/show',
|
||||
);
|
||||
const warehouseReceiptDetail = await warehouse.page(
|
||||
`/recepcoes/${confirmedReceiptId}`,
|
||||
'receipts/show',
|
||||
);
|
||||
check(
|
||||
financialReceiptDetail.props.financialDocumentsHref ===
|
||||
financialDocumentsHref &&
|
||||
warehouseReceiptDetail.props.financialDocumentsHref === null,
|
||||
'confirmed receipt detail offers the exact financial context only to its native reader',
|
||||
);
|
||||
current = await state();
|
||||
check(current.financial_fingerprint === received, 'receipt detail consultation preserves financial and stock sources');
|
||||
check(
|
||||
current.financial_fingerprint === received,
|
||||
'receipt detail consultation preserves financial and stock sources',
|
||||
);
|
||||
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 200);
|
||||
current = await state();
|
||||
check(current.financial_fingerprint === received && current.order.receipts.length === 1 && current.stock.movements === 1 && current.stock.quantity_milli === 1000, 'receipt replay preserves one physical movement');
|
||||
await post(finance, `/ordens/${orderId}/facturas`, { number: 'HTTP-OFFICE-INVOICE-QA', issued_on: date(0), subtotal: '100.00', tax: '0.00', total: '100.00',
|
||||
items: [{ purchase_order_item_id: orderLineId, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00' }] });
|
||||
check(
|
||||
current.financial_fingerprint === received &&
|
||||
current.order.receipts.length === 1 &&
|
||||
current.stock.movements === 1 &&
|
||||
current.stock.quantity_milli === 1000,
|
||||
'receipt replay preserves one physical movement',
|
||||
);
|
||||
await post(finance, `/ordens/${orderId}/facturas`, {
|
||||
number: 'HTTP-OFFICE-INVOICE-QA',
|
||||
issued_on: date(0),
|
||||
subtotal: '100.00',
|
||||
tax: '0.00',
|
||||
total: '100.00',
|
||||
items: [
|
||||
{
|
||||
purchase_order_item_id: orderLineId,
|
||||
quantity: '1.000',
|
||||
unit: 'un',
|
||||
unit_price: '100.00',
|
||||
tax_rate: '0.00',
|
||||
},
|
||||
],
|
||||
});
|
||||
current = await state();
|
||||
const invoiceId = current.invoice.id;
|
||||
await post(finance, `/facturas/${invoiceId}/validar`, {}, 403);
|
||||
current = await state();
|
||||
check(current.invoice.status === 'pending', 'invoice author cannot validate their own invoice');
|
||||
check(
|
||||
current.invoice.status === 'pending',
|
||||
'invoice author cannot validate their own invoice',
|
||||
);
|
||||
await post(reviewer, `/facturas/${invoiceId}/validar`, {});
|
||||
current = await state();
|
||||
check(current.invoice.status === 'validated' && Number(current.budget.balance.consumed_minor) === 10000
|
||||
&& Number(current.budget.balance.available_minor) === 90000, 'native invoice validation consumes the exact commitment');
|
||||
check(
|
||||
current.invoice.status === 'validated' &&
|
||||
Number(current.budget.balance.consumed_minor) === 10000 &&
|
||||
Number(current.budget.balance.available_minor) === 90000,
|
||||
'native invoice validation consumes the exact commitment',
|
||||
);
|
||||
const consumedBudget = JSON.stringify(current.budget.balance);
|
||||
|
||||
stage('bank_and_partial_payment');
|
||||
const supplierId = current.quotes[0].supplier_id;
|
||||
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, { account_key: crypto.randomUUID(), previous_id: 0,
|
||||
bank_name: 'Banco exclusivamente sintético HTTP QA', country: 'MZ', currency: 'MZN', beneficiary: 'Titular exclusivamente sintético',
|
||||
account_identifier: 'HTTP-OFFICE-ACCOUNT-QA', evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP', reason: 'Preparação de conta fictícia sem operação bancária real' });
|
||||
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, {
|
||||
account_key: crypto.randomUUID(),
|
||||
previous_id: 0,
|
||||
bank_name: 'Banco exclusivamente sintético HTTP QA',
|
||||
country: 'MZ',
|
||||
currency: 'MZN',
|
||||
beneficiary: 'Titular exclusivamente sintético',
|
||||
account_identifier: 'HTTP-OFFICE-ACCOUNT-QA',
|
||||
evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP',
|
||||
reason: 'Preparação de conta fictícia sem operação bancária real',
|
||||
});
|
||||
current = await state();
|
||||
const bankId = current.bank.id;
|
||||
for (const bankReviewer of [finance, reviewer]) await post(bankReviewer, `/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`, {
|
||||
decision: 'approved', independently_verified: true, reason: 'Conferência independente de evidência exclusivamente sintética HTTP' });
|
||||
for (const bankReviewer of [finance, reviewer])
|
||||
await post(
|
||||
bankReviewer,
|
||||
`/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`,
|
||||
{
|
||||
decision: 'approved',
|
||||
independently_verified: true,
|
||||
reason: 'Conferência independente de evidência exclusivamente sintética HTTP',
|
||||
},
|
||||
);
|
||||
current = await state();
|
||||
check(current.bank.approved_reviews === 2, 'two independent native bank reviews');
|
||||
const payment = { supplier_bank_detail_id: bankId, amount: '40.00', paid_on: date(0), external_reference: 'HTTP-OFFICE-PARTIAL-QA',
|
||||
evidence_reference: 'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária' };
|
||||
check(
|
||||
current.bank.approved_reviews === 2,
|
||||
'two independent native bank reviews',
|
||||
);
|
||||
const payment = {
|
||||
supplier_bank_detail_id: bankId,
|
||||
amount: '40.00',
|
||||
paid_on: date(0),
|
||||
external_reference: 'HTTP-OFFICE-PARTIAL-QA',
|
||||
evidence_reference:
|
||||
'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária',
|
||||
};
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
|
||||
current = await state();
|
||||
const paymentId = current.payments[0].id;
|
||||
const reviewPage = await reviewer.page(`/pagamentos?payment_id=${paymentId}`, 'payments/index');
|
||||
check(reviewPage.props.payments.data[0].canReview === true && reviewPage.props.focusPaymentId === paymentId, 'independent native payment review workspace');
|
||||
const registrationPage = await finance.page(`/pagamentos?invoice_id=${invoiceId}`, 'payments/index');
|
||||
check(registrationPage.props.focusInvoiceId === invoiceId && registrationPage.props.invoices[0].outstanding_minor === 10000, 'native payment registration workspace uses the authoritative invoice balance');
|
||||
const reviewPage = await reviewer.page(
|
||||
`/pagamentos?payment_id=${paymentId}`,
|
||||
'payments/index',
|
||||
);
|
||||
check(
|
||||
reviewPage.props.payments.data[0].canReview === true &&
|
||||
reviewPage.props.focusPaymentId === paymentId,
|
||||
'independent native payment review workspace',
|
||||
);
|
||||
const registrationPage = await finance.page(
|
||||
`/pagamentos?invoice_id=${invoiceId}`,
|
||||
'payments/index',
|
||||
);
|
||||
check(
|
||||
registrationPage.props.focusInvoiceId === invoiceId &&
|
||||
registrationPage.props.invoices[0].outstanding_minor === 10000,
|
||||
'native payment registration workspace uses the authoritative invoice balance',
|
||||
);
|
||||
const pending = current.financial_fingerprint;
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
|
||||
current = await state();
|
||||
check(current.payments.length === 1 && current.financial_fingerprint === pending, 'payment registration replay has no financial effect');
|
||||
await post(finance, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Tentativa própria exclusivamente sintética que deve ser recusada' }, 403);
|
||||
check((await reviewer.request(`/pagamentos/${paymentId}/categorias`)).status === 409, 'unconfirmed payment cannot be attributed to expense categories');
|
||||
await post(reviewer, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente de evidência fictícia de pagamento parcial' });
|
||||
check(
|
||||
current.payments.length === 1 &&
|
||||
current.financial_fingerprint === pending,
|
||||
'payment registration replay has no financial effect',
|
||||
);
|
||||
await post(
|
||||
finance,
|
||||
`/pagamentos/${paymentId}/conferir`,
|
||||
{
|
||||
decision: 'confirmed',
|
||||
independently_verified: true,
|
||||
reason: 'Tentativa própria exclusivamente sintética que deve ser recusada',
|
||||
},
|
||||
403,
|
||||
);
|
||||
check(
|
||||
(await reviewer.request(`/pagamentos/${paymentId}/categorias`))
|
||||
.status === 409,
|
||||
'unconfirmed payment cannot be attributed to expense categories',
|
||||
);
|
||||
await post(reviewer, `/pagamentos/${paymentId}/conferir`, {
|
||||
decision: 'confirmed',
|
||||
independently_verified: true,
|
||||
reason: 'Conferência independente de evidência fictícia de pagamento parcial',
|
||||
});
|
||||
current = await state();
|
||||
check(current.payments[0].status === 'confirmed' && current.invoice.outstanding_minor === 6000, 'confirmed partial payment preserves the exact outstanding amount');
|
||||
const overpay = await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.01', external_reference: 'HTTP-OFFICE-OVERPAY-QA' }, 422);
|
||||
check(Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'), 'overpayment is refused by the native financial rule');
|
||||
check(
|
||||
current.payments[0].status === 'confirmed' &&
|
||||
current.invoice.outstanding_minor === 6000,
|
||||
'confirmed partial payment preserves the exact outstanding amount',
|
||||
);
|
||||
const overpay = await post(
|
||||
finance,
|
||||
`/facturas/${invoiceId}/pagamentos`,
|
||||
{
|
||||
...payment,
|
||||
amount: '60.01',
|
||||
external_reference: 'HTTP-OFFICE-OVERPAY-QA',
|
||||
},
|
||||
422,
|
||||
);
|
||||
check(
|
||||
Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'),
|
||||
'overpayment is refused by the native financial rule',
|
||||
);
|
||||
|
||||
const attribute = async (id, amount) => {
|
||||
const page = await reviewer.page(`/pagamentos/${id}/categorias`, 'payments/expense-allocation');
|
||||
const page = await reviewer.page(
|
||||
`/pagamentos/${id}/categorias`,
|
||||
'payments/expense-allocation',
|
||||
);
|
||||
const before = (await state()).financial_fingerprint;
|
||||
const data = { operation_key: crypto.randomUUID(), version: page.props.current?.version ?? 0, fingerprint: page.props.fingerprint,
|
||||
reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP', allocations: [{ category: office.category, amount }] };
|
||||
const data = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: page.props.current?.version ?? 0,
|
||||
fingerprint: page.props.fingerprint,
|
||||
reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP',
|
||||
allocations: [{ category: office.category, amount }],
|
||||
};
|
||||
await post(reviewer, `/pagamentos/${id}/categorias`, data);
|
||||
await post(reviewer, `/pagamentos/${id}/categorias`, data);
|
||||
check((await state()).financial_fingerprint === before, 'explicit attribution and its replay never change financial or stock sources');
|
||||
check(
|
||||
(await state()).financial_fingerprint === before,
|
||||
'explicit attribution and its replay never change financial or stock sources',
|
||||
);
|
||||
};
|
||||
await attribute(paymentId, '40.00');
|
||||
|
||||
stage('settlement_and_privacy');
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.00', external_reference: 'HTTP-OFFICE-FINAL-QA' });
|
||||
await post(finance, `/facturas/${invoiceId}/pagamentos`, {
|
||||
...payment,
|
||||
amount: '60.00',
|
||||
external_reference: 'HTTP-OFFICE-FINAL-QA',
|
||||
});
|
||||
current = await state();
|
||||
const finalPaymentId = current.payments.find(p => p.id !== paymentId).id;
|
||||
await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente do saldo exclusivamente sintético HTTP' });
|
||||
const finalPaymentId = current.payments.find((p) => p.id !== paymentId).id;
|
||||
await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, {
|
||||
decision: 'confirmed',
|
||||
independently_verified: true,
|
||||
reason: 'Conferência independente do saldo exclusivamente sintético HTTP',
|
||||
});
|
||||
await attribute(finalPaymentId, '60.00');
|
||||
current = await state();
|
||||
check(current.invoice.outstanding_minor === 0 && current.payments.length === 2 && current.payments.every(p => p.status === 'confirmed'), 'two independently confirmed payments settle exactly 100 MZN');
|
||||
check(String(current.analytics.currencies[0].amount_minor) === '10000' && current.analytics.coverage.confirmed_payments === 2
|
||||
&& String(current.analytics.category_attribution.groups.data[0].amount_minor) === '10000', 'native confirmed-payment analytics and explicit category attribution agree');
|
||||
check(JSON.stringify(current.budget.balance) === consumedBudget && current.stock.quantity_milli === 1000 && current.stock.movements === 1 && current.journals === 0,
|
||||
'settlement preserves budget consumption, stock and documentary chart boundary');
|
||||
const process = await owner.request(`/requisicoes/${requestId}/processo`, { headers: { 'X-Inertia': 'true' } });
|
||||
check(
|
||||
current.invoice.outstanding_minor === 0 &&
|
||||
current.payments.length === 2 &&
|
||||
current.payments.every((p) => p.status === 'confirmed'),
|
||||
'two independently confirmed payments settle exactly 100 MZN',
|
||||
);
|
||||
check(
|
||||
String(current.analytics.currencies[0].amount_minor) === '10000' &&
|
||||
current.analytics.coverage.confirmed_payments === 2 &&
|
||||
String(
|
||||
current.analytics.category_attribution.groups.data[0]
|
||||
.amount_minor,
|
||||
) === '10000',
|
||||
'native confirmed-payment analytics and explicit category attribution agree',
|
||||
);
|
||||
check(
|
||||
JSON.stringify(current.budget.balance) === consumedBudget &&
|
||||
current.stock.quantity_milli === 1000 &&
|
||||
current.stock.movements === 1 &&
|
||||
current.journals === 0,
|
||||
'settlement preserves budget consumption, stock and documentary chart boundary',
|
||||
);
|
||||
const process = await owner.request(`/requisicoes/${requestId}/processo`, {
|
||||
headers: { 'X-Inertia': 'true' },
|
||||
});
|
||||
check(process.status === 200, 'requester native process route');
|
||||
const report = await process.json();
|
||||
check(report.props.stages[7].state === 'restricted' && report.props.stages[8].state === 'restricted'
|
||||
&& !Object.hasOwn(report.props, 'invoices') && !Object.hasOwn(report.props, 'payments') && !Object.hasOwn(report.props, 'bank_snapshot'), 'requester process does not disclose financial or bank records');
|
||||
check(
|
||||
report.props.stages[7].state === 'restricted' &&
|
||||
report.props.stages[8].state === 'restricted' &&
|
||||
!Object.hasOwn(report.props, 'invoices') &&
|
||||
!Object.hasOwn(report.props, 'payments') &&
|
||||
!Object.hasOwn(report.props, 'bank_snapshot'),
|
||||
'requester process does not disclose financial or bank records',
|
||||
);
|
||||
if (capital) {
|
||||
stage('project_trace');
|
||||
const beforeTrace = current.financial_fingerprint;
|
||||
const trace = await finance.page(`/projectos-imobilizado?history=${capital.record_key}`, 'equipment/capital-register');
|
||||
check(trace.props.trace.orders.data.some(row => row.order_id === orderId), 'project trace reaches its actual issued order');
|
||||
check(trace.props.trace.receipts.data.some(row => row.order_id === orderId), 'project trace reaches its actual physical receipt');
|
||||
check(trace.props.history.data[0].record_key === capital.record_key && trace.props.history.data[0].version === 1, 'project history remains its native version');
|
||||
const trace = await finance.page(
|
||||
`/projectos-imobilizado?history=${capital.record_key}`,
|
||||
'equipment/capital-register',
|
||||
);
|
||||
check(
|
||||
trace.props.trace.orders.data.some(
|
||||
(row) => row.order_id === orderId,
|
||||
),
|
||||
'project trace reaches its actual issued order',
|
||||
);
|
||||
check(
|
||||
trace.props.trace.receipts.data.some(
|
||||
(row) => row.order_id === orderId,
|
||||
),
|
||||
'project trace reaches its actual physical receipt',
|
||||
);
|
||||
check(
|
||||
trace.props.history.data[0].record_key === capital.record_key &&
|
||||
trace.props.history.data[0].version === 1,
|
||||
'project history remains its native version',
|
||||
);
|
||||
current = await state();
|
||||
check(current.financial_fingerprint === beforeTrace, 'project trace consultation changes no financial or stock source');
|
||||
check(
|
||||
current.financial_fingerprint === beforeTrace,
|
||||
'project trace consultation changes no financial or stock source',
|
||||
);
|
||||
}
|
||||
for (const client of Object.values(clients)) await client.logout();
|
||||
return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length,
|
||||
request_id: requestId, order_id: orderId, invoice_id: invoiceId, payment_ids: current.payments.map(p => p.id),
|
||||
request_total_minor: current.request.total_minor, order_total_minor: current.order.total_minor, invoice_total_minor: current.invoice.total_minor,
|
||||
confirmed_payments_minor: current.payments.map(p => p.amount_minor), outstanding_minor: current.invoice.outstanding_minor,
|
||||
budget_consumed_minor: current.budget.balance.consumed_minor, budget_available_minor: current.budget.balance.available_minor,
|
||||
return {
|
||||
checks,
|
||||
native_post_requests: commands,
|
||||
fortify_sessions: Object.keys(clients).length,
|
||||
request_id: requestId,
|
||||
order_id: orderId,
|
||||
invoice_id: invoiceId,
|
||||
payment_ids: current.payments.map((p) => p.id),
|
||||
request_total_minor: current.request.total_minor,
|
||||
order_total_minor: current.order.total_minor,
|
||||
invoice_total_minor: current.invoice.total_minor,
|
||||
confirmed_payments_minor: current.payments.map((p) => p.amount_minor),
|
||||
outstanding_minor: current.invoice.outstanding_minor,
|
||||
budget_consumed_minor: current.budget.balance.consumed_minor,
|
||||
budget_available_minor: current.budget.balance.available_minor,
|
||||
order_budget_checked: current.order.budget_checked,
|
||||
stock_quantity_milli: current.stock.quantity_milli, stock_movements: current.stock.movements, journals: current.journals,
|
||||
explicit_finance_category_total_minor: current.analytics.category_attribution.groups.data[0].amount_minor,
|
||||
all_business_mutations_via_native_http: true, assertions_use_readonly_transactions: true, budget_balance_via_native_http: true,
|
||||
selector_self_final_approval_refused: selectorRefused, synthetic_only: true,
|
||||
project_trace: capital ? { record_key: capital.record_key, code: capital.data.code, version: capital.version, order_id: orderId } : null,
|
||||
real_bank_or_sgf_operations: false, browser_visual_acceptance: false };
|
||||
stock_quantity_milli: current.stock.quantity_milli,
|
||||
stock_movements: current.stock.movements,
|
||||
journals: current.journals,
|
||||
explicit_finance_category_total_minor:
|
||||
current.analytics.category_attribution.groups.data[0].amount_minor,
|
||||
all_business_mutations_via_native_http: true,
|
||||
assertions_use_readonly_transactions: true,
|
||||
budget_balance_via_native_http: true,
|
||||
selector_self_final_approval_refused: selectorRefused,
|
||||
synthetic_only: true,
|
||||
project_trace: capital
|
||||
? {
|
||||
record_key: capital.record_key,
|
||||
code: capital.data.code,
|
||||
version: capital.version,
|
||||
order_id: orderId,
|
||||
}
|
||||
: null,
|
||||
real_bank_or_sgf_operations: false,
|
||||
browser_visual_acceptance: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8');
|
||||
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author ='));
|
||||
await new Function('fs','assert','return (async()=>{'+common+`
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -20,4 +31,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Existing pilot access and source binding validation; positive searches and associations exercised in disposable databases.'},null,2));
|
||||
console.log('Pesquisa de saídas conferida sem conceder competências ou criar movimentos no piloto.');
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
@@ -18,4 +29,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
}
|
||||
await fs.writeFile('docs/proofs/search-expansion-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
|
||||
console.log(JSON.stringify({roles_checked:results.length,result:'passed',business_commands:false}));
|
||||
`+'})()')(fs,assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
+131
-40
@@ -2,46 +2,137 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import {spawnSync} from 'node:child_process';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { purchasingHomeOverlay } from './lib/sgf-purchasing-home-overlay.mjs';
|
||||
|
||||
const host=fs.realpathSync(process.argv[2]||'');
|
||||
if(fs.existsSync(path.join(host,'public/hot')))throw Error('Stop the source frontend watcher before freezing a candidate.');
|
||||
const work=path.join('C:/laragon/data/sgf-tempo/run','candidate-ui-'+crypto.randomBytes(6).toString('hex'));
|
||||
fs.mkdirSync(work,{recursive:true});
|
||||
const replace=(text,old,next)=>{if(text.split(old).length!==2)throw Error('Frontend baseline changed: '+old.slice(0,70));return text.replace(old,next);};
|
||||
fs.cpSync(path.join(host,'resources'),path.join(work,'resources'),{recursive:true});
|
||||
for(const file of ['package.json','vite.config.js'])fs.copyFileSync(path.join(host,file),path.join(work,file));
|
||||
fs.mkdirSync(path.join(work,'public/build'),{recursive:true});
|
||||
fs.symlinkSync(path.join(host,'node_modules'),path.join(work,'node_modules'),'junction');
|
||||
let app=fs.readFileSync(path.join(work,'resources/js/app.jsx'),'utf8');
|
||||
app=replace(app,"const options = (unit === null ? ['company.view', 'company.edit', 'unit.create', 'access.manage'] : ['unit.view', 'unit.edit']).filter(p => can(p, unit));", "const options = (list?.catalogue?.[unit === null ? 'company' : 'unit'] ?? []).filter(p => can(p, unit));");
|
||||
app=replace(app,'{labels[p]}','{list?.catalogue_labels?.[p] ?? labels[p] ?? p}');
|
||||
app=replace(app,'{labels[g.permission]}','{list?.catalogue_labels?.[g.permission] ?? labels[g.permission] ?? g.permission}');
|
||||
fs.writeFileSync(path.join(work,'resources/js/app.jsx'),app);
|
||||
let home=fs.readFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),'utf8');
|
||||
home=purchasingHomeOverlay(home);
|
||||
fs.writeFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),home);
|
||||
let config=fs.readFileSync(path.join(work,'vite.config.js'),'utf8');
|
||||
config=replace(config,'defineConfig({',`defineConfig({\n cacheDir: ${JSON.stringify(path.join(work,'vite-cache'))},`);
|
||||
fs.writeFileSync(path.join(work,'vite.config.js'),config);
|
||||
const result=spawnSync(process.execPath,[path.join(host,'node_modules/vite/bin/vite.js'),'build','--config',path.join(work,'vite.config.js'),'--configLoader','native'],{cwd:work,encoding:'utf8',windowsHide:true,maxBuffer:4*1024*1024,env:{...process.env,NODE_ENV:'production'}});
|
||||
fs.writeFileSync(path.join(work,'build.log'),(result.stdout||'')+(result.stderr||''));
|
||||
if(result.status!==0)throw Error('Candidate frontend build failed; private log '+path.join(work,'build.log'));
|
||||
const original=JSON.parse(fs.readFileSync(path.join(work,'public/build/manifest.json'),'utf8'));
|
||||
const assets={};
|
||||
for(const chunk of Object.values(original))for(const file of [chunk.file,...(chunk.css||[]),...(chunk.assets||[])]){
|
||||
if(!/^assets\/[A-Za-z0-9_-]+\.(js|css)$/.test(file))throw Error('Unsupported frontend asset '+file);
|
||||
assets['integrations/sgf/frontend/'+file]=path.join(work,'public/build',file);
|
||||
const host = fs.realpathSync(process.argv[2] || '');
|
||||
if (fs.existsSync(path.join(host, 'public/hot')))
|
||||
throw Error(
|
||||
'Stop the source frontend watcher before freezing a candidate.',
|
||||
);
|
||||
const work = path.join(
|
||||
'C:/laragon/data/sgf-tempo/run',
|
||||
'candidate-ui-' + crypto.randomBytes(6).toString('hex'),
|
||||
);
|
||||
fs.mkdirSync(work, { recursive: true });
|
||||
const replace = (text, old, next) => {
|
||||
if (text.split(old).length !== 2)
|
||||
throw Error('Frontend baseline changed: ' + old.slice(0, 70));
|
||||
return text.replace(old, next);
|
||||
};
|
||||
fs.cpSync(path.join(host, 'resources'), path.join(work, 'resources'), {
|
||||
recursive: true,
|
||||
});
|
||||
for (const file of ['package.json', 'vite.config.js'])
|
||||
fs.copyFileSync(path.join(host, file), path.join(work, file));
|
||||
fs.mkdirSync(path.join(work, 'public/build'), { recursive: true });
|
||||
fs.symlinkSync(
|
||||
path.join(host, 'node_modules'),
|
||||
path.join(work, 'node_modules'),
|
||||
'junction',
|
||||
);
|
||||
let app = fs.readFileSync(path.join(work, 'resources/js/app.jsx'), 'utf8');
|
||||
app = replace(
|
||||
app,
|
||||
"const options = (unit === null ? ['company.view', 'company.edit', 'unit.create', 'access.manage'] : ['unit.view', 'unit.edit']).filter(p => can(p, unit));",
|
||||
"const options = (list?.catalogue?.[unit === null ? 'company' : 'unit'] ?? []).filter(p => can(p, unit));",
|
||||
);
|
||||
app = replace(
|
||||
app,
|
||||
'{labels[p]}',
|
||||
'{list?.catalogue_labels?.[p] ?? labels[p] ?? p}',
|
||||
);
|
||||
app = replace(
|
||||
app,
|
||||
'{labels[g.permission]}',
|
||||
'{list?.catalogue_labels?.[g.permission] ?? labels[g.permission] ?? g.permission}',
|
||||
);
|
||||
fs.writeFileSync(path.join(work, 'resources/js/app.jsx'), app);
|
||||
let home = fs.readFileSync(
|
||||
path.join(work, 'resources/js/PurchasingHome.jsx'),
|
||||
'utf8',
|
||||
);
|
||||
home = purchasingHomeOverlay(home);
|
||||
fs.writeFileSync(path.join(work, 'resources/js/PurchasingHome.jsx'), home);
|
||||
let config = fs.readFileSync(path.join(work, 'vite.config.js'), 'utf8');
|
||||
config = replace(
|
||||
config,
|
||||
'defineConfig({',
|
||||
`defineConfig({\n cacheDir: ${JSON.stringify(path.join(work, 'vite-cache'))},`,
|
||||
);
|
||||
fs.writeFileSync(path.join(work, 'vite.config.js'), config);
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
path.join(host, 'node_modules/vite/bin/vite.js'),
|
||||
'build',
|
||||
'--config',
|
||||
path.join(work, 'vite.config.js'),
|
||||
'--configLoader',
|
||||
'native',
|
||||
],
|
||||
{
|
||||
cwd: work,
|
||||
encoding: 'utf8',
|
||||
windowsHide: true,
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
env: { ...process.env, NODE_ENV: 'production' },
|
||||
},
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(work, 'build.log'),
|
||||
(result.stdout || '') + (result.stderr || ''),
|
||||
);
|
||||
if (result.status !== 0)
|
||||
throw Error(
|
||||
'Candidate frontend build failed; private log ' +
|
||||
path.join(work, 'build.log'),
|
||||
);
|
||||
const original = JSON.parse(
|
||||
fs.readFileSync(path.join(work, 'public/build/manifest.json'), 'utf8'),
|
||||
);
|
||||
const assets = {};
|
||||
for (const chunk of Object.values(original))
|
||||
for (const file of [
|
||||
chunk.file,
|
||||
...(chunk.css || []),
|
||||
...(chunk.assets || []),
|
||||
]) {
|
||||
if (!/^assets\/[A-Za-z0-9_-]+\.(js|css)$/.test(file))
|
||||
throw Error('Unsupported frontend asset ' + file);
|
||||
assets['integrations/sgf/frontend/' + file] = path.join(
|
||||
work,
|
||||
'public/build',
|
||||
file,
|
||||
);
|
||||
}
|
||||
const manifest = JSON.parse(JSON.stringify(original));
|
||||
for (const chunk of Object.values(manifest)) {
|
||||
chunk.file = 'modules/internal-requisitions/' + chunk.file;
|
||||
if (chunk.css)
|
||||
chunk.css = chunk.css.map((p) => 'modules/internal-requisitions/' + p);
|
||||
if (chunk.assets)
|
||||
chunk.assets = chunk.assets.map(
|
||||
(p) => 'modules/internal-requisitions/' + p,
|
||||
);
|
||||
}
|
||||
const manifest=JSON.parse(JSON.stringify(original));
|
||||
for(const chunk of Object.values(manifest)){
|
||||
chunk.file='modules/internal-requisitions/'+chunk.file;
|
||||
if(chunk.css)chunk.css=chunk.css.map(p=>'modules/internal-requisitions/'+p);
|
||||
if(chunk.assets)chunk.assets=chunk.assets.map(p=>'modules/internal-requisitions/'+p);
|
||||
}
|
||||
const manifestFile=path.join(work,'candidate-manifest.json');fs.writeFileSync(manifestFile,JSON.stringify(manifest,null,2)+'\n');
|
||||
const overlays={'resources/js/app.jsx':path.join(work,'resources/js/app.jsx'),'resources/js/PurchasingHome.jsx':path.join(work,'resources/js/PurchasingHome.jsx'),'public/build/manifest.json':manifestFile};
|
||||
const metadata={work,overlays,assets,dependency_install:false,source_host_modified:false};
|
||||
const metadataFile=path.join(work,'candidate-ui.json');fs.writeFileSync(metadataFile,JSON.stringify(metadata,null,2));
|
||||
console.log(JSON.stringify({metadata:metadataFile}));
|
||||
const manifestFile = path.join(work, 'candidate-manifest.json');
|
||||
fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n');
|
||||
const overlays = {
|
||||
'resources/js/app.jsx': path.join(work, 'resources/js/app.jsx'),
|
||||
'resources/js/PurchasingHome.jsx': path.join(
|
||||
work,
|
||||
'resources/js/PurchasingHome.jsx',
|
||||
),
|
||||
'public/build/manifest.json': manifestFile,
|
||||
};
|
||||
const metadata = {
|
||||
work,
|
||||
overlays,
|
||||
assets,
|
||||
dependency_install: false,
|
||||
source_host_modified: false,
|
||||
};
|
||||
const metadataFile = path.join(work, 'candidate-ui.json');
|
||||
fs.writeFileSync(metadataFile, JSON.stringify(metadata, null, 2));
|
||||
console.log(JSON.stringify({ metadata: metadataFile }));
|
||||
|
||||
@@ -102,5 +102,5 @@ try {
|
||||
if ($exit === 0) {
|
||||
$proof['test_database_and_roles_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/sgf-corrected-delivery.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($proof,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n";
|
||||
echo json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n";
|
||||
}exit($exit);
|
||||
|
||||
+331
-75
@@ -1,88 +1,344 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
const root='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939';
|
||||
const privateData=JSON.parse(fs.readFileSync(root+'/private/development.json','utf8'));
|
||||
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]);
|
||||
const stateFile=root+'/private/requisitions-recovery/http-state.json';
|
||||
const state=fs.existsSync(stateFile)?JSON.parse(fs.readFileSync(stateFile,'utf8')):{};
|
||||
const persist=()=>fs.writeFileSync(stateFile,JSON.stringify(state,null,2));
|
||||
const key=name=>{state.keys??={};state.keys[name]??=crypto.randomUUID();persist();return state.keys[name];};
|
||||
const checks=[];
|
||||
const clients={};
|
||||
for(const p of privateData.profiles){
|
||||
const jar=new Map();let csrf='',token='';
|
||||
const api=async(path,method='GET',body,expected=200,commandKey)=>{
|
||||
const r=await fetch('http://127.0.0.1:8039'+path,{method,headers:{Accept:'application/json','Content-Type':'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),'X-CSRF-TOKEN':csrf,'X-SGF-Context':token,'X-Purchasing-Context':'procurement.internal','Idempotency-Key':commandKey??crypto.randomUUID()},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
for(const cookie of r.headers.getSetCookie()){const pair=cookie.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}
|
||||
const text=await r.text();let d;try{d=JSON.parse(text);}catch{d={message:text.slice(0,120)};}
|
||||
assert((Array.isArray(expected)?expected:[expected]).includes(r.status),`${p.role} ${path}: expected ${expected}, got ${r.status}: ${d.message??text.slice(0,180)}`);
|
||||
if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');await api('/api/login','POST',{email:p.email,password:privateData.password});
|
||||
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1});clients[p.role]=api;
|
||||
const root = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939';
|
||||
const privateData = JSON.parse(
|
||||
fs.readFileSync(root + '/private/development.json', 'utf8'),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
|
||||
[1, 1, 1],
|
||||
);
|
||||
const stateFile = root + '/private/requisitions-recovery/http-state.json';
|
||||
const state = fs.existsSync(stateFile)
|
||||
? JSON.parse(fs.readFileSync(stateFile, 'utf8'))
|
||||
: {};
|
||||
const persist = () =>
|
||||
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
|
||||
const key = (name) => {
|
||||
state.keys ??= {};
|
||||
state.keys[name] ??= crypto.randomUUID();
|
||||
persist();
|
||||
return state.keys[name];
|
||||
};
|
||||
const checks = [];
|
||||
const clients = {};
|
||||
for (const p of privateData.profiles) {
|
||||
const jar = new Map();
|
||||
let csrf = '',
|
||||
token = '';
|
||||
const api = async (
|
||||
path,
|
||||
method = 'GET',
|
||||
body,
|
||||
expected = 200,
|
||||
commandKey,
|
||||
) => {
|
||||
const r = await fetch('http://127.0.0.1:8039' + path, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; '),
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'X-SGF-Context': token,
|
||||
'X-Purchasing-Context': 'procurement.internal',
|
||||
'Idempotency-Key': commandKey ?? crypto.randomUUID(),
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
for (const cookie of r.headers.getSetCookie()) {
|
||||
const pair = cookie.split(';')[0],
|
||||
at = pair.indexOf('=');
|
||||
jar.set(pair.slice(0, at), pair.slice(at + 1));
|
||||
}
|
||||
const text = await r.text();
|
||||
let d;
|
||||
try {
|
||||
d = JSON.parse(text);
|
||||
} catch {
|
||||
d = { message: text.slice(0, 120) };
|
||||
}
|
||||
assert(
|
||||
(Array.isArray(expected) ? expected : [expected]).includes(
|
||||
r.status,
|
||||
),
|
||||
`${p.role} ${path}: expected ${expected}, got ${r.status}: ${d.message ?? text.slice(0, 180)}`,
|
||||
);
|
||||
if (d.csrf) csrf = d.csrf;
|
||||
if (d.context?.token) token = d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');
|
||||
await api('/api/login', 'POST', {
|
||||
email: p.email,
|
||||
password: privateData.password,
|
||||
});
|
||||
await api('/api/context', 'POST', {
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 1,
|
||||
});
|
||||
clients[p.role] = api;
|
||||
}
|
||||
checks.push('Existing three synthetic identities authenticate without password changes');
|
||||
const prep=clients.preparador,review=clients.revisor,read=clients.consulta;
|
||||
const rights={1:['purchasing_requisitions.view','purchasing_requisitions.prepare','purchasing_requisitions.configure','purchasing_requisitions.approve.department_head','purchasing_budget.view','purchasing_budget.create','purchasing_budget.approve','purchasing_budget.record'],2:['purchasing_requisitions.view','purchasing_requisitions.approve.department_head','purchasing_budget.view','purchasing_budget.approve'],3:['purchasing_requisitions.view','purchasing_budget.view']};
|
||||
await prep('/api/internal-requisitions/access-initialisation','POST',{operation_key:key('initial'),reason:'Owner-confirmed fourteen rights in synthetic demonstration 8039 only.',administrators:[{user_id:1,rights:rights[1]}]});
|
||||
for(const [role,id] of [['revisor',2],['consulta',3]]){
|
||||
const profile=privateData.profiles.find(p=>p.role===role);
|
||||
for(const permission of rights[id])await prep('/api/accesses','POST',{email:profile.email,unit_id:1,permission,reason:'Owner-confirmed synthetic demonstration access 8039.'});
|
||||
checks.push(
|
||||
'Existing three synthetic identities authenticate without password changes',
|
||||
);
|
||||
const prep = clients.preparador,
|
||||
review = clients.revisor,
|
||||
read = clients.consulta;
|
||||
const rights = {
|
||||
1: [
|
||||
'purchasing_requisitions.view',
|
||||
'purchasing_requisitions.prepare',
|
||||
'purchasing_requisitions.configure',
|
||||
'purchasing_requisitions.approve.department_head',
|
||||
'purchasing_budget.view',
|
||||
'purchasing_budget.create',
|
||||
'purchasing_budget.approve',
|
||||
'purchasing_budget.record',
|
||||
],
|
||||
2: [
|
||||
'purchasing_requisitions.view',
|
||||
'purchasing_requisitions.approve.department_head',
|
||||
'purchasing_budget.view',
|
||||
'purchasing_budget.approve',
|
||||
],
|
||||
3: ['purchasing_requisitions.view', 'purchasing_budget.view'],
|
||||
};
|
||||
await prep('/api/internal-requisitions/access-initialisation', 'POST', {
|
||||
operation_key: key('initial'),
|
||||
reason: 'Owner-confirmed fourteen rights in synthetic demonstration 8039 only.',
|
||||
administrators: [{ user_id: 1, rights: rights[1] }],
|
||||
});
|
||||
for (const [role, id] of [
|
||||
['revisor', 2],
|
||||
['consulta', 3],
|
||||
]) {
|
||||
const profile = privateData.profiles.find((p) => p.role === role);
|
||||
for (const permission of rights[id])
|
||||
await prep('/api/accesses', 'POST', {
|
||||
email: profile.email,
|
||||
unit_id: 1,
|
||||
permission,
|
||||
reason: 'Owner-confirmed synthetic demonstration access 8039.',
|
||||
});
|
||||
}
|
||||
checks.push('Eight plus four plus two explicit authorised grants');
|
||||
for(const api of Object.values(clients))await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'});
|
||||
const centre=await prep('/api/internal-requisitions/centres','POST',{operation_key:key('centre'),code:'SINTETICO-REPRO',reason:'Owner-authorised synthetic centre for demonstration only.'});
|
||||
state.centre_id=centre.centre_id;persist();
|
||||
await read('/api/internal-requisitions/centres','POST',{operation_key:key('read-centre'),code:'REFUSED',reason:'Synthetic read-only refusal verification.'},403);
|
||||
if(!state.budget_id){
|
||||
await prep('/api/purchasing-budget/create','POST',{cost_center_id:state.centre_id,year:2026,kind:'operating',includes_tax:true,amount:'10000.00',reason:'Owner-authorised synthetic 10000 MZN allocation for 2026.'},200,key('budget'));
|
||||
const list=await prep('/api/purchasing-budget');
|
||||
fs.writeFileSync(root+'/private/requisitions-recovery/budget-response.json',JSON.stringify(list,null,2));
|
||||
state.budget_pending=true;persist();
|
||||
for (const api of Object.values(clients))
|
||||
await api('/api/context', 'POST', {
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 1,
|
||||
module_id: 'purchasing',
|
||||
});
|
||||
const centre = await prep('/api/internal-requisitions/centres', 'POST', {
|
||||
operation_key: key('centre'),
|
||||
code: 'SINTETICO-REPRO',
|
||||
reason: 'Owner-authorised synthetic centre for demonstration only.',
|
||||
});
|
||||
state.centre_id = centre.centre_id;
|
||||
persist();
|
||||
await read(
|
||||
'/api/internal-requisitions/centres',
|
||||
'POST',
|
||||
{
|
||||
operation_key: key('read-centre'),
|
||||
code: 'REFUSED',
|
||||
reason: 'Synthetic read-only refusal verification.',
|
||||
},
|
||||
403,
|
||||
);
|
||||
if (!state.budget_id) {
|
||||
await prep(
|
||||
'/api/purchasing-budget/create',
|
||||
'POST',
|
||||
{
|
||||
cost_center_id: state.centre_id,
|
||||
year: 2026,
|
||||
kind: 'operating',
|
||||
includes_tax: true,
|
||||
amount: '10000.00',
|
||||
reason: 'Owner-authorised synthetic 10000 MZN allocation for 2026.',
|
||||
},
|
||||
200,
|
||||
key('budget'),
|
||||
);
|
||||
const list = await prep('/api/purchasing-budget');
|
||||
fs.writeFileSync(
|
||||
root + '/private/requisitions-recovery/budget-response.json',
|
||||
JSON.stringify(list, null, 2),
|
||||
);
|
||||
state.budget_pending = true;
|
||||
persist();
|
||||
}
|
||||
// Obtain exact budget identifier from the native response; no guessing IDs.
|
||||
const workspace=await prep('/api/purchasing-budget');
|
||||
const candidates=workspace.budgets??workspace.allocations??workspace.records;
|
||||
if(!state.budget_id){
|
||||
assert(Array.isArray(candidates),'Inspect native budget response shape before proceeding');
|
||||
const found=candidates.filter(b=>Number(b.cost_center_id??b.centre_id)===Number(state.centre_id)&&Number(b.year)===2026);
|
||||
assert.equal(found.length,1,'Exactly one synthetic allocation');state.budget_id=found[0].id;persist();
|
||||
const workspace = await prep('/api/purchasing-budget');
|
||||
const candidates =
|
||||
workspace.budgets ?? workspace.allocations ?? workspace.records;
|
||||
if (!state.budget_id) {
|
||||
assert(
|
||||
Array.isArray(candidates),
|
||||
'Inspect native budget response shape before proceeding',
|
||||
);
|
||||
const found = candidates.filter(
|
||||
(b) =>
|
||||
Number(b.cost_center_id ?? b.centre_id) ===
|
||||
Number(state.centre_id) && Number(b.year) === 2026,
|
||||
);
|
||||
assert.equal(found.length, 1, 'Exactly one synthetic allocation');
|
||||
state.budget_id = found[0].id;
|
||||
persist();
|
||||
}
|
||||
if(!state.budget_approved){
|
||||
await prep('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},403,key('self-budget'));
|
||||
await read('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},403,key('read-budget'));
|
||||
await review('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},200,key('approve-budget'));
|
||||
state.budget_approved=true;persist();
|
||||
if (!state.budget_approved) {
|
||||
await prep(
|
||||
'/api/purchasing-budget/approve',
|
||||
'POST',
|
||||
{ budget_id: state.budget_id },
|
||||
403,
|
||||
key('self-budget'),
|
||||
);
|
||||
await read(
|
||||
'/api/purchasing-budget/approve',
|
||||
'POST',
|
||||
{ budget_id: state.budget_id },
|
||||
403,
|
||||
key('read-budget'),
|
||||
);
|
||||
await review(
|
||||
'/api/purchasing-budget/approve',
|
||||
'POST',
|
||||
{ budget_id: state.budget_id },
|
||||
200,
|
||||
key('approve-budget'),
|
||||
);
|
||||
state.budget_approved = true;
|
||||
persist();
|
||||
}
|
||||
checks.push('Synthetic allocation 10000 MZN approved by second identity; self and read-only approvals refused');
|
||||
const policy={version:0,reason:'Owner-confirmed synthetic OPER policy, demonstration 8039 only.',enabled:true,budget_required:true,first_limit_minor:1000000,second_limit_minor:2000000,approval_includes_tax:true,centres:[{id:state.centre_id,department_ref:'OPER'}],members:[{user_id:1,department_ref:'OPER'},{user_id:2,department_ref:'OPER'}]};
|
||||
await read('/api/internal-requisitions/policy','POST',policy,403);
|
||||
if(!state.policy_configured){await prep('/api/internal-requisitions/policy','POST',policy);state.policy_configured=true;persist();}
|
||||
const draft={operation_key:key('draft'),cost_center_id:state.centre_id,priority:'normal',needed_by:'2026-11-30',justification:'Synthetic demonstration requisition, no Tempo business operation.',items:[{description:'Synthetic demonstration material',category:'Consumiveis',purchase_type:'consumable',quantity:'1.000',unit:'UN',unit_price:'100.00',tax_rate:'0.00'}]};
|
||||
await read('/api/internal-requisitions/save','POST',{...draft,operation_key:key('read-save')},403);
|
||||
if(!state.request_id){const saved=await prep('/api/internal-requisitions/save','POST',draft);state.request_id=saved.id;persist();}
|
||||
const path='/api/internal-requisitions/'+state.request_id;
|
||||
if(!state.submitted){
|
||||
const submitted=await prep(path+'/submit','POST',{operation_key:key('submit'),version:1});
|
||||
state.submitted=submitted;persist();
|
||||
const replay=await prep(path+'/submit','POST',{operation_key:key('submit'),version:1});
|
||||
assert.equal(replay.id,state.request_id);checks.push('Submission retry reuses same requisition');
|
||||
checks.push(
|
||||
'Synthetic allocation 10000 MZN approved by second identity; self and read-only approvals refused',
|
||||
);
|
||||
const policy = {
|
||||
version: 0,
|
||||
reason: 'Owner-confirmed synthetic OPER policy, demonstration 8039 only.',
|
||||
enabled: true,
|
||||
budget_required: true,
|
||||
first_limit_minor: 1000000,
|
||||
second_limit_minor: 2000000,
|
||||
approval_includes_tax: true,
|
||||
centres: [{ id: state.centre_id, department_ref: 'OPER' }],
|
||||
members: [
|
||||
{ user_id: 1, department_ref: 'OPER' },
|
||||
{ user_id: 2, department_ref: 'OPER' },
|
||||
],
|
||||
};
|
||||
await read('/api/internal-requisitions/policy', 'POST', policy, 403);
|
||||
if (!state.policy_configured) {
|
||||
await prep('/api/internal-requisitions/policy', 'POST', policy);
|
||||
state.policy_configured = true;
|
||||
persist();
|
||||
}
|
||||
if(!state.approved){
|
||||
const decision={operation_key:key('decision'),version:state.submitted.version,decision:'approved'};
|
||||
await prep(path+'/decide','POST',decision,403);
|
||||
await read(path+'/decide','POST',decision,[403,404]);
|
||||
await read(path+'/submit','POST',{operation_key:key('read-submit'),version:state.submitted.version},[403,404]);
|
||||
const approved=await review(path+'/decide','POST',decision);assert.equal(approved.status,'approved');state.approved=true;persist();
|
||||
const draft = {
|
||||
operation_key: key('draft'),
|
||||
cost_center_id: state.centre_id,
|
||||
priority: 'normal',
|
||||
needed_by: '2026-11-30',
|
||||
justification:
|
||||
'Synthetic demonstration requisition, no Tempo business operation.',
|
||||
items: [
|
||||
{
|
||||
description: 'Synthetic demonstration material',
|
||||
category: 'Consumiveis',
|
||||
purchase_type: 'consumable',
|
||||
quantity: '1.000',
|
||||
unit: 'UN',
|
||||
unit_price: '100.00',
|
||||
tax_rate: '0.00',
|
||||
},
|
||||
],
|
||||
};
|
||||
await read(
|
||||
'/api/internal-requisitions/save',
|
||||
'POST',
|
||||
{ ...draft, operation_key: key('read-save') },
|
||||
403,
|
||||
);
|
||||
if (!state.request_id) {
|
||||
const saved = await prep('/api/internal-requisitions/save', 'POST', draft);
|
||||
state.request_id = saved.id;
|
||||
persist();
|
||||
}
|
||||
for(const api of [prep,review]){const d=await api(path);assert.equal(d.record.status,'approved');assert.equal(d.history.length,3);}
|
||||
await read(path,'GET',undefined,404);
|
||||
const path = '/api/internal-requisitions/' + state.request_id;
|
||||
if (!state.submitted) {
|
||||
const submitted = await prep(path + '/submit', 'POST', {
|
||||
operation_key: key('submit'),
|
||||
version: 1,
|
||||
});
|
||||
state.submitted = submitted;
|
||||
persist();
|
||||
const replay = await prep(path + '/submit', 'POST', {
|
||||
operation_key: key('submit'),
|
||||
version: 1,
|
||||
});
|
||||
assert.equal(replay.id, state.request_id);
|
||||
checks.push('Submission retry reuses same requisition');
|
||||
}
|
||||
if (!state.approved) {
|
||||
const decision = {
|
||||
operation_key: key('decision'),
|
||||
version: state.submitted.version,
|
||||
decision: 'approved',
|
||||
};
|
||||
await prep(path + '/decide', 'POST', decision, 403);
|
||||
await read(path + '/decide', 'POST', decision, [403, 404]);
|
||||
await read(
|
||||
path + '/submit',
|
||||
'POST',
|
||||
{ operation_key: key('read-submit'), version: state.submitted.version },
|
||||
[403, 404],
|
||||
);
|
||||
const approved = await review(path + '/decide', 'POST', decision);
|
||||
assert.equal(approved.status, 'approved');
|
||||
state.approved = true;
|
||||
persist();
|
||||
}
|
||||
for (const api of [prep, review]) {
|
||||
const d = await api(path);
|
||||
assert.equal(d.record.status, 'approved');
|
||||
assert.equal(d.history.length, 3);
|
||||
}
|
||||
await read(path, 'GET', undefined, 404);
|
||||
await read('/api/internal-requisitions');
|
||||
await read('/api/accesses','GET',undefined,403);
|
||||
checks.push('Full request lifecycle, independent approval and three-event history consulted by preparer and reviewer');
|
||||
checks.push('Existing record visibility rule returns 404 to read-only third identity; listing remains accessible; no extra rights granted');
|
||||
checks.push('Read-only profile refused centre, budget approval, policy, preparation, submission, decision and access administration');
|
||||
fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-demo-8039-http.json',JSON.stringify({passed:true,url:'http://127.0.0.1:8039',scope:'1:1:1',rights,centre_id:state.centre_id,budget_id:state.budget_id,request_id:state.request_id,checks,checked_at:new Date().toISOString(),visual_review:false,real_installation_changed:false},null,2));
|
||||
console.log(JSON.stringify({passed:true,checks,request_id:state.request_id}));
|
||||
await read('/api/accesses', 'GET', undefined, 403);
|
||||
checks.push(
|
||||
'Full request lifecycle, independent approval and three-event history consulted by preparer and reviewer',
|
||||
);
|
||||
checks.push(
|
||||
'Existing record visibility rule returns 404 to read-only third identity; listing remains accessible; no extra rights granted',
|
||||
);
|
||||
checks.push(
|
||||
'Read-only profile refused centre, budget approval, policy, preparation, submission, decision and access administration',
|
||||
);
|
||||
fs.writeFileSync(
|
||||
'C:/laragon/www/compras/docs/proofs/sgf-demo-8039-http.json',
|
||||
JSON.stringify(
|
||||
{
|
||||
passed: true,
|
||||
url: 'http://127.0.0.1:8039',
|
||||
scope: '1:1:1',
|
||||
rights,
|
||||
centre_id: state.centre_id,
|
||||
budget_id: state.budget_id,
|
||||
request_id: state.request_id,
|
||||
checks,
|
||||
checked_at: new Date().toISOString(),
|
||||
visual_review: false,
|
||||
real_installation_changed: false,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({ passed: true, checks, request_id: state.request_id }),
|
||||
);
|
||||
|
||||
+121
-69
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
// Explicitly authorised persistent synthetic demonstration only. No GRANT/REVOKE.
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -6,79 +7,130 @@ use Symfony\Component\Process\Process;
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
use Tempo\Purchasing\Delivery\Installation;
|
||||
|
||||
$root=dirname(__DIR__);
|
||||
$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
|
||||
$action=$argv[1]??'';
|
||||
$recovery='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/requisitions-recovery';
|
||||
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$bundle=$proof['artifact']['directory'];
|
||||
$root = dirname(__DIR__);
|
||||
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
|
||||
$action = $argv[1] ?? '';
|
||||
$recovery = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/requisitions-recovery';
|
||||
$proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$bundle = $proof['artifact']['directory'];
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app=require $host.'/bootstrap/app.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$db=DB::connection();
|
||||
$identity=$db->selectOne("select current_database() as db,current_user as role,current_setting('cluster_name') as cluster,inet_server_port() as port");
|
||||
if ($app->basePath()!==str_replace('/',DIRECTORY_SEPARATOR,$host) && str_replace('\\','/',$app->basePath())!==$host) throw new RuntimeException('Wrong application folder');
|
||||
if ($identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||$identity->cluster!=='sgf_modular_regression_2576427d1939'||(int)$identity->port!==55439||config('app.url')!=='http://127.0.0.1:8039') throw new RuntimeException('Wrong isolated identity');
|
||||
if (!$db->table('units')->where(['id'=>1,'tenant_id'=>1,'company_id'=>1])->exists()) throw new RuntimeException('Wrong scope');
|
||||
$private=json_decode(file_get_contents(dirname($host).'/private/development.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
if ([$private['tenant_id'],$private['company_id'],$private['unit_id']]!==[1,1,1]) throw new RuntimeException('Wrong synthetic provenance');
|
||||
foreach([1=>'Preparador',2=>'Revisor',3=>'Consulta'] as $id=>$suffix) if(!str_ends_with($db->table('users')->where('id',$id)->value('name'),$suffix)) throw new RuntimeException('Wrong synthetic user');
|
||||
if(!class_exists(Installation::class))require_once $bundle.'/integrations/sgf/operational/bootstrap.php';
|
||||
require_once $bundle.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$deploy=new CodeDeployment($host);
|
||||
$mh=$proof['artifact']['archive']['manifest_sha256'];
|
||||
if ($action==='prepare') {
|
||||
if(is_dir($recovery)) throw new RuntimeException('Recovery already exists; inspect before retry');
|
||||
$plan=$deploy->plan($bundle,$mh);
|
||||
mkdir($recovery,0700,true);
|
||||
$manifest=json_decode(file_get_contents($bundle.'/manifest.json'),true);
|
||||
foreach([...array_keys($manifest['host_overlays']),'.env','config/modules.php','packages/purchasing/current.json'] as $file){
|
||||
if(!is_dir(dirname($recovery.'/files/'.$file)))mkdir(dirname($recovery.'/files/'.$file),0700,true);
|
||||
copy($host.'/'.$file,$recovery.'/files/'.$file);
|
||||
$db = DB::connection();
|
||||
$identity = $db->selectOne("select current_database() as db,current_user as role,current_setting('cluster_name') as cluster,inet_server_port() as port");
|
||||
if ($app->basePath() !== str_replace('/', DIRECTORY_SEPARATOR, $host) && str_replace('\\', '/', $app->basePath()) !== $host) {
|
||||
throw new RuntimeException('Wrong application folder');
|
||||
}
|
||||
if ($identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || (int) $identity->port !== 55439 || config('app.url') !== 'http://127.0.0.1:8039') {
|
||||
throw new RuntimeException('Wrong isolated identity');
|
||||
}
|
||||
if (! $db->table('units')->where(['id' => 1, 'tenant_id' => 1, 'company_id' => 1])->exists()) {
|
||||
throw new RuntimeException('Wrong scope');
|
||||
}
|
||||
$private = json_decode(file_get_contents(dirname($host).'/private/development.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ([$private['tenant_id'], $private['company_id'], $private['unit_id']] !== [1, 1, 1]) {
|
||||
throw new RuntimeException('Wrong synthetic provenance');
|
||||
}
|
||||
foreach ([1 => 'Preparador', 2 => 'Revisor', 3 => 'Consulta'] as $id => $suffix) {
|
||||
if (! str_ends_with($db->table('users')->where('id', $id)->value('name'), $suffix)) {
|
||||
throw new RuntimeException('Wrong synthetic user');
|
||||
}
|
||||
$cfg=$db->getConfig();
|
||||
$dump=new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe','--format=custom','--file='.$recovery.'/before.dump','--dbname='.$identity->db],null,['PGHOST'=>'127.0.0.1','PGPORT'=>'55439','PGUSER'=>$identity->role,'PGPASSWORD'=>$cfg['password']],null,90);
|
||||
}
|
||||
if (! class_exists(Installation::class)) {
|
||||
require_once $bundle.'/integrations/sgf/operational/bootstrap.php';
|
||||
}
|
||||
require_once $bundle.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$deploy = new CodeDeployment($host);
|
||||
$mh = $proof['artifact']['archive']['manifest_sha256'];
|
||||
if ($action === 'prepare') {
|
||||
if (is_dir($recovery)) {
|
||||
throw new RuntimeException('Recovery already exists; inspect before retry');
|
||||
}
|
||||
$plan = $deploy->plan($bundle, $mh);
|
||||
mkdir($recovery, 0700, true);
|
||||
$manifest = json_decode(file_get_contents($bundle.'/manifest.json'), true);
|
||||
foreach ([...array_keys($manifest['host_overlays']), '.env', 'config/modules.php', 'packages/purchasing/current.json'] as $file) {
|
||||
if (! is_dir(dirname($recovery.'/files/'.$file))) {
|
||||
mkdir(dirname($recovery.'/files/'.$file), 0700, true);
|
||||
}
|
||||
copy($host.'/'.$file, $recovery.'/files/'.$file);
|
||||
}
|
||||
$cfg = $db->getConfig();
|
||||
$dump = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90);
|
||||
$dump->mustRun();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--list',$recovery.'/before.dump']))->mustRun();
|
||||
$baseline=['identity'=>$identity,'host'=>$host,'code_plan'=>$plan,'backup_sha256'=>hash_file('sha256',$recovery.'/before.dump'),'grants'=>$db->table('permission_grants')->orderBy('id')->get()->all(),'users_sha256'=>hash('sha256',json_encode($db->table('users')->orderBy('id')->get())),'pointer_sha256'=>hash_file('sha256',$host.'/packages/purchasing/current.json')];
|
||||
file_put_contents($recovery.'/baseline.json',json_encode($baseline,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['prepared'=>true,'identity'=>$identity,'host'=>$host,'recovery'=>$recovery,'backup_sha256'=>$baseline['backup_sha256'],'code_plan'=>$plan],JSON_PRETTY_PRINT);
|
||||
} elseif($action==='install') {
|
||||
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
if(!hash_equals($baseline['backup_sha256'],hash_file('sha256',$recovery.'/before.dump')))throw new RuntimeException('Backup changed');
|
||||
if(json_decode(json_encode($db->table('permission_grants')->orderBy('id')->get()),true)!==$baseline['grants'])throw new RuntimeException('Grants changed since backup');
|
||||
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance');
|
||||
file_put_contents($host.'/storage/framework/down',json_encode(['time'=>time(),'retry'=>60]));
|
||||
$migration=Installation::migrate($db,Installation::target($db),$baseline['backup_sha256'],'Owner-authorised synthetic 8039 setup');
|
||||
$applied=$deploy->apply($bundle,$mh,$baseline['code_plan']['target_sha256'],'Owner-authorised synthetic 8039 setup',true);
|
||||
file_put_contents($recovery.'/applied.json',json_encode($applied,JSON_PRETTY_PRINT));
|
||||
$config=['enabled'=>true,'target'=>Installation::target($db),'scopes'=>['1:1:1']];
|
||||
file_put_contents($host.'/config/purchasing-operational.php','<?php return '.var_export($config,true).';');
|
||||
file_put_contents($host.'/config/purchasing-internal.php','<?php return ["candidate_enabled"=>true];');
|
||||
file_put_contents($host.'/config/purchasing-access.php','<?php return ["initialisation_scopes"=>["1:1:1"]];');
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
|
||||
$baseline = ['identity' => $identity, 'host' => $host, 'code_plan' => $plan, 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'grants' => $db->table('permission_grants')->orderBy('id')->get()->all(), 'users_sha256' => hash('sha256', json_encode($db->table('users')->orderBy('id')->get())), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json')];
|
||||
file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['prepared' => true, 'identity' => $identity, 'host' => $host, 'recovery' => $recovery, 'backup_sha256' => $baseline['backup_sha256'], 'code_plan' => $plan], JSON_PRETTY_PRINT);
|
||||
} elseif ($action === 'install') {
|
||||
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
if (! hash_equals($baseline['backup_sha256'], hash_file('sha256', $recovery.'/before.dump'))) {
|
||||
throw new RuntimeException('Backup changed');
|
||||
}
|
||||
if (json_decode(json_encode($db->table('permission_grants')->orderBy('id')->get()), true) !== $baseline['grants']) {
|
||||
throw new RuntimeException('Grants changed since backup');
|
||||
}
|
||||
if (is_file($host.'/storage/framework/down')) {
|
||||
throw new RuntimeException('Unexpected prior maintenance');
|
||||
}
|
||||
file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60]));
|
||||
$migration = Installation::migrate($db, Installation::target($db), $baseline['backup_sha256'], 'Owner-authorised synthetic 8039 setup');
|
||||
$applied = $deploy->apply($bundle, $mh, $baseline['code_plan']['target_sha256'], 'Owner-authorised synthetic 8039 setup', true);
|
||||
file_put_contents($recovery.'/applied.json', json_encode($applied, JSON_PRETTY_PRINT));
|
||||
$config = ['enabled' => true, 'target' => Installation::target($db), 'scopes' => ['1:1:1']];
|
||||
file_put_contents($host.'/config/purchasing-operational.php', '<?php return '.var_export($config, true).';');
|
||||
file_put_contents($host.'/config/purchasing-internal.php', '<?php return ["candidate_enabled"=>true];');
|
||||
file_put_contents($host.'/config/purchasing-access.php', '<?php return ["initialisation_scopes"=>["1:1:1"]];');
|
||||
// The development server reloads PHP for every request; keep normal uncached config.
|
||||
foreach(['config.php','routes-v7.php','events.php'] as $file)if(is_file($host.'/bootstrap/cache/'.$file))throw new RuntimeException('Unexpected native cache; retain maintenance and reconcile');
|
||||
foreach (['config.php', 'routes-v7.php', 'events.php'] as $file) {
|
||||
if (is_file($host.'/bootstrap/cache/'.$file)) {
|
||||
throw new RuntimeException('Unexpected native cache; retain maintenance and reconcile');
|
||||
}
|
||||
}
|
||||
unlink($host.'/storage/framework/down');
|
||||
echo json_encode(['installed_synthetic_only'=>true,'migration'=>$migration,'deployment'=>$applied,'recovery'=>$recovery],JSON_PRETTY_PRINT);
|
||||
} elseif($action==='verify') {
|
||||
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$http=json_decode(file_get_contents($root.'/docs/proofs/sgf-demo-8039-http.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$current=$db->table('permission_grants')->orderBy('id')->get()->all();
|
||||
$oldById=[];foreach($current as $grant)$oldById[$grant->id]=json_decode(json_encode($grant),true);
|
||||
foreach($baseline['grants'] as $grant)if(($oldById[$grant['id']]??null)!==$grant)throw new RuntimeException('Existing grant changed');
|
||||
$oldIds=array_column($baseline['grants'],'id');
|
||||
$added=array_values(array_filter($current,fn($g)=>!in_array($g->id,$oldIds,true)));
|
||||
if(count($added)!==14)throw new RuntimeException('Expected exactly fourteen new grants');
|
||||
foreach($added as $grant)if([$grant->tenant_id,$grant->company_id,$grant->unit_id]!==[1,1,1]||!in_array($grant->permission,$http['rights'][$grant->user_id]??[],true))throw new RuntimeException('Unapproved new grant');
|
||||
if(hash('sha256',json_encode($db->table('users')->orderBy('id')->get()))!==$baseline['users_sha256'])throw new RuntimeException('Existing accounts changed');
|
||||
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed');
|
||||
$requests=$db->table('ir_requests')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1])->get();
|
||||
if(count($requests)!==1||$requests[0]->status!=='approved'||$requests[0]->requester_id!==1)throw new RuntimeException('Unexpected request state');
|
||||
if($db->table('cb_budget_entries')->where('kind','reserve')->count()!==1)throw new RuntimeException('Expected exactly one reservation');
|
||||
$budget=$db->table('cb_budgets')->first();
|
||||
$decision=$db->table('ir_steps')->first();
|
||||
$report=['passed'=>true,'identity'=>$identity,'scope'=>'1:1:1','added_grants'=>$added,'existing_grants_preserved'=>true,'existing_accounts_preserved'=>true,'single_approved_request'=>true,'single_reservation'=>true,'reservation'=>$db->table('cb_budget_entries')->where('kind','reserve')->first(),'budget'=>$budget,'decision'=>$decision,'pointer_preserved'=>true,'backup_sha256'=>$baseline['backup_sha256'],'recovery_directory'=>$recovery,'checked_at'=>gmdate('c'),'owner_runtime_limitation'=>true,'visual_review'=>false,'read_only_record_visibility_limitation'=>true];
|
||||
file_put_contents($root.'/docs/proofs/sgf-demo-8039-delivery.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['installed_synthetic_only' => true, 'migration' => $migration, 'deployment' => $applied, 'recovery' => $recovery], JSON_PRETTY_PRINT);
|
||||
} elseif ($action === 'verify') {
|
||||
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$http = json_decode(file_get_contents($root.'/docs/proofs/sgf-demo-8039-http.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$current = $db->table('permission_grants')->orderBy('id')->get()->all();
|
||||
$oldById = [];
|
||||
foreach ($current as $grant) {
|
||||
$oldById[$grant->id] = json_decode(json_encode($grant), true);
|
||||
}
|
||||
foreach ($baseline['grants'] as $grant) {
|
||||
if (($oldById[$grant['id']] ?? null) !== $grant) {
|
||||
throw new RuntimeException('Existing grant changed');
|
||||
}
|
||||
}
|
||||
$oldIds = array_column($baseline['grants'], 'id');
|
||||
$added = array_values(array_filter($current, fn ($g) => ! in_array($g->id, $oldIds, true)));
|
||||
if (count($added) !== 14) {
|
||||
throw new RuntimeException('Expected exactly fourteen new grants');
|
||||
}
|
||||
foreach ($added as $grant) {
|
||||
if ([$grant->tenant_id, $grant->company_id, $grant->unit_id] !== [1, 1, 1] || ! in_array($grant->permission, $http['rights'][$grant->user_id] ?? [], true)) {
|
||||
throw new RuntimeException('Unapproved new grant');
|
||||
}
|
||||
}
|
||||
if (hash('sha256', json_encode($db->table('users')->orderBy('id')->get())) !== $baseline['users_sha256']) {
|
||||
throw new RuntimeException('Existing accounts changed');
|
||||
}
|
||||
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
|
||||
throw new RuntimeException('Pointer changed');
|
||||
}
|
||||
$requests = $db->table('ir_requests')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->get();
|
||||
if (count($requests) !== 1 || $requests[0]->status !== 'approved' || $requests[0]->requester_id !== 1) {
|
||||
throw new RuntimeException('Unexpected request state');
|
||||
}
|
||||
if ($db->table('cb_budget_entries')->where('kind', 'reserve')->count() !== 1) {
|
||||
throw new RuntimeException('Expected exactly one reservation');
|
||||
}
|
||||
$budget = $db->table('cb_budgets')->first();
|
||||
$decision = $db->table('ir_steps')->first();
|
||||
$report = ['passed' => true, 'identity' => $identity, 'scope' => '1:1:1', 'added_grants' => $added, 'existing_grants_preserved' => true, 'existing_accounts_preserved' => true, 'single_approved_request' => true, 'single_reservation' => true, 'reservation' => $db->table('cb_budget_entries')->where('kind', 'reserve')->first(), 'budget' => $budget, 'decision' => $decision, 'pointer_preserved' => true, 'backup_sha256' => $baseline['backup_sha256'], 'recovery_directory' => $recovery, 'checked_at' => gmdate('c'), 'owner_runtime_limitation' => true, 'visual_review' => false, 'read_only_record_visibility_limitation' => true];
|
||||
file_put_contents($root.'/docs/proofs/sgf-demo-8039-delivery.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
file_put_contents($host.'/config/purchasing-access.php','<?php return ["initialisation_scopes"=>[]];');
|
||||
echo json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
} else throw new RuntimeException('Use prepare, install or verify');
|
||||
echo json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
} else {
|
||||
throw new RuntimeException('Use prepare, install or verify');
|
||||
}
|
||||
|
||||
+209
-44
@@ -1,49 +1,214 @@
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
const legacy=process.argv.includes('--previous');
|
||||
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8'));
|
||||
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]);
|
||||
const checks=[];
|
||||
for(const profile of privateData.profiles){
|
||||
const jar=new Map();let csrf='',token='';
|
||||
const api=async(path,method='GET',body,status=200,overrides={})=>{
|
||||
const response=await fetch('http://127.0.0.1:8039'+path,{method,headers:{Accept:'application/json','Content-Type':'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),'X-CSRF-TOKEN':csrf,'X-SGF-Context':token,'X-Purchasing-Context':'procurement.internal','Idempotency-Key':crypto.randomUUID(),...overrides},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
for(const cookie of response.headers.getSetCookie()){const pair=cookie.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}
|
||||
const text=await response.text();let d;try{d=JSON.parse(text);}catch{d={};}
|
||||
assert((Array.isArray(status)?status:[status]).includes(response.status),`${profile.role} ${path}: expected ${status}, got ${response.status}: ${d.message??''}`);
|
||||
if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');await api('/api/login','POST',{email:profile.email,password:privateData.password});
|
||||
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'});
|
||||
const list=await api('/api/internal-requisitions');
|
||||
if(legacy&&profile.role==='consulta'){
|
||||
assert(!list.records.some(r=>r.id===1));await api('/api/internal-requisitions/1','GET',undefined,404);
|
||||
checks.push('Previous version reproduces missing read-only listing/detail');continue;
|
||||
}
|
||||
assert(list.records.some(r=>r.id===1),'Existing request must be listed');
|
||||
const detail=await api('/api/internal-requisitions/1');
|
||||
assert.equal(detail.record.id,1);assert.equal(detail.record.version,3);assert.equal(detail.record.status,'approved');assert.equal(detail.record.total_minor,10000);
|
||||
assert.equal(detail.history.length,3);
|
||||
checks.push(`${profile.role}: existing request 1 listed, detail and three-event history readable`);
|
||||
if(profile.role==='consulta'){
|
||||
assert.equal(list.permissions.prepare,false);assert.equal(list.permissions.configure,false);assert.deepEqual(detail.record.allowed_actions,[]);
|
||||
await api('/api/internal-requisitions/save','POST',{operation_key:crypto.randomUUID()},403);
|
||||
for(const action of ['save','submit','decide'])await api('/api/internal-requisitions/1/'+action,'POST',{operation_key:crypto.randomUUID(),version:3,...(action==='decide'?{decision:'approved'}:{})},[403,404]);
|
||||
await api('/api/internal-requisitions/policy','POST',{version:1,reason:'Denied read-only configuration verification.',enabled:true,budget_required:true,first_limit_minor:1000000,second_limit_minor:2000000,approval_includes_tax:true,centres:[{id:1,department_ref:'OPER'}],members:[{user_id:1,department_ref:'OPER'},{user_id:2,department_ref:'OPER'}]},403);
|
||||
await api('/api/internal-requisitions/centres','POST',{operation_key:crypto.randomUUID(),code:'REFUSED',reason:'Read-only denial check.'},403);
|
||||
await api('/api/purchasing-budget/approve','POST',{budget_id:1},403);
|
||||
await api('/api/accesses','GET',undefined,403);
|
||||
checks.push('Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused');
|
||||
await api('/api/internal-requisitions/1','GET',undefined,409,{'X-SGF-Context':'invalid'});
|
||||
await api('/api/internal-requisitions/1','GET',undefined,403,{'X-Purchasing-Context':'procurement.third_party'});
|
||||
await api('/api/internal-requisitions/999999999','GET',undefined,404);
|
||||
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:2,module_id:'purchasing'},403);
|
||||
await api('/api/context','POST',{tenant_id:1,company_id:2,unit_id:3,module_id:'purchasing'},403);
|
||||
checks.push('Consulta: forged context, wrong option, missing record and unauthorised company/unit refused');
|
||||
}
|
||||
const legacy = process.argv.includes('--previous');
|
||||
const privateData = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
|
||||
[1, 1, 1],
|
||||
);
|
||||
const checks = [];
|
||||
for (const profile of privateData.profiles) {
|
||||
const jar = new Map();
|
||||
let csrf = '',
|
||||
token = '';
|
||||
const api = async (
|
||||
path,
|
||||
method = 'GET',
|
||||
body,
|
||||
status = 200,
|
||||
overrides = {},
|
||||
) => {
|
||||
const response = await fetch('http://127.0.0.1:8039' + path, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; '),
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'X-SGF-Context': token,
|
||||
'X-Purchasing-Context': 'procurement.internal',
|
||||
'Idempotency-Key': crypto.randomUUID(),
|
||||
...overrides,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
for (const cookie of response.headers.getSetCookie()) {
|
||||
const pair = cookie.split(';')[0],
|
||||
at = pair.indexOf('=');
|
||||
jar.set(pair.slice(0, at), pair.slice(at + 1));
|
||||
}
|
||||
const text = await response.text();
|
||||
let d;
|
||||
try {
|
||||
d = JSON.parse(text);
|
||||
} catch {
|
||||
d = {};
|
||||
}
|
||||
assert(
|
||||
(Array.isArray(status) ? status : [status]).includes(
|
||||
response.status,
|
||||
),
|
||||
`${profile.role} ${path}: expected ${status}, got ${response.status}: ${d.message ?? ''}`,
|
||||
);
|
||||
if (d.csrf) csrf = d.csrf;
|
||||
if (d.context?.token) token = d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');
|
||||
await api('/api/login', 'POST', {
|
||||
email: profile.email,
|
||||
password: privateData.password,
|
||||
});
|
||||
await api('/api/context', 'POST', {
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 1,
|
||||
module_id: 'purchasing',
|
||||
});
|
||||
const list = await api('/api/internal-requisitions');
|
||||
if (legacy && profile.role === 'consulta') {
|
||||
assert(!list.records.some((r) => r.id === 1));
|
||||
await api('/api/internal-requisitions/1', 'GET', undefined, 404);
|
||||
checks.push(
|
||||
'Previous version reproduces missing read-only listing/detail',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
assert(
|
||||
list.records.some((r) => r.id === 1),
|
||||
'Existing request must be listed',
|
||||
);
|
||||
const detail = await api('/api/internal-requisitions/1');
|
||||
assert.equal(detail.record.id, 1);
|
||||
assert.equal(detail.record.version, 3);
|
||||
assert.equal(detail.record.status, 'approved');
|
||||
assert.equal(detail.record.total_minor, 10000);
|
||||
assert.equal(detail.history.length, 3);
|
||||
checks.push(
|
||||
`${profile.role}: existing request 1 listed, detail and three-event history readable`,
|
||||
);
|
||||
if (profile.role === 'consulta') {
|
||||
assert.equal(list.permissions.prepare, false);
|
||||
assert.equal(list.permissions.configure, false);
|
||||
assert.deepEqual(detail.record.allowed_actions, []);
|
||||
await api(
|
||||
'/api/internal-requisitions/save',
|
||||
'POST',
|
||||
{ operation_key: crypto.randomUUID() },
|
||||
403,
|
||||
);
|
||||
for (const action of ['save', 'submit', 'decide'])
|
||||
await api(
|
||||
'/api/internal-requisitions/1/' + action,
|
||||
'POST',
|
||||
{
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: 3,
|
||||
...(action === 'decide' ? { decision: 'approved' } : {}),
|
||||
},
|
||||
[403, 404],
|
||||
);
|
||||
await api(
|
||||
'/api/internal-requisitions/policy',
|
||||
'POST',
|
||||
{
|
||||
version: 1,
|
||||
reason: 'Denied read-only configuration verification.',
|
||||
enabled: true,
|
||||
budget_required: true,
|
||||
first_limit_minor: 1000000,
|
||||
second_limit_minor: 2000000,
|
||||
approval_includes_tax: true,
|
||||
centres: [{ id: 1, department_ref: 'OPER' }],
|
||||
members: [
|
||||
{ user_id: 1, department_ref: 'OPER' },
|
||||
{ user_id: 2, department_ref: 'OPER' },
|
||||
],
|
||||
},
|
||||
403,
|
||||
);
|
||||
await api(
|
||||
'/api/internal-requisitions/centres',
|
||||
'POST',
|
||||
{
|
||||
operation_key: crypto.randomUUID(),
|
||||
code: 'REFUSED',
|
||||
reason: 'Read-only denial check.',
|
||||
},
|
||||
403,
|
||||
);
|
||||
await api(
|
||||
'/api/purchasing-budget/approve',
|
||||
'POST',
|
||||
{ budget_id: 1 },
|
||||
403,
|
||||
);
|
||||
await api('/api/accesses', 'GET', undefined, 403);
|
||||
checks.push(
|
||||
'Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused',
|
||||
);
|
||||
await api('/api/internal-requisitions/1', 'GET', undefined, 409, {
|
||||
'X-SGF-Context': 'invalid',
|
||||
});
|
||||
await api('/api/internal-requisitions/1', 'GET', undefined, 403, {
|
||||
'X-Purchasing-Context': 'procurement.third_party',
|
||||
});
|
||||
await api(
|
||||
'/api/internal-requisitions/999999999',
|
||||
'GET',
|
||||
undefined,
|
||||
404,
|
||||
);
|
||||
await api(
|
||||
'/api/context',
|
||||
'POST',
|
||||
{
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 2,
|
||||
module_id: 'purchasing',
|
||||
},
|
||||
403,
|
||||
);
|
||||
await api(
|
||||
'/api/context',
|
||||
'POST',
|
||||
{
|
||||
tenant_id: 1,
|
||||
company_id: 2,
|
||||
unit_id: 3,
|
||||
module_id: 'purchasing',
|
||||
},
|
||||
403,
|
||||
);
|
||||
checks.push(
|
||||
'Consulta: forged context, wrong option, missing record and unauthorised company/unit refused',
|
||||
);
|
||||
}
|
||||
}
|
||||
const report={passed:true,mode:legacy?'previous-version-recovery':'corrected-version',url:'http://127.0.0.1:8039',scope:'1:1:1',request_id:1,request_recreated:false,reservation_commands_executed:false,rights_changed:false,checks,checked_at:new Date().toISOString(),visual_review:false};
|
||||
fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-read-8039-'+(legacy?'rollback':'http')+'.json',JSON.stringify(report,null,2));
|
||||
const report = {
|
||||
passed: true,
|
||||
mode: legacy ? 'previous-version-recovery' : 'corrected-version',
|
||||
url: 'http://127.0.0.1:8039',
|
||||
scope: '1:1:1',
|
||||
request_id: 1,
|
||||
request_recreated: false,
|
||||
reservation_commands_executed: false,
|
||||
rights_changed: false,
|
||||
checks,
|
||||
checked_at: new Date().toISOString(),
|
||||
visual_review: false,
|
||||
};
|
||||
fs.writeFileSync(
|
||||
'C:/laragon/www/compras/docs/proofs/sgf-read-8039-' +
|
||||
(legacy ? 'rollback' : 'http') +
|
||||
'.json',
|
||||
JSON.stringify(report, null, 2),
|
||||
);
|
||||
console.log(JSON.stringify(report));
|
||||
|
||||
+93
-61
@@ -1,75 +1,107 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
|
||||
$root=dirname(__DIR__);
|
||||
$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
|
||||
$recovery=dirname($host).'/private/read-correction-recovery';
|
||||
$candidate=json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
$root = dirname(__DIR__);
|
||||
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
|
||||
$recovery = dirname($host).'/private/read-correction-recovery';
|
||||
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app=require $host.'/bootstrap/app.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$db=DB::connection();
|
||||
$identity=$db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
|
||||
if(str_replace('\\','/',$app->basePath())!==$host||$identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||(int)$identity->port!==55439||$identity->cluster!=='sgf_modular_regression_2576427d1939'||config('app.url')!=='http://127.0.0.1:8039')throw new RuntimeException('Wrong demonstration');
|
||||
$record=$db->table('ir_requests')->where(['id'=>1,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1])->first();
|
||||
if(!$record||$record->status!=='approved'||$record->total_minor!==10000||$record->version!==3||$db->table('cb_budget_entries')->where('kind','reserve')->count()!==1)throw new RuntimeException('Wrong existing request');
|
||||
$db = DB::connection();
|
||||
$identity = $db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
|
||||
if (str_replace('\\', '/', $app->basePath()) !== $host || $identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || (int) $identity->port !== 55439 || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || config('app.url') !== 'http://127.0.0.1:8039') {
|
||||
throw new RuntimeException('Wrong demonstration');
|
||||
}
|
||||
$record = $db->table('ir_requests')->where(['id' => 1, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first();
|
||||
if (! $record || $record->status !== 'approved' || $record->total_minor !== 10000 || $record->version !== 3 || $db->table('cb_budget_entries')->where('kind', 'reserve')->count() !== 1) {
|
||||
throw new RuntimeException('Wrong existing request');
|
||||
}
|
||||
require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$deploy=new CodeDeployment($host);
|
||||
$fingerprints=function()use($db){
|
||||
return $db->transaction(function()use($db){
|
||||
$db->statement('SET TRANSACTION READ ONLY');$hashes=[];
|
||||
foreach($db->select("select tablename from pg_tables where schemaname='public' order by tablename") as $t){
|
||||
$rows=$db->select('select to_jsonb(t)::text as data from "'.$t->tablename.'" t order by to_jsonb(t)::text');
|
||||
$hashes[$t->tablename]=hash('sha256',json_encode(array_column($rows,'data'),JSON_THROW_ON_ERROR));
|
||||
}return $hashes;
|
||||
$deploy = new CodeDeployment($host);
|
||||
$fingerprints = function () use ($db) {
|
||||
return $db->transaction(function () use ($db) {
|
||||
$db->statement('SET TRANSACTION READ ONLY');
|
||||
$hashes = [];
|
||||
foreach ($db->select("select tablename from pg_tables where schemaname='public' order by tablename") as $t) {
|
||||
$rows = $db->select('select to_jsonb(t)::text as data from "'.$t->tablename.'" t order by to_jsonb(t)::text');
|
||||
$hashes[$t->tablename] = hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $hashes;
|
||||
});
|
||||
};
|
||||
$action=$argv[1]??'';
|
||||
if($action==='prepare'){
|
||||
if(is_dir($recovery))throw new RuntimeException('Recovery exists; no overwrite');
|
||||
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);
|
||||
mkdir($recovery,0700,true);
|
||||
$cfg=$db->getConfig();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe','--format=custom','--file='.$recovery.'/before.dump','--dbname='.$identity->db],null,['PGHOST'=>'127.0.0.1','PGPORT'=>'55439','PGUSER'=>$identity->role,'PGPASSWORD'=>$cfg['password']],null,90))->mustRun();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--list',$recovery.'/before.dump']))->mustRun();
|
||||
$baseline=['identity'=>$identity,'plan'=>$plan,'data_fingerprints'=>$fingerprints(),'backup_sha256'=>hash_file('sha256',$recovery.'/before.dump'),'pointer_sha256'=>hash_file('sha256',$host.'/packages/purchasing/current.json'),'config_hashes'=>[]];
|
||||
foreach(['.env','config/modules.php','config/purchasing-operational.php','config/purchasing-internal.php','config/purchasing-access.php'] as $file)$baseline['config_hashes'][$file]=hash_file('sha256',$host.'/'.$file);
|
||||
file_put_contents($recovery.'/baseline.json',json_encode($baseline,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['prepared'=>true,'tables'=>count($baseline['data_fingerprints']),'backup_sha256'=>$baseline['backup_sha256'],'plan'=>$plan],JSON_PRETTY_PRINT);
|
||||
}else{
|
||||
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$currentFingerprints=$fingerprints();
|
||||
$changedTables=array_keys(array_filter($currentFingerprints,fn($hash,$table)=>$hash!==($baseline['data_fingerprints'][$table]??null),ARRAY_FILTER_USE_BOTH));
|
||||
$auditAppended=false;
|
||||
if(in_array('identity_audit',$changedTables,true)){
|
||||
$extract=new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--data-only','--table=identity_audit','--file=-',$recovery.'/before.dump']);$extract->mustRun();
|
||||
if(!preg_match('~COPY public\.identity_audit \(id,[^)]*\) FROM stdin;\r?\n(.*?)\r?\n\\\\\.~s',$extract->getOutput(),$match))throw new RuntimeException('Audit baseline cannot be reconciled');
|
||||
$ids=array_map(fn($line)=>(int)explode("\t",$line)[0],preg_split('/\r?\n/',$match[1]));
|
||||
$rows=$db->select('select to_jsonb(t)::text as data from identity_audit t where id<=? order by to_jsonb(t)::text',[max($ids)]);
|
||||
if(hash('sha256',json_encode(array_column($rows,'data'),JSON_THROW_ON_ERROR))!==$baseline['data_fingerprints']['identity_audit'])throw new RuntimeException('Existing audit modified');
|
||||
$auditAppended=true;$changedTables=array_values(array_diff($changedTables,['identity_audit']));
|
||||
$action = $argv[1] ?? '';
|
||||
if ($action === 'prepare') {
|
||||
if (is_dir($recovery)) {
|
||||
throw new RuntimeException('Recovery exists; no overwrite');
|
||||
}
|
||||
if($changedTables!==[])throw new RuntimeException('Database rows changed: '.implode(', ',$changedTables));
|
||||
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed');
|
||||
foreach($baseline['config_hashes'] as $file=>$hash)if(hash_file('sha256',$host.'/'.$file)!==$hash)throw new RuntimeException('Configuration changed');
|
||||
if($action==='verify'){
|
||||
$report=['passed'=>true,'identity'=>$identity,'data_tables_reconciled'=>count($baseline['data_fingerprints']),'audit_appended_only'=>$auditAppended,'request_id'=>1,'request_version'=>3,'amount_minor'=>10000,'reservation_count'=>1,'rights_and_accounts_unchanged'=>true,'config_unchanged'=>true,'pointer_unchanged'=>true,'candidate_manifest_sha256'=>hash_file('sha256',$host.'/packages/internal-requisitions/manifest.json'),'backup_sha256'=>$baseline['backup_sha256'],'checked_at'=>gmdate('c')];
|
||||
file_put_contents($root.'/docs/proofs/sgf-read-8039-data.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT);
|
||||
}else{
|
||||
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected maintenance');
|
||||
file_put_contents($host.'/storage/framework/down',json_encode(['time'=>time(),'retry'=>60]));
|
||||
if($action==='rollback'){
|
||||
$applied=json_decode(file_get_contents($recovery.'/applied.json'),true);
|
||||
$result=$deploy->rollback($applied['deployment_id'],'Authorised read fix recovery proof 8039',true);
|
||||
file_put_contents($recovery.'/rollback.json',json_encode($result,JSON_PRETTY_PRINT));
|
||||
}elseif(in_array($action,['apply','reapply'],true)){
|
||||
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);
|
||||
$result=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Authorised read-only visibility correction 8039',true);
|
||||
file_put_contents($recovery.'/'.($action==='apply'?'applied':'reapplied').'.json',json_encode($result,JSON_PRETTY_PRINT));
|
||||
}else throw new RuntimeException('Use prepare/apply/rollback/reapply/verify');
|
||||
unlink($host.'/storage/framework/down');echo json_encode($result,JSON_PRETTY_PRINT);
|
||||
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
mkdir($recovery, 0700, true);
|
||||
$cfg = $db->getConfig();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90))->mustRun();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
|
||||
$baseline = ['identity' => $identity, 'plan' => $plan, 'data_fingerprints' => $fingerprints(), 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json'), 'config_hashes' => []];
|
||||
foreach (['.env', 'config/modules.php', 'config/purchasing-operational.php', 'config/purchasing-internal.php', 'config/purchasing-access.php'] as $file) {
|
||||
$baseline['config_hashes'][$file] = hash_file('sha256', $host.'/'.$file);
|
||||
}
|
||||
file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['prepared' => true, 'tables' => count($baseline['data_fingerprints']), 'backup_sha256' => $baseline['backup_sha256'], 'plan' => $plan], JSON_PRETTY_PRINT);
|
||||
} else {
|
||||
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$currentFingerprints = $fingerprints();
|
||||
$changedTables = array_keys(array_filter($currentFingerprints, fn ($hash, $table) => $hash !== ($baseline['data_fingerprints'][$table] ?? null), ARRAY_FILTER_USE_BOTH));
|
||||
$auditAppended = false;
|
||||
if (in_array('identity_audit', $changedTables, true)) {
|
||||
$extract = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--data-only', '--table=identity_audit', '--file=-', $recovery.'/before.dump']);
|
||||
$extract->mustRun();
|
||||
if (! preg_match('~COPY public\.identity_audit \(id,[^)]*\) FROM stdin;\r?\n(.*?)\r?\n\\\\\.~s', $extract->getOutput(), $match)) {
|
||||
throw new RuntimeException('Audit baseline cannot be reconciled');
|
||||
}
|
||||
$ids = array_map(fn ($line) => (int) explode("\t", $line)[0], preg_split('/\r?\n/', $match[1]));
|
||||
$rows = $db->select('select to_jsonb(t)::text as data from identity_audit t where id<=? order by to_jsonb(t)::text', [max($ids)]);
|
||||
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $baseline['data_fingerprints']['identity_audit']) {
|
||||
throw new RuntimeException('Existing audit modified');
|
||||
}
|
||||
$auditAppended = true;
|
||||
$changedTables = array_values(array_diff($changedTables, ['identity_audit']));
|
||||
}
|
||||
if ($changedTables !== []) {
|
||||
throw new RuntimeException('Database rows changed: '.implode(', ', $changedTables));
|
||||
}
|
||||
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
|
||||
throw new RuntimeException('Pointer changed');
|
||||
}
|
||||
foreach ($baseline['config_hashes'] as $file => $hash) {
|
||||
if (hash_file('sha256', $host.'/'.$file) !== $hash) {
|
||||
throw new RuntimeException('Configuration changed');
|
||||
}
|
||||
}
|
||||
if ($action === 'verify') {
|
||||
$report = ['passed' => true, 'identity' => $identity, 'data_tables_reconciled' => count($baseline['data_fingerprints']), 'audit_appended_only' => $auditAppended, 'request_id' => 1, 'request_version' => 3, 'amount_minor' => 10000, 'reservation_count' => 1, 'rights_and_accounts_unchanged' => true, 'config_unchanged' => true, 'pointer_unchanged' => true, 'candidate_manifest_sha256' => hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json'), 'backup_sha256' => $baseline['backup_sha256'], 'checked_at' => gmdate('c')];
|
||||
file_put_contents($root.'/docs/proofs/sgf-read-8039-data.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($report, JSON_PRETTY_PRINT);
|
||||
} else {
|
||||
if (is_file($host.'/storage/framework/down')) {
|
||||
throw new RuntimeException('Unexpected maintenance');
|
||||
}
|
||||
file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60]));
|
||||
if ($action === 'rollback') {
|
||||
$applied = json_decode(file_get_contents($recovery.'/applied.json'), true);
|
||||
$result = $deploy->rollback($applied['deployment_id'], 'Authorised read fix recovery proof 8039', true);
|
||||
file_put_contents($recovery.'/rollback.json', json_encode($result, JSON_PRETTY_PRINT));
|
||||
} elseif (in_array($action, ['apply', 'reapply'], true)) {
|
||||
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
$result = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised read-only visibility correction 8039', true);
|
||||
file_put_contents($recovery.'/'.($action === 'apply' ? 'applied' : 'reapplied').'.json',json_encode($result,JSON_PRETTY_PRINT));
|
||||
} else {
|
||||
throw new RuntimeException('Use prepare/apply/rollback/reapply/verify');
|
||||
}
|
||||
unlink($host.'/storage/framework/down');
|
||||
echo json_encode($result,JSON_PRETTY_PRINT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,42 @@
|
||||
<?php
|
||||
|
||||
// Freeze only the authorised adapter correction over the previously proved artifact.
|
||||
$root=dirname(__DIR__);
|
||||
$prior=json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$old=$prior['artifact']['directory'];
|
||||
$manifest=json_decode(file_get_contents($old.'/manifest.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$file='integrations/sgf/internal-requisitions/Port.php';
|
||||
$payload=[];
|
||||
foreach($manifest['support_files'] as $path=>$hash){
|
||||
$text=file_get_contents($old.'/'.$path);
|
||||
if(!hash_equals($hash,hash('sha256',$text)))throw new RuntimeException('Prior artifact changed');
|
||||
$payload[$path]=$path===$file?file_get_contents($root.'/'.$file):$text;
|
||||
$root = dirname(__DIR__);
|
||||
$prior = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$old = $prior['artifact']['directory'];
|
||||
$manifest = json_decode(file_get_contents($old.'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$file = 'integrations/sgf/internal-requisitions/Port.php';
|
||||
$payload = [];
|
||||
foreach ($manifest['support_files'] as $path => $hash) {
|
||||
$text = file_get_contents($old.'/'.$path);
|
||||
if (! hash_equals($hash, hash('sha256', $text))) {
|
||||
throw new RuntimeException('Prior artifact changed');
|
||||
}
|
||||
$payload[$path] = $path === $file ? file_get_contents($root.'/'.$file) : $text;
|
||||
}
|
||||
$manifest['support_files'][$file]=hash('sha256',$payload[$file]);
|
||||
$manifestText=json_encode($manifest,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
$id='OPERATIONAL-CANDIDATE-'.substr(hash('sha256',$manifestText),0,16);
|
||||
$dir=$root.'/storage/app/private/candidates/'.$id;
|
||||
if(file_exists($dir))throw new RuntimeException('Candidate already exists; verify rather than overwrite');
|
||||
mkdir($dir,0700,true);
|
||||
foreach($payload+['manifest.json'=>$manifestText] as $path=>$text){
|
||||
if(!is_dir(dirname($dir.'/'.$path)))mkdir(dirname($dir.'/'.$path),0700,true);
|
||||
file_put_contents($dir.'/'.$path,$text);
|
||||
$manifest['support_files'][$file] = hash('sha256', $payload[$file]);
|
||||
$manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
$id = 'OPERATIONAL-CANDIDATE-'.substr(hash('sha256', $manifestText), 0, 16);
|
||||
$dir = $root.'/storage/app/private/candidates/'.$id;
|
||||
if (file_exists($dir)) {
|
||||
throw new RuntimeException('Candidate already exists; verify rather than overwrite');
|
||||
}
|
||||
mkdir($dir, 0700, true);
|
||||
foreach ($payload + ['manifest.json' => $manifestText] as $path => $text) {
|
||||
if (! is_dir(dirname($dir.'/'.$path))) {
|
||||
mkdir(dirname($dir.'/'.$path), 0700, true);
|
||||
}
|
||||
file_put_contents($dir.'/'.$path, $text);
|
||||
}
|
||||
$archive = $root.'/storage/app/private/candidate-archives/'.$id.'.zip';
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
|
||||
throw new RuntimeException('Archive collision');
|
||||
}
|
||||
foreach ([...array_keys($payload), 'manifest.json'] as $path) {
|
||||
$zip->addFile($dir.'/'.$path, $path);
|
||||
}
|
||||
$archive=$root.'/storage/app/private/candidate-archives/'.$id.'.zip';
|
||||
$zip=new ZipArchive;
|
||||
if($zip->open($archive,ZipArchive::CREATE|ZipArchive::EXCL)!==true)throw new RuntimeException('Archive collision');
|
||||
foreach([...array_keys($payload),'manifest.json'] as $path)$zip->addFile($dir.'/'.$path,$path);
|
||||
$zip->close();
|
||||
$result=['directory'=>$dir,'archive'=>['file'=>$archive,'sha256'=>hash_file('sha256',$archive),'manifest_sha256'=>hash('sha256',$manifestText)],'prior_manifest_sha256'=>$prior['artifact']['archive']['manifest_sha256'],'changed_files'=>[$file],'schema_changed'=>false,'rights_changed'=>false,'installed_real'=>false];
|
||||
file_put_contents($root.'/docs/proofs/sgf-read-candidate.json',json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
$result = ['directory' => $dir, 'archive' => ['file' => $archive, 'sha256' => hash_file('sha256', $archive), 'manifest_sha256' => hash('sha256', $manifestText)], 'prior_manifest_sha256' => $prior['artifact']['archive']['manifest_sha256'], 'changed_files' => [$file], 'schema_changed' => false, 'rights_changed' => false, 'installed_real' => false];
|
||||
file_put_contents($root.'/docs/proofs/sgf-read-candidate.json', json_encode($result,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
|
||||
@@ -1,24 +1,63 @@
|
||||
<?php
|
||||
$root=dirname(__DIR__);
|
||||
$old=json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
$manifest=json_decode(file_get_contents($old['directory'].'/manifest.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$payload=[];
|
||||
foreach($manifest['support_files'] as $file=>$hash){$text=file_get_contents($old['directory'].'/'.$file);if(hash('sha256',$text)!==$hash)throw new RuntimeException('Prior candidate changed');$payload[$file]=$text;}
|
||||
foreach(['integrations/sgf/sourcing','packages/purchasing/src'] as $dir)foreach(new DirectoryIterator($root.'/'.$dir) as $file)if($file->isFile())$payload[$dir.'/'.$file->getFilename()]=file_get_contents($file->getPathname());
|
||||
foreach(['integrations/sgf/operational/Installation.php','integrations/sgf/operational/CodeDeployment.php','integrations/sgf/access/AccessOverlay.php','integrations/sgf/operational/routes.php','integrations/sgf/internal-requisitions/Controller.php','integrations/sgf/internal-requisitions/screen.mjs'] as $file)$payload[$file]=file_get_contents($root.'/'.$file);
|
||||
$payload['bootstrap.php']=file_get_contents($root.'/integrations/sgf/operational/entry.php');
|
||||
$payload['scripts/sgf-sourcing-install.php']=file_get_contents($root.'/scripts/sgf-sourcing-install.php');
|
||||
|
||||
use App\Services\ComparisonPolicy;
|
||||
use Tempo\Purchasing\Delivery\AccessOverlay;
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$old = json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$manifest = json_decode(file_get_contents($old['directory'].'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$payload = [];
|
||||
foreach ($manifest['support_files'] as $file => $hash) {
|
||||
$text = file_get_contents($old['directory'].'/'.$file);
|
||||
if (hash('sha256', $text) !== $hash) {
|
||||
throw new RuntimeException('Prior candidate changed');
|
||||
}$payload[$file] = $text;
|
||||
}
|
||||
foreach (['integrations/sgf/sourcing', 'packages/purchasing/src'] as $dir) {
|
||||
foreach (new DirectoryIterator($root.'/'.$dir) as $file) {
|
||||
if ($file->isFile()) {
|
||||
$payload[$dir.'/'.$file->getFilename()] = file_get_contents($file->getPathname());
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/CodeDeployment.php', 'integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/routes.php', 'integrations/sgf/internal-requisitions/Controller.php', 'integrations/sgf/internal-requisitions/screen.mjs'] as $file) {
|
||||
$payload[$file] = file_get_contents($root.'/'.$file);
|
||||
}
|
||||
$payload['bootstrap.php'] = file_get_contents($root.'/integrations/sgf/operational/entry.php');
|
||||
$payload['scripts/sgf-sourcing-install.php'] = file_get_contents($root.'/scripts/sgf-sourcing-install.php');
|
||||
require_once $root.'/app/Services/ComparisonPolicy.php';
|
||||
$payload['integrations/sgf/sourcing/comparison-defaults.json']=json_encode(App\Services\ComparisonPolicy::DEFAULTS,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
$file='app/Modules/Identity/Services/Permissions.php';
|
||||
$payload[$file]=preg_replace('/public const UNIT = .*?;/s','public const UNIT = '.var_export(['unit.view','unit.edit',...requireRights($root)],true).';',$payload[$file],1);
|
||||
$manifest['host_overlays'][$file]['after_sha256']=hash('sha256',$payload[$file]);
|
||||
$payload['integrations/sgf/sourcing/comparison-defaults.json'] = json_encode(ComparisonPolicy::DEFAULTS, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
$file = 'app/Modules/Identity/Services/Permissions.php';
|
||||
$payload[$file] = preg_replace('/public const UNIT = .*?;/s', 'public const UNIT = '.var_export(['unit.view', 'unit.edit', ...requireRights($root)], true).';', $payload[$file], 1);
|
||||
$manifest['host_overlays'][$file]['after_sha256'] = hash('sha256', $payload[$file]);
|
||||
// The same native catalogue and delegation workflow remain in use.
|
||||
foreach($payload as $file=>$text)$manifest['support_files'][$file]=hash('sha256',$text);
|
||||
$manifestText=json_encode($manifest,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
$id='OPERATIONAL-CANDIDATE-'.substr(hash('sha256',$manifestText),0,16);$dir=$root.'/storage/app/private/candidates/'.$id;
|
||||
if(file_exists($dir))throw new RuntimeException('Immutable candidate exists');mkdir($dir,0700,true);
|
||||
foreach($payload+['manifest.json'=>$manifestText] as $file=>$text){if(!is_dir(dirname($dir.'/'.$file)))mkdir(dirname($dir.'/'.$file),0700,true);file_put_contents($dir.'/'.$file,$text);}
|
||||
$archive=$root.'/storage/app/private/candidate-archives/'.$id.'.zip';$zip=new ZipArchive;if($zip->open($archive,ZipArchive::CREATE|ZipArchive::EXCL)!==true)throw new RuntimeException('Archive exists');foreach([...array_keys($payload),'manifest.json'] as $file)$zip->addFile($dir.'/'.$file,$file);$zip->close();
|
||||
$out=['directory'=>$dir,'archive'=>['file'=>$archive,'sha256'=>hash_file('sha256',$archive),'manifest_sha256'=>hash('sha256',$manifestText)],'prior_manifest_sha256'=>$old['archive']['manifest_sha256'],'schema_extension'=>'sourcing revision 1; four ss_* tables and explicit catalogue extension','real_activated'=>false];file_put_contents($root.'/docs/proofs/sgf-sourcing-candidate.json',json_encode($out,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($out,JSON_PRETTY_PRINT);
|
||||
function requireRights(string $root):array{require_once $root.'/integrations/sgf/access/AccessOverlay.php';return Tempo\Purchasing\Delivery\AccessOverlay::RIGHTS;}
|
||||
foreach ($payload as $file => $text) {
|
||||
$manifest['support_files'][$file] = hash('sha256', $text);
|
||||
}
|
||||
$manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
$id = 'OPERATIONAL-CANDIDATE-'.substr(hash('sha256', $manifestText), 0, 16);
|
||||
$dir = $root.'/storage/app/private/candidates/'.$id;
|
||||
if (file_exists($dir)) {
|
||||
throw new RuntimeException('Immutable candidate exists');
|
||||
}mkdir($dir, 0700, true);
|
||||
foreach ($payload + ['manifest.json' => $manifestText] as $file => $text) {
|
||||
if (! is_dir(dirname($dir.'/'.$file))) {
|
||||
mkdir(dirname($dir.'/'.$file), 0700, true);
|
||||
}file_put_contents($dir.'/'.$file, $text);
|
||||
}
|
||||
$archive = $root.'/storage/app/private/candidate-archives/'.$id.'.zip';
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
|
||||
throw new RuntimeException('Archive exists');
|
||||
}foreach ([...array_keys($payload), 'manifest.json'] as $file) {
|
||||
$zip->addFile($dir.'/'.$file, $file);
|
||||
}$zip->close();
|
||||
$out = ['directory' => $dir, 'archive' => ['file' => $archive, 'sha256' => hash_file('sha256', $archive), 'manifest_sha256' => hash('sha256', $manifestText)], 'prior_manifest_sha256' => $old['archive']['manifest_sha256'], 'schema_extension' => 'sourcing revision 1; four ss_* tables and explicit catalogue extension', 'real_activated' => false];
|
||||
file_put_contents($root.'/docs/proofs/sgf-sourcing-candidate.json', json_encode($out, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($out, JSON_PRETTY_PRINT);
|
||||
function requireRights(string $root): array
|
||||
{
|
||||
require_once $root.'/integrations/sgf/access/AccessOverlay.php';
|
||||
|
||||
return AccessOverlay::RIGHTS;
|
||||
}
|
||||
|
||||
@@ -1,35 +1,70 @@
|
||||
<?php
|
||||
|
||||
use App\Services\ComparisonPolicy;
|
||||
use Tempo\Purchasing\Internal\RequisitionFailure;
|
||||
use Tempo\Purchasing\Sourcing\Sourcing;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
foreach(['QuotationPricing','ProposalScoring','RequisitionFailure','Sourcing'] as $c)require_once dirname(__DIR__).'/packages/purchasing/src/'.$c.'.php';
|
||||
foreach (['QuotationPricing', 'ProposalScoring', 'RequisitionFailure', 'Sourcing'] as $c) {
|
||||
require_once dirname(__DIR__).'/packages/purchasing/src/'.$c.'.php';
|
||||
}
|
||||
require_once dirname(__DIR__).'/app/Services/ComparisonPolicy.php';
|
||||
$engine=new Tempo\Purchasing\Sourcing\Sourcing;
|
||||
$policy=App\Services\ComparisonPolicy::DEFAULTS;
|
||||
$request=['status'=>'approved','requester_id'=>1,'data'=>['items'=>[['description'=>'Synthetic material','quantity'=>'1.000','tax_rate'=>'0.00']]]];
|
||||
$state=['version'=>0,'suppliers'=>[],'quotes'=>[],'proposals'=>[],'confirmed'=>null];$checks=[];
|
||||
$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;};
|
||||
$deny=function($call,$status,$label)use($check){try{$call();throw new RuntimeException('Unexpected success: '.$label);}catch(Tempo\Purchasing\Internal\RequisitionFailure $e){$check($e->status===$status,$label);}};
|
||||
$step=function($s,$actor,$action,$input)use($engine,$request,$policy){$next=$engine->transition($s,$request,$actor,$action,$input,$policy,'2026-11-02');$next['version']=$s['version']+1;return $next;};
|
||||
foreach([1,2,3] as $id){$state=$step($state,1,'select',['supplier'=>['id'=>$id,'eligible'=>true,'snapshot'=>['name'=>'Synthetic '.$id]]]);$state=$step($state,1,'quote',['supplier_id'=>$id,'reference'=>'Q-'.$id,'currency'=>'MZN','valid_until'=>'2026-12-31','delivery_days'=>5,'payment_terms'=>'30 days','items'=>[['line'=>0,'unit_price'=>(string)(90+$id*10)]]]);}
|
||||
$check(!$engine->comparison($state,$policy,'2026-11-02')['ready'],'Existing minimum independent evaluations retained');
|
||||
$evaluation=fn($id)=>['supplier_id'=>$id,'quote_revision'=>1,'quality'=>8,'history'=>8,'payment'=>8,'reason'=>'Synthetic evaluation reason'];
|
||||
$deny(fn()=>$step($state,1,'evaluate',$evaluation(1)),403,'Requester cannot evaluate');
|
||||
foreach([1,2,3] as $id)foreach([2,4] as $actor)$state=$step($state,$actor,'evaluate',$evaluation($id));
|
||||
$comparison=$engine->comparison($state,$policy,'2026-11-02');$check($comparison['ready']&&$comparison['top_ids']===[1],'Existing weighted scoring identifies best eligible quote');
|
||||
$proposal=['supplier_id'=>1,'comparison_hash'=>$comparison['fingerprint'],'reason'=>'Synthetic award proposal justification','delivery_date'=>'2027-01-15','delivery_location'=>'Local de entrega exclusivamente sintético OPER'];
|
||||
$deny(fn()=>$step($state,1,'propose',$proposal),403,'Requester cannot propose award');
|
||||
$state=$step($state,2,'propose',$proposal);
|
||||
$confirmation=['proposal_index'=>0,'comparison_hash'=>$comparison['fingerprint'],'reason'=>'Independent synthetic confirmation'];
|
||||
$deny(fn()=>$step($state,2,'confirm',$confirmation),403,'Proposer cannot confirm own award');
|
||||
$deny(fn()=>$step($state,1,'confirm',$confirmation),403,'Requester cannot confirm award');
|
||||
$changed=$step($state,1,'quote',['supplier_id'=>1,'reference'=>'Q-1-r2','currency'=>'MZN','valid_until'=>'2026-12-31','delivery_days'=>6,'payment_terms'=>'30 days','items'=>[['line'=>0,'unit_price'=>'100.00']]]);
|
||||
$deny(fn()=>$step($changed,4,'confirm',$confirmation),409,'Quote revision invalidates existing award basis and evaluations');
|
||||
$revoked=$state;$revoked['quotes'][1]['evaluations'][4]['eligible']=false;
|
||||
$deny(fn()=>$step($revoked,4,'confirm',$confirmation),409,'Evaluator revocation invalidates confirmation basis');
|
||||
$expired=$state;$expired['quotes'][1]['valid_until']='2026-11-01';
|
||||
$deny(fn()=>$step($expired,4,'confirm',$confirmation),409,'Expired quote invalidates confirmation');
|
||||
$ok=$step($state,4,'confirm',$confirmation);
|
||||
$check($ok['confirmed']['confirmed_by']===4&&$ok['confirmed']['proposal']['proposed_by']===2,'Independent confirmation preserves exact proposed comparison');
|
||||
$deny(fn()=>$step($ok,1,'quote',[]),409,'Confirmed process cannot be rewritten');
|
||||
$check($state['proposals'][0]['comparison']['fingerprint']===$comparison['fingerprint'],'Comparison snapshot and justification preserved');
|
||||
$report=['passed'=>true,'checks'=>$checks,'synthetic_only'=>true,'persistent_demo_accounts_created'=>false,'checked_at'=>gmdate('c')];
|
||||
file_put_contents(dirname(__DIR__).'/docs/proofs/sgf-sourcing-core.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT);
|
||||
$engine = new Sourcing;
|
||||
$policy = ComparisonPolicy::DEFAULTS;
|
||||
$request = ['status' => 'approved', 'requester_id' => 1, 'data' => ['items' => [['description' => 'Synthetic material', 'quantity' => '1.000', 'tax_rate' => '0.00']]]];
|
||||
$state = ['version' => 0, 'suppliers' => [], 'quotes' => [], 'proposals' => [], 'confirmed' => null];
|
||||
$checks = [];
|
||||
$check = function ($ok, $label) use (&$checks) {
|
||||
if (! $ok) {
|
||||
throw new RuntimeException($label);
|
||||
}$checks[] = $label;
|
||||
};
|
||||
$deny = function ($call, $status, $label) use ($check) {
|
||||
try {
|
||||
$call();
|
||||
throw new RuntimeException('Unexpected success: '.$label);
|
||||
} catch (RequisitionFailure $e) {
|
||||
$check($e->status === $status, $label);
|
||||
}
|
||||
};
|
||||
$step = function ($s, $actor, $action, $input) use ($engine, $request, $policy) {
|
||||
$next = $engine->transition($s, $request, $actor, $action, $input, $policy, '2026-11-02');
|
||||
$next['version'] = $s['version'] + 1;
|
||||
|
||||
return $next;
|
||||
};
|
||||
foreach ([1, 2, 3] as $id) {
|
||||
$state = $step($state, 1, 'select', ['supplier' => ['id' => $id, 'eligible' => true, 'snapshot' => ['name' => 'Synthetic '.$id]]]);
|
||||
$state = $step($state, 1, 'quote', ['supplier_id' => $id, 'reference' => 'Q-'.$id, 'currency' => 'MZN', 'valid_until' => '2026-12-31', 'delivery_days' => 5, 'payment_terms' => '30 days', 'items' => [['line' => 0, 'unit_price' => (string) (90 + $id * 10)]]]);
|
||||
}
|
||||
$check(! $engine->comparison($state, $policy, '2026-11-02')['ready'], 'Existing minimum independent evaluations retained');
|
||||
$evaluation = fn ($id) => ['supplier_id' => $id, 'quote_revision' => 1, 'quality' => 8, 'history' => 8, 'payment' => 8, 'reason' => 'Synthetic evaluation reason'];
|
||||
$deny(fn () => $step($state, 1, 'evaluate', $evaluation(1)), 403, 'Requester cannot evaluate');
|
||||
foreach ([1, 2, 3] as $id) {
|
||||
foreach ([2, 4] as $actor) {
|
||||
$state = $step($state, $actor, 'evaluate', $evaluation($id));
|
||||
}
|
||||
}
|
||||
$comparison = $engine->comparison($state, $policy, '2026-11-02');
|
||||
$check($comparison['ready'] && $comparison['top_ids'] === [1], 'Existing weighted scoring identifies best eligible quote');
|
||||
$proposal = ['supplier_id' => 1, 'comparison_hash' => $comparison['fingerprint'], 'reason' => 'Synthetic award proposal justification', 'delivery_date' => '2027-01-15', 'delivery_location' => 'Local de entrega exclusivamente sintético OPER'];
|
||||
$deny(fn () => $step($state, 1, 'propose', $proposal), 403, 'Requester cannot propose award');
|
||||
$state = $step($state, 2, 'propose', $proposal);
|
||||
$confirmation = ['proposal_index' => 0, 'comparison_hash' => $comparison['fingerprint'], 'reason' => 'Independent synthetic confirmation'];
|
||||
$deny(fn () => $step($state, 2, 'confirm', $confirmation), 403, 'Proposer cannot confirm own award');
|
||||
$deny(fn () => $step($state, 1, 'confirm', $confirmation), 403, 'Requester cannot confirm award');
|
||||
$changed = $step($state, 1, 'quote', ['supplier_id' => 1, 'reference' => 'Q-1-r2', 'currency' => 'MZN', 'valid_until' => '2026-12-31', 'delivery_days' => 6, 'payment_terms' => '30 days', 'items' => [['line' => 0, 'unit_price' => '100.00']]]);
|
||||
$deny(fn () => $step($changed, 4, 'confirm', $confirmation), 409, 'Quote revision invalidates existing award basis and evaluations');
|
||||
$revoked = $state;
|
||||
$revoked['quotes'][1]['evaluations'][4]['eligible'] = false;
|
||||
$deny(fn () => $step($revoked, 4, 'confirm', $confirmation), 409, 'Evaluator revocation invalidates confirmation basis');
|
||||
$expired = $state;
|
||||
$expired['quotes'][1]['valid_until'] = '2026-11-01';
|
||||
$deny(fn () => $step($expired, 4, 'confirm', $confirmation), 409, 'Expired quote invalidates confirmation');
|
||||
$ok = $step($state, 4, 'confirm', $confirmation);
|
||||
$check($ok['confirmed']['confirmed_by'] === 4 && $ok['confirmed']['proposal']['proposed_by'] === 2, 'Independent confirmation preserves exact proposed comparison');
|
||||
$deny(fn () => $step($ok, 1, 'quote', []), 409, 'Confirmed process cannot be rewritten');
|
||||
$check($state['proposals'][0]['comparison']['fingerprint'] === $comparison['fingerprint'], 'Comparison snapshot and justification preserved');
|
||||
$report = ['passed' => true, 'checks' => $checks, 'synthetic_only' => true, 'persistent_demo_accounts_created' => false, 'checked_at' => gmdate('c')];
|
||||
file_put_contents(dirname(__DIR__).'/docs/proofs/sgf-sourcing-core.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($report,JSON_PRETTY_PRINT);
|
||||
|
||||
@@ -1,26 +1,195 @@
|
||||
import fs from 'node:fs';import assert from 'node:assert/strict';import crypto from 'node:crypto';
|
||||
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8'));
|
||||
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]);
|
||||
const clients={},checks=[];
|
||||
for(const p of privateData.profiles){let csrf='',token='';const jar=new Map();
|
||||
const api=async(path,method='GET',body,status=200)=>{const r=await fetch('http://127.0.0.1:8039'+path,{method,headers:{Accept:'application/json','Content-Type':'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),'X-CSRF-TOKEN':csrf,'X-SGF-Context':token,'X-Purchasing-Context':'procurement.internal'},...(body===undefined?{}:{body:JSON.stringify(body)})});for(const c of r.headers.getSetCookie()){const pair=c.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}const text=await r.text();let d;try{d=JSON.parse(text);}catch{d={message:text.slice(0,160)};}assert.equal(r.status,status,`${p.role} ${path}: ${d.message??JSON.stringify(d.errors)}`);if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token;return d;};
|
||||
await api('/api/session');await api('/api/login','POST',{email:p.email,password:privateData.password});await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'});clients[p.role]=api;
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
const privateData = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.deepEqual(
|
||||
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
|
||||
[1, 1, 1],
|
||||
);
|
||||
const clients = {},
|
||||
checks = [];
|
||||
for (const p of privateData.profiles) {
|
||||
let csrf = '',
|
||||
token = '';
|
||||
const jar = new Map();
|
||||
const api = async (path, method = 'GET', body, status = 200) => {
|
||||
const r = await fetch('http://127.0.0.1:8039' + path, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; '),
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'X-SGF-Context': token,
|
||||
'X-Purchasing-Context': 'procurement.internal',
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
for (const c of r.headers.getSetCookie()) {
|
||||
const pair = c.split(';')[0],
|
||||
at = pair.indexOf('=');
|
||||
jar.set(pair.slice(0, at), pair.slice(at + 1));
|
||||
}
|
||||
const text = await r.text();
|
||||
let d;
|
||||
try {
|
||||
d = JSON.parse(text);
|
||||
} catch {
|
||||
d = { message: text.slice(0, 160) };
|
||||
}
|
||||
assert.equal(
|
||||
r.status,
|
||||
status,
|
||||
`${p.role} ${path}: ${d.message ?? JSON.stringify(d.errors)}`,
|
||||
);
|
||||
if (d.csrf) csrf = d.csrf;
|
||||
if (d.context?.token) token = d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');
|
||||
await api('/api/login', 'POST', {
|
||||
email: p.email,
|
||||
password: privateData.password,
|
||||
});
|
||||
await api('/api/context', 'POST', {
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 1,
|
||||
module_id: 'purchasing',
|
||||
});
|
||||
clients[p.role] = api;
|
||||
}
|
||||
const read=who=>clients[who]('/api/sourcing/1');
|
||||
async function command(who,action,body,status=200){const current=await read(who);return clients[who]('/api/sourcing/1/'+action,'POST',{operation_key:crypto.randomUUID(),version:current.state.version,...(action==='propose'?{delivery_date:'2027-01-15',delivery_location:'Local de entrega apenas sintético para teste de recusa'}:{}),...body},status);}
|
||||
let initial=await read('preparador');assert.equal(initial.request.total_minor,10000);assert.equal(initial.request.version,3);assert.equal(initial.suppliers.length,3);
|
||||
for(const [index,supplier] of initial.suppliers.entries()){
|
||||
let current=await read('preparador');if(!current.state.suppliers[supplier.id])await command('preparador','select',{supplier_id:supplier.id});
|
||||
current=await read('preparador');
|
||||
if(!current.state.quotes[supplier.id])await command('preparador','quote',{supplier_id:supplier.id,reference:'DEMO-COTACAO-'+supplier.reference,currency:'MZN',valid_until:'2027-12-31',delivery_days:5+index,payment_terms:'Condições sintéticas: pagamento a 30 dias',items:current.request.data.items.map((_,line)=>({line,unit_price:(100+index*10).toFixed(2)}))});
|
||||
current=await read('revisor');const q=current.state.quotes[supplier.id];
|
||||
if(!q.evaluations[2])await command('revisor','evaluate',{supplier_id:supplier.id,quote_revision:q.revision,quality:8,history:8,payment:8,no_conflict:true,reason:'Avaliação exclusivamente sintética de demonstração; sem contacto externo.'});
|
||||
const read = (who) => clients[who]('/api/sourcing/1');
|
||||
async function command(who, action, body, status = 200) {
|
||||
const current = await read(who);
|
||||
return clients[who](
|
||||
'/api/sourcing/1/' + action,
|
||||
'POST',
|
||||
{
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: current.state.version,
|
||||
...(action === 'propose'
|
||||
? {
|
||||
delivery_date: '2027-01-15',
|
||||
delivery_location:
|
||||
'Local de entrega apenas sintético para teste de recusa',
|
||||
}
|
||||
: {}),
|
||||
...body,
|
||||
},
|
||||
status,
|
||||
);
|
||||
}
|
||||
const pending=await read('consulta');assert.equal(pending.comparison.ready,false);assert(pending.comparison.rows.every(r=>r.evaluation_count===1));assert.equal(pending.state.confirmed,null);assert.equal(pending.state.proposals.length,0);
|
||||
await command('revisor','propose',{supplier_id:pending.comparison.rows[0].supplier_id,comparison_hash:pending.comparison.fingerprint,reason:'Verificar bloqueio por falta de segundo avaliador independente.'},422);
|
||||
await command('revisor','propose',{supplier_id:pending.comparison.rows[1].supplier_id,comparison_hash:pending.comparison.fingerprint,reason:'Verificar sinalização de adaptação orçamental sem movimento financeiro.'},409);
|
||||
for(const action of ['select','quote','evaluate','propose','confirm'])await clients.consulta('/api/sourcing/1/'+action,'POST',{},403);
|
||||
await clients.revisor('/api/sourcing/1/confirm','POST',{},403);
|
||||
for(const who of ['preparador','revisor','consulta']){const origin=await clients[who]('/api/internal-requisitions/1');assert.equal(origin.record.version,3);assert.equal(origin.record.total_minor,10000);assert.equal(origin.history.length,3);assert(origin.canSourcing);await clients[who]('/purchasing/sourcing/1');}
|
||||
checks.push('Existing request reused with version 3 and unchanged three-event history');checks.push('Three selected synthetic suppliers, three quotes and one eligible evaluation per quote');checks.push('Comparison and award proposal remain blocked without second eligible evaluator');checks.push('Quoted amount differing from reserved amount is signalled without a budget movement');checks.push('Consulta retains full sourcing read and no preparation/evaluation/proposal/confirmation');checks.push('No persistent identity has award-confirmation right; no award created');checks.push('Protected sourcing screen is accessible to all three existing profiles');
|
||||
const proof={passed:true,url:'http://127.0.0.1:8039',scope:'1:1:1',request_id:1,checks,confirmation_completed:false,owner_decision_no_fourth_account:true,visual_review:false,checked_at:new Date().toISOString()};fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-sourcing-demo-http.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof));
|
||||
let initial = await read('preparador');
|
||||
assert.equal(initial.request.total_minor, 10000);
|
||||
assert.equal(initial.request.version, 3);
|
||||
assert.equal(initial.suppliers.length, 3);
|
||||
for (const [index, supplier] of initial.suppliers.entries()) {
|
||||
let current = await read('preparador');
|
||||
if (!current.state.suppliers[supplier.id])
|
||||
await command('preparador', 'select', { supplier_id: supplier.id });
|
||||
current = await read('preparador');
|
||||
if (!current.state.quotes[supplier.id])
|
||||
await command('preparador', 'quote', {
|
||||
supplier_id: supplier.id,
|
||||
reference: 'DEMO-COTACAO-' + supplier.reference,
|
||||
currency: 'MZN',
|
||||
valid_until: '2027-12-31',
|
||||
delivery_days: 5 + index,
|
||||
payment_terms: 'Condições sintéticas: pagamento a 30 dias',
|
||||
items: current.request.data.items.map((_, line) => ({
|
||||
line,
|
||||
unit_price: (100 + index * 10).toFixed(2),
|
||||
})),
|
||||
});
|
||||
current = await read('revisor');
|
||||
const q = current.state.quotes[supplier.id];
|
||||
if (!q.evaluations[2])
|
||||
await command('revisor', 'evaluate', {
|
||||
supplier_id: supplier.id,
|
||||
quote_revision: q.revision,
|
||||
quality: 8,
|
||||
history: 8,
|
||||
payment: 8,
|
||||
no_conflict: true,
|
||||
reason: 'Avaliação exclusivamente sintética de demonstração; sem contacto externo.',
|
||||
});
|
||||
}
|
||||
const pending = await read('consulta');
|
||||
assert.equal(pending.comparison.ready, false);
|
||||
assert(pending.comparison.rows.every((r) => r.evaluation_count === 1));
|
||||
assert.equal(pending.state.confirmed, null);
|
||||
assert.equal(pending.state.proposals.length, 0);
|
||||
await command(
|
||||
'revisor',
|
||||
'propose',
|
||||
{
|
||||
supplier_id: pending.comparison.rows[0].supplier_id,
|
||||
comparison_hash: pending.comparison.fingerprint,
|
||||
reason: 'Verificar bloqueio por falta de segundo avaliador independente.',
|
||||
},
|
||||
422,
|
||||
);
|
||||
await command(
|
||||
'revisor',
|
||||
'propose',
|
||||
{
|
||||
supplier_id: pending.comparison.rows[1].supplier_id,
|
||||
comparison_hash: pending.comparison.fingerprint,
|
||||
reason: 'Verificar sinalização de adaptação orçamental sem movimento financeiro.',
|
||||
},
|
||||
409,
|
||||
);
|
||||
for (const action of ['select', 'quote', 'evaluate', 'propose', 'confirm'])
|
||||
await clients.consulta('/api/sourcing/1/' + action, 'POST', {}, 403);
|
||||
await clients.revisor('/api/sourcing/1/confirm', 'POST', {}, 403);
|
||||
for (const who of ['preparador', 'revisor', 'consulta']) {
|
||||
const origin = await clients[who]('/api/internal-requisitions/1');
|
||||
assert.equal(origin.record.version, 3);
|
||||
assert.equal(origin.record.total_minor, 10000);
|
||||
assert.equal(origin.history.length, 3);
|
||||
assert(origin.canSourcing);
|
||||
await clients[who]('/purchasing/sourcing/1');
|
||||
}
|
||||
checks.push(
|
||||
'Existing request reused with version 3 and unchanged three-event history',
|
||||
);
|
||||
checks.push(
|
||||
'Three selected synthetic suppliers, three quotes and one eligible evaluation per quote',
|
||||
);
|
||||
checks.push(
|
||||
'Comparison and award proposal remain blocked without second eligible evaluator',
|
||||
);
|
||||
checks.push(
|
||||
'Quoted amount differing from reserved amount is signalled without a budget movement',
|
||||
);
|
||||
checks.push(
|
||||
'Consulta retains full sourcing read and no preparation/evaluation/proposal/confirmation',
|
||||
);
|
||||
checks.push(
|
||||
'No persistent identity has award-confirmation right; no award created',
|
||||
);
|
||||
checks.push(
|
||||
'Protected sourcing screen is accessible to all three existing profiles',
|
||||
);
|
||||
const proof = {
|
||||
passed: true,
|
||||
url: 'http://127.0.0.1:8039',
|
||||
scope: '1:1:1',
|
||||
request_id: 1,
|
||||
checks,
|
||||
confirmation_completed: false,
|
||||
owner_decision_no_fourth_account: true,
|
||||
visual_review: false,
|
||||
checked_at: new Date().toISOString(),
|
||||
};
|
||||
fs.writeFileSync(
|
||||
'C:/laragon/www/compras/docs/proofs/sgf-sourcing-demo-http.json',
|
||||
JSON.stringify(proof, null, 2),
|
||||
);
|
||||
console.log(JSON.stringify(proof));
|
||||
|
||||
+157
-58
@@ -1,65 +1,164 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Identity\Services\Audit;
|
||||
use App\Modules\Identity\Services\Permissions;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
use App\Modules\Identity\Services\Permissions;
|
||||
use App\Modules\Identity\Services\Audit;
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
use Tempo\Purchasing\SgfSourcing\Schema;
|
||||
$root=dirname(__DIR__);$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';$recovery=dirname($host).'/private/sourcing-recovery';
|
||||
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
|
||||
try{
|
||||
$db=DB::connection();$identity=$db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
|
||||
if(str_replace('\\','/',$app->basePath())!==$host||$identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||(int)$identity->port!==55439||$identity->cluster!=='sgf_modular_regression_2576427d1939'||config('app.url')!=='http://127.0.0.1:8039')throw new RuntimeException('Wrong persistent synthetic demonstration');
|
||||
app(Permissions::class)->require(1,1,1,'access.manage');
|
||||
$candidate=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
if(!class_exists(Schema::class))require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$hash=function(string $table)use($db){return hash('sha256',json_encode($db->table($table)->orderBy('id')->get(),JSON_THROW_ON_ERROR));};
|
||||
$action=$argv[1]??'';
|
||||
if($action==='prepare'){
|
||||
if(is_dir($recovery))throw new RuntimeException('Recovery exists: do not overwrite');
|
||||
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'),true);if(!$proof['passed']||!$proof['persistent_demo_unchanged']||!($proof['recovery']['data_schema_restore_verified']??false)||$proof['setup']['deployment']['deployment_id']!==substr($candidate['archive']['manifest_sha256'],0,24))throw new RuntimeException('Current candidate needs accepted isolation/recovery proof');
|
||||
if($db->table('users')->count()!==3)throw new RuntimeException('Unexpected accounts: reconcile before proceeding');
|
||||
mkdir($recovery,0700,true);$cfg=$db->getConfig();(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe','--format=custom','--file='.$recovery.'/before.dump','--dbname='.$identity->db],null,['PGHOST'=>'127.0.0.1','PGPORT'=>'55439','PGUSER'=>$identity->role,'PGPASSWORD'=>$cfg['password']],null,90))->mustRun();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--list',$recovery.'/before.dump']))->mustRun();
|
||||
$baseline=['candidate'=>$candidate,'identity'=>$identity,'backup_sha256'=>hash_file('sha256',$recovery.'/before.dump'),'users'=>$hash('users'),'requests'=>$hash('ir_requests'),'budget'=>$hash('cb_budget_entries'),'consumption'=>$hash('cb_budget_consumptions'),'grants'=>$db->table('permission_grants')->orderBy('id')->get()->all(),'pointer_sha256'=>hash_file('sha256',$host.'/packages/purchasing/current.json')];
|
||||
file_put_contents($recovery.'/baseline.json',json_encode($baseline,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode(['prepared'=>true,'identity'=>$identity,'backup_sha256'=>$baseline['backup_sha256']]);
|
||||
}elseif($action==='apply'){
|
||||
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
foreach(['users'=>'users','requests'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)if($baseline[$key]!==$hash($table))throw new RuntimeException('Baseline changed: '.$table);
|
||||
if($baseline['candidate']['archive']['manifest_sha256']!==$candidate['archive']['manifest_sha256']||!hash_equals($baseline['backup_sha256'],hash_file('sha256',$recovery.'/before.dump')))throw new RuntimeException('Candidate/backup changed');
|
||||
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance');file_put_contents($host.'/storage/framework/down','{}');
|
||||
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true);$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true);$next=json_decode(file_get_contents($candidate['directory'].'/manifest.json'),true);
|
||||
$migration=Schema::migrate($db,$baseline['backup_sha256'],'Owner-confirmed synthetic sourcing 8039');
|
||||
$receipt=['host'=>$host,'from_manifest_sha256'=>$current['manifest_sha256'],'to_manifest_sha256'=>$candidate['archive']['manifest_sha256'],'schema_verified'=>Schema::compatible($db),'changes'=>[]];
|
||||
foreach($next['support_files'] as $file=>$sha)if(($old['support_files'][$file]??null)!==$sha)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$sha];
|
||||
file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$candidate['archive']['manifest_sha256'].'.json',json_encode($receipt));
|
||||
$deploy=new CodeDeployment($host);$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Owner-confirmed synthetic sourcing 8039',true);file_put_contents($recovery.'/applied.json',json_encode($applied,JSON_PRETTY_PRINT));
|
||||
$db->transaction(function()use($db){
|
||||
foreach([1=>['purchasing_sourcing.prepare'],2=>['purchasing_sourcing.evaluate','purchasing_sourcing.propose']] as $id=>$rights)foreach($rights as $right){
|
||||
$scope=['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'permission'=>$right];$inserted=$db->table('permission_grants')->insertOrIgnore($scope+['created_at'=>now(),'updated_at'=>now()]);
|
||||
if($inserted)Audit::record('access.granted',1,1,1,1,$id,details:['permission'=>$right,'reason'=>'Owner explicitly authorised exact sourcing map; no fourth persistent account.']);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
|
||||
$recovery = dirname($host).'/private/sourcing-recovery';
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
try {
|
||||
$db = DB::connection();
|
||||
$identity = $db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
|
||||
if (str_replace('\\', '/', $app->basePath()) !== $host || $identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || (int) $identity->port !== 55439 || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || config('app.url') !== 'http://127.0.0.1:8039') {
|
||||
throw new RuntimeException('Wrong persistent synthetic demonstration');
|
||||
}
|
||||
foreach(['A','B','C'] as $letter)$db->table('ss_suppliers')->insertOrIgnore(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'reference'=>'SOURCING-DEMO-'.$letter,'payload'=>json_encode(['name'=>'Fornecedor sintético '.$letter,'active'=>true,'blocked'=>false,'review_until'=>'2027-12-31','version'=>1,'synthetic_only'=>true]),'created_at'=>now()]);
|
||||
});
|
||||
file_put_contents($host.'/config/purchasing-sourcing.php','<?php return ["enabled"=>true];');unlink($host.'/storage/framework/down');echo json_encode(['applied'=>true,'deployment'=>$applied,'schema'=>$migration,'persistent_accounts_created'=>false,'grants_added'=>3,'confirmation_blocked_without_independent_identity'=>true]);
|
||||
}elseif($action==='apply-code'){
|
||||
if(!Schema::compatible($db))throw new RuntimeException('Code-only update requires the existing compatible sourcing schema');
|
||||
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'),true);if(!$proof['passed']||$proof['setup']['deployment']['deployment_id']!==substr($candidate['archive']['manifest_sha256'],0,24))throw new RuntimeException('Candidate proof mismatch');
|
||||
$before=[];foreach([...Schema::TABLES,'ir_requests','cb_budget_entries','cb_budget_consumptions','permission_grants','users'] as $table)$before[$table]=$hash($table);
|
||||
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance');
|
||||
$deploy=new CodeDeployment($host);$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);
|
||||
file_put_contents($recovery.'/before-final-code.json',json_encode(['candidate'=>$candidate,'data_hashes'=>$before,'plan'=>$plan],JSON_PRETTY_PRINT));file_put_contents($host.'/storage/framework/down','{}');
|
||||
$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Authorised sourcing final code refinement',true);
|
||||
foreach($before as $table=>$expected)if($hash($table)!==$expected)throw new RuntimeException('Code update changed data: '.$table);
|
||||
file_put_contents($recovery.'/final-code.json',json_encode($applied,JSON_PRETTY_PRINT));unlink($host.'/storage/framework/down');echo json_encode(['applied'=>true,'code_only'=>true,'deployment'=>$applied,'data_preserved'=>true,'schema_changed'=>false,'rights_changed'=>false]);
|
||||
}elseif($action==='verify'){
|
||||
if(hash_file('sha256',$host.'/packages/internal-requisitions/manifest.json')!==$candidate['archive']['manifest_sha256'])throw new RuntimeException('Installed candidate does not match the delivery report');
|
||||
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);foreach(['users'=>'users','requests'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)if($baseline[$key]!==$hash($table))throw new RuntimeException('Protected baseline changed: '.$table);
|
||||
$current=$db->table('permission_grants')->orderBy('id')->get()->keyBy('id');foreach($baseline['grants'] as $old)if((array)$current[$old['id']]!=$old)throw new RuntimeException('Previous grant changed');
|
||||
$new=$current->except(array_column($baseline['grants'],'id'))->values()->all();if(count($new)!==3)throw new RuntimeException('Expected exactly three authorised new rights');foreach($new as $g)if([$g->tenant_id,$g->company_id,$g->unit_id]!==[1,1,1]||!in_array([$g->user_id,$g->permission],[[1,'purchasing_sourcing.prepare'],[2,'purchasing_sourcing.evaluate'],[2,'purchasing_sourcing.propose']],true))throw new RuntimeException('Unapproved grant');
|
||||
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed');
|
||||
$process=$db->table('ss_processes')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'request_id'=>1])->first();$state=json_decode($process->payload,true);if($state['confirmed']!==null||$state['proposals']!==[])throw new RuntimeException('Incomplete comparison must not be awarded');
|
||||
$report=['passed'=>true,'identity'=>$identity,'scope'=>'1:1:1','candidate'=>$candidate,'protected_users_requisition_reservation_consumption_unchanged'=>true,'previous_grants_preserved'=>true,'new_grants'=>$new,'persistent_accounts_created'=>false,'proposals'=>0,'confirmed'=>false,'suppliers_selected'=>count($state['suppliers']),'quotations'=>count($state['quotes']),'pending'=>'Second eligible evaluator and independent confirmer absent; no account created by owner decision.','backup_sha256'=>$baseline['backup_sha256'],'recovery_directory'=>$recovery,'checked_at'=>gmdate('c')];file_put_contents($root.'/docs/proofs/sgf-sourcing-demo.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT);
|
||||
}else throw new RuntimeException('Use prepare/apply/verify');
|
||||
}catch(Throwable $e){fwrite(STDERR,$e->getMessage()."\n");exit(1);}
|
||||
app(Permissions::class)->require(1, 1, 1, 'access.manage');
|
||||
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! class_exists(Schema::class)) {
|
||||
require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';
|
||||
}require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$hash = function (string $table) use ($db) {
|
||||
return hash('sha256', json_encode($db->table($table)->orderBy('id')->get(), JSON_THROW_ON_ERROR));
|
||||
};
|
||||
$action = $argv[1] ?? '';
|
||||
if ($action === 'prepare') {
|
||||
if (is_dir($recovery)) {
|
||||
throw new RuntimeException('Recovery exists: do not overwrite');
|
||||
}
|
||||
$proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'), true);
|
||||
if (! $proof['passed'] || ! $proof['persistent_demo_unchanged'] || ! ($proof['recovery']['data_schema_restore_verified'] ?? false) || $proof['setup']['deployment']['deployment_id'] !== substr($candidate['archive']['manifest_sha256'], 0, 24)) {
|
||||
throw new RuntimeException('Current candidate needs accepted isolation/recovery proof');
|
||||
}
|
||||
if ($db->table('users')->count() !== 3) {
|
||||
throw new RuntimeException('Unexpected accounts: reconcile before proceeding');
|
||||
}
|
||||
mkdir($recovery, 0700, true);
|
||||
$cfg = $db->getConfig();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90))->mustRun();
|
||||
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
|
||||
$baseline = ['candidate' => $candidate, 'identity' => $identity, 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'users' => $hash('users'), 'requests' => $hash('ir_requests'), 'budget' => $hash('cb_budget_entries'), 'consumption' => $hash('cb_budget_consumptions'), 'grants' => $db->table('permission_grants')->orderBy('id')->get()->all(), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json')];
|
||||
file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['prepared' => true, 'identity' => $identity, 'backup_sha256' => $baseline['backup_sha256']]);
|
||||
} elseif ($action === 'apply') {
|
||||
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
foreach (['users' => 'users', 'requests' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
|
||||
if ($baseline[$key] !== $hash($table)) {
|
||||
throw new RuntimeException('Baseline changed: '.$table);
|
||||
}
|
||||
}
|
||||
if ($baseline['candidate']['archive']['manifest_sha256'] !== $candidate['archive']['manifest_sha256'] || ! hash_equals($baseline['backup_sha256'], hash_file('sha256', $recovery.'/before.dump'))) {
|
||||
throw new RuntimeException('Candidate/backup changed');
|
||||
}
|
||||
if (is_file($host.'/storage/framework/down')) {
|
||||
throw new RuntimeException('Unexpected prior maintenance');
|
||||
}file_put_contents($host.'/storage/framework/down', '{}');
|
||||
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true);
|
||||
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true);
|
||||
$next = json_decode(file_get_contents($candidate['directory'].'/manifest.json'), true);
|
||||
$migration = Schema::migrate($db, $baseline['backup_sha256'], 'Owner-confirmed synthetic sourcing 8039');
|
||||
$receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'schema_verified' => Schema::compatible($db), 'changes' => []];
|
||||
foreach ($next['support_files'] as $file => $sha) {
|
||||
if (($old['support_files'][$file] ?? null) !== $sha) {
|
||||
$receipt['changes'][$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $sha];
|
||||
}
|
||||
}
|
||||
file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$candidate['archive']['manifest_sha256'].'.json', json_encode($receipt));
|
||||
$deploy = new CodeDeployment($host);
|
||||
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Owner-confirmed synthetic sourcing 8039', true);
|
||||
file_put_contents($recovery.'/applied.json', json_encode($applied, JSON_PRETTY_PRINT));
|
||||
$db->transaction(function () use ($db) {
|
||||
foreach ([1 => ['purchasing_sourcing.prepare'], 2 => ['purchasing_sourcing.evaluate', 'purchasing_sourcing.propose']] as $id => $rights) {
|
||||
foreach ($rights as $right) {
|
||||
$scope = ['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'permission' => $right];
|
||||
$inserted = $db->table('permission_grants')->insertOrIgnore($scope + ['created_at' => now(), 'updated_at' => now()]);
|
||||
if ($inserted) {
|
||||
Audit::record('access.granted', 1, 1, 1, 1, $id, details: ['permission' => $right, 'reason' => 'Owner explicitly authorised exact sourcing map; no fourth persistent account.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['A', 'B', 'C'] as $letter) {
|
||||
$db->table('ss_suppliers')->insertOrIgnore(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'reference' => 'SOURCING-DEMO-'.$letter, 'payload' => json_encode(['name' => 'Fornecedor sintético '.$letter, 'active' => true, 'blocked' => false, 'review_until' => '2027-12-31', 'version' => 1, 'synthetic_only' => true]), 'created_at' => now()]);
|
||||
}
|
||||
});
|
||||
file_put_contents($host.'/config/purchasing-sourcing.php', '<?php return ["enabled"=>true];');
|
||||
unlink($host.'/storage/framework/down');
|
||||
echo json_encode(['applied' => true, 'deployment' => $applied, 'schema' => $migration, 'persistent_accounts_created' => false, 'grants_added' => 3, 'confirmation_blocked_without_independent_identity' => true]);
|
||||
} elseif ($action === 'apply-code') {
|
||||
if (! Schema::compatible($db)) {
|
||||
throw new RuntimeException('Code-only update requires the existing compatible sourcing schema');
|
||||
}
|
||||
$proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'), true);
|
||||
if (! $proof['passed'] || $proof['setup']['deployment']['deployment_id'] !== substr($candidate['archive']['manifest_sha256'], 0, 24)) {
|
||||
throw new RuntimeException('Candidate proof mismatch');
|
||||
}
|
||||
$before = [];
|
||||
foreach ([...Schema::TABLES, 'ir_requests', 'cb_budget_entries', 'cb_budget_consumptions', 'permission_grants', 'users'] as $table) {
|
||||
$before[$table] = $hash($table);
|
||||
}
|
||||
if (is_file($host.'/storage/framework/down')) {
|
||||
throw new RuntimeException('Unexpected prior maintenance');
|
||||
}
|
||||
$deploy = new CodeDeployment($host);
|
||||
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
file_put_contents($recovery.'/before-final-code.json', json_encode(['candidate' => $candidate, 'data_hashes' => $before, 'plan' => $plan], JSON_PRETTY_PRINT));
|
||||
file_put_contents($host.'/storage/framework/down', '{}');
|
||||
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised sourcing final code refinement', true);
|
||||
foreach ($before as $table => $expected) {
|
||||
if ($hash($table) !== $expected) {
|
||||
throw new RuntimeException('Code update changed data: '.$table);
|
||||
}
|
||||
}
|
||||
file_put_contents($recovery.'/final-code.json', json_encode($applied, JSON_PRETTY_PRINT));
|
||||
unlink($host.'/storage/framework/down');
|
||||
echo json_encode(['applied' => true, 'code_only' => true, 'deployment' => $applied, 'data_preserved' => true, 'schema_changed' => false, 'rights_changed' => false]);
|
||||
} elseif ($action === 'verify') {
|
||||
if (hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json') !== $candidate['archive']['manifest_sha256']) {
|
||||
throw new RuntimeException('Installed candidate does not match the delivery report');
|
||||
}
|
||||
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
foreach (['users' => 'users', 'requests' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
|
||||
if ($baseline[$key] !== $hash($table)) {
|
||||
throw new RuntimeException('Protected baseline changed: '.$table);
|
||||
}
|
||||
}
|
||||
$current = $db->table('permission_grants')->orderBy('id')->get()->keyBy('id');
|
||||
foreach ($baseline['grants'] as $old) {
|
||||
if ((array) $current[$old['id']] != $old) {
|
||||
throw new RuntimeException('Previous grant changed');
|
||||
}
|
||||
}
|
||||
$new = $current->except(array_column($baseline['grants'], 'id'))->values()->all();
|
||||
if (count($new) !== 3) {
|
||||
throw new RuntimeException('Expected exactly three authorised new rights');
|
||||
}foreach ($new as $g) {
|
||||
if ([$g->tenant_id, $g->company_id, $g->unit_id] !== [1, 1, 1] || ! in_array([$g->user_id, $g->permission], [[1, 'purchasing_sourcing.prepare'], [2, 'purchasing_sourcing.evaluate'], [2, 'purchasing_sourcing.propose']], true)) {
|
||||
throw new RuntimeException('Unapproved grant');
|
||||
}
|
||||
}
|
||||
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
|
||||
throw new RuntimeException('Pointer changed');
|
||||
}
|
||||
$process = $db->table('ss_processes')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'request_id' => 1])->first();
|
||||
$state = json_decode($process->payload, true);
|
||||
if ($state['confirmed'] !== null || $state['proposals'] !== []) {
|
||||
throw new RuntimeException('Incomplete comparison must not be awarded');
|
||||
}
|
||||
$report = ['passed' => true, 'identity' => $identity, 'scope' => '1:1:1', 'candidate' => $candidate, 'protected_users_requisition_reservation_consumption_unchanged' => true, 'previous_grants_preserved' => true, 'new_grants' => $new, 'persistent_accounts_created' => false, 'proposals' => 0, 'confirmed' => false, 'suppliers_selected' => count($state['suppliers']), 'quotations' => count($state['quotes']), 'pending' => 'Second eligible evaluator and independent confirmer absent; no account created by owner decision.', 'backup_sha256' => $baseline['backup_sha256'], 'recovery_directory' => $recovery, 'checked_at' => gmdate('c')];
|
||||
file_put_contents($root.'/docs/proofs/sgf-sourcing-demo.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($report,JSON_PRETTY_PRINT);
|
||||
} else {
|
||||
throw new RuntimeException('Use prepare/apply/verify');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
fwrite(STDERR,$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -1,31 +1,65 @@
|
||||
<?php
|
||||
|
||||
// Offline additive migration; no rights, credentials, contacts or activation are provisioned.
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Purchasing\Delivery\Installation;
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
use Tempo\Purchasing\Delivery\Installation;
|
||||
use Tempo\Purchasing\SgfSourcing\Schema;
|
||||
$root=dirname(__DIR__);$action=$argv[1]??'';$host=realpath($argv[2]??'');
|
||||
try{
|
||||
if(!$host||!in_array($action,['plan','migrate'],true))throw new RuntimeException('Usage: plan <host> | migrate <host> <target-sha> <backup-file> <backup-sha> <operator> <manifest-sha>');
|
||||
$host=str_replace('\\','/',$host);$manifestText=file_get_contents($root.'/manifest.json');$manifest=json_decode($manifestText,true,64,JSON_THROW_ON_ERROR);$manifestHash=hash('sha256',$manifestText);
|
||||
foreach($manifest['support_files'] as $file=>$hash)if(str_contains($file,'..')||!preg_match('~^[A-Za-z0-9_./-]+$~D',$file)||is_link($root.'/'.$file)||!hash_equals($hash,hash_file('sha256',$root.'/'.$file)))throw new RuntimeException('Bundle integrity failed');
|
||||
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
|
||||
if(!class_exists(Installation::class))require_once $root.'/integrations/sgf/operational/bootstrap.php';
|
||||
if(!class_exists(Schema::class))require_once $root.'/integrations/sgf/sourcing/Schema.php';
|
||||
require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$db=DB::connection();$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
(new CodeDeployment($host))->plan($host.'/packages/internal-requisitions',$current['manifest_sha256']);
|
||||
$plan=['target_sha256'=>Installation::target($db),'manifest_sha256'=>$manifestHash,'schema_changes'=>Schema::TABLES,'new_rights'=>Schema::RIGHTS,'grant_performed'=>false,'activated'=>false];
|
||||
if($action==='plan'){echo json_encode($plan,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);exit;}
|
||||
$backup=$argv[4]??'';$backupHash=$argv[5]??'';$operator=$argv[6]??'';
|
||||
if(!hash_equals($plan['target_sha256'],$argv[3]??'')||!hash_equals($manifestHash,$argv[7]??'')||!is_file($backup)||!hash_equals($backupHash,hash_file('sha256',$backup))||trim($operator)===''||!is_file($host.'/storage/framework/down'))throw new RuntimeException('Target, manifest, backup, operator and maintenance are required');
|
||||
(new Process([getenv('PG_RESTORE_BINARY')?:'pg_restore','--list',$backup],null,null,null,60))->mustRun();
|
||||
$result=Schema::migrate($db,$backupHash,$operator);
|
||||
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true,64,JSON_THROW_ON_ERROR);
|
||||
$receipt=['host'=>$host,'from_manifest_sha256'=>$current['manifest_sha256'],'to_manifest_sha256'=>$manifestHash,'schema_verified'=>Schema::compatible($db),'changes'=>[]];
|
||||
foreach($manifest['support_files'] as $file=>$hash)if(($old['support_files'][$file]??null)!==$hash)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$hash];
|
||||
file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json',json_encode($receipt,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result+['activated'=>false,'rights_granted'=>false],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
|
||||
}catch(Throwable $e){fwrite(STDERR,$e->getMessage()."\n");exit(1);}
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
$action = $argv[1] ?? '';
|
||||
$host = realpath($argv[2] ?? '');
|
||||
try {
|
||||
if (! $host || ! in_array($action, ['plan', 'migrate'], true)) {
|
||||
throw new RuntimeException('Usage: plan <host> | migrate <host> <target-sha> <backup-file> <backup-sha> <operator> <manifest-sha>');
|
||||
}
|
||||
$host = str_replace('\\', '/', $host);
|
||||
$manifestText = file_get_contents($root.'/manifest.json');
|
||||
$manifest = json_decode($manifestText, true, 64, JSON_THROW_ON_ERROR);
|
||||
$manifestHash = hash('sha256', $manifestText);
|
||||
foreach ($manifest['support_files'] as $file => $hash) {
|
||||
if (str_contains($file, '..') || ! preg_match('~^[A-Za-z0-9_./-]+$~D', $file) || is_link($root.'/'.$file) || ! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
|
||||
throw new RuntimeException('Bundle integrity failed');
|
||||
}
|
||||
}
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! class_exists(Installation::class)) {
|
||||
require_once $root.'/integrations/sgf/operational/bootstrap.php';
|
||||
}
|
||||
if (! class_exists(Schema::class)) {
|
||||
require_once $root.'/integrations/sgf/sourcing/Schema.php';
|
||||
}
|
||||
require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$db = DB::connection();
|
||||
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
(new CodeDeployment($host))->plan($host.'/packages/internal-requisitions', $current['manifest_sha256']);
|
||||
$plan = ['target_sha256' => Installation::target($db), 'manifest_sha256' => $manifestHash, 'schema_changes' => Schema::TABLES, 'new_rights' => Schema::RIGHTS, 'grant_performed' => false, 'activated' => false];
|
||||
if ($action === 'plan') {
|
||||
echo json_encode($plan, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
$backup = $argv[4] ?? '';
|
||||
$backupHash = $argv[5] ?? '';
|
||||
$operator = $argv[6] ?? '';
|
||||
if (! hash_equals($plan['target_sha256'], $argv[3] ?? '') || ! hash_equals($manifestHash, $argv[7] ?? '') || ! is_file($backup) || ! hash_equals($backupHash, hash_file('sha256', $backup)) || trim($operator) === '' || ! is_file($host.'/storage/framework/down')) {
|
||||
throw new RuntimeException('Target, manifest, backup, operator and maintenance are required');
|
||||
}
|
||||
(new Process([getenv('PG_RESTORE_BINARY') ?: 'pg_restore', '--list', $backup], null, null, null, 60))->mustRun();
|
||||
$result = Schema::migrate($db, $backupHash, $operator);
|
||||
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $manifestHash, 'schema_verified' => Schema::compatible($db), 'changes' => []];
|
||||
foreach ($manifest['support_files'] as $file => $hash) {
|
||||
if (($old['support_files'][$file] ?? null) !== $hash) {
|
||||
$receipt['changes'][$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $hash];
|
||||
}
|
||||
}
|
||||
file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json', json_encode($receipt, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode($result + ['activated' => false, 'rights_granted' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
} catch (Throwable $e) {
|
||||
fwrite(STDERR,$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -1,54 +1,448 @@
|
||||
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import {spawnSync,spawn} from 'node:child_process';import net from 'node:net';
|
||||
const repo='C:/laragon/www/compras',parent='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939',source=parent+'/development-app';
|
||||
const suffix=crypto.randomBytes(6).toString('hex'),database='sgf_sourcing_test_'+suffix,work=parent+'/private/sourcing-'+suffix,clone=work+'/app';
|
||||
const pg='C:/Program Files/PostgreSQL/17/bin',php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';fs.mkdirSync(work,{recursive:true});
|
||||
const envText=fs.readFileSync(source+'/.env','utf8');const env=Object.fromEntries([...envText.matchAll(/^([A-Z_]+)=(.*)$/gm)].map(m=>[m[1],m[2].trim().replace(/^['"]|['"]$/g,'')]));
|
||||
if(env.DB_DATABASE!=='sgf_modules_dev_2576427d1939'||env.DB_PORT!=='55439')throw Error('Wrong demonstration');
|
||||
const admin=fs.readFileSync(parent+'/private/admin-password.txt','utf8');
|
||||
function run(exe,args,options={}){const r=spawnSync(exe,args,{windowsHide:true,encoding:'utf8',maxBuffer:16*1024*1024,...options});if(r.status!==0)throw Error((r.stdout??'')+(r.stderr??''));return r.stdout;}
|
||||
const adminEnv={...process.env,PGPASSWORD:admin};const qaEnv={...process.env,PGPASSWORD:env.DB_PASSWORD};
|
||||
const fingerprintSQL="BEGIN READ ONLY;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM ir_requests t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM cb_budget_entries t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM users t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM permission_grants t;COMMIT;";
|
||||
const sourceFingerprint=(db=env.DB_DATABASE)=>run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',db,'-At','-v','ON_ERROR_STOP=1','-c',fingerprintSQL],{env:qaEnv});
|
||||
const before=sourceFingerprint();let created=false,server;
|
||||
try{
|
||||
const archivedBaseline=parent+'/private/sourcing-recovery/before.dump',useArchivedBaseline=fs.existsSync(archivedBaseline);
|
||||
if(useArchivedBaseline)fs.copyFileSync(archivedBaseline,work+'/before.dump');else run(pg+'/pg_dump.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',env.DB_DATABASE,'-Fc','-f',work+'/before.dump'],{env:qaEnv});
|
||||
const cluster=run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-At','-c',"select current_setting('cluster_name')"],{env:adminEnv}).trim();if(cluster!=='sgf_modular_regression_2576427d1939')throw Error('Wrong cluster');
|
||||
run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`],{env:adminEnv});created=true;
|
||||
run(pg+'/pg_restore.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'--no-owner','--no-privileges','--exit-on-error',work+'/before.dump'],{env:qaEnv});
|
||||
const copyBaselineFingerprint=sourceFingerprint(database);
|
||||
fs.mkdirSync(clone,{recursive:true});
|
||||
for(const dir of ['app','config','routes','bootstrap','scripts','packages','resources','public'])fs.cpSync(source+'/'+dir,clone+'/'+dir,{recursive:true});
|
||||
const guard=clone+'/app/Shared/Testing/TestingDatabaseGuard.php';fs.writeFileSync(guard,fs.readFileSync(guard,'utf8').replaceAll('sgf_modules_dev_2576427d1939',database)); // Exact physical identity adaptation; guards remain enabled.
|
||||
for(const file of ['artisan','composer.json','composer.lock'])fs.copyFileSync(source+'/'+file,clone+'/'+file);fs.cpSync(source+'/storage/app/private/module-deployments',clone+'/storage/app/private/module-deployments',{recursive:true});
|
||||
for(const d of ['storage/framework/sessions','storage/framework/views','storage/framework/cache/data','storage/logs'])fs.mkdirSync(clone+'/'+d,{recursive:true});
|
||||
fs.cpSync(source+'/vendor',clone+'/vendor',{recursive:true}); // Independent autoloader and dependencies; never mutate the demo vendor.
|
||||
for(const dir of fs.readdirSync(clone+'/storage/app/private/module-deployments',{withFileTypes:true})){if(!dir.isDirectory())continue;const file=clone+'/storage/app/private/module-deployments/'+dir.name+'/journal.json';if(fs.existsSync(file)){const j=JSON.parse(fs.readFileSync(file));j.host_identity=crypto.createHash('sha256').update(clone).digest('hex');fs.writeFileSync(file,JSON.stringify(j,null,2));}}
|
||||
if(useArchivedBaseline){
|
||||
const expectedBaseline=JSON.parse(fs.readFileSync(repo+'/docs/proofs/sgf-read-candidate.json','utf8')).archive.manifest_sha256;let hops=0;fs.writeFileSync(clone+'/storage/framework/down','{}');
|
||||
while(true){const current=JSON.parse(fs.readFileSync(clone+'/storage/app/private/module-deployments/current.json','utf8'));if(current.manifest_sha256===expectedBaseline)break;if(++hops>4)throw Error('Unexpected baseline ancestry');const rolled=JSON.parse(run(php,[repo+'/scripts/sgf-code-deploy.php','rollback',clone,current.deployment_id,'Disposable reproduction of pre-sourcing baseline','--offline'],{cwd:clone}));if(rolled.state!=='rolled-back')throw Error('Failed to reproduce prior code');}fs.unlinkSync(clone+'/storage/framework/down');
|
||||
}
|
||||
fs.writeFileSync(clone+'/.env',envText.replace(/^DB_DATABASE=.*$/m,'DB_DATABASE='+database).replace(/^APP_ENV=.*$/m,'APP_ENV=testing').replace(/^APP_DEBUG=.*$/m,'APP_DEBUG=false'));
|
||||
const vars={...process.env,SOURCING_CLONE:clone,SOURCING_DB:database,SOURCING_WORK:work,SOURCING_REPO:repo,APP_BASE_PATH:clone};
|
||||
const setup=run(php,[repo+'/tests/Support/sgf-sourcing-copy.php','setup'],{cwd:clone,env:vars});
|
||||
fs.writeFileSync(work+'/setup-output.txt',setup);let receipt;try{receipt=JSON.parse(setup);}catch{throw Error('Setup failed; private diagnostic '+work+'/setup-output.txt');}if(!receipt.passed)throw Error('Setup proof did not pass');
|
||||
const listener=net.createServer();await new Promise(r=>listener.listen(0,'127.0.0.1',r));const port=listener.address().port;await new Promise(r=>listener.close(r));
|
||||
server=spawn(php,['-S','127.0.0.1:'+port,'-t','public','scripts/router.php'],{cwd:clone,env:vars,windowsHide:true,stdio:['ignore',fs.openSync(work+'/web-out.log','a'),fs.openSync(work+'/web-error.log','a')]});
|
||||
await new Promise((resolve,reject)=>{let tries=0;const poll=()=>{const s=net.connect(port,'127.0.0.1');s.once('connect',()=>{s.destroy();resolve();});s.once('error',()=>{s.destroy();if(++tries>50)reject(Error('Test web host unavailable'));else setTimeout(poll,100);});};poll();});
|
||||
const http=run(process.execPath,[repo+'/tests/Support/sgf-sourcing-http.mjs'],{cwd:repo,env:{...vars,SOURCING_PORT:String(port)}});fs.writeFileSync(work+'/http-output.txt',http);
|
||||
const result=JSON.parse(http);if(!result.passed)throw Error('HTTP test failed');
|
||||
server.kill();await new Promise(r=>setTimeout(r,200));server=null;
|
||||
const recovered=JSON.parse(run(php,[repo+'/tests/Support/sgf-sourcing-copy.php','verify'],{cwd:clone,env:vars}));
|
||||
// Data/schema recovery is separate from the successful code rollback above.
|
||||
run(pg+'/pg_dump.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'-Fc','-f',work+'/confirmed-before-recovery.dump'],{env:qaEnv});
|
||||
run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,'-c',`DROP DATABASE ${database}`,'-c',`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`],{env:adminEnv});
|
||||
run(pg+'/pg_restore.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'--no-owner','--no-privileges','--exit-on-error',work+'/before.dump'],{env:qaEnv});
|
||||
if(sourceFingerprint(database)!==copyBaselineFingerprint)throw Error('Restored source request, reservation, accounts or grants diverged');
|
||||
const schemaRestored=run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'-At','-c',"SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'ss_%'; SELECT count(*) FROM sgc_installations WHERE module='sourcing'"],{env:qaEnv}).trim();if(schemaRestored!=='0\n0'&&schemaRestored!=='0\r\n0')throw Error('Schema recovery diverged');
|
||||
recovered.data_schema_restore_verified=true;recovered.pre_recovery_state_archived=true;recovered.restored_requests_reservations_accounts_grants_match=true;
|
||||
const proof={passed:true,database,work,setup:receipt,http:result,recovery:recovered,persistent_demo_unchanged:before===sourceFingerprint(),synthetic_copy_only:true,checked_at:new Date().toISOString()};if(!proof.persistent_demo_unchanged)throw Error('Original demo changed');
|
||||
fs.writeFileSync(repo+'/docs/proofs/sgf-sourcing-isolated.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof));
|
||||
}finally{
|
||||
if(server)server.kill();
|
||||
if(created)run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,'-c',`DROP DATABASE ${database}`],{env:adminEnv});
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawnSync, spawn } from 'node:child_process';
|
||||
import net from 'node:net';
|
||||
const repo = 'C:/laragon/www/compras',
|
||||
parent = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939',
|
||||
source = parent + '/development-app';
|
||||
const suffix = crypto.randomBytes(6).toString('hex'),
|
||||
database = 'sgf_sourcing_test_' + suffix,
|
||||
work = parent + '/private/sourcing-' + suffix,
|
||||
clone = work + '/app';
|
||||
const pg = 'C:/Program Files/PostgreSQL/17/bin',
|
||||
php = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
|
||||
fs.mkdirSync(work, { recursive: true });
|
||||
const envText = fs.readFileSync(source + '/.env', 'utf8');
|
||||
const env = Object.fromEntries(
|
||||
[...envText.matchAll(/^([A-Z_]+)=(.*)$/gm)].map((m) => [
|
||||
m[1],
|
||||
m[2].trim().replace(/^['"]|['"]$/g, ''),
|
||||
]),
|
||||
);
|
||||
if (
|
||||
env.DB_DATABASE !== 'sgf_modules_dev_2576427d1939' ||
|
||||
env.DB_PORT !== '55439'
|
||||
)
|
||||
throw Error('Wrong demonstration');
|
||||
const admin = fs.readFileSync(parent + '/private/admin-password.txt', 'utf8');
|
||||
function run(exe, args, options = {}) {
|
||||
const r = spawnSync(exe, args, {
|
||||
windowsHide: true,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
...options,
|
||||
});
|
||||
if (r.status !== 0) throw Error((r.stdout ?? '') + (r.stderr ?? ''));
|
||||
return r.stdout;
|
||||
}
|
||||
const adminEnv = { ...process.env, PGPASSWORD: admin };
|
||||
const qaEnv = { ...process.env, PGPASSWORD: env.DB_PASSWORD };
|
||||
const fingerprintSQL =
|
||||
"BEGIN READ ONLY;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM ir_requests t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM cb_budget_entries t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM users t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM permission_grants t;COMMIT;";
|
||||
const sourceFingerprint = (db = env.DB_DATABASE) =>
|
||||
run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
db,
|
||||
'-At',
|
||||
'-v',
|
||||
'ON_ERROR_STOP=1',
|
||||
'-c',
|
||||
fingerprintSQL,
|
||||
],
|
||||
{ env: qaEnv },
|
||||
);
|
||||
const before = sourceFingerprint();
|
||||
let created = false,
|
||||
server;
|
||||
try {
|
||||
const archivedBaseline = parent + '/private/sourcing-recovery/before.dump',
|
||||
useArchivedBaseline = fs.existsSync(archivedBaseline);
|
||||
if (useArchivedBaseline)
|
||||
fs.copyFileSync(archivedBaseline, work + '/before.dump');
|
||||
else
|
||||
run(
|
||||
pg + '/pg_dump.exe',
|
||||
[
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
env.DB_DATABASE,
|
||||
'-Fc',
|
||||
'-f',
|
||||
work + '/before.dump',
|
||||
],
|
||||
{ env: qaEnv },
|
||||
);
|
||||
const cluster = run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
'sgf_regression_owner',
|
||||
'-d',
|
||||
'postgres',
|
||||
'-At',
|
||||
'-c',
|
||||
"select current_setting('cluster_name')",
|
||||
],
|
||||
{ env: adminEnv },
|
||||
).trim();
|
||||
if (cluster !== 'sgf_modular_regression_2576427d1939')
|
||||
throw Error('Wrong cluster');
|
||||
run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
'sgf_regression_owner',
|
||||
'-d',
|
||||
'postgres',
|
||||
'-v',
|
||||
'ON_ERROR_STOP=1',
|
||||
'-c',
|
||||
`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`,
|
||||
],
|
||||
{ env: adminEnv },
|
||||
);
|
||||
created = true;
|
||||
run(
|
||||
pg + '/pg_restore.exe',
|
||||
[
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
database,
|
||||
'--no-owner',
|
||||
'--no-privileges',
|
||||
'--exit-on-error',
|
||||
work + '/before.dump',
|
||||
],
|
||||
{ env: qaEnv },
|
||||
);
|
||||
const copyBaselineFingerprint = sourceFingerprint(database);
|
||||
fs.mkdirSync(clone, { recursive: true });
|
||||
for (const dir of [
|
||||
'app',
|
||||
'config',
|
||||
'routes',
|
||||
'bootstrap',
|
||||
'scripts',
|
||||
'packages',
|
||||
'resources',
|
||||
'public',
|
||||
])
|
||||
fs.cpSync(source + '/' + dir, clone + '/' + dir, { recursive: true });
|
||||
const guard = clone + '/app/Shared/Testing/TestingDatabaseGuard.php';
|
||||
fs.writeFileSync(
|
||||
guard,
|
||||
fs
|
||||
.readFileSync(guard, 'utf8')
|
||||
.replaceAll('sgf_modules_dev_2576427d1939', database),
|
||||
); // Exact physical identity adaptation; guards remain enabled.
|
||||
for (const file of ['artisan', 'composer.json', 'composer.lock'])
|
||||
fs.copyFileSync(source + '/' + file, clone + '/' + file);
|
||||
fs.cpSync(
|
||||
source + '/storage/app/private/module-deployments',
|
||||
clone + '/storage/app/private/module-deployments',
|
||||
{ recursive: true },
|
||||
);
|
||||
for (const d of [
|
||||
'storage/framework/sessions',
|
||||
'storage/framework/views',
|
||||
'storage/framework/cache/data',
|
||||
'storage/logs',
|
||||
])
|
||||
fs.mkdirSync(clone + '/' + d, { recursive: true });
|
||||
fs.cpSync(source + '/vendor', clone + '/vendor', { recursive: true }); // Independent autoloader and dependencies; never mutate the demo vendor.
|
||||
for (const dir of fs.readdirSync(
|
||||
clone + '/storage/app/private/module-deployments',
|
||||
{ withFileTypes: true },
|
||||
)) {
|
||||
if (!dir.isDirectory()) continue;
|
||||
const file =
|
||||
clone +
|
||||
'/storage/app/private/module-deployments/' +
|
||||
dir.name +
|
||||
'/journal.json';
|
||||
if (fs.existsSync(file)) {
|
||||
const j = JSON.parse(fs.readFileSync(file));
|
||||
j.host_identity = crypto
|
||||
.createHash('sha256')
|
||||
.update(clone)
|
||||
.digest('hex');
|
||||
fs.writeFileSync(file, JSON.stringify(j, null, 2));
|
||||
}
|
||||
}
|
||||
if (useArchivedBaseline) {
|
||||
const expectedBaseline = JSON.parse(
|
||||
fs.readFileSync(
|
||||
repo + '/docs/proofs/sgf-read-candidate.json',
|
||||
'utf8',
|
||||
),
|
||||
).archive.manifest_sha256;
|
||||
let hops = 0;
|
||||
fs.writeFileSync(clone + '/storage/framework/down', '{}');
|
||||
while (true) {
|
||||
const current = JSON.parse(
|
||||
fs.readFileSync(
|
||||
clone +
|
||||
'/storage/app/private/module-deployments/current.json',
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
if (current.manifest_sha256 === expectedBaseline) break;
|
||||
if (++hops > 4) throw Error('Unexpected baseline ancestry');
|
||||
const rolled = JSON.parse(
|
||||
run(
|
||||
php,
|
||||
[
|
||||
repo + '/scripts/sgf-code-deploy.php',
|
||||
'rollback',
|
||||
clone,
|
||||
current.deployment_id,
|
||||
'Disposable reproduction of pre-sourcing baseline',
|
||||
'--offline',
|
||||
],
|
||||
{ cwd: clone },
|
||||
),
|
||||
);
|
||||
if (rolled.state !== 'rolled-back')
|
||||
throw Error('Failed to reproduce prior code');
|
||||
}
|
||||
fs.unlinkSync(clone + '/storage/framework/down');
|
||||
}
|
||||
fs.writeFileSync(
|
||||
clone + '/.env',
|
||||
envText
|
||||
.replace(/^DB_DATABASE=.*$/m, 'DB_DATABASE=' + database)
|
||||
.replace(/^APP_ENV=.*$/m, 'APP_ENV=testing')
|
||||
.replace(/^APP_DEBUG=.*$/m, 'APP_DEBUG=false'),
|
||||
);
|
||||
const vars = {
|
||||
...process.env,
|
||||
SOURCING_CLONE: clone,
|
||||
SOURCING_DB: database,
|
||||
SOURCING_WORK: work,
|
||||
SOURCING_REPO: repo,
|
||||
APP_BASE_PATH: clone,
|
||||
};
|
||||
const setup = run(
|
||||
php,
|
||||
[repo + '/tests/Support/sgf-sourcing-copy.php', 'setup'],
|
||||
{ cwd: clone, env: vars },
|
||||
);
|
||||
fs.writeFileSync(work + '/setup-output.txt', setup);
|
||||
let receipt;
|
||||
try {
|
||||
receipt = JSON.parse(setup);
|
||||
} catch {
|
||||
throw Error(
|
||||
'Setup failed; private diagnostic ' + work + '/setup-output.txt',
|
||||
);
|
||||
}
|
||||
if (!receipt.passed) throw Error('Setup proof did not pass');
|
||||
const listener = net.createServer();
|
||||
await new Promise((r) => listener.listen(0, '127.0.0.1', r));
|
||||
const port = listener.address().port;
|
||||
await new Promise((r) => listener.close(r));
|
||||
server = spawn(
|
||||
php,
|
||||
['-S', '127.0.0.1:' + port, '-t', 'public', 'scripts/router.php'],
|
||||
{
|
||||
cwd: clone,
|
||||
env: vars,
|
||||
windowsHide: true,
|
||||
stdio: [
|
||||
'ignore',
|
||||
fs.openSync(work + '/web-out.log', 'a'),
|
||||
fs.openSync(work + '/web-error.log', 'a'),
|
||||
],
|
||||
},
|
||||
);
|
||||
await new Promise((resolve, reject) => {
|
||||
let tries = 0;
|
||||
const poll = () => {
|
||||
const s = net.connect(port, '127.0.0.1');
|
||||
s.once('connect', () => {
|
||||
s.destroy();
|
||||
resolve();
|
||||
});
|
||||
s.once('error', () => {
|
||||
s.destroy();
|
||||
if (++tries > 50) reject(Error('Test web host unavailable'));
|
||||
else setTimeout(poll, 100);
|
||||
});
|
||||
};
|
||||
poll();
|
||||
});
|
||||
const http = run(
|
||||
process.execPath,
|
||||
[repo + '/tests/Support/sgf-sourcing-http.mjs'],
|
||||
{ cwd: repo, env: { ...vars, SOURCING_PORT: String(port) } },
|
||||
);
|
||||
fs.writeFileSync(work + '/http-output.txt', http);
|
||||
const result = JSON.parse(http);
|
||||
if (!result.passed) throw Error('HTTP test failed');
|
||||
server.kill();
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
server = null;
|
||||
const recovered = JSON.parse(
|
||||
run(php, [repo + '/tests/Support/sgf-sourcing-copy.php', 'verify'], {
|
||||
cwd: clone,
|
||||
env: vars,
|
||||
}),
|
||||
);
|
||||
// Data/schema recovery is separate from the successful code rollback above.
|
||||
run(
|
||||
pg + '/pg_dump.exe',
|
||||
[
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
database,
|
||||
'-Fc',
|
||||
'-f',
|
||||
work + '/confirmed-before-recovery.dump',
|
||||
],
|
||||
{ env: qaEnv },
|
||||
);
|
||||
run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
'sgf_regression_owner',
|
||||
'-d',
|
||||
'postgres',
|
||||
'-v',
|
||||
'ON_ERROR_STOP=1',
|
||||
'-c',
|
||||
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,
|
||||
'-c',
|
||||
`DROP DATABASE ${database}`,
|
||||
'-c',
|
||||
`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`,
|
||||
],
|
||||
{ env: adminEnv },
|
||||
);
|
||||
run(
|
||||
pg + '/pg_restore.exe',
|
||||
[
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
database,
|
||||
'--no-owner',
|
||||
'--no-privileges',
|
||||
'--exit-on-error',
|
||||
work + '/before.dump',
|
||||
],
|
||||
{ env: qaEnv },
|
||||
);
|
||||
if (sourceFingerprint(database) !== copyBaselineFingerprint)
|
||||
throw Error(
|
||||
'Restored source request, reservation, accounts or grants diverged',
|
||||
);
|
||||
const schemaRestored = run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
env.DB_USERNAME,
|
||||
'-d',
|
||||
database,
|
||||
'-At',
|
||||
'-c',
|
||||
"SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'ss_%'; SELECT count(*) FROM sgc_installations WHERE module='sourcing'",
|
||||
],
|
||||
{ env: qaEnv },
|
||||
).trim();
|
||||
if (schemaRestored !== '0\n0' && schemaRestored !== '0\r\n0')
|
||||
throw Error('Schema recovery diverged');
|
||||
recovered.data_schema_restore_verified = true;
|
||||
recovered.pre_recovery_state_archived = true;
|
||||
recovered.restored_requests_reservations_accounts_grants_match = true;
|
||||
const proof = {
|
||||
passed: true,
|
||||
database,
|
||||
work,
|
||||
setup: receipt,
|
||||
http: result,
|
||||
recovery: recovered,
|
||||
persistent_demo_unchanged: before === sourceFingerprint(),
|
||||
synthetic_copy_only: true,
|
||||
checked_at: new Date().toISOString(),
|
||||
};
|
||||
if (!proof.persistent_demo_unchanged) throw Error('Original demo changed');
|
||||
fs.writeFileSync(
|
||||
repo + '/docs/proofs/sgf-sourcing-isolated.json',
|
||||
JSON.stringify(proof, null, 2),
|
||||
);
|
||||
console.log(JSON.stringify(proof));
|
||||
} finally {
|
||||
if (server) server.kill();
|
||||
if (created)
|
||||
run(
|
||||
pg + '/psql.exe',
|
||||
[
|
||||
'-X',
|
||||
'-h',
|
||||
'127.0.0.1',
|
||||
'-p',
|
||||
'55439',
|
||||
'-U',
|
||||
'sgf_regression_owner',
|
||||
'-d',
|
||||
'postgres',
|
||||
'-v',
|
||||
'ON_ERROR_STOP=1',
|
||||
'-c',
|
||||
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,
|
||||
'-c',
|
||||
`DROP DATABASE ${database}`,
|
||||
],
|
||||
{ env: adminEnv },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,48 +2,138 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
|
||||
export async function verifyConfigurationConcurrency(workspace, root, database, environment) {
|
||||
if (environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false') throw Error('Verified standalone configuration required');
|
||||
export async function verifyConfigurationConcurrency(
|
||||
workspace,
|
||||
root,
|
||||
database,
|
||||
environment,
|
||||
) {
|
||||
if (
|
||||
environment.COMPRAS_RUNTIME_ENABLED !== 'true' ||
|
||||
environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false'
|
||||
)
|
||||
throw Error('Verified standalone configuration required');
|
||||
const worker = (mode, round) => {
|
||||
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode, round], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment,
|
||||
});
|
||||
if (result.status !== 0) throw Error('Standalone configuration fixture/read worker failed');
|
||||
const result = spawnSync(
|
||||
'php',
|
||||
[
|
||||
'tests/Support/standalone-runtime-worker.php',
|
||||
database,
|
||||
mode,
|
||||
round,
|
||||
],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
encoding: 'utf8',
|
||||
env: environment,
|
||||
},
|
||||
);
|
||||
if (result.status !== 0)
|
||||
throw Error('Standalone configuration fixture/read worker failed');
|
||||
return JSON.parse(result.stdout.trim());
|
||||
};
|
||||
for (const round of ['same', 'different']) {
|
||||
if (worker('prepare-configuration-race', round).prepared !== true) throw Error('Race fixture not prepared');
|
||||
const children = [0, 1].map(index => {
|
||||
const child = spawn('php', ['tests/Support/standalone-runtime-worker.php', database, 'run-configuration-race', round, String(index)], {
|
||||
cwd: workspace, windowsHide: true, env: environment,
|
||||
});
|
||||
if (worker('prepare-configuration-race', round).prepared !== true)
|
||||
throw Error('Race fixture not prepared');
|
||||
const children = [0, 1].map((index) => {
|
||||
const child = spawn(
|
||||
'php',
|
||||
[
|
||||
'tests/Support/standalone-runtime-worker.php',
|
||||
database,
|
||||
'run-configuration-race',
|
||||
round,
|
||||
String(index),
|
||||
],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
env: environment,
|
||||
},
|
||||
);
|
||||
let output = '';
|
||||
child.stdout.on('data', chunk => { output += chunk.toString(); });
|
||||
child.stdout.on('data', (chunk) => {
|
||||
output += chunk.toString();
|
||||
});
|
||||
child.stderr.on('data', () => {});
|
||||
const complete = new Promise(resolve => child.on('close', code => resolve({ code, output })));
|
||||
const complete = new Promise((resolve) =>
|
||||
child.on('close', (code) => resolve({ code, output })),
|
||||
);
|
||||
return { child, complete };
|
||||
});
|
||||
try {
|
||||
const until = Date.now() + 15000;
|
||||
while (![0, 1].every(index => fs.existsSync(path.join(root, `configuration-${round}-${index}.ready`)))) {
|
||||
if (Date.now() > until || children.some(({ child }) => child.exitCode !== null)) throw Error('Concurrent candidate workers did not reach the gate');
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
while (
|
||||
![0, 1].every((index) =>
|
||||
fs.existsSync(
|
||||
path.join(
|
||||
root,
|
||||
`configuration-${round}-${index}.ready`,
|
||||
),
|
||||
),
|
||||
)
|
||||
) {
|
||||
if (
|
||||
Date.now() > until ||
|
||||
children.some(({ child }) => child.exitCode !== null)
|
||||
)
|
||||
throw Error(
|
||||
'Concurrent candidate workers did not reach the gate',
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
fs.writeFileSync(path.join(root, `configuration-${round}.go`), 'go', { flag: 'wx' });
|
||||
fs.writeFileSync(
|
||||
path.join(root, `configuration-${round}.go`),
|
||||
'go',
|
||||
{ flag: 'wx' },
|
||||
);
|
||||
const results = await Promise.race([
|
||||
Promise.all(children.map(({ complete }) => complete)),
|
||||
new Promise((_, reject) => { const timer = setTimeout(() => reject(Error('Concurrent candidate writers timed out')), 20000); timer.unref(); }),
|
||||
new Promise((_, reject) => {
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
Error('Concurrent candidate writers timed out'),
|
||||
),
|
||||
20000,
|
||||
);
|
||||
timer.unref();
|
||||
}),
|
||||
]);
|
||||
if (results.some(result => result.code !== 0)) throw Error('Concurrent candidate writer failed');
|
||||
const outcomes = results.map(result => JSON.parse(result.output.trim()));
|
||||
if (outcomes.filter(result => result.state === 'saved' && result.replayed === false).length !== 1
|
||||
|| (round === 'same' ? outcomes.filter(result => result.state === 'saved' && result.replayed === true).length !== 1
|
||||
: outcomes.filter(result => result.state === 'stale').length !== 1)) throw Error('Unexpected concurrent configuration outcome');
|
||||
if (results.some((result) => result.code !== 0))
|
||||
throw Error('Concurrent candidate writer failed');
|
||||
const outcomes = results.map((result) =>
|
||||
JSON.parse(result.output.trim()),
|
||||
);
|
||||
if (
|
||||
outcomes.filter(
|
||||
(result) =>
|
||||
result.state === 'saved' && result.replayed === false,
|
||||
).length !== 1 ||
|
||||
(round === 'same'
|
||||
? outcomes.filter(
|
||||
(result) =>
|
||||
result.state === 'saved' &&
|
||||
result.replayed === true,
|
||||
).length !== 1
|
||||
: outcomes.filter((result) => result.state === 'stale')
|
||||
.length !== 1)
|
||||
)
|
||||
throw Error('Unexpected concurrent configuration outcome');
|
||||
const proof = worker('read-configuration-race', round);
|
||||
if (proof.verified !== true) throw Error('Concurrent configuration conservation missing');
|
||||
console.log(JSON.stringify({ standalone_configuration_concurrency: true, ...proof, outcomes }));
|
||||
if (proof.verified !== true)
|
||||
throw Error('Concurrent configuration conservation missing');
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
standalone_configuration_concurrency: true,
|
||||
...proof,
|
||||
outcomes,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
for (const { child } of children) if (child.exitCode === null) child.kill();
|
||||
for (const { child } of children)
|
||||
if (child.exitCode === null) child.kill();
|
||||
await Promise.all(children.map(({ complete }) => complete));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,65 +5,150 @@ import crypto from 'node:crypto';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { createServer } from 'node:net';
|
||||
|
||||
export async function reviewStandaloneFinance({ workspace, root, database, environment, assets, manifestPin }) {
|
||||
const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
|
||||
export async function reviewStandaloneFinance({
|
||||
workspace,
|
||||
root,
|
||||
database,
|
||||
environment,
|
||||
assets,
|
||||
manifestPin,
|
||||
}) {
|
||||
const parent = fs.realpathSync(
|
||||
path.join(workspace, 'storage/framework/testing'),
|
||||
);
|
||||
const owned = fs.realpathSync(root);
|
||||
const match = /^compras_standalone_qa_([a-f0-9]{12})$/.exec(database);
|
||||
if (!match || path.dirname(owned) !== parent || path.basename(owned) !== `rq01-ledger-qa-${match[1]}`
|
||||
|| environment.DB_DATABASE !== database || environment.DB_USERNAME !== `compras_standalone_app_${match[1]}`
|
||||
|| environment.COMPRAS_RUNTIME_ENABLED !== 'true' || environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false'
|
||||
|| environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned synthetic standalone preview required');
|
||||
const worker = mode => {
|
||||
const result = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, mode], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment, maxBuffer: 1024 * 1024,
|
||||
});
|
||||
if (result.status !== 0) throw Error('Standalone UI fixture/conservation failed');
|
||||
if (
|
||||
!match ||
|
||||
path.dirname(owned) !== parent ||
|
||||
path.basename(owned) !== `rq01-ledger-qa-${match[1]}` ||
|
||||
environment.DB_DATABASE !== database ||
|
||||
environment.DB_USERNAME !== `compras_standalone_app_${match[1]}` ||
|
||||
environment.COMPRAS_RUNTIME_ENABLED !== 'true' ||
|
||||
environment.COMPRAS_RUNTIME_PREPARE_ONLY !== 'false' ||
|
||||
environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true'
|
||||
)
|
||||
throw Error('Owned synthetic standalone preview required');
|
||||
const worker = (mode) => {
|
||||
const result = spawnSync(
|
||||
'php',
|
||||
['tests/Support/standalone-runtime-worker.php', database, mode],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
encoding: 'utf8',
|
||||
env: environment,
|
||||
maxBuffer: 1024 * 1024,
|
||||
},
|
||||
);
|
||||
if (result.status !== 0)
|
||||
throw Error('Standalone UI fixture/conservation failed');
|
||||
return JSON.parse(result.stdout.trim());
|
||||
};
|
||||
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) {
|
||||
for (const relative of [
|
||||
'public',
|
||||
'storage/framework/sessions',
|
||||
'storage/framework/views',
|
||||
'storage/framework/cache/data',
|
||||
'storage/logs',
|
||||
'storage/app/private',
|
||||
]) {
|
||||
fs.mkdirSync(path.join(root, relative), { recursive: true });
|
||||
}
|
||||
const fixture = worker('prepare-ui');
|
||||
if (fixture.ui_prepared !== true || fixture.no_initial_financial_grants !== true) throw Error('UI setup inherited grants');
|
||||
if (
|
||||
fixture.ui_prepared !== true ||
|
||||
fixture.no_initial_financial_grants !== true
|
||||
)
|
||||
throw Error('UI setup inherited grants');
|
||||
const bytes = fs.readFileSync(path.join(assets, 'manifest.json'));
|
||||
if (crypto.createHash('sha256').update(bytes).digest('hex') !== manifestPin) throw Error('Pinned UI build required');
|
||||
if (crypto.createHash('sha256').update(bytes).digest('hex') !== manifestPin)
|
||||
throw Error('Pinned UI build required');
|
||||
for (const entry of Object.values(JSON.parse(bytes))) {
|
||||
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('UI build entry missing');
|
||||
if (!fs.existsSync(path.join(assets, entry.file)))
|
||||
throw Error('UI build entry missing');
|
||||
}
|
||||
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
|
||||
fs.cpSync(assets, path.join(root, 'public/build'), {
|
||||
recursive: true,
|
||||
errorOnExist: true,
|
||||
});
|
||||
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) {
|
||||
fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
|
||||
fs.copyFileSync(
|
||||
path.join(workspace, 'public', file),
|
||||
path.join(root, 'public', file),
|
||||
);
|
||||
}
|
||||
const port = await new Promise((resolve, reject) => {
|
||||
const socket = createServer(); socket.on('error', reject);
|
||||
socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
|
||||
const socket = createServer();
|
||||
socket.on('error', reject);
|
||||
socket.listen(0, '127.0.0.1', () => {
|
||||
const address = socket.address();
|
||||
socket.close(() => resolve(address.port));
|
||||
});
|
||||
});
|
||||
const url = `http://localhost:${port}`;
|
||||
const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-qa-http-router.php'], {
|
||||
cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
|
||||
env: { ...environment, APP_URL: url, SGC_STANDALONE_QA_PORT: String(port), SESSION_DRIVER: 'file', SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false' },
|
||||
});
|
||||
const server = spawn(
|
||||
'php',
|
||||
[
|
||||
'-S',
|
||||
`127.0.0.1:${port}`,
|
||||
'-t',
|
||||
path.join(root, 'public'),
|
||||
'tests/Support/standalone-qa-http-router.php',
|
||||
],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
env: {
|
||||
...environment,
|
||||
APP_URL: url,
|
||||
SGC_STANDALONE_QA_PORT: String(port),
|
||||
SESSION_DRIVER: 'file',
|
||||
SESSION_DOMAIN: '',
|
||||
SESSION_SECURE_COOKIE: 'false',
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 20 && !ready; attempt++) {
|
||||
try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
|
||||
if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
|
||||
try {
|
||||
const response = await fetch(url + '/login');
|
||||
ready = response.status === 200;
|
||||
await response.arrayBuffer();
|
||||
} catch {}
|
||||
if (!ready)
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
if (!ready) throw Error('Standalone UI did not start');
|
||||
const stop = path.join(root, 'stop-finance-review');
|
||||
console.log(JSON.stringify({ standalone_finance_preview: true, url, stop_file: stop, manifest_sha256: manifestPin, ...fixture }));
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
standalone_finance_preview: true,
|
||||
url,
|
||||
stop_file: stop,
|
||||
manifest_sha256: manifestPin,
|
||||
...fixture,
|
||||
}),
|
||||
);
|
||||
const until = Date.now() + 20 * 60 * 1000;
|
||||
while (!fs.existsSync(stop) && Date.now() < until) {
|
||||
if (server.exitCode !== null) throw Error('Standalone UI stopped unexpectedly');
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
if (server.exitCode !== null)
|
||||
throw Error('Standalone UI stopped unexpectedly');
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
const proof = worker('read-ui');
|
||||
if (proof.ui_conservation_verified !== true) throw Error('UI conservation not verified');
|
||||
if (proof.ui_conservation_verified !== true)
|
||||
throw Error('UI conservation not verified');
|
||||
console.log(JSON.stringify(proof));
|
||||
} finally {
|
||||
if (server.exitCode === null) {
|
||||
const closed = new Promise(resolve => server.once('exit', resolve));
|
||||
server.kill(); await closed;
|
||||
const closed = new Promise((resolve) =>
|
||||
server.once('exit', resolve),
|
||||
);
|
||||
server.kill();
|
||||
await closed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,60 +5,179 @@ import crypto from 'node:crypto';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { createServer } from 'node:net';
|
||||
|
||||
export async function reviewStandaloneInventory({ workspace, root, database, environment, cancellation = false, analytics = false }) {
|
||||
const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
|
||||
export async function reviewStandaloneInventory({
|
||||
workspace,
|
||||
root,
|
||||
database,
|
||||
environment,
|
||||
cancellation = false,
|
||||
analytics = false,
|
||||
}) {
|
||||
const parent = fs.realpathSync(
|
||||
path.join(workspace, 'storage/framework/testing'),
|
||||
);
|
||||
const match = /^compras_receipts_test_([a-f0-9]{12})$/.exec(database);
|
||||
if (!match || path.dirname(fs.realpathSync(root)) !== parent || path.basename(root) !== `rq01-ledger-qa-${match[1]}`
|
||||
|| environment.DB_USERNAME !== `payable_history_native_${match[1]}` || environment.DB_HOST !== '127.0.0.1'
|
||||
|| environment.DB_PORT !== '55439' || environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned inventory preview required');
|
||||
if (cancellation) environment = { ...environment, COMPRAS_ORDER_CANCELLATION_ENABLED: 'true' };
|
||||
const prepared = spawnSync('php', ['tests/Concurrency/unit-conversion-worker.php', database, analytics ? 'prepare-analytics-preview' : cancellation ? 'prepare-cancellation-preview' : 'prepare-preview'], {
|
||||
cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'testing' },
|
||||
});
|
||||
if (prepared.status !== 0) throw Error('Synthetic inventory preview fixture failed');
|
||||
if (
|
||||
!match ||
|
||||
path.dirname(fs.realpathSync(root)) !== parent ||
|
||||
path.basename(root) !== `rq01-ledger-qa-${match[1]}` ||
|
||||
environment.DB_USERNAME !== `payable_history_native_${match[1]}` ||
|
||||
environment.DB_HOST !== '127.0.0.1' ||
|
||||
environment.DB_PORT !== '55439' ||
|
||||
environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true'
|
||||
)
|
||||
throw Error('Owned inventory preview required');
|
||||
if (cancellation)
|
||||
environment = {
|
||||
...environment,
|
||||
COMPRAS_ORDER_CANCELLATION_ENABLED: 'true',
|
||||
};
|
||||
const prepared = spawnSync(
|
||||
'php',
|
||||
[
|
||||
'tests/Concurrency/unit-conversion-worker.php',
|
||||
database,
|
||||
analytics
|
||||
? 'prepare-analytics-preview'
|
||||
: cancellation
|
||||
? 'prepare-cancellation-preview'
|
||||
: 'prepare-preview',
|
||||
],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
encoding: 'utf8',
|
||||
env: { ...environment, APP_ENV: 'testing' },
|
||||
},
|
||||
);
|
||||
if (prepared.status !== 0)
|
||||
throw Error('Synthetic inventory preview fixture failed');
|
||||
const fixture = JSON.parse(prepared.stdout);
|
||||
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) fs.mkdirSync(path.join(root, relative), { recursive: true });
|
||||
const assets = path.join(workspace, 'storage/framework/testing', analytics ? 'sgc-analytics-print-qa-20261129' : 'sgc-standalone-finance-help-qa-20261129');
|
||||
for (const relative of [
|
||||
'public',
|
||||
'storage/framework/sessions',
|
||||
'storage/framework/views',
|
||||
'storage/framework/cache/data',
|
||||
'storage/logs',
|
||||
'storage/app/private',
|
||||
])
|
||||
fs.mkdirSync(path.join(root, relative), { recursive: true });
|
||||
const assets = path.join(
|
||||
workspace,
|
||||
'storage/framework/testing',
|
||||
analytics
|
||||
? 'sgc-analytics-print-qa-20261129'
|
||||
: 'sgc-standalone-finance-help-qa-20261129',
|
||||
);
|
||||
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
|
||||
if (crypto.createHash('sha256').update(manifest).digest('hex') !== (analytics ? 'c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022' : '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b')) throw Error('Pinned UI build required');
|
||||
fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
|
||||
if (
|
||||
crypto.createHash('sha256').update(manifest).digest('hex') !==
|
||||
(analytics
|
||||
? 'c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022'
|
||||
: '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b')
|
||||
)
|
||||
throw Error('Pinned UI build required');
|
||||
fs.cpSync(assets, path.join(root, 'public/build'), {
|
||||
recursive: true,
|
||||
errorOnExist: true,
|
||||
});
|
||||
const verifyAnalytics = (mode) => {
|
||||
const check = spawnSync('php', ['scripts/check-analytics-preview.php', root, mode], { cwd: workspace, windowsHide: true, encoding: 'utf8' });
|
||||
if (check.status !== 0) throw Error('Synthetic analytical conservation failed');
|
||||
const check = spawnSync(
|
||||
'php',
|
||||
['scripts/check-analytics-preview.php', root, mode],
|
||||
{ cwd: workspace, windowsHide: true, encoding: 'utf8' },
|
||||
);
|
||||
if (check.status !== 0)
|
||||
throw Error('Synthetic analytical conservation failed');
|
||||
return JSON.parse(check.stdout);
|
||||
};
|
||||
if (analytics) verifyAnalytics('--capture');
|
||||
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
|
||||
for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png'])
|
||||
fs.copyFileSync(
|
||||
path.join(workspace, 'public', file),
|
||||
path.join(root, 'public', file),
|
||||
);
|
||||
const port = await new Promise((resolve, reject) => {
|
||||
const socket = createServer(); socket.on('error', reject);
|
||||
socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
|
||||
const socket = createServer();
|
||||
socket.on('error', reject);
|
||||
socket.listen(0, '127.0.0.1', () => {
|
||||
const address = socket.address();
|
||||
socket.close(() => resolve(address.port));
|
||||
});
|
||||
});
|
||||
const url = `http://localhost:${port}`;
|
||||
const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-inventory-http-router.php'], {
|
||||
cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
|
||||
env: { ...environment, APP_URL: url, ASSET_URL: url, SGC_STANDALONE_QA_ROOT: root, SGC_STANDALONE_QA_PORT: String(port),
|
||||
SESSION_DRIVER: 'file', SESSION_COOKIE: `sgc_inventory_qa_${match[1]}`, SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false',
|
||||
SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({ [fixture.tenant_id]: ['procurement.internal'] }) },
|
||||
});
|
||||
const server = spawn(
|
||||
'php',
|
||||
[
|
||||
'-S',
|
||||
`127.0.0.1:${port}`,
|
||||
'-t',
|
||||
path.join(root, 'public'),
|
||||
'tests/Support/standalone-inventory-http-router.php',
|
||||
],
|
||||
{
|
||||
cwd: workspace,
|
||||
windowsHide: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore'],
|
||||
env: {
|
||||
...environment,
|
||||
APP_URL: url,
|
||||
ASSET_URL: url,
|
||||
SGC_STANDALONE_QA_ROOT: root,
|
||||
SGC_STANDALONE_QA_PORT: String(port),
|
||||
SESSION_DRIVER: 'file',
|
||||
SESSION_COOKIE: `sgc_inventory_qa_${match[1]}`,
|
||||
SESSION_DOMAIN: '',
|
||||
SESSION_SECURE_COOKIE: 'false',
|
||||
SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({
|
||||
[fixture.tenant_id]: ['procurement.internal'],
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
try {
|
||||
let ready = false;
|
||||
for (let attempt = 0; attempt < 30 && !ready; attempt++) {
|
||||
try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
|
||||
if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
|
||||
try {
|
||||
const response = await fetch(url + '/login');
|
||||
ready = response.status === 200;
|
||||
await response.arrayBuffer();
|
||||
} catch {}
|
||||
if (!ready)
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
if (!ready) throw Error('Inventory preview did not start');
|
||||
const stop = path.join(root, 'stop-inventory-review');
|
||||
console.log(JSON.stringify({ inventory_preview: !cancellation && !analytics, cancellation_preview: cancellation, analytics_preview: analytics, url, stop_file: stop, ...fixture, normal_authentication_required: true }));
|
||||
const until = Date.now()+20*60*1000;
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
inventory_preview: !cancellation && !analytics,
|
||||
cancellation_preview: cancellation,
|
||||
analytics_preview: analytics,
|
||||
url,
|
||||
stop_file: stop,
|
||||
...fixture,
|
||||
normal_authentication_required: true,
|
||||
}),
|
||||
);
|
||||
const until = Date.now() + 20 * 60 * 1000;
|
||||
while (!fs.existsSync(stop) && Date.now() < until) {
|
||||
if (server.exitCode !== null) throw Error('Inventory preview stopped unexpectedly');
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
if (server.exitCode !== null)
|
||||
throw Error('Inventory preview stopped unexpectedly');
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
if (analytics) console.log(JSON.stringify({ analytical_conservation: verifyAnalytics('--verify') }));
|
||||
if (analytics)
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
analytical_conservation: verifyAnalytics('--verify'),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
if (server.exitCode === null) {
|
||||
const closed = new Promise(resolve => server.once('exit', resolve));
|
||||
server.kill(); await closed;
|
||||
const closed = new Promise((resolve) =>
|
||||
server.once('exit', resolve),
|
||||
);
|
||||
server.kill();
|
||||
await closed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const routes=[];
|
||||
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Live synthetic scope has no manual suggestions or specific execution grants; review, conversion and closure tested in disposable databases.'},null,2));
|
||||
console.log('Sugestoes e tarefas conferidas, preservando competencias especificas.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['procurement','finance','department_head']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -17,4 +28,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('docs/proofs/supplier-improvement-task-integration-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
business_commands:false,created_quality_evaluations_or_measures:false,visual_review:false},null,2));
|
||||
console.log('Consulta de qualidade e tarefas conferidas, sem criar avaliações ou medidas no piloto.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['procurement','finance','department_head']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -32,4 +43,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
await fs.writeFile('docs/proofs/supplier-quality-task-integration-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
|
||||
business_commands:false,accounts_or_grants_changed:false,supplier_selection_or_order:false,visual_review:false},null,2));
|
||||
console.log('Tarefas de qualidade, páginas autorizadas e seis avaliações anteriores conferidas sem decisões novas.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
|
||||
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
|
||||
await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
const source = await fs.readFile(
|
||||
'scripts/supplier-evaluation-check.mjs',
|
||||
'utf8',
|
||||
);
|
||||
const common = source.slice(
|
||||
source.indexOf('const base ='),
|
||||
source.indexOf('const author ='),
|
||||
);
|
||||
await new Function(
|
||||
'fs',
|
||||
'assert',
|
||||
'return (async()=>{' +
|
||||
common +
|
||||
`
|
||||
const records=[];
|
||||
for(const role of ['procurement','finance','requester']) {
|
||||
const viewer=client();await viewer.enter(role);
|
||||
@@ -26,4 +37,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
|
||||
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
|
||||
coverage:'Current supplier records are active; pending review, stale forms and revoked authority tested in disposable databases.'},null,2));
|
||||
console.log('Cadastros, tarefas e competencias de preparacao e conferencia confirmados.');
|
||||
` + '})()')(fs, assert);
|
||||
` +
|
||||
'})()',
|
||||
)(fs, assert);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user