336 lines
23 KiB
PHP
336 lines
23 KiB
PHP
<?php
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\Supplier;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use App\Services\CommonBudget;
|
|
use App\Services\ImportCostDocumentHealth;
|
|
use App\Services\ImportDossier;
|
|
use App\Services\ImportLandedCosts;
|
|
use App\Services\ImportParties;
|
|
use App\Services\SupplyPlanning;
|
|
use Illuminate\Contracts\Console\Kernel;
|
|
use Illuminate\Database\Connection;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
use Symfony\Component\Process\Process;
|
|
use Tempo\Finance\Budget\BudgetImportEstimate;
|
|
|
|
require_once __DIR__.'/../Support/ImportQaIdentity.php';
|
|
|
|
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/SupplyFixture.php';
|
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
|
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
|
|
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
|
|
$importEstimates = ($argv[2] ?? '') === 'import-estimates';
|
|
$landedCosts = $importEstimates || ($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, $importEstimates ? 'prepare-estimate' : ($orderPartsAmendment ? 'prepare-amend' : '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);
|
|
if ($importEstimates) {
|
|
$estimateInput = $input;
|
|
$estimateComponents = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic recovery assumption',
|
|
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
|
|
$estimateComponents[0] = [...$estimateComponents[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
|
|
$estimateApply = static fn ($engine) => $engine->reserveImportEstimate($estimateInput['plan'], 1, $estimateInput['budget'], $estimateInput['requisition'],
|
|
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $estimateComponents, $estimateInput['operation']);
|
|
$estimated = $estimateApply($engine);
|
|
$input['plan'] = (string) Str::uuid();
|
|
$input['operation'] = (string) Str::uuid();
|
|
$engine->reconcileImportEstimate($estimateInput['plan'], 1, $estimated['plan_hash'], 1, 1000, $input['plan'], 1, $input['budget'],
|
|
$input['components'], $input['documents'], (string) Str::uuid(), $input['operation']);
|
|
}
|
|
$apply = static fn ($engine) => $landedCosts
|
|
? ($importEstimates ? $engine->landedCostState($input['plan'])['result']
|
|
: $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']))
|
|
: ($orderPartsAmendment ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic amendment preserved in backup.', $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, 'import-dossier.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"));
|
|
auth()->guard()->setUser($f['issuer']);
|
|
$dossier = app(ImportDossier::class);
|
|
$typedInput = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-RECOVERY-QA',
|
|
'issuer_reference' => 'Synthetic packing list issuer', 'reason' => 'Retain a synthetic private packing list for recovery.'];
|
|
$typedFirst = $dossier->record($f['issuer'], $nativeImport, $typedInput,
|
|
UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic packing original\n%%EOF"));
|
|
$typedCorrection = $dossier->record($f['issuer'], $nativeImport, [...$typedInput, 'operation_key' => (string) Str::uuid(),
|
|
'record_key' => $typedFirst->record_key, 'version' => 1],
|
|
UploadedFile::fake()->createWithContent('packing-correction.pdf', "%PDF-1.4\nSynthetic packing correction\n%%EOF"));
|
|
$partyBuyer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
|
supplyGrant($partyBuyer, ['procurement', 'import_prepare']);
|
|
auth()->guard()->setUser($partyBuyer);
|
|
$partySupplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
|
|
$partySupplier->name = 'Synthetic recovery broker';
|
|
$partySupplier->nuit = '987654321';
|
|
$partySupplier->save();
|
|
$instructionsInput = [...$typedInput, 'operation_key' => (string) Str::uuid(), 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-RECOVERY-QA'];
|
|
$instructions = $dossier->record($partyBuyer, $nativeImport, $instructionsInput,
|
|
UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nSynthetic recovery instructions\n%%EOF"));
|
|
$partyInput = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $partySupplier->id,
|
|
'supplier_version' => $partySupplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
|
|
'reason' => 'Explicit synthetic broker and instructions for recovery.'];
|
|
$party = app(ImportParties::class)->select($partyBuyer, $nativeImport, $partyInput);
|
|
$instructionsCorrection = $dossier->record($partyBuyer, $nativeImport, [...$instructionsInput, 'operation_key' => (string) Str::uuid(),
|
|
'record_key' => $instructions->record_key, 'version' => 1],
|
|
UploadedFile::fake()->createWithContent('instructions-correction.pdf', "%PDF-1.4\nSynthetic revised recovery instructions\n%%EOF"));
|
|
app(ImportParties::class)->select($partyBuyer, $nativeImport, [...$partyInput, 'operation_key' => (string) Str::uuid(),
|
|
'version' => 1, 'instruction_document_id' => $instructionsCorrection->id]);
|
|
$nativeEvidenceRecords = [$nativeDoc, $correction, $typedFirst, $typedCorrection, $instructions, $instructionsCorrection];
|
|
$evidenceManifest = [];
|
|
foreach ($nativeEvidenceRecords 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);
|
|
}
|
|
clearImportQaIdentity();
|
|
if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== count($nativeEvidenceRecords)) {
|
|
throw new RuntimeException('The recovery test must demonstrate actual loss of its 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 ($importEstimates) {
|
|
$restoredEngine = app(CommonBudget::class)->for($restoredActor);
|
|
$estimateState = $restoredEngine->landedCostState($estimateInput['plan']);
|
|
$estimateReplay = $estimateApply($restoredEngine);
|
|
if ($estimateState['result']['reserved_minor'] !== 1000 || ! $estimateReplay['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
|
|
throw new RuntimeException('The restored estimate remainder, original replay or complete SQL fingerprint differs.');
|
|
}
|
|
echo json_encode(['estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
|
}
|
|
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]));
|
|
clearImportQaIdentity();
|
|
$health = app(ImportCostDocumentHealth::class)->inspect();
|
|
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== count($nativeEvidenceRecords) || $health['files_checked'] !== count($nativeEvidenceRecords)) {
|
|
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.');
|
|
}
|
|
}
|
|
auth()->guard()->setUser(User::query()->findOrFail($f['issuer']->id));
|
|
foreach ([$typedFirst, $typedCorrection, $instructions, $instructionsCorrection] as $record) {
|
|
$recovered = $dossier->evidence(auth()->user(), $nativeImport, $record->id);
|
|
if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) {
|
|
throw new RuntimeException('Restored typed dossier version lost its original evidence.');
|
|
}
|
|
}
|
|
$restoredBuyer = User::query()->findOrFail($partyBuyer->id);
|
|
auth()->guard()->setUser($restoredBuyer);
|
|
$restoredOrder = PurchaseOrder::query()->whereKey($f['order']->id)->firstOrFail();
|
|
app(ImportParties::class)->assertCurrent($restoredBuyer, $restoredOrder, $nativeImport->record_key);
|
|
$restoredParty = SupplyRecord::query()->where('kind', 'import_party')->where('record_key', $party->record_key)->latest('version')->firstOrFail();
|
|
if ($restoredParty->version !== 2) {
|
|
throw new RuntimeException('Restored broker version differs: '.get_debug_type($restoredParty->version).' '.json_encode($restoredParty->version));
|
|
}
|
|
if ($restoredParty->data['instruction_document_id'] !== $instructionsCorrection->id) {
|
|
throw new RuntimeException('Restored instruction identity differs: '.get_debug_type($restoredParty->data['instruction_document_id']).'/'.get_debug_type($instructionsCorrection->id));
|
|
}
|
|
$readFingerprint = $fingerprint($restored, $afterColumns);
|
|
if ($readFingerprint !== $after) {
|
|
throw new RuntimeException('Native restored read changed tables: '.implode(',', array_keys(array_diff_assoc($readFingerprint, $after))));
|
|
}
|
|
echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => 4,
|
|
'selected_party_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;
|
|
}
|
|
}
|