Aplicar Pint e formatação de frontend; delimitar o âmbito do lint

Só formatação automática (pint, vp check --fix), sem alterar comportamento.
Excluídos da formatação os registos e artefactos com bytes fixos: docs/,
integrations/, storage/, tmp/, output/, resources/data/, tests/Fixtures/,
compras-release.json e AGENTS*.md. Scripts operacionais, integrations e
auxiliares de teste ficam fora do lint (usam new Function; limpeza na fase 2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 23:01:42 +02:00
co-authored by Claude Opus 5.5
parent 9f719695e3
commit ec934455e7
148 changed files with 9455 additions and 2413 deletions
+3 -1
View File
@@ -12,6 +12,8 @@ use App\Models\Supplier;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\PurchaseLineAmounts;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -31,7 +33,7 @@ function receiptFixture(string $quantity = '1.000', string $purchaseType = 'cons
throw new LogicException('The explicit multi-category fixture uses one unit per line.');
}
$lineMinor = intdiv(10000, count($categories));
$amounts = \App\Services\PurchaseLineAmounts::portion($lineMinor, '0', 0, \App\Services\ReceiptWorkflow::milli($quantity));
$amounts = PurchaseLineAmounts::portion($lineMinor, '0', 0, ReceiptWorkflow::milli($quantity));
$documentMinor = $amounts['total_minor'] * count($categories);
$tenant = Tenant::query()->create(['name' => 'Empresa fictícia de recepção']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
+40 -15
View File
@@ -1,16 +1,41 @@
<?php
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$file=realpath($argv[1]??'');
if(!$root||!$file||dirname($file)!==$root)throw new RuntimeException('Unexpected private worker');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->name,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong receipt worker database');
$input=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)",[$input['application']]);$db->statement("SET lock_timeout='8s'");$db->statement("SET statement_timeout='12s'");
$actor=App\Models\User::findOrFail($input['actor']);auth()->guard()->setUser($actor);
file_put_contents($file.'.ready','ready');
$start=hrtime(true);
try{$receipt=app(App\Services\ReceiptWorkflow::class)->confirm($actor,App\Models\PurchaseOrder::findOrFail($input['order']),$input['payload']);
$result=['status'=>200,'receipt_id'=>$receipt->id];
}catch(Illuminate\Validation\ValidationException){$result=['status'=>422];}
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$result=['status'=>$e->getStatusCode()];}
$result['elapsed_ms']=round((hrtime(true)-$start)/1e6,3);file_put_contents($file.'.result',json_encode($result,JSON_THROW_ON_ERROR));
use App\Models\PurchaseOrder;
use App\Models\User;
use App\Services\ReceiptWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
$file = realpath($argv[1] ?? '');
if (! $root || ! $file || dirname($file) !== $root) {
throw new RuntimeException('Unexpected private worker');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->name, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new RuntimeException('Wrong receipt worker database');
}
$input = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)", [$input['application']]);
$db->statement("SET lock_timeout='8s'");
$db->statement("SET statement_timeout='12s'");
$actor = User::findOrFail($input['actor']);
auth()->guard()->setUser($actor);
file_put_contents($file.'.ready', 'ready');
$start = hrtime(true);
try {
$receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::findOrFail($input['order']), $input['payload']);
$result = ['status' => 200, 'receipt_id' => $receipt->id];
} catch (ValidationException) {
$result = ['status' => 422];
} catch (HttpExceptionInterface $e) {
$result = ['status' => $e->getStatusCode()];
}
$result['elapsed_ms'] = round((hrtime(true) - $start) / 1e6, 3);
file_put_contents($file.'.result', json_encode($result,JSON_THROW_ON_ERROR));
+91 -23
View File
@@ -9,43 +9,97 @@ if (!root) throw Error('Explicit verified candidate package root required');
function workspace(file, host = true) {
const forms = [0, 1].map(() => ({
dataset: { action: file.startsWith('general-ledger') ? 'prepare' : 'payment-prepare' },
values: new Map([['reason', '']]), button: { disabled: false }, appended: [],
querySelector(selector) { return selector === 'button' ? this.button : null; },
querySelectorAll(selector) { return selector === 'button' ? [this.button] : []; },
append(...nodes) { this.appended.push(...nodes); },
dataset: {
action: file.startsWith('general-ledger')
? 'prepare'
: 'payment-prepare',
},
values: new Map([['reason', '']]),
button: { disabled: false },
appended: [],
querySelector(selector) {
return selector === 'button' ? this.button : null;
},
querySelectorAll(selector) {
return selector === 'button' ? [this.button] : [];
},
append(...nodes) {
this.appended.push(...nodes);
},
}));
const nodes = Object.fromEntries(['#finance', '#reload', '#status', '#error', 'main'].map(id => [id, { textContent: '', focus() {}, prepend() {} }]));
const nodes = Object.fromEntries(
['#finance', '#reload', '#status', '#error', 'main'].map((id) => [
id,
{ textContent: '', focus() {}, prepend() {} },
]),
);
const events = new Map();
const state = { reloads: 0, requests: [], response: async () => ({ ok: true, json: async () => ({ state: 'saved' }) }) };
const settings = { api: '/api/supplier-payments', csrf: 'synthetic', host_journal_policy: host, host_settlement_policy: host };
const state = {
reloads: 0,
requests: [],
response: async () => ({
ok: true,
json: async () => ({ state: 'saved' }),
}),
};
const settings = {
api: '/api/supplier-payments',
csrf: 'synthetic',
host_journal_policy: host,
host_settlement_policy: host,
};
const source = readFileSync(path.join(root, file), 'utf8');
const script = source.match(/<script>([\s\S]*?)<\/script>/)[1]
.replace(/const settings=<\?=[\s\S]*?\?>;/, `const settings=${JSON.stringify(settings)};`);
const script = source
.match(/<script>([\s\S]*?)<\/script>/)[1]
.replace(
/const settings=<\?=[\s\S]*?\?>;/,
`const settings=${JSON.stringify(settings)};`,
);
let key = 0;
const context = vm.createContext({
document: {
querySelector: selector => nodes[selector],
querySelectorAll: selector => selector === '[data-action]' ? forms : [],
querySelector: (selector) => nodes[selector],
querySelectorAll: (selector) =>
selector === '[data-action]' ? forms : [],
createElement: () => ({ textContent: '', setAttribute() {} }),
},
FormData: class { constructor(form) { this.form = form; } [Symbol.iterator]() { return this.form.values.entries(); } },
window: { addEventListener: (event, callback) => events.set(event, callback) },
FormData: class {
constructor(form) {
this.form = form;
}
[Symbol.iterator]() {
return this.form.values.entries();
}
},
window: {
addEventListener: (event, callback) => events.set(event, callback),
},
location: { reload: () => state.reloads++, assign() {} },
crypto: { randomUUID: () => `synthetic-operation-${++key}` },
fetch: async (url, options) => { state.requests.push({ url, ...options }); return state.response(); },
fetch: async (url, options) => {
state.requests.push({ url, ...options });
return state.response();
},
});
vm.runInContext(script, context);
const leaving = () => {
const event = { prevented: false, preventDefault() { this.prevented = true; } };
const event = {
prevented: false,
preventDefault() {
this.prevented = true;
},
};
events.get('beforeunload')?.(event);
return event.prevented;
};
const submit = form => form.onsubmit({ preventDefault() {} });
const submit = (form) => form.onsubmit({ preventDefault() {} });
return { forms, state, leaving, submit, nodes };
}
for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php']) {
for (const file of [
'general-ledger/ui/cycle.php',
'payables/ui/settlements.php',
]) {
test(`${file}: only an edited preparation warns before leaving`, () => {
const w = workspace(file);
assert.equal(w.leaving(), false);
@@ -62,7 +116,10 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
await w.submit(w.forms[0]);
assert.equal(w.state.reloads, 0);
assert.equal(w.forms[0].button.disabled, true);
assert.equal(w.forms[1].values.get('reason'), 'Preserve this separate preparation');
assert.equal(
w.forms[1].values.get('reason'),
'Preserve this separate preparation',
);
assert.equal(w.leaving(), true);
assert.equal(w.forms[0].appended.length, 2);
assert.match(w.forms[0].appended[0].textContent, /registada/);
@@ -76,8 +133,13 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
test(`${file}: unknown network result preserves values and retries the same command identity`, async () => {
const w = workspace(file);
w.forms[0].values.set('reason', 'Do not lose an interrupted synthetic operation');
w.state.response = async () => { throw Error('Synthetic lost response'); };
w.forms[0].values.set(
'reason',
'Do not lose an interrupted synthetic operation',
);
w.state.response = async () => {
throw Error('Synthetic lost response');
};
await w.submit(w.forms[0]);
assert.equal(w.forms[0].button.disabled, false);
assert.equal(w.state.reloads, 0);
@@ -87,14 +149,20 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
w.state.response = async () => ({ ok: true, json: async () => ({}) });
await w.submit(w.forms[0]);
assert.equal(w.state.requests[1].headers['Idempotency-Key'], key);
assert.equal(w.forms[0].values.get('reason'), 'Do not lose an interrupted synthetic operation');
assert.equal(
w.forms[0].values.get('reason'),
'Do not lose an interrupted synthetic operation',
);
assert.equal(w.state.reloads, 1);
});
test(`${file}: a second submit while pending cannot start another request`, async () => {
const w = workspace(file);
let finish;
w.state.response = () => new Promise(resolve => { finish = resolve; });
w.state.response = () =>
new Promise((resolve) => {
finish = resolve;
});
const pending = w.submit(w.forms[0]);
await w.submit(w.forms[0]);
assert.equal(w.state.requests.length, 1);
+24 -7
View File
@@ -4,22 +4,36 @@ import { test } from 'node:test';
import { createNativeInertiaClient } from '../../scripts/lib/native-inertia-client.mjs';
test('owned native client drains large closed responses while preserving body headers cookies and manual redirects', async () => {
const payload = { synthetic_only: true, content: 'x'.repeat(2 * 1024 * 1024) };
const payload = {
synthetic_only: true,
content: 'x'.repeat(2 * 1024 * 1024),
};
let cookiesSeen = '';
const server = createServer((request, response) => {
response.setHeader('Connection', 'close');
response.useChunkedEncodingByDefault = false;
if (request.url === '/cookies') {
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
response.setHeader('Set-Cookie', [
'QA_SESSION=first; Path=/',
'QA_CONTEXT=second; Path=/',
]);
}
if (request.url === '/empty') {
response.writeHead(204);
response.end();
return;
}
if (request.url === '/redirect') {
response.writeHead(302, { Location: '/large' });
response.end('Synthetic redirect');
return;
}
if (request.url === '/empty') { response.writeHead(204); response.end(); return; }
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
cookiesSeen = request.headers.cookie ?? '';
response.writeHead(200, { 'Content-Type': 'application/json' });
response.write(JSON.stringify(payload));
response.end();
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const origin = `http://127.0.0.1:${server.address().port}`;
const client = createNativeInertiaClient(origin, assert.ok);
@@ -44,9 +58,12 @@ test('owned native client drains large closed responses while preserving body he
assert.equal(redirect.status, 302);
assert.equal(redirect.headers.get('Location'), '/large');
assert.equal(await redirect.text(), 'Synthetic redirect');
await assert.rejects(client.request('//example.test/foreign'), /External HTTP destination refused/);
await assert.rejects(
client.request('//example.test/foreign'),
/External HTTP destination refused/,
);
} finally {
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
await new Promise((resolve) => server.close(resolve));
}
});
+32 -9
View File
@@ -1,10 +1,33 @@
<?php
$file=realpath($argv[1]??'');$private=realpath(getcwd().'/../private');
if(!$file||!$private||!str_starts_with($file,$private.DIRECTORY_SEPARATOR))throw new LogicException('Private QA worker input refused');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$p=json_decode(file_get_contents($file),true,64,JSON_THROW_ON_ERROR);$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new LogicException('QA worker database refused');
config(['common-payables.enabled'=>true,'common-payables.history_enabled'=>true,'common-payables.paged_read_enabled'=>true,'common-payables.source_instance'=>$p['instance']]);$u=App\Models\User::query()->findOrFail($p['actor']);auth()->setUser($u);$time=hrtime(true);
try{$d=app(App\Services\SupplierPayables::class)->listing($u);$out=['status'=>200,'documents'=>count($d['documents']),'balances'=>array_column($d['obligations'],'balance_minor'),'time_ms'=>(hrtime(true)-$time)/1e6];}
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
file_put_contents($file.'.result',json_encode($out,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
use App\Models\User;
use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$file = realpath($argv[1] ?? '');
$private = realpath(getcwd().'/../private');
if (! $file || ! $private || ! str_starts_with($file, $private.DIRECTORY_SEPARATOR)) {
throw new LogicException('Private QA worker input refused');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$p = json_decode(file_get_contents($file), true, 64, JSON_THROW_ON_ERROR);
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new LogicException('QA worker database refused');
}
config(['common-payables.enabled' => true, 'common-payables.history_enabled' => true, 'common-payables.paged_read_enabled' => true, 'common-payables.source_instance' => $p['instance']]);
$u = User::query()->findOrFail($p['actor']);
auth()->setUser($u);
$time = hrtime(true);
try {
$d = app(SupplierPayables::class)->listing($u);
$out = ['status' => 200, 'documents' => count($d['documents']), 'balances' => array_column($d['obligations'], 'balance_minor'), 'time_ms' => (hrtime(true) - $time) / 1e6];
} catch (HttpExceptionInterface $e) {
$out = ['status' => $e->getStatusCode()];
}
file_put_contents($file.'.result', json_encode($out, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
+58 -34
View File
@@ -1,44 +1,68 @@
<?php
use App\Models\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Purchasing\Delivery\SqlPrivileges;
// Runs only inside the disposable reproduction after its authorised lifecycle.
// Inherits the explicit test scope/clients; never creates grants in the host.
$catalogue=$call($actor,'/api/accesses');
$check($catalogue['status']===200&&in_array('purchasing_requisitions.prepare',$catalogue['data']['catalogue']['unit'],true),'native administration receives complete unit catalogue');
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare']??'')==='Preparar e submeter requisições','native administration receives canonical server labels');
$check($call($head,'/api/accesses')['status']===403,'reviewer cannot inspect administrative catalogue without management right');
$check($call($actor,'/api/accesses','POST',['email'=>\App\Models\User::findOrFail($head)->email,'unit_id'=>$scope['unit_id'],'permission'=>'purchasing_budget.consume','reason'=>'Forbidden delegation outside own synthetic authority'])['status']===403,'forged delegation of an unowned catalogue right refused');
$catalogue = $call($actor, '/api/accesses');
$check($catalogue['status'] === 200 && in_array('purchasing_requisitions.prepare', $catalogue['data']['catalogue']['unit'], true), 'native administration receives complete unit catalogue');
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare'] ?? '') === 'Preparar e submeter requisições', 'native administration receives canonical server labels');
$check($call($head, '/api/accesses')['status'] === 403, 'reviewer cannot inspect administrative catalogue without management right');
$check($call($actor, '/api/accesses', 'POST', ['email' => User::findOrFail($head)->email, 'unit_id' => $scope['unit_id'], 'permission' => 'purchasing_budget.consume', 'reason' => 'Forbidden delegation outside own synthetic authority'])['status'] === 403, 'forged delegation of an unowned catalogue right refused');
$uiManifest=json_decode(file_get_contents($clone.'/public/build/manifest.json'),true,32,JSON_THROW_ON_ERROR);
foreach($uiManifest as $chunk)foreach([$chunk['file'],...($chunk['css']??[])] as $file){
$asset=$anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
$check($asset->getStatusCode()===200&&strlen((string)$asset->getBody())>100,'packaged frontend dependency served before authentication');
$uiManifest = json_decode(file_get_contents($clone.'/public/build/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
foreach ($uiManifest as $chunk) {
foreach ([$chunk['file'], ...($chunk['css'] ?? [])] as $file) {
$asset = $anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
$check($asset->getStatusCode() === 200 && strlen((string) $asset->getBody()) > 100, 'packaged frontend dependency served before authentication');
}
}
$main=$anonymous->get('http://127.0.0.1:'.$port.'/');
$check($main->getStatusCode()===200&&str_contains((string)$main->getBody(),'/build/modules/internal-requisitions/assets/'),'native SGF entry renders the packaged frontend manifest');
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode()===404,'undeclared frontend asset refused');
$main = $anonymous->get('http://127.0.0.1:'.$port.'/');
$check($main->getStatusCode() === 200 && str_contains((string) $main->getBody(), '/build/modules/internal-requisitions/assets/'), 'native SGF entry renders the packaged frontend manifest');
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode() === 404, 'undeclared frontend asset refused');
// Reproduce destination-style broad inherited ACLs on NEW objects, then prove
// the proposed map narrows them without touching any of the 87 prior tables.
$beforeAcl=[];
foreach($inventory['tables'] as $table)$beforeAcl[$table]=$db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl;
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::TABLES as $table=>$rights)$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::plan($runtime)['statements'] as $sql)$db->statement($sql);
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed&&!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed,'minimal plan removes inherited update and delete on new append-only sources');
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed,'runtime cannot truncate requisitions');
foreach($beforeAcl as $table=>$acl)$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl===$acl,'existing table ACL preserved '.$table);
try{$rt->transaction(fn()=>$rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));throw new LogicException('Unexpected runtime DDL');}
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime CREATE denied');}
try{$rt->transaction(fn()=>$rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));throw new LogicException('Unexpected runtime ALTER');}
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime ALTER of identity catalogue denied');}
$badCentre=['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'code'=>'NOT-ALLOWED','reason'=>'Validation in the isolated reproduction only'];
$check($call($head,'/api/internal-requisitions/centres','POST',$badCentre)['status']===403,'centre creation requires own configuration and budget rights');
$check($call($actor,'/api/internal-requisitions/centres','POST',$badCentre+['company_id'=>999999])['status']===422,'centre context cannot be forged');
$check(\Illuminate\Support\Facades\DB::table('cb_centres')->count()===1,'refused centre operations leave original source intact');
foreach(['equipment','part'] as $unsupported){
$r=$call($actor,'/api/internal-requisitions/save','POST',['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'cost_center_id'=>$f['centre'],'priority'=>'normal','needed_by'=>date('Y-m-d',time()+864000),'justification'=>'Unsupported type must remain outside this increment.','items'=>[['description'=>'Unsupported source','category'=>'Excluded','purchase_type'=>$unsupported,'quantity'=>'1.000','unit'=>'UN','unit_price'=>'1.00','tax_rate'=>'0.00']]]);
$check($r['status']===422,'unsupported requisition type refused '.$unsupported);
$beforeAcl = [];
foreach ($inventory['tables'] as $table) {
$beforeAcl[$table] = $db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl;
}
$data=json_decode(\Illuminate\Support\Facades\DB::table('ir_requests')->where('id',$id)->value('data'),true,32,JSON_THROW_ON_ERROR);
$check(array_column($data['items'],'purchase_type')===['consumable','service','other'],'approved lifecycle covers the three supported basic types');
$check(\Illuminate\Support\Facades\DB::table('ir_requests')->count()===1&&\Illuminate\Support\Facades\DB::table('cb_budget_entries')->where('kind','reserve')->count()===1,'unsupported types create neither a second request nor reservation');
foreach (SqlPrivileges::TABLES as $table => $rights) {
$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
}
foreach (SqlPrivileges::plan($runtime)['statements'] as $sql) {
$db->statement($sql);
}
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed && ! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed, 'minimal plan removes inherited update and delete on new append-only sources');
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed, 'runtime cannot truncate requisitions');
foreach ($beforeAcl as $table => $acl) {
$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl === $acl, 'existing table ACL preserved '.$table);
}
try {
$rt->transaction(fn () => $rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));
throw new LogicException('Unexpected runtime DDL');
} catch (QueryException $e) {
$check($e->errorInfo[0] === '42501', 'actual runtime CREATE denied');
}
try {
$rt->transaction(fn () => $rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));
throw new LogicException('Unexpected runtime ALTER');
} catch (QueryException $e) {
$check($e->errorInfo[0] === '42501', 'actual runtime ALTER of identity catalogue denied');
}
$badCentre = ['operation_key' => (string) Str::uuid(), 'code' => 'NOT-ALLOWED', 'reason' => 'Validation in the isolated reproduction only'];
$check($call($head, '/api/internal-requisitions/centres', 'POST', $badCentre)['status'] === 403, 'centre creation requires own configuration and budget rights');
$check($call($actor, '/api/internal-requisitions/centres', 'POST', $badCentre + ['company_id' => 999999])['status'] === 422, 'centre context cannot be forged');
$check(DB::table('cb_centres')->count() === 1, 'refused centre operations leave original source intact');
foreach (['equipment', 'part'] as $unsupported) {
$r = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Unsupported type must remain outside this increment.', 'items' => [['description' => 'Unsupported source', 'category' => 'Excluded', 'purchase_type' => $unsupported, 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '1.00', 'tax_rate' => '0.00']]]);
$check($r['status'] === 422, 'unsupported requisition type refused '.$unsupported);
}
$data = json_decode(DB::table('ir_requests')->where('id', $id)->value('data'), true, 32, JSON_THROW_ON_ERROR);
$check(array_column($data['items'], 'purchase_type') === ['consumable', 'service', 'other'], 'approved lifecycle covers the three supported basic types');
$check(DB::table('ir_requests')->count() === 1 && DB::table('cb_budget_entries')->where('kind','reserve')->count() === 1, 'unsupported types create neither a second request nor reservation');
+1 -1
View File
@@ -218,7 +218,7 @@ try {
$check($call($actor, '/api/purchasing-budget/movement', 'POST', [], ['Idempotency-Key' => (string) Str::uuid()])['status'] === 403, 'direct budget movements cannot bypass requisition lifecycle');
$policy = ['version' => 0, 'reason' => 'Política sintética na composição integrada.', 'enabled' => true, 'budget_required' => true, 'first_limit_minor' => 1000000, 'second_limit_minor' => 2000000, 'approval_includes_tax' => true, 'centres' => [['id' => $f['centre'], 'department_ref' => 'OPER']], 'members' => [['user_id' => $actor, 'department_ref' => 'OPER'], ['user_id' => $head, 'department_ref' => 'OPER']]];
$check($call($actor, '/api/internal-requisitions/policy', 'POST', $policy)['status'] === 200, 'operational policy configured via HTTP');
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description'=>'Servi?o sint?tico','category'=>'Servi?os','purchase_type'=>'service','quantity'=>'1.000','unit'=>'UN','unit_price'=>'25.00','tax_rate'=>'0.00'], ['description'=>'Outro sint?tico','category'=>'Outros','purchase_type'=>'other','quantity'=>'1.000','unit'=>'UN','unit_price'=>'10.00','tax_rate'=>'0.00']]]);
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description' => 'Servi?o sint?tico', 'category' => 'Servi?os', 'purchase_type' => 'service', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '25.00', 'tax_rate' => '0.00'], ['description' => 'Outro sint?tico', 'category' => 'Outros', 'purchase_type' => 'other', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '10.00', 'tax_rate' => '0.00']]]);
$check($draft['status'] === 200, 'integrated operational draft');
$id = $draft['data']['id'];
$submitted = $call($actor, "/api/internal-requisitions/$id/submit", 'POST', ['operation_key' => (string) Str::uuid(), 'version' => 1]);
+6 -2
View File
@@ -4,7 +4,9 @@
$variant = $work.'/code-only-successor';
$vm = json_decode(file_get_contents($bundle.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
foreach ([...array_keys($vm['support_files']), 'manifest.json'] as $file) {
if (! is_dir(dirname($variant.'/'.$file))) mkdir(dirname($variant.'/'.$file), 0700, true);
if (! is_dir(dirname($variant.'/'.$file))) {
mkdir(dirname($variant.'/'.$file), 0700, true);
}
copy($bundle.'/'.$file, $variant.'/'.$file);
}
$file = 'integrations/sgf/internal-requisitions/screen.php';
@@ -19,6 +21,8 @@ $deploy->rollback($vu['deployment_id'], 'Isolated successor recovery', true);
$check(hash_file('sha256', $clone.'/packages/internal-requisitions/manifest.json') === hash_file('sha256', $bundle.'/manifest.json'), 'code-only successor rollback restores exact candidate');
foreach ($fingerprints as $table => $expected) {
$rows = $db->select('select to_jsonb(t)::text as data from "'.$table.'" t order by to_jsonb(t)::text');
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) throw new RuntimeException('Update changed '.$table);
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) {
throw new RuntimeException('Update changed '.$table);
}
}
$check(true, 'code update and rollback preserve every reproduced data table');
+35 -13
View File
@@ -1,16 +1,38 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
$host=getenv('SOURCING_CLONE');$work=getenv('SOURCING_WORK');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
$fixture=json_decode(file_get_contents($work.'/fixture.json'),true);$command=$argv[1];
if(in_array($command,['revoke-evaluate','restore-evaluate','revoke-propose','restore-propose','revoke-view','restore-view'])){
$right=str_contains($command,'evaluate')?'purchasing_sourcing.evaluate':(str_contains($command,'propose')?'purchasing_sourcing.propose':'purchasing_requisitions.view');$id=str_contains($command,'evaluate')?$fixture['user_id']:(str_contains($command,'propose')?2:3);
$scope=['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'permission'=>$right];
if(str_starts_with($command,'revoke'))$db->table('permission_grants')->where($scope)->delete();else $db->table('permission_grants')->insertOrIgnore($scope+['created_at'=>now(),'updated_at'=>now()]);
}elseif($command==='fail-on')file_put_contents($host.'/storage/framework/sourcing-failure.fixture','isolated failure injection');
elseif($command==='fail-off')unlink($host.'/storage/framework/sourcing-failure.fixture');
else throw new RuntimeException('Unsupported fixture control');
echo json_encode(['ok'=>true]);
}catch(Throwable $e){fwrite(STDERR,$e->getMessage());exit(1);}
$host = getenv('SOURCING_CLONE');
$work = getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
throw new RuntimeException('Copy only');
}
$fixture = json_decode(file_get_contents($work.'/fixture.json'), true);
$command = $argv[1];
if (in_array($command, ['revoke-evaluate', 'restore-evaluate', 'revoke-propose', 'restore-propose', 'revoke-view', 'restore-view'])) {
$right = str_contains($command, 'evaluate') ? 'purchasing_sourcing.evaluate' : (str_contains($command, 'propose') ? 'purchasing_sourcing.propose' : 'purchasing_requisitions.view');
$id = str_contains($command, 'evaluate') ? $fixture['user_id'] : (str_contains($command, 'propose') ? 2 : 3);
$scope = ['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'permission' => $right];
if (str_starts_with($command, 'revoke')) {
$db->table('permission_grants')->where($scope)->delete();
} else {
$db->table('permission_grants')->insertOrIgnore($scope + ['created_at' => now(), 'updated_at' => now()]);
}
} elseif ($command === 'fail-on') {
file_put_contents($host.'/storage/framework/sourcing-failure.fixture', 'isolated failure injection');
} elseif ($command === 'fail-off') {
unlink($host.'/storage/framework/sourcing-failure.fixture');
} else {
throw new RuntimeException('Unsupported fixture control');
}
echo json_encode(['ok' => true]);
} catch (Throwable $e) {
fwrite(STDERR, $e->getMessage());
exit(1);
}
+126 -46
View File
@@ -1,51 +1,131 @@
<?php
use App\Models\User;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\User;
use Tempo\Purchasing\SgfSourcing\Schema;
use Symfony\Component\Process\Process;
use Tempo\Purchasing\Delivery\CodeDeployment;
$host=getenv('SOURCING_CLONE');$root=getenv('SOURCING_REPO');$work=getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();$name=$db->selectOne('select current_database() as db')->db;
if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$name)||$name!==getenv('SOURCING_DB')||!str_contains(str_replace('\\','/',$host),'/private/sourcing-')||str_replace('\\','/',$app->basePath())!==$host)throw new RuntimeException('Not an isolated sourcing copy');
$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';
$deploy=new CodeDeployment($host);$checks=[];$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;};
$fingerprint=function(string $table)use($db){return hash('sha256',json_encode($db->table($table)->orderBy('id')->get(),JSON_THROW_ON_ERROR));};
if(($argv[1]??'')==='setup'){
$baseline=['request'=>$fingerprint('ir_requests'),'budget'=>$fingerprint('cb_budget_entries'),'consumption'=>$fingerprint('cb_budget_consumptions'),'grants_count'=>$db->table('permission_grants')->count()];file_put_contents($work.'/origin.json',json_encode($baseline));
$armed=true;$db->listen(function($query)use(&$armed){if($armed&&str_contains(strtolower($query->sql),'create table "ss_events"')){$armed=false;throw new RuntimeException('Injected migration failure');}});
try{Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated failure proof');throw new RuntimeException('Expected failure');}catch(RuntimeException $e){$check($e->getMessage()==='Injected migration failure','Injected migration failure surfaced');}
$check(!$db->getSchemaBuilder()->hasTable('ss_suppliers')&&!$db->table('sgc_installations')->where('module','sourcing')->exists(),'Migration failure rolls back tables and catalogue');
$migration=Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated sourcing proof');$check($migration['prepared'],'Additive migration accepted');$check(Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated replay')['replayed'],'Migration replay is stable');
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true);$next=json_decode(file_get_contents($candidate['directory'].'/manifest.json'),true);
$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true);
try{$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);throw new RuntimeException('Unprepared plan accepted');}catch(RuntimeException $e){$check(str_contains($e->getMessage(),'migração própria'),'Schema-changing update refuses missing migration receipt');}
$receipt=['from_manifest_sha256'=>$current['manifest_sha256'],'to_manifest_sha256'=>$candidate['archive']['manifest_sha256'],'host'=>$host,'schema_verified'=>Schema::compatible($db),'changes'=>[]];
foreach($next['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/framework/down','{}');
$cli=new Symfony\Component\Process\Process([PHP_BINARY,$candidate['directory'].'/scripts/sgf-sourcing-install.php','migrate',$host,Tempo\Purchasing\Delivery\Installation::target($db),$work.'/before.dump',hash_file('sha256',$work.'/before.dump'),'Isolated migration CLI',$candidate['archive']['manifest_sha256']],$host,['PG_RESTORE_BINARY'=>'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);$cli->mustRun();
$cliResult=json_decode($cli->getOutput(),true,32,JSON_THROW_ON_ERROR);$check($cliResult['prepared']&&!$cliResult['activated']&&!$cliResult['rights_granted'],'Packaged migration CLI produces exact receipt without activation or grants');
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Isolated sourcing update',true);unlink($host.'/storage/framework/down');file_put_contents($work.'/applied.json',json_encode($applied));
$target=Tempo\Purchasing\Delivery\Installation::target($db);file_put_contents($host.'/config/purchasing-operational.php','<?php return '.var_export(['enabled'=>true,'target'=>$target,'scopes'=>['1:1:1']],true).';');file_put_contents($host.'/config/purchasing-sourcing.php','<?php return ["enabled"=>true];');
$private=json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'),true);
$user=User::forceCreate(['name'=>'Synthetic isolated evaluator','email'=>'fixture-'.Str::uuid().'@example.invalid','password'=>$private['password'],'auth_version'=>1]);
$db->table('company_memberships')->insert(['user_id'=>$user->id,'tenant_id'=>1,'company_id'=>1]);
$departmentPolicy=$db->table('ir_policies')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1])->first();$departmentPayload=json_decode($departmentPolicy->payload,true);$departmentPayload['members'][]=['user_id'=>$user->id,'department_ref'=>'OPER'];$db->table('ir_policies')->where('id',$departmentPolicy->id)->update(['payload'=>json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
$grants=[1=>['purchasing_sourcing.prepare'],2=>['purchasing_sourcing.evaluate','purchasing_sourcing.propose'],$user->id=>['company.view','unit.view','purchasing_requisitions.view','purchasing_sourcing.evaluate','purchasing_sourcing.confirm']];
foreach($grants as $id=>$rights)foreach($rights as $right)$db->table('permission_grants')->insert(['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>$right==='company.view'?null:1,'permission'=>$right,'created_at'=>now(),'updated_at'=>now()]);
foreach([1,2,3] as $n)$db->table('ss_suppliers')->insert(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'reference'=>'SYNTHETIC-'.$n,'payload'=>json_encode(['name'=>'Fornecedor sintético '.$n,'active'=>true,'blocked'=>false,'review_until'=>'2027-12-31','version'=>1,'synthetic_only'=>true]),'created_at'=>now()]);
file_put_contents($work.'/fixture.json',json_encode(['user_id'=>$user->id,'email'=>$user->email,'password'=>$private['password']]));
echo json_encode(['passed'=>true,'checks'=>$checks,'fixture_user_only_in_disposable_copy'=>true,'deployment'=>$applied]);
}elseif(($argv[1]??'')==='verify'){
$baseline=json_decode(file_get_contents($work.'/origin.json'),true);foreach(['request'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)$check($baseline[$key]===$fingerprint($table),'Origin '.$key.' unchanged');
$check($db->table('ss_processes')->count()===1,'Exactly one sourcing process');$check($db->table('ss_commands')->count()===$db->table('ss_events')->count(),'One event per committed command');
$saved=$db->table('ss_processes')->first();$state=json_decode($saved->payload,true);$check($state['confirmed']!==null,'Independent award confirmed in isolated copy');
$before=$fingerprint('ss_events');$failed=false;try{$db->transaction(fn()=>$db->table('ss_events')->where('id',1)->update(['action'=>'tampered']));}catch(Throwable){$failed=true;}$check($failed&&$before===$fingerprint('ss_events'),'Database rejects event tampering');
$applied=json_decode(file_get_contents($work.'/applied.json'),true);file_put_contents($host.'/storage/framework/down','{}');$rolled=$deploy->rollback($applied['deployment_id'],'Isolated sourcing code recovery',true);
$check($state===json_decode($db->table('ss_processes')->first()->payload,true),'Code rollback preserves award data');
echo json_encode(['passed'=>true,'checks'=>$checks,'code_recovery'=>$rolled,'old_code_requires_schema_recovery'=>true]);
}else throw new RuntimeException('Use setup/verify');
}catch(Throwable $e){fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");exit(1);}
use Tempo\Purchasing\Delivery\Installation;
use Tempo\Purchasing\SgfSourcing\Schema;
$host = getenv('SOURCING_CLONE');
$root = getenv('SOURCING_REPO');
$work = getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
$name = $db->selectOne('select current_database() as db')->db;
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $name) || $name !== getenv('SOURCING_DB') || ! str_contains(str_replace('\\', '/', $host), '/private/sourcing-') || str_replace('\\', '/', $app->basePath()) !== $host) {
throw new RuntimeException('Not an isolated sourcing copy');
}
$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';
$deploy = new CodeDeployment($host);
$checks = [];
$check = function ($ok, $label) use (&$checks) {
if (! $ok) {
throw new RuntimeException($label);
}$checks[] = $label;
};
$fingerprint = function (string $table) use ($db) {
return hash('sha256', json_encode($db->table($table)->orderBy('id')->get(), JSON_THROW_ON_ERROR));
};
if (($argv[1] ?? '') === 'setup') {
$baseline = ['request' => $fingerprint('ir_requests'), 'budget' => $fingerprint('cb_budget_entries'), 'consumption' => $fingerprint('cb_budget_consumptions'), 'grants_count' => $db->table('permission_grants')->count()];
file_put_contents($work.'/origin.json', json_encode($baseline));
$armed = true;
$db->listen(function ($query) use (&$armed) {
if ($armed && str_contains(strtolower($query->sql), 'create table "ss_events"')) {
$armed = false;
throw new RuntimeException('Injected migration failure');
}
});
try {
Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated failure proof');
throw new RuntimeException('Expected failure');
} catch (RuntimeException $e) {
$check($e->getMessage() === 'Injected migration failure', 'Injected migration failure surfaced');
}
$check(! $db->getSchemaBuilder()->hasTable('ss_suppliers') && ! $db->table('sgc_installations')->where('module', 'sourcing')->exists(), 'Migration failure rolls back tables and catalogue');
$migration = Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated sourcing proof');
$check($migration['prepared'], 'Additive migration accepted');
$check(Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated replay')['replayed'], 'Migration replay is stable');
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true);
$next = json_decode(file_get_contents($candidate['directory'].'/manifest.json'), true);
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true);
try {
$deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
throw new RuntimeException('Unprepared plan accepted');
} catch (RuntimeException $e) {
$check(str_contains($e->getMessage(), 'migração própria'), 'Schema-changing update refuses missing migration receipt');
}
$receipt = ['from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'host' => $host, 'schema_verified' => Schema::compatible($db), 'changes' => []];
foreach ($next['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/framework/down', '{}');
$cli = new Process([PHP_BINARY, $candidate['directory'].'/scripts/sgf-sourcing-install.php', 'migrate', $host, Installation::target($db), $work.'/before.dump', hash_file('sha256', $work.'/before.dump'), 'Isolated migration CLI', $candidate['archive']['manifest_sha256']], $host, ['PG_RESTORE_BINARY' => 'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);
$cli->mustRun();
$cliResult = json_decode($cli->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$check($cliResult['prepared'] && ! $cliResult['activated'] && ! $cliResult['rights_granted'], 'Packaged migration CLI produces exact receipt without activation or grants');
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Isolated sourcing update', true);
unlink($host.'/storage/framework/down');
file_put_contents($work.'/applied.json', json_encode($applied));
$target = Installation::target($db);
file_put_contents($host.'/config/purchasing-operational.php', '<?php return '.var_export(['enabled' => true, 'target' => $target, 'scopes' => ['1:1:1']], true).';');
file_put_contents($host.'/config/purchasing-sourcing.php', '<?php return ["enabled"=>true];');
$private = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'), true);
$user = User::forceCreate(['name' => 'Synthetic isolated evaluator', 'email' => 'fixture-'.Str::uuid().'@example.invalid', 'password' => $private['password'], 'auth_version' => 1]);
$db->table('company_memberships')->insert(['user_id' => $user->id, 'tenant_id' => 1, 'company_id' => 1]);
$departmentPolicy = $db->table('ir_policies')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first();
$departmentPayload = json_decode($departmentPolicy->payload, true);
$departmentPayload['members'][] = ['user_id' => $user->id, 'department_ref' => 'OPER'];
$db->table('ir_policies')->where('id', $departmentPolicy->id)->update(['payload' => json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
$grants = [1 => ['purchasing_sourcing.prepare'], 2 => ['purchasing_sourcing.evaluate', 'purchasing_sourcing.propose'], $user->id => ['company.view', 'unit.view', 'purchasing_requisitions.view', 'purchasing_sourcing.evaluate', 'purchasing_sourcing.confirm']];
foreach ($grants as $id => $rights) {
foreach ($rights as $right) {
$db->table('permission_grants')->insert(['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => $right === 'company.view' ? null : 1, 'permission' => $right, 'created_at' => now(), 'updated_at' => now()]);
}
}
foreach ([1, 2, 3] as $n) {
$db->table('ss_suppliers')->insert(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'reference' => 'SYNTHETIC-'.$n, 'payload' => json_encode(['name' => 'Fornecedor sintético '.$n, 'active' => true, 'blocked' => false, 'review_until' => '2027-12-31', 'version' => 1, 'synthetic_only' => true]), 'created_at' => now()]);
}
file_put_contents($work.'/fixture.json', json_encode(['user_id' => $user->id, 'email' => $user->email, 'password' => $private['password']]));
echo json_encode(['passed' => true, 'checks' => $checks, 'fixture_user_only_in_disposable_copy' => true, 'deployment' => $applied]);
} elseif (($argv[1] ?? '') === 'verify') {
$baseline = json_decode(file_get_contents($work.'/origin.json'), true);
foreach (['request' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
$check($baseline[$key] === $fingerprint($table), 'Origin '.$key.' unchanged');
}
$check($db->table('ss_processes')->count() === 1, 'Exactly one sourcing process');
$check($db->table('ss_commands')->count() === $db->table('ss_events')->count(), 'One event per committed command');
$saved = $db->table('ss_processes')->first();
$state = json_decode($saved->payload, true);
$check($state['confirmed'] !== null, 'Independent award confirmed in isolated copy');
$before = $fingerprint('ss_events');
$failed = false;
try {
$db->transaction(fn () => $db->table('ss_events')->where('id', 1)->update(['action' => 'tampered']));
} catch (Throwable) {
$failed = true;
}$check($failed && $before === $fingerprint('ss_events'), 'Database rejects event tampering');
$applied = json_decode(file_get_contents($work.'/applied.json'), true);
file_put_contents($host.'/storage/framework/down', '{}');
$rolled = $deploy->rollback($applied['deployment_id'], 'Isolated sourcing code recovery', true);
$check($state === json_decode($db->table('ss_processes')->first()->payload, true), 'Code rollback preserves award data');
echo json_encode(['passed' => true, 'checks' => $checks, 'code_recovery' => $rolled, 'old_code_requires_schema_recovery' => true]);
} else {
throw new RuntimeException('Use setup/verify');
}
} catch (Throwable $e) {
fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");
exit(1);
}
+331 -51
View File
@@ -1,55 +1,335 @@
import fs from 'node:fs';import assert from 'node:assert/strict';import crypto from 'node:crypto';import {spawn,spawnSync} from 'node:child_process';
const repo=process.env.SOURCING_REPO,work=process.env.SOURCING_WORK,host=process.env.SOURCING_CLONE,base='http://127.0.0.1:'+process.env.SOURCING_PORT,php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
import fs from 'node:fs';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
const repo = process.env.SOURCING_REPO,
work = process.env.SOURCING_WORK,
host = process.env.SOURCING_CLONE,
base = 'http://127.0.0.1:' + process.env.SOURCING_PORT,
php = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
assert(/^sgf_sourcing_test_[a-f0-9]{12}$/.test(process.env.SOURCING_DB));
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8')),fixture=JSON.parse(fs.readFileSync(work+'/fixture.json','utf8'));
const clients={},checks=[];
for(const p of [...privateData.profiles,{role:'decisor',email:fixture.email}]){
const jar=new Map();let csrf='',token='';
const api=async(path,method='GET',body,status=200,override={})=>{
const r=await fetch(base+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',...override},...(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.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 privateData = JSON.parse(
fs.readFileSync(
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
'utf8',
),
),
fixture = JSON.parse(fs.readFileSync(work + '/fixture.json', 'utf8'));
const clients = {},
checks = [];
for (const p of [
...privateData.profiles,
{ role: 'decisor', email: fixture.email },
]) {
const jar = new Map();
let csrf = '',
token = '';
const api = async (
path,
method = 'GET',
body,
status = 200,
override = {},
) => {
const r = await fetch(base + 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',
...override,
},
...(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.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,data,status=200){const current=await read(who);const payload={operation_key:crypto.randomUUID(),version:current.state.version,...(action==='propose'?{delivery_date:'2027-01-15',delivery_location:'Local de entrega exclusivamente sintético OPER'}:{}),...data};return {result:await clients[who]('/api/sourcing/1/'+action,'POST',payload,status),payload};}
const prep='preparador',rev='revisor',dec='decisor',consult='consulta';
for(const id of [1,2,3])await command(prep,'select',{supplier_id:id});
const quote=(id,price='100.00',days=5)=>({supplier_id:id,reference:'SYNTHETIC-Q-'+id,currency:'MZN',valid_until:'2027-12-31',delivery_days:days,payment_terms:'Pagamento sintético a 30 dias',items:[{line:0,unit_price:price}]});
for(const [id,amount] of [[1,'100.00'],[2,'110.00'],[3,'120.00']])await command(prep,'quote',{...quote(id,amount),delivery_days:'5',supplier_id:String(id)});
const qSaved=await read(prep);assert.equal(qSaved.request.id,1);assert.equal(qSaved.request.total_minor,10000);assert(!qSaved.comparison.ready);
for(const action of ['select','quote','evaluate','propose','confirm'])await clients[consult]('/api/sourcing/1/'+action,'POST',{},403);
await clients[consult]('/api/sourcing/1','GET',undefined,409,{'X-SGF-Context':'bad'});await clients[consult]('/api/sourcing/1','GET',undefined,403,{'X-Purchasing-Context':'procurement.third_party'});await clients[consult]('/api/sourcing/9999999','GET',undefined,404);
checks.push('Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected');
const evalData=async(id,who)=>{const s=await read(who);return {supplier_id:id,quote_revision:s.state.quotes[id].revision,quality:8,history:8,payment:8,no_conflict:true,reason:'Synthetic independent evaluation for isolated test.'};};
const read = (who) => clients[who]('/api/sourcing/1');
async function command(who, action, data, status = 200) {
const current = await read(who);
const payload = {
operation_key: crypto.randomUUID(),
version: current.state.version,
...(action === 'propose'
? {
delivery_date: '2027-01-15',
delivery_location:
'Local de entrega exclusivamente sintético OPER',
}
: {}),
...data,
};
return {
result: await clients[who](
'/api/sourcing/1/' + action,
'POST',
payload,
status,
),
payload,
};
}
const prep = 'preparador',
rev = 'revisor',
dec = 'decisor',
consult = 'consulta';
for (const id of [1, 2, 3]) await command(prep, 'select', { supplier_id: id });
const quote = (id, price = '100.00', days = 5) => ({
supplier_id: id,
reference: 'SYNTHETIC-Q-' + id,
currency: 'MZN',
valid_until: '2027-12-31',
delivery_days: days,
payment_terms: 'Pagamento sintético a 30 dias',
items: [{ line: 0, unit_price: price }],
});
for (const [id, amount] of [
[1, '100.00'],
[2, '110.00'],
[3, '120.00'],
])
await command(prep, 'quote', {
...quote(id, amount),
delivery_days: '5',
supplier_id: String(id),
});
const qSaved = await read(prep);
assert.equal(qSaved.request.id, 1);
assert.equal(qSaved.request.total_minor, 10000);
assert(!qSaved.comparison.ready);
for (const action of ['select', 'quote', 'evaluate', 'propose', 'confirm'])
await clients[consult]('/api/sourcing/1/' + action, 'POST', {}, 403);
await clients[consult]('/api/sourcing/1', 'GET', undefined, 409, {
'X-SGF-Context': 'bad',
});
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403, {
'X-Purchasing-Context': 'procurement.third_party',
});
await clients[consult]('/api/sourcing/9999999', 'GET', undefined, 404);
checks.push(
'Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected',
);
const evalData = async (id, who) => {
const s = await read(who);
return {
supplier_id: id,
quote_revision: s.state.quotes[id].revision,
quality: 8,
history: 8,
payment: 8,
no_conflict: true,
reason: 'Synthetic independent evaluation for isolated test.',
};
};
// Real concurrent database sessions, not just serial requests to PHP's development server.
const initial=await read(rev),workerInput={actor_id:2,payload:{operation_key:crypto.randomUUID(),version:initial.state.version,...await evalData(1,rev)}};fs.writeFileSync(work+'/worker.json',JSON.stringify(workerInput));
const worker=(file='worker.json')=>new Promise((resolve,reject)=>{const p=spawn(php,[repo+'/tests/Support/sgf-sourcing-worker.php',work+'/'+file],{cwd:host,env:process.env,windowsHide:true});let out='',err='';p.stdout.on('data',d=>out+=d);p.stderr.on('data',d=>err+=d);p.on('exit',code=>{try{if(code!==0)throw Error(err);resolve(JSON.parse(out));}catch(e){reject(e);}});});
const workers=await Promise.all([worker(),worker()]);assert(workers.every(w=>w.status===200),JSON.stringify(workers));assert.deepEqual(workers[0].result,workers[1].result);checks.push('Concurrent identical commands return one committed version');
const raceVersion=(await read(rev)).state.version;
for(const [file,id] of [['race-a.json',2],['race-b.json',3]])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:2,payload:{operation_key:crypto.randomUUID(),version:raceVersion,...await evalData(id,rev)}}));
const racing=await Promise.all([worker('race-a.json'),worker('race-b.json')]);assert.deepEqual(racing.map(r=>r.status).sort(),[200,409]);checks.push('Concurrent distinct commands use compare-and-swap; stale version refused');
for(const id of [1,2,3]){if(id!==1)await command(rev,'evaluate',await evalData(id,rev));await command(dec,'evaluate',await evalData(id,dec));}
let ready=await read(rev);assert(ready.comparison.ready);assert.deepEqual(ready.comparison.top_ids,[1]);
const proposed=await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Best eligible synthetic quote with exact comparison version.'});
await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload);checks.push('Proposal retry is idempotent');
const confirmData=async()=>{const d=await read(dec);return {proposal_index:d.state.proposals.length-1,comparison_hash:d.state.proposals.at(-1).comparison_hash,reason:'Independent confirmation of the preserved comparison.'};};
const initial = await read(rev),
workerInput = {
actor_id: 2,
payload: {
operation_key: crypto.randomUUID(),
version: initial.state.version,
...(await evalData(1, rev)),
},
};
fs.writeFileSync(work + '/worker.json', JSON.stringify(workerInput));
const worker = (file = 'worker.json') =>
new Promise((resolve, reject) => {
const p = spawn(
php,
[
repo + '/tests/Support/sgf-sourcing-worker.php',
work + '/' + file,
],
{ cwd: host, env: process.env, windowsHide: true },
);
let out = '',
err = '';
p.stdout.on('data', (d) => (out += d));
p.stderr.on('data', (d) => (err += d));
p.on('exit', (code) => {
try {
if (code !== 0) throw Error(err);
resolve(JSON.parse(out));
} catch (e) {
reject(e);
}
});
});
const workers = await Promise.all([worker(), worker()]);
assert(
workers.every((w) => w.status === 200),
JSON.stringify(workers),
);
assert.deepEqual(workers[0].result, workers[1].result);
checks.push('Concurrent identical commands return one committed version');
const raceVersion = (await read(rev)).state.version;
for (const [file, id] of [
['race-a.json', 2],
['race-b.json', 3],
])
fs.writeFileSync(
work + '/' + file,
JSON.stringify({
actor_id: 2,
payload: {
operation_key: crypto.randomUUID(),
version: raceVersion,
...(await evalData(id, rev)),
},
}),
);
const racing = await Promise.all([
worker('race-a.json'),
worker('race-b.json'),
]);
assert.deepEqual(racing.map((r) => r.status).sort(), [200, 409]);
checks.push(
'Concurrent distinct commands use compare-and-swap; stale version refused',
);
for (const id of [1, 2, 3]) {
if (id !== 1) await command(rev, 'evaluate', await evalData(id, rev));
await command(dec, 'evaluate', await evalData(id, dec));
}
let ready = await read(rev);
assert(ready.comparison.ready);
assert.deepEqual(ready.comparison.top_ids, [1]);
const proposed = await command(rev, 'propose', {
supplier_id: 1,
comparison_hash: ready.comparison.fingerprint,
reason: 'Best eligible synthetic quote with exact comparison version.',
});
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload);
checks.push('Proposal retry is idempotent');
const confirmData = async () => {
const d = await read(dec);
return {
proposal_index: d.state.proposals.length - 1,
comparison_hash: d.state.proposals.at(-1).comparison_hash,
reason: 'Independent confirmation of the preserved comparison.',
};
};
// The proposer does not possess confirm; independence is also tested in the shared core.
await command(rev,'confirm',await confirmData(),403);
await command(prep,'quote',quote(1,'100.00',6));await command(dec,'confirm',await confirmData(),409);checks.push('Changed quote blocks stale confirmation and invalidates evaluations');
function control(name){const r=spawnSync(php,[repo+'/tests/Support/sgf-sourcing-controls.php',name],{cwd:host,env:process.env,encoding:'utf8',windowsHide:true});assert.equal(r.status,0,r.stderr);}
for(const who of [rev,dec])await command(who,'evaluate',await evalData(1,who));
ready=await read(rev);await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Re-proposed using current quote revision and comparison.'});
control('revoke-evaluate');await command(dec,'confirm',await confirmData(),409);control('restore-evaluate');
control('revoke-propose');await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload,403);control('restore-propose');
control('revoke-view');await clients[consult]('/api/sourcing/1','GET',undefined,403);control('restore-view');checks.push('Revocation is effective for existing sessions, replay and qualified evaluations');
const beforeFail=await read(prep);control('fail-on');await command(prep,'quote',quote(2,'110.00',7),500);control('fail-off');const afterFail=await read(prep);assert.equal(afterFail.state.version,beforeFail.state.version);assert.equal(afterFail.history.length,beforeFail.history.length);checks.push('Injected failure after event rolls back state, event and receipt');
const confirmVersion=(await read(dec)).state.version,confirmation=await confirmData();
for(const file of ['confirm-a.json','confirm-b.json'])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:fixture.user_id,action:'confirm',payload:{operation_key:crypto.randomUUID(),version:confirmVersion,...confirmation}}));
const confirmations=await Promise.all([worker('confirm-a.json'),worker('confirm-b.json')]);assert.deepEqual(confirmations.map(r=>r.status).sort(),[200,409]);
const confirmed=await read(consult);assert(confirmed.state.confirmed);assert.equal(confirmed.state.confirmed.confirmed_by,fixture.user_id);assert.equal(confirmed.state.confirmed.proposal.proposed_by,2);checks.push('Concurrent confirmations produce one immutable independent award');
await command(prep,'quote',quote(1),409);checks.push('Independent confirmation references exact comparison and final state is immutable');
const origin=await clients[consult]('/api/internal-requisitions/1');assert.equal(origin.record.version,3);assert.equal(origin.record.total_minor,10000);assert.equal(origin.history.length,3);checks.push('Accepted requisition read path remains intact');
await clients[consult]('/purchasing/sourcing/1');await clients[consult]('/purchasing/sourcing/screen.mjs');checks.push('Authenticated read-only screen and module script served through protected routes');
console.log(JSON.stringify({passed:true,checks,request_id:1,confirmed_only_in_isolated_copy:true,account_fixture_only_in_copy:true}));
await command(rev, 'confirm', await confirmData(), 403);
await command(prep, 'quote', quote(1, '100.00', 6));
await command(dec, 'confirm', await confirmData(), 409);
checks.push(
'Changed quote blocks stale confirmation and invalidates evaluations',
);
function control(name) {
const r = spawnSync(
php,
[repo + '/tests/Support/sgf-sourcing-controls.php', name],
{ cwd: host, env: process.env, encoding: 'utf8', windowsHide: true },
);
assert.equal(r.status, 0, r.stderr);
}
for (const who of [rev, dec])
await command(who, 'evaluate', await evalData(1, who));
ready = await read(rev);
await command(rev, 'propose', {
supplier_id: 1,
comparison_hash: ready.comparison.fingerprint,
reason: 'Re-proposed using current quote revision and comparison.',
});
control('revoke-evaluate');
await command(dec, 'confirm', await confirmData(), 409);
control('restore-evaluate');
control('revoke-propose');
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload, 403);
control('restore-propose');
control('revoke-view');
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403);
control('restore-view');
checks.push(
'Revocation is effective for existing sessions, replay and qualified evaluations',
);
const beforeFail = await read(prep);
control('fail-on');
await command(prep, 'quote', quote(2, '110.00', 7), 500);
control('fail-off');
const afterFail = await read(prep);
assert.equal(afterFail.state.version, beforeFail.state.version);
assert.equal(afterFail.history.length, beforeFail.history.length);
checks.push('Injected failure after event rolls back state, event and receipt');
const confirmVersion = (await read(dec)).state.version,
confirmation = await confirmData();
for (const file of ['confirm-a.json', 'confirm-b.json'])
fs.writeFileSync(
work + '/' + file,
JSON.stringify({
actor_id: fixture.user_id,
action: 'confirm',
payload: {
operation_key: crypto.randomUUID(),
version: confirmVersion,
...confirmation,
},
}),
);
const confirmations = await Promise.all([
worker('confirm-a.json'),
worker('confirm-b.json'),
]);
assert.deepEqual(confirmations.map((r) => r.status).sort(), [200, 409]);
const confirmed = await read(consult);
assert(confirmed.state.confirmed);
assert.equal(confirmed.state.confirmed.confirmed_by, fixture.user_id);
assert.equal(confirmed.state.confirmed.proposal.proposed_by, 2);
checks.push('Concurrent confirmations produce one immutable independent award');
await command(prep, 'quote', quote(1), 409);
checks.push(
'Independent confirmation references exact comparison and final state is immutable',
);
const origin = await clients[consult]('/api/internal-requisitions/1');
assert.equal(origin.record.version, 3);
assert.equal(origin.record.total_minor, 10000);
assert.equal(origin.history.length, 3);
checks.push('Accepted requisition read path remains intact');
await clients[consult]('/purchasing/sourcing/1');
await clients[consult]('/purchasing/sourcing/screen.mjs');
checks.push(
'Authenticated read-only screen and module script served through protected routes',
);
console.log(
JSON.stringify({
passed: true,
checks,
request_id: 1,
confirmed_only_in_isolated_copy: true,
account_fixture_only_in_copy: true,
}),
);
+28 -11
View File
@@ -1,15 +1,32 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Shared\Context\CompanyContext;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
$host=getenv('SOURCING_CLONE');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
$input=json_decode(file_get_contents($argv[1]),true,32,JSON_THROW_ON_ERROR);$user=User::findOrFail($input['actor_id']);
auth()->setUser($user);app(CompanyContext::class)->selectFor($user->id,1,1,1);
$request=Request::create('/api/sourcing/1/evaluate','POST');$request->headers->set('X-Purchasing-Context','procurement.internal');$app->instance('request',$request);
$result=(new Tempo\Purchasing\SgfSourcing\Workspace($user))->command(1,$input['action']??'evaluate',$input['payload']);
echo json_encode(['status'=>200,'result'=>$result]);
}catch(Throwable $e){echo json_encode(['status'=>$e instanceof Symfony\Component\HttpKernel\Exception\HttpExceptionInterface?$e->getStatusCode():($e instanceof Tempo\Purchasing\Internal\RequisitionFailure?$e->status:500),'message'=>$e->getMessage()]);}
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Purchasing\Internal\RequisitionFailure;
use Tempo\Purchasing\SgfSourcing\Workspace;
$host = getenv('SOURCING_CLONE');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
throw new RuntimeException('Copy only');
}
$input = json_decode(file_get_contents($argv[1]), true, 32, JSON_THROW_ON_ERROR);
$user = User::findOrFail($input['actor_id']);
auth()->setUser($user);
app(CompanyContext::class)->selectFor($user->id, 1, 1, 1);
$request = Request::create('/api/sourcing/1/evaluate', 'POST');
$request->headers->set('X-Purchasing-Context', 'procurement.internal');
$app->instance('request', $request);
$result = (new Workspace($user))->command(1, $input['action'] ?? 'evaluate', $input['payload']);
echo json_encode(['status' => 200, 'result' => $result]);
} catch (Throwable $e) {
echo json_encode(['status' => $e instanceof HttpExceptionInterface ? $e->getStatusCode() : ($e instanceof RequisitionFailure ? $e->status : 500), 'message' => $e->getMessage()]);
}
+10 -6
View File
@@ -37,7 +37,9 @@ function updateFixture(string $original, array $manifest, bool $native = false):
}
copy($original.'/composer.json', $root.'/composer.json');
copy($original.'/artisan', $root.'/artisan');
if (!is_dir($root.'/public')) mkdir($root.'/public', 0700, true);
if (! is_dir($root.'/public')) {
mkdir($root.'/public', 0700, true);
}
copy($original.'/public/index.php', $root.'/public/index.php');
} else {
foreach ($manifest['host_overlays'] as $file => $values) {
@@ -49,9 +51,11 @@ function updateFixture(string $original, array $manifest, bool $native = false):
// Frontend overlays are existing host files too; preserve their exact baseline
// in native copies without sharing mutable assets with the real destination.
foreach ($manifest['host_overlays'] as $file => $values) {
if (!is_file($root.'/'.$file)) {
if (!is_dir(dirname($root.'/'.$file))) mkdir(dirname($root.'/'.$file),0700,true);
copy($original.'/'.$file,$root.'/'.$file);
if (! is_file($root.'/'.$file)) {
if (! is_dir(dirname($root.'/'.$file))) {
mkdir(dirname($root.'/'.$file), 0700, true);
}
copy($original.'/'.$file, $root.'/'.$file);
}
}
foreach (['bootstrap/cache', 'packages/purchasing', 'storage/framework/views', 'storage/framework/cache', 'storage/framework/sessions', 'storage/logs'] as $directory) {
@@ -59,8 +63,8 @@ function updateFixture(string $original, array $manifest, bool $native = false):
mkdir($root.'/'.$directory, 0700, true);
}
}
copy($original.'/packages/purchasing/current.json',$root.'/packages/purchasing/current.json');
file_put_contents($root.'/storage/framework/down','{"status":503}');
copy($original.'/packages/purchasing/current.json', $root.'/packages/purchasing/current.json');
file_put_contents($root.'/storage/framework/down', '{"status":503}');
return $root;
}
+47 -9
View File
@@ -1,11 +1,49 @@
<?php
$file=realpath($argv[1]??'');$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));if(!$file||!$root||!str_starts_with($file,$root.DIRECTORY_SEPARATOR))throw new RuntimeException('Wrong native return worker input');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong worker QA database');
$p=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);$db->select("SELECT set_config('application_name',?,false)",[$p['application']]);$db->statement("SET lock_timeout='8s'");
$actor=App\Models\User::findOrFail($p['actor']);auth()->guard()->setUser($actor);config(['stock_returns.enabled'=>true]);
$action=$p['action']??'confirm';if(!in_array($action,['confirm','withdraw','reject'],true))throw new RuntimeException('Invalid worker action');
$input=['version'=>1,'reason'=>'Synthetic concurrent native warehouse decision.']+($action==='confirm'?['received_in_warehouse'=>true]:[]);
try{if($p['http']??false){$request=Illuminate\Http\Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action,'POST',$input,[],[],['HTTP_ACCEPT'=>'application/json','HTTP_X_REQUESTED_WITH'=>'XMLHttpRequest']);$kernel=$app->make(Illuminate\Contracts\Http\Kernel::class);$response=$kernel->handle($request);$out=['status'=>$response->getStatusCode(),'result'=>json_decode($response->getContent(),true)];$kernel->terminate($request,$response);}else{$flow=app(App\Services\WarehouseReturns::class);$result=$action==='confirm'?$flow->confirm($actor,$p['proposal'],$input):$flow->close($actor,$p['proposal'],$input,$action==='withdraw'?'withdrawn':'rejected');$out=['status'=>200,'result'=>$result];}}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
use App\Models\User;
use App\Services\WarehouseReturns;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$file = realpath($argv[1] ?? '');
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
if (! $file || ! $root || ! str_starts_with($file, $root.DIRECTORY_SEPARATOR)) {
throw new RuntimeException('Wrong native return worker input');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new RuntimeException('Wrong worker QA database');
}
$p = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)", [$p['application']]);
$db->statement("SET lock_timeout='8s'");
$actor = User::findOrFail($p['actor']);
auth()->guard()->setUser($actor);
config(['stock_returns.enabled' => true]);
$action = $p['action'] ?? 'confirm';
if (! in_array($action, ['confirm', 'withdraw', 'reject'], true)) {
throw new RuntimeException('Invalid worker action');
}
$input = ['version' => 1, 'reason' => 'Synthetic concurrent native warehouse decision.'] + ($action === 'confirm' ? ['received_in_warehouse' => true] : []);
try {
if ($p['http'] ?? false) {
$request = Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action, 'POST', $input, [], [], ['HTTP_ACCEPT' => 'application/json', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle($request);
$out = ['status' => $response->getStatusCode(), 'result' => json_decode($response->getContent(), true)];
$kernel->terminate($request, $response);
} else {
$flow = app(WarehouseReturns::class);
$result = $action === 'confirm' ? $flow->confirm($actor, $p['proposal'], $input) : $flow->close($actor, $p['proposal'], $input, $action === 'withdraw' ? 'withdrawn' : 'rejected');
$out = ['status' => 200, 'result' => $result];
}
} catch (HttpExceptionInterface $e) {
$out = ['status' => $e->getStatusCode()];
}
file_put_contents($file.'.result',json_encode($out,JSON_THROW_ON_ERROR));