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
@@ -0,0 +1,135 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$db = DB::connection();
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $db->getConfig('host') !== '127.0.0.1') {
throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$f = receiptFixture();
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
auth()->guard()->setUser($author);
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Synthetic pre-extension budget.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
auth()->guard()->setUser($author);
app(CommonBudget::class)->for($author)->record($f['r']->id, $f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
$balanceBefore = app(CommonBudget::class)->for($author)->balance($budget);
$columns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$columns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
}
$fingerprint = static function (Connection $connection, array $definition): array {
$result = [];
foreach ($definition as $table => $names) {
$quoted = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$quoted.' from "'.$table.'") t order by row_to_json(t)::text');
$result[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $result;
};
$before = $fingerprint($db, $columns);
$config = $db->getConfig();
unset($config['name']);
$directory = storage_path('framework/testing/distribution-recovery-'.$database);
if (! mkdir($directory, 0700, true) && ! is_dir($directory)) {
throw new RuntimeException('Unable to create the synthetic recovery directory.');
}
$pg = static function (string $binary, array $arguments) use ($config): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
['PGHOST' => $config['host'], 'PGPORT' => (string) $config['port'], 'PGUSER' => $config['username'], 'PGPASSWORD' => $config['password']], timeout: 60);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Synthetic backup/restore failed.');
}
};
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema();
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
$prepare = new Process([PHP_BINARY, __DIR__.'/budget-distribution-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor);
$engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']);
$afterColumns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
}
$after = $fingerprint($db, $afterColumns);
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $restore) || $restore === $database) {
throw new LogicException('Invalid isolated restore database.');
}
config(['database.connections.distribution_restore_admin' => [...$config, 'database' => 'postgres', 'url' => null],
'database.connections.distribution_restore' => [...$config, 'database' => $restore, 'url' => null]]);
$admin = DB::connection('distribution_restore_admin');
$created = false;
$default = DB::getDefaultConnection();
try {
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Restored distribution history or source data differs.');
}
DB::setDefaultConnection('distribution_restore');
$restoredActor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($restoredActor);
$again = app(CommonBudget::class)->for($restoredActor)->amendDistribution($input['origin'], $input['plan'], $input['hash'],
'Explicit synthetic amendment preserved in backup.', $input['operation']);
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.');
}
DB::setDefaultConnection($default);
DB::purge('distribution_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
$created = false;
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions')
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.');
}
DB::setDefaultConnection('distribution_restore');
auth()->guard()->setUser(User::query()->findOrFail($author->id));
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
throw new RuntimeException('Pre-extension recovery changed the native balance.');
}
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => 4, 'existing_balances_preserved' => true,
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
DB::setDefaultConnection($default);
DB::purge('distribution_restore');
if ($created) {
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
}