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/SupplyFixture.php'; require_once __DIR__.'/../Support/BudgetDistributionSchema.php'; $orderParts = ($argv[2] ?? '') === 'order-parts'; $landedCosts = ($argv[2] ?? '') === 'landed-costs'; $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]); if ($landedCosts) { (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up(); } else { budgetDistributionFixtureSchema(); } if ($orderParts) { (require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up(); } $unexpectedEffects = $landedCosts ? ($db->table('budget_landed_commands')->exists() || $db->table('budget_landed_entries')->exists()) : ($db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()); if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore || $unexpectedEffects) { throw new RuntimeException('Optional schema changed pre-existing data or native balances.'); } $prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/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); $apply = static fn ($engine) => $landedCosts ? $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']) : ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation']) : $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation'])); $applied = $apply($engine); if ($landedCosts) { foreach (['commit', 'consume'] as $kind) { $engine->transitionLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $kind, (string) Str::uuid()); } $money = ['subtotal_minor' => 500, 'tax_minor' => 0, 'total_minor' => 500, 'reference_subtotal_minor' => 500, 'reference_tax_minor' => 0, 'reference_total_minor' => 500]; $input['documents']['late'] = ['kind' => 'other_charge', 'id' => 2, 'source_key' => (string) Str::uuid(), 'source_version' => 1, 'creditor_key' => 'synthetic-late-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic late cost for recovery'), ...$money]; $input['components'][] = ['component_key' => 'late', 'kind' => 'other', 'origin' => 'late', ...$money]; $input['amend_operation'] = (string) Str::uuid(); $apply = static fn ($engine) => $engine->amendLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $input['version'] + 1, $input['components'], $input['documents'], $input['amend_operation']); $amended = $apply($engine); if ($amended['consumed_minor'] !== 2000 || $amended['reserved_minor'] !== 500 || $amended['phase'] !== 'mixed') { throw new RuntimeException('The recovery fixture must retain a consumption and a separate late reservation.'); } // Separate native documentary fixture; the core-only source declarations above are not native invoices. // All three file roots belong to this freshly generated disposable recovery directory. $privateLive = $directory.'/private-live'; $privateBackup = $directory.'/private-backup'; $privateRestore = $directory.'/private-restored'; File::ensureDirectoryExists($privateLive); Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateLive, 'throw' => true])); config(['import-landed-costs.qa_enabled' => true]); supplyGrant($f['issuer'], ['procurement', 'import_prepare']); supplyGrant($author, ['finance']); auth()->guard()->setUser($f['issuer']); $nativeImport = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput([ 'purchase_order_id' => $f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic recovery jurisdiction', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary recovery', ])); auth()->guard()->setUser($author); $costs = app(ImportLandedCosts::class); $nativeData = ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'RECOVERY-QA-ONLY', 'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic documentary authority', 'currency' => 'MZN', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null, 'reason' => 'Synthetic private evidence recovery; no legal rate or payment.']; $nativeDoc = $costs->recordDocument($author, $nativeImport, $nativeData, UploadedFile::fake()->createWithContent('recovery.pdf', "%PDF-1.4\nSynthetic original QA bytes\n%%EOF")); $correction = $costs->recordDocument($author, $nativeImport, [...$nativeData, 'operation_key' => (string) Str::uuid(), 'record_key' => $nativeDoc->record_key, 'version' => 1, 'subtotal_minor' => 2100, 'total_minor' => 2100], UploadedFile::fake()->createWithContent('recovery-correction.pdf', "%PDF-1.4\nSynthetic corrected QA bytes\n%%EOF")); $evidenceManifest = []; foreach ([$nativeDoc, $correction] as $record) { $evidence = $record->snapshot['evidence']; $evidenceManifest[$evidence['path']] = $evidence['sha256']; } if (! File::copyDirectory($privateLive, $privateBackup)) { throw new RuntimeException('Unable to back up isolated native evidence.'); } foreach ($evidenceManifest as $path => $checksum) { if (hash_file('sha256', $privateBackup.'/'.$path) !== $checksum) { throw new RuntimeException('Private evidence backup differs from the frozen documentary hash.'); } Storage::disk('local')->delete($path); } auth()->guard()->logout(); if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== 2) { throw new RuntimeException('The recovery test must demonstrate actual loss of its two synthetic original files.'); } } auth()->guard()->setUser($author); if (app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore) { throw new RuntimeException('The original company budget changed while preparing another synthetic source.'); } auth()->guard()->setUser($actor); $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 = $apply(app(CommonBudget::class)->for($restoredActor)); if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) { throw new RuntimeException('Recovered command was not replayed without new effects.'); } if ($landedCosts) { $position = app(CommonBudget::class)->for($restoredActor)->landedCostState($input['plan']); if ($position['result']['consumed_minor'] !== 2000 || $position['result']['reserved_minor'] !== 500 || $position['result']['phase'] !== 'mixed') { throw new RuntimeException('Restored per-origin positions do not match the preserved journal.'); } if (! File::copyDirectory($privateBackup, $privateRestore)) { throw new RuntimeException('Unable to restore private evidence into the separate QA root.'); } Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateRestore, 'throw' => true])); auth()->guard()->logout(); $health = app(ImportCostDocumentHealth::class)->inspect(); if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) { throw new RuntimeException('Restored native evidence did not match the restored SQL metadata.'); } auth()->guard()->setUser(User::query()->findOrFail($author->id)); foreach ([$nativeDoc, $correction] as $record) { $recovered = $costs->evidence(auth()->user(), $nativeImport, $record->id); if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) { throw new RuntimeException('Private native download no longer resolves the preserved original version.'); } } echo json_encode(['private_original_versions_restored' => 2, 'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true, 'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL; } 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'); $unexpectedSchema = $landedCosts ? ($restored->getSchemaBuilder()->hasTable('budget_landed_commands') || $restored->getSchemaBuilder()->hasTable('budget_landed_entries')) : ($restored->getSchemaBuilder()->hasTable('budget_distributions') || $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')); if ($fingerprint($restored, $columns) !== $before || $unexpectedSchema) { 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' => $landedCosts ? 2 : ($orderParts ? 8 : 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; } }