Files
compras/tests/Support/standalone-inventory-recovery-worker.php
T
nala 96b30368bc
tests / ci (push) Canceled after 0s
commit compras5 2911
2026-11-29 19:49:19 +02:00

119 lines
6.2 KiB
PHP

<?php
use App\Models\GoodsReceiptItem;
use App\Models\OrderCancellation;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\InventoryConversionRuntime;
use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptQuantityConversion;
use App\Services\ReceiptStockMovement;
use App\Services\StandaloneInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})(_restored)?$/D', $database, $match)
|| getenv('DB_DATABASE') !== $database || getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| getenv('DB_USERNAME') !== 'payable_history_native_'.$match[1].($match[2] ?? '')
|| getenv('APP_ENV') !== 'standalone-qa' || getenv('COMPRAS_STANDALONE_CONVERSION_QA') !== '1'
|| $root === false || dirname($root) !== realpath(dirname(__DIR__, 2).'/storage/framework/testing')
|| basename($root) !== 'rq01-ledger-qa-'.$match[1] || ! in_array($mode, ['read', 'read-cancellation', 'reject-restore', 'rebind'], true)) {
throw new LogicException('Owned synthetic inventory recovery required.');
}
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->useStoragePath($root.'/recovery-storage');
try {
$app->make(Kernel::class)->bootstrap();
} catch (LogicException $e) {
if ($mode !== 'reject-restore' || $e->getMessage() !== 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH') {
throw $e;
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'reject-restore') {
throw new LogicException('Restored database started with the original binding.');
}
if (DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned recovery cluster required.');
}
if ($mode === 'rebind') {
$result = app(StandaloneInstallation::class)->prepare($database, getenv('DB_USERNAME'), 'Synthetic inventory recovery',
'Authorised isolated backup restoration', apply: true, rebind: true);
if ($result['state'] !== 'rebound') {
throw new LogicException('Recovery binding not recorded.');
}
echo json_encode(['state' => 'rebound'], JSON_THROW_ON_ERROR);
exit;
}
if (! app(InventoryConversionRuntime::class)->available() || config('inventory_conversion.qa_enabled') !== false) {
throw new LogicException('Operational inventory component required.');
}
$frames = static function (): array {
$hashes = [];
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
if ($table->tablename === 'compras_runtime_installations') {
continue;
}
$rows = DB::table($table->tablename)->get()->map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR))->all();
sort($rows, SORT_STRING);
$hashes[$table->tablename] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
return $hashes;
};
$hashes = $frames();
$cancellation = $mode === 'read-cancellation';
if ($cancellation) {
app(OrderCancellationRuntime::class)->assertReady();
$record = DB::table('order_cancellations')->sole();
$actor = User::query()->findOrFail($record->reviewed_by);
auth()->guard()->setUser($actor);
$model = OrderCancellation::query()->findOrFail($record->id);
app(OrderCancellationWorkflow::class)->decide($actor, $model, 'approved', $record->review_reason);
$order = DB::table('purchase_orders')->where('id', $record->purchase_order_id)->firstOrFail();
$reversal = DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('kind', 'order-cancel-'.$order->id)->sole();
if ((int) $reversal->requisition_cycle !== 2 || $record->status !== 'approved'
|| (int) DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('requisition_cycle', 2)->sum('committed_minor') !== 0) {
throw new LogicException('Recovered cancellation cycle or balance changed.');
}
} else {
$movements = DB::table('stock_movements')->whereNotNull('snapshot->quantity_conversion')->get();
if ($movements->count() !== 2) {
throw new LogicException('Both synthetic contention scenarios must survive recovery.');
}
foreach ($movements as $movement) {
$snapshot = json_decode($movement->snapshot, true, 512, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($movement->moved_by);
auth()->guard()->setUser($actor);
$line = GoodsReceiptItem::query()->findOrFail($movement->goods_receipt_item_id);
if (app(ReceiptQuantityConversion::class)->documentary($line, (int) $movement->quantity_milli) !== 1000) {
throw new LogicException('Restored documentary equivalence changed.');
}
$result = DB::transaction(function () use ($actor, $movement, $snapshot) {
app(ConflictGuard::class)->lockCompany($actor);
return app(ReceiptStockMovement::class)->for($actor)->write($movement->goods_receipt_item_id, $snapshot['inventory_source_hash']);
});
if ($result['replayed'] !== true || (int) $result['movement_id'] !== (int) $movement->id) {
throw new LogicException('Restored movement was not replayed exactly.');
}
}
}
$original = DB::table('compras_runtime_installations')->where('id', getenv('COMPRAS_QA_ORIGINAL_INSTALLATION_ID'))->first();
if ($original === null) {
throw new LogicException('Original immutable installation history lost.');
}
if ($frames() !== $hashes) {
throw new LogicException('Replay changed synthetic business data.');
}
echo json_encode(['business_tables' => count($hashes), 'business_sha256' => hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR)),
'original_installation_sha256' => hash('sha256', json_encode($original, JSON_THROW_ON_ERROR)),
...($cancellation ? ['approved_cancellations' => 1, 'source_cycle' => 2, 'exact_replays' => 1]
: ['converted_movements' => 2, 'exact_replays' => 2])], JSON_THROW_ON_ERROR);