Binary file not shown.
@@ -0,0 +1,29 @@
|
||||
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 results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
for(const path of ['/compras/pesquisa','/compras/pesquisa?q=REQ','/administracao/parametrizacao','/relatorios']) {
|
||||
const response=await viewer.request(path);
|
||||
const expected=path==='/administracao/parametrizacao' ? (role==='admin'?200:403) : path==='/relatorios'&&role==='warehouse'?403:200;
|
||||
assert.equal(response.status,expected,role+' '+path);
|
||||
if(response.status===200) {
|
||||
if(path==='/compras/pesquisa') assert.deepEqual(response.page.props.groups,[]);
|
||||
if(path==='/compras/pesquisa?q=REQ') assert.ok(Array.isArray(response.page.props.groups));
|
||||
if(path==='/administracao/parametrizacao') {
|
||||
assert.equal(response.page.props.companyDetailsReady,true);
|
||||
assert.equal(response.page.props.companyDetails,null);
|
||||
}
|
||||
if(path==='/relatorios') assert.equal(typeof response.page.props.insights.approval_times.measured,'number');
|
||||
}
|
||||
results.push({role,path,status:response.status,component:response.page?.component??null});
|
||||
}
|
||||
}
|
||||
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);
|
||||
@@ -0,0 +1,44 @@
|
||||
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 results = [];
|
||||
for (const role of ['admin', 'procurement', 'finance']) {
|
||||
const viewer = client();
|
||||
await viewer.enter(role);
|
||||
assert.equal((await viewer.request('/contexto', 'POST', {area:'procurement', option:'procurement.internal'})).status, 302);
|
||||
const geography=await viewer.request('/api/divisao-administrativa?parent=&page=1','GET',undefined,false);
|
||||
assert.equal(geography.status,200);
|
||||
assert.equal(geography.page.data.length,11);
|
||||
assert.equal(geography.page.catalogue,'70996d9a9133785a848de90bedb4bf685e24d8f823cd153c0adc43eac642a292');
|
||||
results.push({role,path:'administrative-geography',status:200,topLevelOptions:11});
|
||||
for (const path of ['/requisicoes', '/cotacoes', '/fornecedores', '/compras/fornecimento', '/compras/acordos/vigencia']) {
|
||||
const response = await viewer.request(path);
|
||||
assert.ok([200,403].includes(response.status), role+' '+path+' returned '+response.status);
|
||||
results.push({role,path,status:response.status,component:response.page?.component??null});
|
||||
if (path === '/cotacoes' && response.status === 200) {
|
||||
const row=response.page.props.requisitions.data[0];
|
||||
if(row) {
|
||||
const detail=await viewer.request('/requisicoes/'+row.id+'/cotacoes');
|
||||
assert.equal(detail.status,200);
|
||||
assert.equal(detail.page.props.exchangeAvailable,true);
|
||||
results.push({role,path:'quotation-detail',status:200,exchangeAvailable:true});
|
||||
}
|
||||
}
|
||||
if(path === '/fornecedores' && response.status === 200) {
|
||||
const row=response.page.props.suppliers.data[0];
|
||||
if(row) {
|
||||
const detail=await viewer.request('/fornecedores/'+row.id+'/dados-bancarios');
|
||||
assert.equal(detail.status,200);
|
||||
assert.equal(detail.page.props.multiAccountsAvailable,true);
|
||||
results.push({role,path:'supplier-bank-detail',status:200,multiAccountsAvailable:true});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
if (! in_array('--inspect-commercial-schema', $argv, true)) {
|
||||
throw new LogicException('Exige a opção explícita de inspecção, sem instalação.');
|
||||
}
|
||||
$root = dirname(__DIR__);
|
||||
$settings = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|
||||
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|
||||
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
|
||||
throw new LogicException('Destino do piloto não coincide com a configuração aprovada.');
|
||||
}
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$base = DB::connection('pgsql')->getConfig();
|
||||
unset($base['name']);
|
||||
config(['database.connections.commercial_preflight' => [...$base, 'url' => null, 'host' => $settings['DB_HOST'],
|
||||
'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']]]);
|
||||
$db = DB::connection('commercial_preflight');
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
|
||||
throw new LogicException('Identidade do destino não confirmada.');
|
||||
}
|
||||
$schema = $db->getSchemaBuilder();
|
||||
$targets = ['2026_11_21_000001_create_quotation_exchange_rates.php', '2026_11_21_000002_add_supplier_bank_account_keys.php'];
|
||||
$hashes = [];
|
||||
foreach ($targets as $name) {
|
||||
$hashes[$name] = hash_file('sha256', $root.'/database/migrations/'.$name);
|
||||
}
|
||||
$report = ['inspection_only' => true, 'target' => 'SGC local 8005', 'consistent_read_only' => true,
|
||||
'public_tables' => (int) $db->selectOne("select count(*) as n from pg_tables where schemaname='public'")->n,
|
||||
'fx_table_present' => $schema->hasTable('quotation_exchange_rates'), 'quotation_fx_column_present' => $schema->hasColumn('quotations', 'exchange_basis'),
|
||||
'bank_account_key_present' => $schema->hasColumn('supplier_bank_details', 'account_key'),
|
||||
'migration_hashes' => $hashes, 'pilot_manifest_sha256' => hash_file('sha256', $root.'/public/build/manifest.json')];
|
||||
$db->commit();
|
||||
echo json_encode($report, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($db->transactionLevel() !== 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
DB::purge('commercial_preflight');
|
||||
}
|
||||
@@ -0,0 +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 ='));
|
||||
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);
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
const response=await viewer.request('/compras/pesquisa?q=TEST');
|
||||
assert.equal(response.status,200);
|
||||
assert.equal(response.page.props.groups.length,role==='warehouse'?5:7);
|
||||
results.push({role,path:'/compras/pesquisa?q=TEST',status:200,sources:response.page.props.groups.map(group=>group.key)});
|
||||
if(role==='admin') {
|
||||
const form=await viewer.request('/requisicoes/criar');
|
||||
assert.equal(form.status,200);
|
||||
assert.equal(form.page.props.incompleteDraftsAvailable,true);
|
||||
results.push({role,path:'/requisicoes/criar',status:200,incompleteDraftsAvailable:true});
|
||||
const report=await viewer.request('/relatorios');
|
||||
assert.equal(report.status,200);
|
||||
results.push({role,path:'/relatorios',status:200});
|
||||
}
|
||||
}
|
||||
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);
|
||||
@@ -0,0 +1,30 @@
|
||||
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 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']){
|
||||
const viewer=client();await viewer.enter(role);
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
for(const path of paths){
|
||||
const response=await viewer.request(path);assert.ok([200,403,503].includes(response.status),role+' '+path+' '+response.status);
|
||||
const props=response.page?.props??{};
|
||||
const list=props.orders?.data??props.receipts?.data??props.requests?.data??props.records?.data??[];
|
||||
rows.push({role,path,status:response.status,component:response.page?.component??null,visible_page_records:Array.isArray(list)?list.length:null});
|
||||
if(role==='procurement'&&path==='/ordens')for(const item of list.slice(0,2))prints.add('/ordens/'+item.id+'/imprimir');
|
||||
if(role==='procurement'&&path==='/recepcoes')for(const item of list.slice(0,2))prints.add('/recepcoes/'+item.id+'/imprimir');
|
||||
}
|
||||
if(role==='admin'){
|
||||
const change=await viewer.request('/contexto','POST',{area:'people',option:'people.internal'});
|
||||
if(change.status===302)for(const path of ['/pessoas','/pessoas/tarefas','/pessoas/relatorios','/pessoas/cadastro']){
|
||||
const r=await viewer.request(path);assert.ok([200,403,503].includes(r.status));
|
||||
rows.push({role,path,status:r.status,component:r.page?.component??null,visible_page_records:r.page?.props.processes?.data?.length??null});
|
||||
}
|
||||
}
|
||||
}
|
||||
await fs.writeFile('docs/proofs/final-review-inventory.json',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);
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
if (! in_array('--apply-authorized', $argv, true)) {
|
||||
throw new LogicException('Instalação exige opção explícita e autorização registada.');
|
||||
}
|
||||
$authorization = json_decode(file_get_contents($root.'/docs/proofs/benchmark-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$expected = ['2026_11_22_000001_add_company_details_to_tenants.php' => '47477a97242f5b0b30e130853b91c463e5257cac250aee662a5b681fe544b923'];
|
||||
$manifestHash = '4c8c11cc7a5908ae7c12fcd74073b728fc0adec0faff041f4546a50ab4bd05ee';
|
||||
$oldManifestHash = '31ae1a57572bd509381fc29512b09d7d3bf9b33f5f3671db2db04186f03ba50e';
|
||||
$candidate = $root.'/storage/framework/testing/benchmark-candidate-20261122';
|
||||
if (($authorization['status'] ?? '') !== 'approved' || ($authorization['environment'] ?? '') !== 'http://127.0.0.1:8005'
|
||||
|| ($authorization['scope'] ?? '') !== 'company_details_schema_and_benchmark_assets' || ($authorization['migration_hashes'] ?? []) !== $expected
|
||||
|| ($authorization['manifest_sha256'] ?? '') !== $manifestHash || file_exists($root.'/docs/proofs/benchmark-pilot-installation.json')) {
|
||||
throw new LogicException('Autorização incompatível ou instalação já registada.');
|
||||
}
|
||||
foreach ($expected as $name => $hash) {
|
||||
if (hash_file('sha256', $root.'/database/migrations/'.$name) !== $hash) {
|
||||
throw new LogicException('Migração mudou desde a proposta.');
|
||||
}
|
||||
}
|
||||
if (hash_file('sha256', $candidate.'/manifest.json') !== $manifestHash || hash_file('sha256', $root.'/public/build/manifest.json') !== $oldManifestHash) {
|
||||
throw new LogicException('Candidata ou manifesto anterior não coincide.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($candidate.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$assets = [];
|
||||
foreach ($manifest as $entry) {
|
||||
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
|
||||
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! is_file($candidate.'/'.$file)) {
|
||||
throw new LogicException('Alvo de assets inválido.');
|
||||
}
|
||||
$assets[$file] = hash_file('sha256', $candidate.'/'.$file);
|
||||
if (is_file($root.'/public/build/'.$file) && hash_file('sha256', $root.'/public/build/'.$file) !== $assets[$file]) {
|
||||
throw new LogicException('Não sobrescrever um chunk existente divergente.');
|
||||
}
|
||||
}
|
||||
}
|
||||
$s = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($s['APP_ENV'] ?? '') !== 'payable-testing' || ($s['DB_HOST'] ?? '') !== '127.0.0.1' || realpath($s['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $s['DB_DATABASE'] ?? '', $m) || $s['DB_USERNAME'] !== 'payable_qa_'.$m[1]) {
|
||||
throw new LogicException('Destino do piloto não confirmado.');
|
||||
}
|
||||
$settingsHash = hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json');
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$owner = DB::connection('pgsql')->getConfig();
|
||||
unset($owner['name']);
|
||||
if ($owner['host'] !== '127.0.0.1') {
|
||||
throw new LogicException('Servidor administrativo não local.');
|
||||
}
|
||||
$qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']];
|
||||
config(['database.connections.commercial_install' => $qa, 'database.connections.commercial_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
|
||||
DB::setDefaultConnection('commercial_install');
|
||||
$db = DB::connection();
|
||||
$admin = DB::connection('commercial_owner');
|
||||
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $s['DB_DATABASE'] || $identity->role !== $s['DB_USERNAME']) {
|
||||
throw new LogicException('Identidade do piloto não coincide.');
|
||||
}
|
||||
$schema = $db->getSchemaBuilder();
|
||||
if ($schema->hasColumn('tenants', 'company_details')) {
|
||||
throw new LogicException('Estruturas já presentes: inspeccionar sem repetir.');
|
||||
}
|
||||
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$columns = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = $schema->getColumnListing($table);
|
||||
}
|
||||
$fingerprint = static function ($connection) use ($columns): array {
|
||||
$out = [];
|
||||
foreach ($columns as $table => $names) {
|
||||
$selected = implode(',', array_map(fn ($c) => '"'.str_replace('"', '""', $c).'"', $names));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
|
||||
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$pg = static function ($binary, $args, $connection): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $connection['host'],
|
||||
'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Cópia/restauro não aprovado; nenhuma instalação deve prosseguir.');
|
||||
}
|
||||
};
|
||||
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-benchmark-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new RuntimeException('Salvaguarda indisponível.');
|
||||
}
|
||||
$dump = $directory.'/before.dump';
|
||||
if (! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
|
||||
throw new RuntimeException('Não foi possível preservar o manifesto anterior.');
|
||||
}
|
||||
$restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
$paths = array_map(fn ($name) => 'database/migrations/'.$name, array_keys($expected));
|
||||
$migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($fingerprint, $paths): void {
|
||||
$previous = DB::getDefaultConnection();
|
||||
DB::setDefaultConnection($name);
|
||||
try {
|
||||
if (Artisan::call('migrate', ['--database' => $name, '--path' => $paths, '--force' => true]) !== 0) {
|
||||
throw new RuntimeException('Migrações delimitadas falharam.');
|
||||
}
|
||||
$after = $fingerprint($connection);
|
||||
unset($after['migrations'], $baseline['migrations']);
|
||||
if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 1
|
||||
|| $connection->table('tenants')->whereNotNull('company_details')->exists()) {
|
||||
throw new LogicException('Dados anteriores ou valores novos divergentes.');
|
||||
}
|
||||
} finally {
|
||||
DB::setDefaultConnection($previous);
|
||||
}
|
||||
};
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
||||
$baseline = $fingerprint($db);
|
||||
$migrationCount = $db->table('migrations')->count();
|
||||
$snapshot = $db->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$qa['database']], $qa);
|
||||
$db->commit();
|
||||
// Restore with the same existing role, not an administrative reader bypassing RLS.
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'" OWNER "'.$s['DB_USERNAME'].'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump], $qa);
|
||||
config(['database.connections.commercial_restore' => [...$qa, 'database' => $restore]]);
|
||||
$restored = DB::connection('commercial_restore');
|
||||
if ($fingerprint($restored) !== $baseline) {
|
||||
throw new LogicException('Restauro difere sob a mesma identidade/contexto.');
|
||||
}
|
||||
$migrateAndCheck($restored, 'commercial_restore', $baseline, $migrationCount);
|
||||
$db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount) {
|
||||
$db->statement("SET LOCAL lock_timeout = '5s'");
|
||||
foreach ($tables as $table) {
|
||||
$db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
|
||||
}
|
||||
if ($fingerprint($db) !== $baseline) {
|
||||
throw new LogicException('Piloto mudou desde a salvaguarda; instalação recusada.');
|
||||
}
|
||||
$migrateAndCheck($db, 'commercial_install', $baseline, $migrationCount);
|
||||
});
|
||||
$result = ['environment' => 'http://127.0.0.1:8005', 'scope' => 'company_details_schema_and_benchmark_assets', 'schema_installed' => true,
|
||||
'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'restored_tables_checked' => count($tables),
|
||||
'previous_tables_preserved' => count($tables) - 1, 'migration_delta' => 1, 'new_values_empty' => true, 'same_restore_role' => true,
|
||||
'assets_installed' => false, 'settings_preserved' => $settingsHash === hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json')];
|
||||
file_put_contents($root.'/docs/proofs/benchmark-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
foreach ($assets as $file => $hash) {
|
||||
$target = $root.'/public/build/'.$file;
|
||||
if (! is_dir(dirname($target)) && ! mkdir(dirname($target), 0755, true)) {
|
||||
throw new RuntimeException('Não foi possível preparar pasta de assets.');
|
||||
}
|
||||
if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
|
||||
throw new RuntimeException('Cópia de asset falhou; manifesto anterior preservado.');
|
||||
}
|
||||
if (hash_file('sha256', $target) !== $hash) {
|
||||
throw new RuntimeException('Asset copiado diverge; manifesto anterior preservado.');
|
||||
}
|
||||
}
|
||||
if (! copy($candidate.'/manifest.json', $root.'/public/build/manifest.benchmark.tmp')
|
||||
|| ! rename($root.'/public/build/manifest.benchmark.tmp', $root.'/public/build/manifest.json')) {
|
||||
throw new RuntimeException('Troca do manifesto falhou; consultar salvaguarda.');
|
||||
}
|
||||
$result['assets_installed'] = hash_file('sha256', $root.'/public/build/manifest.json') === $manifestHash;
|
||||
$result['manifest_sha256'] = $manifestHash;
|
||||
$result['assets_verified'] = count($assets);
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
DB::purge('commercial_restore');
|
||||
if ($created) {
|
||||
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||
}
|
||||
}
|
||||
$result['restore_database_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/benchmark-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
if (! in_array('--apply-authorized', $argv, true)) {
|
||||
throw new LogicException('Instalação exige opção explícita e autorização registada.');
|
||||
}
|
||||
$authorization = json_decode(file_get_contents($root.'/docs/proofs/commercial-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$expected = ['2026_11_21_000001_create_quotation_exchange_rates.php' => '09bac87b702137955fa5caff8f977c4124c534458a656471f209eae26dd9dcfc',
|
||||
'2026_11_21_000002_add_supplier_bank_account_keys.php' => 'b1ce78ac221a0c220c4e166d6514d7b183637513409f46e97ccd84b8d7d67499'];
|
||||
$manifestHash = '238f343ff567e17a44234dd49a02e3985952e98233642647669a621ad39bfb19';
|
||||
$oldManifestHash = 'af3cb4e0f8ae9708da8bfb35489fad67051b869d12242d9adaaafdf401511b3b';
|
||||
$candidate = $root.'/storage/framework/testing/sgc-validation-candidate-20261122';
|
||||
if (($authorization['status'] ?? '') !== 'approved' || ($authorization['environment'] ?? '') !== 'http://127.0.0.1:8005'
|
||||
|| ($authorization['scope'] ?? '') !== 'commercial_schema_and_assets' || ($authorization['migration_hashes'] ?? []) !== $expected
|
||||
|| ($authorization['manifest_sha256'] ?? '') !== $manifestHash || file_exists($root.'/docs/proofs/commercial-pilot-installation.json')) {
|
||||
throw new LogicException('Autorização incompatível ou instalação já registada.');
|
||||
}
|
||||
foreach ($expected as $name => $hash) {
|
||||
if (hash_file('sha256', $root.'/database/migrations/'.$name) !== $hash) {
|
||||
throw new LogicException('Migração mudou desde a proposta.');
|
||||
}
|
||||
}
|
||||
if (hash_file('sha256', $candidate.'/manifest.json') !== $manifestHash || hash_file('sha256', $root.'/public/build/manifest.json') !== $oldManifestHash) {
|
||||
throw new LogicException('Candidata ou manifesto anterior não coincide.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($candidate.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$assets = [];
|
||||
foreach ($manifest as $entry) {
|
||||
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
|
||||
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! is_file($candidate.'/'.$file)) {
|
||||
throw new LogicException('Alvo de assets inválido.');
|
||||
}
|
||||
$assets[$file] = hash_file('sha256', $candidate.'/'.$file);
|
||||
if (is_file($root.'/public/build/'.$file) && hash_file('sha256', $root.'/public/build/'.$file) !== $assets[$file]) {
|
||||
throw new LogicException('Não sobrescrever um chunk existente divergente.');
|
||||
}
|
||||
}
|
||||
}
|
||||
$s = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($s['APP_ENV'] ?? '') !== 'payable-testing' || ($s['DB_HOST'] ?? '') !== '127.0.0.1' || realpath($s['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $s['DB_DATABASE'] ?? '', $m) || $s['DB_USERNAME'] !== 'payable_qa_'.$m[1]) {
|
||||
throw new LogicException('Destino do piloto não confirmado.');
|
||||
}
|
||||
$settingsHash = hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json');
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$owner = DB::connection('pgsql')->getConfig();
|
||||
unset($owner['name']);
|
||||
if ($owner['host'] !== '127.0.0.1') {
|
||||
throw new LogicException('Servidor administrativo não local.');
|
||||
}
|
||||
$qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']];
|
||||
config(['database.connections.commercial_install' => $qa, 'database.connections.commercial_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
|
||||
DB::setDefaultConnection('commercial_install');
|
||||
$db = DB::connection();
|
||||
$admin = DB::connection('commercial_owner');
|
||||
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $s['DB_DATABASE'] || $identity->role !== $s['DB_USERNAME']) {
|
||||
throw new LogicException('Identidade do piloto não coincide.');
|
||||
}
|
||||
$schema = $db->getSchemaBuilder();
|
||||
if ($schema->hasTable('quotation_exchange_rates') || $schema->hasColumn('quotations', 'exchange_basis') || $schema->hasColumn('supplier_bank_details', 'account_key')) {
|
||||
throw new LogicException('Estruturas já presentes: inspeccionar sem repetir.');
|
||||
}
|
||||
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$columns = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = $schema->getColumnListing($table);
|
||||
}
|
||||
$fingerprint = static function ($connection) use ($columns): array {
|
||||
$out = [];
|
||||
foreach ($columns as $table => $names) {
|
||||
$selected = implode(',', array_map(fn ($c) => '"'.str_replace('"', '""', $c).'"', $names));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
|
||||
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$pg = static function ($binary, $args, $connection): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $connection['host'],
|
||||
'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Cópia/restauro não aprovado; nenhuma instalação deve prosseguir.');
|
||||
}
|
||||
};
|
||||
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-commercial-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new RuntimeException('Salvaguarda indisponível.');
|
||||
}
|
||||
$dump = $directory.'/before.dump';
|
||||
if (! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
|
||||
throw new RuntimeException('Não foi possível preservar o manifesto anterior.');
|
||||
}
|
||||
$restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
$paths = array_map(fn ($name) => 'database/migrations/'.$name, array_keys($expected));
|
||||
$migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($fingerprint, $paths): void {
|
||||
$previous = DB::getDefaultConnection();
|
||||
DB::setDefaultConnection($name);
|
||||
try {
|
||||
if (Artisan::call('migrate', ['--database' => $name, '--path' => $paths, '--force' => true]) !== 0) {
|
||||
throw new RuntimeException('Migrações delimitadas falharam.');
|
||||
}
|
||||
$after = $fingerprint($connection);
|
||||
unset($after['migrations'], $baseline['migrations']);
|
||||
if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 2
|
||||
|| $connection->table('quotation_exchange_rates')->exists() || $connection->table('quotations')->whereNotNull('exchange_basis')->exists()
|
||||
|| $connection->table('supplier_bank_details')->whereNotNull('account_key')->exists()) {
|
||||
throw new LogicException('Dados anteriores ou valores novos divergentes.');
|
||||
}
|
||||
} finally {
|
||||
DB::setDefaultConnection($previous);
|
||||
}
|
||||
};
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
||||
$baseline = $fingerprint($db);
|
||||
$migrationCount = $db->table('migrations')->count();
|
||||
$snapshot = $db->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$qa['database']], $qa);
|
||||
$db->commit();
|
||||
// Restore with the same existing role, not an administrative reader bypassing RLS.
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'" OWNER "'.$s['DB_USERNAME'].'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump], $qa);
|
||||
config(['database.connections.commercial_restore' => [...$qa, 'database' => $restore]]);
|
||||
$restored = DB::connection('commercial_restore');
|
||||
if ($fingerprint($restored) !== $baseline) {
|
||||
throw new LogicException('Restauro difere sob a mesma identidade/contexto.');
|
||||
}
|
||||
$migrateAndCheck($restored, 'commercial_restore', $baseline, $migrationCount);
|
||||
$db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount) {
|
||||
$db->statement("SET LOCAL lock_timeout = '5s'");
|
||||
foreach ($tables as $table) {
|
||||
$db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
|
||||
}
|
||||
if ($fingerprint($db) !== $baseline) {
|
||||
throw new LogicException('Piloto mudou desde a salvaguarda; instalação recusada.');
|
||||
}
|
||||
$migrateAndCheck($db, 'commercial_install', $baseline, $migrationCount);
|
||||
});
|
||||
$result = ['environment' => 'http://127.0.0.1:8005', 'scope' => 'commercial_schema_and_assets', 'schema_installed' => true,
|
||||
'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'restored_tables_checked' => count($tables),
|
||||
'previous_tables_preserved' => count($tables) - 1, 'migration_delta' => 2, 'new_values_empty' => true, 'same_restore_role' => true,
|
||||
'assets_installed' => false, 'settings_preserved' => $settingsHash === hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json')];
|
||||
file_put_contents($root.'/docs/proofs/commercial-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
foreach ($assets as $file => $hash) {
|
||||
$target = $root.'/public/build/'.$file;
|
||||
if (! is_dir(dirname($target)) && ! mkdir(dirname($target), 0755, true)) {
|
||||
throw new RuntimeException('Não foi possível preparar pasta de assets.');
|
||||
}
|
||||
if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
|
||||
throw new RuntimeException('Cópia de asset falhou; manifesto anterior preservado.');
|
||||
}
|
||||
if (hash_file('sha256', $target) !== $hash) {
|
||||
throw new RuntimeException('Asset copiado diverge; manifesto anterior preservado.');
|
||||
}
|
||||
}
|
||||
if (! copy($candidate.'/manifest.json', $root.'/public/build/manifest.commercial.tmp')
|
||||
|| ! rename($root.'/public/build/manifest.commercial.tmp', $root.'/public/build/manifest.json')) {
|
||||
throw new RuntimeException('Troca do manifesto falhou; consultar salvaguarda.');
|
||||
}
|
||||
$result['assets_installed'] = hash_file('sha256', $root.'/public/build/manifest.json') === $manifestHash;
|
||||
$result['manifest_sha256'] = $manifestHash;
|
||||
$result['assets_verified'] = count($assets);
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
DB::purge('commercial_restore');
|
||||
if ($created) {
|
||||
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||
}
|
||||
}
|
||||
$result['restore_database_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/commercial-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$root = dirname(__DIR__);
|
||||
if (! in_array('--apply-authorized', $argv, true)) {
|
||||
throw new LogicException('Instalação exige opção explícita e autorização registada.');
|
||||
}
|
||||
$authorization = json_decode(file_get_contents($root.'/docs/proofs/draft-preparation-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$expected = ['2026_11_22_000002_allow_incomplete_requisition_drafts.php' => '5d1caaac0a0d21efb46974fc226168910b16391724e6642994859e893e8cd893'];
|
||||
$manifestHash = 'c2203372527050e083f6cc0aab47a1e08534015d692b3a8781a26ddf65109c23';
|
||||
$oldManifestHash = '4c8c11cc7a5908ae7c12fcd74073b728fc0adec0faff041f4546a50ab4bd05ee';
|
||||
$candidate = $root.'/storage/framework/testing/draft-preparation-candidate-20261122';
|
||||
if (($authorization['status'] ?? '') !== 'approved' || ($authorization['environment'] ?? '') !== 'http://127.0.0.1:8005'
|
||||
|| ($authorization['scope'] ?? '') !== 'incomplete_requisition_schema_and_search_assets' || ($authorization['migration_hashes'] ?? []) !== $expected
|
||||
|| ($authorization['manifest_sha256'] ?? '') !== $manifestHash || file_exists($root.'/docs/proofs/draft-preparation-pilot-installation.json')) {
|
||||
throw new LogicException('Autorização incompatível ou instalação já registada.');
|
||||
}
|
||||
foreach ($expected as $name => $hash) {
|
||||
if (hash_file('sha256', $root.'/database/migrations/'.$name) !== $hash) {
|
||||
throw new LogicException('Migração mudou desde a proposta.');
|
||||
}
|
||||
}
|
||||
if (hash_file('sha256', $candidate.'/manifest.json') !== $manifestHash || hash_file('sha256', $root.'/public/build/manifest.json') !== $oldManifestHash) {
|
||||
throw new LogicException('Candidata ou manifesto anterior não coincide.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($candidate.'/manifest.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$assets = [];
|
||||
foreach ($manifest as $entry) {
|
||||
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
|
||||
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! is_file($candidate.'/'.$file)) {
|
||||
throw new LogicException('Alvo de assets inválido.');
|
||||
}
|
||||
$assets[$file] = hash_file('sha256', $candidate.'/'.$file);
|
||||
if (is_file($root.'/public/build/'.$file) && hash_file('sha256', $root.'/public/build/'.$file) !== $assets[$file]) {
|
||||
throw new LogicException('Não sobrescrever um chunk existente divergente.');
|
||||
}
|
||||
}
|
||||
}
|
||||
$s = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($s['APP_ENV'] ?? '') !== 'payable-testing' || ($s['DB_HOST'] ?? '') !== '127.0.0.1' || realpath($s['HOST_ROOT'] ?? '') !== realpath($root)
|
||||
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $s['DB_DATABASE'] ?? '', $m) || $s['DB_USERNAME'] !== 'payable_qa_'.$m[1]) {
|
||||
throw new LogicException('Destino do piloto não confirmado.');
|
||||
}
|
||||
$settingsHash = hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json');
|
||||
$app = require $root.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$owner = DB::connection('pgsql')->getConfig();
|
||||
unset($owner['name']);
|
||||
if ($owner['host'] !== '127.0.0.1') {
|
||||
throw new LogicException('Servidor administrativo não local.');
|
||||
}
|
||||
$qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']];
|
||||
config(['database.connections.commercial_install' => $qa, 'database.connections.commercial_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
|
||||
DB::setDefaultConnection('commercial_install');
|
||||
$db = DB::connection();
|
||||
$admin = DB::connection('commercial_owner');
|
||||
$identity = $db->selectOne('select current_database() as db, current_user as role');
|
||||
if ($identity->db !== $s['DB_DATABASE'] || $identity->role !== $s['DB_USERNAME']) {
|
||||
throw new LogicException('Identidade do piloto não coincide.');
|
||||
}
|
||||
$schema = $db->getSchemaBuilder();
|
||||
if ($schema->hasColumn('requisitions', 'draft_input')) {
|
||||
throw new LogicException('Estruturas já presentes: inspeccionar sem repetir.');
|
||||
}
|
||||
$requisitionKeys = $schema->getForeignKeys('requisitions');
|
||||
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
|
||||
$columns = [];
|
||||
foreach ($tables as $table) {
|
||||
$columns[$table] = $schema->getColumnListing($table);
|
||||
}
|
||||
$fingerprint = static function ($connection) use ($columns): array {
|
||||
$out = [];
|
||||
foreach ($columns as $table => $names) {
|
||||
$selected = implode(',', array_map(fn ($c) => '"'.str_replace('"', '""', $c).'"', $names));
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
|
||||
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$pg = static function ($binary, $args, $connection): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$args], null, ['PGHOST' => $connection['host'],
|
||||
'PGPORT' => (string) $connection['port'], 'PGUSER' => $connection['username'], 'PGPASSWORD' => $connection['password']], timeout: 120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Cópia/restauro não aprovado; nenhuma instalação deve prosseguir.');
|
||||
}
|
||||
};
|
||||
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-drafts-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
|
||||
if (! mkdir($directory, 0700, true)) {
|
||||
throw new RuntimeException('Salvaguarda indisponível.');
|
||||
}
|
||||
$dump = $directory.'/before.dump';
|
||||
if (! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
|
||||
throw new RuntimeException('Não foi possível preservar o manifesto anterior.');
|
||||
}
|
||||
$restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
$paths = array_map(fn ($name) => 'database/migrations/'.$name, array_keys($expected));
|
||||
$migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($fingerprint, $paths, $requisitionKeys): void {
|
||||
$previous = DB::getDefaultConnection();
|
||||
DB::setDefaultConnection($name);
|
||||
try {
|
||||
if (Artisan::call('migrate', ['--database' => $name, '--path' => $paths, '--force' => true]) !== 0) {
|
||||
throw new RuntimeException('Migrações delimitadas falharam.');
|
||||
}
|
||||
$after = $fingerprint($connection);
|
||||
unset($after['migrations'], $baseline['migrations']);
|
||||
if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 1
|
||||
|| $connection->table('requisitions')->whereNotNull('draft_input')->exists()
|
||||
|| (int) $connection->selectOne("SELECT count(*) AS n FROM pg_constraint WHERE conname = 'requisitions_complete_before_submission' AND conrelid = 'requisitions'::regclass")->n !== 1
|
||||
|| $connection->getSchemaBuilder()->getForeignKeys('requisitions') !== $requisitionKeys) {
|
||||
throw new LogicException('Dados anteriores ou valores novos divergentes.');
|
||||
}
|
||||
} finally {
|
||||
DB::setDefaultConnection($previous);
|
||||
}
|
||||
};
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
||||
$baseline = $fingerprint($db);
|
||||
$migrationCount = $db->table('migrations')->count();
|
||||
$snapshot = $db->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
|
||||
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$qa['database']], $qa);
|
||||
$db->commit();
|
||||
// Restore with the same existing role, not an administrative reader bypassing RLS.
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'" OWNER "'.$s['DB_USERNAME'].'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $dump], $qa);
|
||||
config(['database.connections.commercial_restore' => [...$qa, 'database' => $restore]]);
|
||||
$restored = DB::connection('commercial_restore');
|
||||
if ($fingerprint($restored) !== $baseline) {
|
||||
throw new LogicException('Restauro difere sob a mesma identidade/contexto.');
|
||||
}
|
||||
$migrateAndCheck($restored, 'commercial_restore', $baseline, $migrationCount);
|
||||
$db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount) {
|
||||
$db->statement("SET LOCAL lock_timeout = '5s'");
|
||||
foreach ($tables as $table) {
|
||||
$db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
|
||||
}
|
||||
if ($fingerprint($db) !== $baseline) {
|
||||
throw new LogicException('Piloto mudou desde a salvaguarda; instalação recusada.');
|
||||
}
|
||||
$migrateAndCheck($db, 'commercial_install', $baseline, $migrationCount);
|
||||
});
|
||||
$result = ['environment' => 'http://127.0.0.1:8005', 'scope' => 'incomplete_requisition_schema_and_search_assets', 'schema_installed' => true,
|
||||
'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'restored_tables_checked' => count($tables),
|
||||
'previous_tables_preserved' => count($tables) - 1, 'migration_delta' => 1, 'new_values_empty' => true, 'same_restore_role' => true,
|
||||
'assets_installed' => false, 'settings_preserved' => $settingsHash === hash_file('sha256', 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json')];
|
||||
file_put_contents($root.'/docs/proofs/draft-preparation-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
foreach ($assets as $file => $hash) {
|
||||
$target = $root.'/public/build/'.$file;
|
||||
if (! is_dir(dirname($target)) && ! mkdir(dirname($target), 0755, true)) {
|
||||
throw new RuntimeException('Não foi possível preparar pasta de assets.');
|
||||
}
|
||||
if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
|
||||
throw new RuntimeException('Cópia de asset falhou; manifesto anterior preservado.');
|
||||
}
|
||||
if (hash_file('sha256', $target) !== $hash) {
|
||||
throw new RuntimeException('Asset copiado diverge; manifesto anterior preservado.');
|
||||
}
|
||||
}
|
||||
if (! copy($candidate.'/manifest.json', $root.'/public/build/manifest.drafts.tmp')
|
||||
|| ! rename($root.'/public/build/manifest.drafts.tmp', $root.'/public/build/manifest.json')) {
|
||||
throw new RuntimeException('Troca do manifesto falhou; consultar salvaguarda.');
|
||||
}
|
||||
$result['assets_installed'] = hash_file('sha256', $root.'/public/build/manifest.json') === $manifestHash;
|
||||
$result['manifest_sha256'] = $manifestHash;
|
||||
$result['assets_verified'] = count($assets);
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
DB::purge('commercial_restore');
|
||||
if ($created) {
|
||||
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
|
||||
}
|
||||
}
|
||||
$result['restore_database_removed'] = true;
|
||||
file_put_contents($root.'/docs/proofs/draft-preparation-pilot-installation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -8,6 +8,11 @@ import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
|
||||
def catalogue_bytes(data):
|
||||
# Preserve the exact approved Windows artifact on every platform.
|
||||
return (json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\r\n").encode("utf-8")
|
||||
|
||||
|
||||
def prepare(source, destination):
|
||||
content = Path(source).read_bytes()
|
||||
digest = hashlib.sha256(content).hexdigest()
|
||||
@@ -81,7 +86,7 @@ def prepare(source, destination):
|
||||
if previous["manifest"]["source_sha256"] != digest:
|
||||
raise ValueError("Preserve previous catalogue: use a new destination for a new source revision")
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
|
||||
destination.write_bytes(catalogue_bytes(result))
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
|
||||
@@ -37,10 +37,39 @@ try {
|
||||
}
|
||||
$bankMode = in_array('--bank-accounts-only', $argv, true);
|
||||
$conversionMode = in_array('--unit-conversion-only', $argv, true);
|
||||
$agreementMode = in_array('--agreement-followup-only', $argv, true);
|
||||
$orderLimitMode = in_array('--agreement-order-limits-only', $argv, true);
|
||||
$upgradeMode = in_array('--commercial-upgrade-only', $argv, true);
|
||||
$benchmarkMode = in_array('--benchmark-read-only', $argv, true);
|
||||
$draftMode = in_array('--draft-preparation-only', $argv, true);
|
||||
$searchMode = in_array('--procurement-search-only', $argv, true);
|
||||
$productionMode = in_array('--warehouse-production-only', $argv, true);
|
||||
if ($productionMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/WarehouseRequestsTest.php', 'tests/Feature/WarehouseFulfilmentTest.php', 'tests/Feature/AutomaticPurchasesTest.php']];
|
||||
}
|
||||
if ($searchMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementSearchTest.php']];
|
||||
}
|
||||
if ($draftMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/IncompleteRequisitionDraftTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionCatalogueTest.php', 'tests/Feature/PurchaseProcessTest.php', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/ProcurementReportsTest.php']];
|
||||
}
|
||||
if ($benchmarkMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ProcurementSearchTest.php', 'tests/Feature/ProcurementReportsTest.php']];
|
||||
}
|
||||
if ($upgradeMode) {
|
||||
$commands = [[PHP_BINARY, 'tests/Concurrency/commercial-upgrade-worker.php', $database]];
|
||||
}
|
||||
if ($conversionMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Conversion/ReceiptQuantityConversionTest.php']];
|
||||
$commands[] = [PHP_BINARY, 'tests/Concurrency/unit-conversion-worker.php', $database, 'race'];
|
||||
}
|
||||
if ($agreementMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/AgreementFollowupTest.php', 'tests/Feature/SupplyPlanningTest.php'],
|
||||
[PHP_BINARY, 'tests/Concurrency/agreement-followup-report-worker.php', $database]];
|
||||
}
|
||||
if ($orderLimitMode) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=per order']];
|
||||
}
|
||||
if ($bankMode && ! in_array('--concurrency-only', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierBankAccountsTest.php', 'tests/Feature/SupplierBankTest.php',
|
||||
'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/PaymentIntegrationTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php']];
|
||||
@@ -54,7 +83,7 @@ try {
|
||||
throw new RuntimeException('Validação PostgreSQL não aprovada.');
|
||||
}
|
||||
}
|
||||
if ($conversionMode) {
|
||||
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode) {
|
||||
return;
|
||||
}
|
||||
config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]);
|
||||
|
||||
@@ -0,0 +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', 'return (async()=>{' + common + `
|
||||
const results=[];
|
||||
for(const role of ['admin','procurement','finance','warehouse']) {
|
||||
const viewer=client(); await viewer.enter(role);
|
||||
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
|
||||
const response=await viewer.request('/compras/pesquisa?q=TEST');
|
||||
assert.equal(response.status,200);
|
||||
const keys=response.page.props.groups.map(group=>group.key);
|
||||
assert.equal(keys.length,role==='warehouse'?5:7);
|
||||
assert.equal(new Set(keys).size,keys.length);
|
||||
for(const key of ['equipment','stock','warehouses','receipts']) assert.ok(keys.includes(key));
|
||||
results.push({role,status:200,sources:keys});
|
||||
}
|
||||
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);
|
||||
Reference in New Issue
Block a user