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

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
+187
View File
@@ -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;