commit melhorias compras4
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 16:28:03 +02:00
parent efd97e265b
commit 36dcfdf00c
118 changed files with 6042 additions and 92 deletions
+192
View File
@@ -0,0 +1,192 @@
<?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__);
$proof = $root.'/docs/proofs/approval-search-pilot-installation.json';
$settingsFile = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$authorization = json_decode(file_get_contents($root.'/docs/proofs/approval-search-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$proposal = json_decode(file_get_contents($root.'/docs/proofs/approval-search-pilot-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
if (! in_array('--apply-authorized', $argv, true) || $authorization['status'] !== 'approved'
|| $authorization['environment'] !== 'http://127.0.0.1:8005' || $authorization['proposal'] !== 'approval-search-pilot-proposal.json'
|| file_exists($proof)) {
throw new LogicException('Explicit authorization required; never repeat a recorded installation.');
}
$migration = 'database/migrations/2026_11_22_000003_add_configured_requisition_levels.php';
if ($proposal['migration']['file'] !== $migration || hash_file('sha256', $root.'/'.$migration) !== $authorization['migration_sha256']
|| $proposal['migration']['sha256'] !== $authorization['migration_sha256']
|| hash_file('sha256', $root.'/public/build/manifest.json') !== $authorization['manifest_sha256']) {
throw new LogicException('Reviewed migration or installed assets changed.');
}
$candidate = $root.'/storage/framework/testing/sgc-product-review-candidate-20261122';
$manifest = json_decode(file_get_contents($root.'/public/build/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, '..')
|| hash_file('sha256', $candidate.'/'.$file) !== hash_file('sha256', $root.'/public/build/'.$file)) {
throw new LogicException('Installed asset differs from the verified candidate.');
}
$assets[$file] = true;
}
}
$settingsBytes = file_get_contents($settingsFile);
$settingsHash = hash('sha256', $settingsBytes);
$s = json_decode($settingsBytes, 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'] ?? '', $match) || $s['DB_USERNAME'] !== 'payable_qa_'.$match[1]) {
throw new LogicException('Named pilot identity not confirmed.');
}
$flagNames = ['SGC_REQUISITION_APPROVAL_LEVELS_ENABLED', 'SGC_PROCUREMENT_FINANCE_SEARCH_ENABLED'];
foreach ($flagNames as $flag) {
if (filter_var($s[$flag] ?? false, FILTER_VALIDATE_BOOLEAN) || ($proposal['private_deployment_settings'][$flag] ?? null) !== true) {
throw new LogicException('Unexpected capability state; inspect without reapplying.');
}
}
$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('Administrative server must be local.');
}
$qa = [...$owner, 'url' => null, 'host' => $s['DB_HOST'], 'database' => $s['DB_DATABASE'], 'username' => $s['DB_USERNAME'], 'password' => $s['DB_PASSWORD']];
config(['database.connections.approval_install' => $qa, 'database.connections.approval_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
DB::setDefaultConnection('approval_install');
$db = DB::connection();
$admin = DB::connection('approval_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('Effective database identity mismatch.');
}
$schema = $db->getSchemaBuilder();
if ($schema->hasColumn('tenants', 'requisition_approval_policy') || $schema->hasColumn('approval_steps', 'routing')) {
throw new LogicException('Schema already present; do not reapply.');
}
$tables = array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
$columns = $keys = [];
foreach ($tables as $table) {
$columns[$table] = $schema->getColumnListing($table);
$keys[$table] = $schema->getForeignKeys($table);
}
$fingerprint = static function ($connection) use ($columns): array {
$out = [];
foreach ($columns as $table => $names) {
$selected = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $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, array $args, array $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('Backup/restore failed; do not install.');
}
};
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-approval-search-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
if (! mkdir($directory, 0700, true) || file_put_contents($directory.'/settings.before.json', $settingsBytes) !== strlen($settingsBytes)
|| ! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
throw new RuntimeException('Could not preserve deployment state.');
}
$dump = $directory.'/before.dump';
$restore = 'compras_pilot_restore_'.bin2hex(random_bytes(6));
$created = false;
$migrateAndCheck = static function ($connection, string $name, array $baseline, int $migrationCount) use ($migration, $fingerprint, $keys): void {
$previous = DB::getDefaultConnection();
DB::setDefaultConnection($name);
try {
if (Artisan::call('migrate', ['--database' => $name, '--path' => [$migration], '--force' => true]) !== 0) {
throw new RuntimeException('Exact migration failed.');
}
$after = $fingerprint($connection);
unset($after['migrations'], $baseline['migrations']);
if ($after !== $baseline || $connection->table('migrations')->count() !== $migrationCount + 1
|| $connection->table('tenants')->whereNotNull('requisition_approval_policy')->exists()
|| $connection->table('approval_steps')->whereNotNull('routing')->exists()) {
throw new LogicException('Old data changed or new columns are not empty.');
}
foreach ($keys as $table => $expected) {
if ($connection->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
throw new LogicException('Foreign keys changed.');
}
}
} 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();
$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.approval_restore' => [...$qa, 'database' => $restore]]);
$restored = DB::connection('approval_restore');
if ($fingerprint($restored) !== $baseline) {
throw new LogicException('Same-role restore differs from backup snapshot.');
}
$migrateAndCheck($restored, 'approval_restore', $baseline, $migrationCount);
$db->transaction(function () use ($db, $tables, $baseline, $fingerprint, $migrateAndCheck, $migrationCount, $settingsHash, $settingsFile) {
$db->statement("SET LOCAL lock_timeout = '5s'");
foreach ($tables as $table) {
$db->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
}
if ($fingerprint($db) !== $baseline || hash_file('sha256', $settingsFile) !== $settingsHash) {
throw new LogicException('Pilot changed after backup; installation refused.');
}
$migrateAndCheck($db, 'approval_install', $baseline, $migrationCount);
});
$result = ['environment' => 'http://127.0.0.1:8005', 'schema_installed' => true, 'capabilities_enabled' => false,
'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump), 'settings_backup' => $directory.'/settings.before.json',
'restored_tables_checked' => count($tables), 'previous_business_tables_preserved' => count($tables) - 1,
'same_restore_role' => true, 'foreign_keys_preserved' => true, 'new_values_null' => true, 'migration_delta' => 1,
'assets_verified' => count($assets), 'manifest_sha256' => $authorization['manifest_sha256'], 'business_commands' => false, 'grants_changed' => false];
file_put_contents($proof, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
if (hash_file('sha256', $settingsFile) !== $settingsHash) {
throw new LogicException('Settings changed before activation; schema retained, capabilities not enabled.');
}
$after = [...$s, $flagNames[0] => 'true', $flagNames[1] => 'true'];
$protected = $after;
foreach ($flagNames as $flag) {
unset($protected[$flag]);
}
$beforeProtected = $s;
foreach ($flagNames as $flag) {
unset($beforeProtected[$flag]);
}
if ($protected !== $beforeProtected) {
throw new LogicException('Unrelated deployment settings changed.');
}
$temporary = $settingsFile.'.approval-search.tmp';
$bytes = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
if (file_put_contents($temporary, $bytes) !== strlen($bytes) || ! rename($temporary, $settingsFile)) {
throw new RuntimeException('Could not atomically activate approved capabilities.');
}
$result['capabilities_enabled'] = json_decode(file_get_contents($settingsFile), true, 32, JSON_THROW_ON_ERROR) === $after;
$result['other_settings_preserved'] = true;
$result['changed_settings'] = $flagNames;
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
DB::purge('approval_restore');
if ($created) {
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
}
}
$result['restore_database_removed'] = true;
file_put_contents($proof, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;