@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\Connection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Str;
|
||||
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
|
||||
|| $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Cycle recovery requires disposable local PostgreSQL QA.');
|
||||
}
|
||||
config(['requisition-expiry.qa_enabled' => true]);
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
receiptFixture();
|
||||
$fingerprint = static function (Connection $connection): array {
|
||||
$result = [];
|
||||
foreach ($connection->select("select tablename from pg_tables where schemaname='public' order by tablename") as $row) {
|
||||
$table = str_replace('"', '""', $row->tablename);
|
||||
$rows = $connection->select('select row_to_json(t)::text as row from "'.$table.'" t order by row_to_json(t)::text');
|
||||
$result[$row->tablename] = hash('sha256', json_encode([$connection->getSchemaBuilder()->getColumnListing($row->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $result;
|
||||
};
|
||||
$before = $fingerprint($db);
|
||||
$connectionConfig = $db->getConfig();
|
||||
unset($connectionConfig['name']);
|
||||
$directory = storage_path('framework/testing/cycle-recovery-'.$database);
|
||||
File::ensureDirectoryExists($directory, 0700);
|
||||
$pg = static function (string $binary, array $arguments) use ($connectionConfig): void {
|
||||
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
|
||||
['PGHOST' => $connectionConfig['host'], 'PGPORT' => (string) $connectionConfig['port'], 'PGUSER' => $connectionConfig['username'], 'PGPASSWORD' => $connectionConfig['password']], timeout: 60);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('Synthetic cycle backup/restore failed.');
|
||||
}
|
||||
};
|
||||
$preDump = $directory.'/before.dump';
|
||||
$postDump = $directory.'/after.dump';
|
||||
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
|
||||
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
Carbon::setTestNow($input['clock']);
|
||||
$owner = User::query()->findOrFail($input['owner']);
|
||||
auth()->guard()->setUser($owner);
|
||||
$request = Requisition::query()->findOrFail($input['request']);
|
||||
$workflow = app(RequisitionWorkflow::class);
|
||||
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
|
||||
$request->refresh();
|
||||
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version,
|
||||
'cost_center_id' => $request->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
|
||||
'justification' => 'Synthetic revised request retained through recovery',
|
||||
'items' => [['description' => 'Synthetic revised item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '120.00', 'tax_rate' => '0.00']]], $request);
|
||||
$submission = (string) Str::uuid();
|
||||
$version = $request->process_version;
|
||||
$workflow->submit($owner, $request, $submission, $version);
|
||||
$after = $fingerprint($db);
|
||||
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
|
||||
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
|
||||
$originalDefault = DB::getDefaultConnection();
|
||||
config(['database.connections.cycle_recovery_admin' => [...$connectionConfig, 'database' => 'postgres'],
|
||||
'database.connections.cycle_recovery_restore' => [...$connectionConfig, 'database' => $restore]]);
|
||||
$admin = DB::connection('cycle_recovery_admin');
|
||||
$created = false;
|
||||
try {
|
||||
$admin->statement('CREATE DATABASE "'.$restore.'"');
|
||||
$created = true;
|
||||
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
|
||||
$restored = DB::connection('cycle_recovery_restore');
|
||||
if ($fingerprint($restored) !== $after) {
|
||||
throw new RuntimeException('Restored cycle schema or complete table contents differ.');
|
||||
}
|
||||
DB::setDefaultConnection('cycle_recovery_restore');
|
||||
$owner = User::query()->findOrFail($input['owner']);
|
||||
auth()->guard()->setUser($owner);
|
||||
$request = Requisition::query()->findOrFail($input['request']);
|
||||
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
|
||||
$workflow->submit($owner, $request, $submission, $version);
|
||||
if ($fingerprint($restored) !== $after || $request->fresh()->approval_cycle !== 2
|
||||
|| (int) $restored->table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor') !== 12000
|
||||
|| $restored->table('approval_steps')->where('requisition_id', $request->id)->where('decision', 'expired')->count() !== 1) {
|
||||
throw new RuntimeException('Restored native expiry/submission replay changed history or reservation.');
|
||||
}
|
||||
DB::setDefaultConnection($originalDefault);
|
||||
DB::purge('cycle_recovery_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('cycle_recovery_restore');
|
||||
if ($fingerprint($restored) !== $before || $restored->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
|
||||
throw new RuntimeException('Pre-extension restore did not preserve its exact original schema and records.');
|
||||
}
|
||||
echo json_encode(['cycle_post_extension_all_tables_equal' => true, 'cycle_native_replays_without_effects' => true,
|
||||
'cycle_history_and_reserve_restored' => true, 'cycle_reserved_minor' => 12000,
|
||||
'cycle_pre_extension_all_tables_equal' => true, 'pre_extension_tables' => count($before), 'post_extension_tables' => count($after)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
DB::setDefaultConnection($originalDefault);
|
||||
DB::purge('cycle_recovery_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;
|
||||
$resolved = realpath($directory);
|
||||
$testingRoot = realpath(storage_path('framework/testing'));
|
||||
if ($resolved !== false && $testingRoot !== false && str_starts_with($resolved, $testingRoot.DIRECTORY_SEPARATOR)) {
|
||||
File::deleteDirectory($resolved);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user