@@ -1,10 +1,15 @@
|
||||
<?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;
|
||||
@@ -14,6 +19,9 @@ 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';
|
||||
@@ -27,8 +35,10 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
|
||||
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';
|
||||
$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]);
|
||||
@@ -86,16 +96,31 @@ $unexpectedEffects = $landedCosts
|
||||
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 = 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
|
||||
? $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']));
|
||||
? ($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) {
|
||||
@@ -119,7 +144,7 @@ if ($landedCosts) {
|
||||
$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]);
|
||||
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']);
|
||||
@@ -138,8 +163,37 @@ if ($landedCosts) {
|
||||
$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 ([$nativeDoc, $correction] as $record) {
|
||||
foreach ($nativeEvidenceRecords as $record) {
|
||||
$evidence = $record->snapshot['evidence'];
|
||||
$evidenceManifest[$evidence['path']] = $evidence['sha256'];
|
||||
}
|
||||
@@ -152,9 +206,9 @@ if ($landedCosts) {
|
||||
}
|
||||
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.');
|
||||
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);
|
||||
@@ -197,13 +251,22 @@ try {
|
||||
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]));
|
||||
auth()->guard()->logout();
|
||||
clearImportQaIdentity();
|
||||
$health = app(ImportCostDocumentHealth::class)->inspect();
|
||||
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) {
|
||||
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));
|
||||
@@ -213,7 +276,30 @@ try {
|
||||
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,
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Finance\Budget\BudgetFailure;
|
||||
use Tempo\Finance\Budget\BudgetImportEstimate;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
@@ -21,22 +22,24 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
|
||||
throw new LogicException('Landed-cost contention requires the approved common source and isolated local QA.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
if (($argv[2] ?? '') === 'legacy') {
|
||||
if (in_array($argv[2] ?? '', ['legacy', 'legacy-estimate'], true)) {
|
||||
$legacyEstimate = ($argv[2] ?? '') === 'legacy-estimate';
|
||||
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
app(CommonBudget::class)->for($actor);
|
||||
throw new RuntimeException('The old runtime must refuse balances with landed-cost effects.');
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if ($error->getStatusCode() !== 503 || (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT)) {
|
||||
if ($error->getStatusCode() !== 503 || ($legacyEstimate ? defined(BudgetControl::class.'::IMPORT_ESTIMATE_VERSION')
|
||||
: (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT))) {
|
||||
throw $error;
|
||||
}
|
||||
echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503,
|
||||
echo json_encode(['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => $legacyEstimate, 'status' => 503,
|
||||
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
if (in_array($argv[2] ?? '', ['prepare', 'prepare-estimate', 'prepare-reconcile'], true)) {
|
||||
$f = receiptFixture();
|
||||
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
@@ -48,11 +51,22 @@ if (($argv[2] ?? '') === 'prepare') {
|
||||
$money = ['subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
|
||||
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000];
|
||||
// Contract fixture, not a native document upload or statutory customs action.
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
|
||||
$prepared = ['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
|
||||
'estimate' => in_array($argv[2] ?? '', ['prepare-estimate', 'prepare-reconcile'], true), 'reconciliation' => ($argv[2] ?? '') === 'prepare-reconcile', 'requisition' => $f['r']->id,
|
||||
'version' => 1, 'operation' => (string) Str::uuid(),
|
||||
'documents' => ['customs' => ['kind' => 'customs_assessment', 'id' => 1, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
|
||||
'creditor_key' => 'synthetic-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic customs source'), ...$money]],
|
||||
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]], JSON_THROW_ON_ERROR);
|
||||
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]];
|
||||
if ($prepared['reconciliation']) {
|
||||
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
|
||||
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
|
||||
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
|
||||
auth()->guard()->setUser($finance);
|
||||
$estimate = app(CommonBudget::class)->for($finance)->reserveImportEstimate($prepared['plan'], 1, $budget, $f['r']->id,
|
||||
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
|
||||
$prepared += ['estimate_hash' => $estimate['plan_hash'], 'actual_plan' => (string) Str::uuid(), 'actual_operation' => (string) Str::uuid()];
|
||||
}
|
||||
echo json_encode($prepared, JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'write') {
|
||||
@@ -61,7 +75,19 @@ if (($argv[2] ?? '') === 'write') {
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$result = app(CommonBudget::class)->for($actor)->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
if ($input['reconciliation'] ?? false) {
|
||||
$result = $engine->reconcileImportEstimate($input['plan'], $input['version'], $input['estimate_hash'], 1, 1000,
|
||||
$input['actual_plan'], 1, $input['budget'], $input['components'], $input['documents'], $input['operation'], $input['actual_operation']);
|
||||
} elseif ($input['estimate'] ?? false) {
|
||||
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
|
||||
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
|
||||
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
|
||||
$result = $engine->reserveImportEstimate($input['plan'], $input['version'], $input['budget'], $input['requisition'],
|
||||
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, $input['operation']);
|
||||
} else {
|
||||
$result = $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
|
||||
}
|
||||
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
|
||||
} catch (BudgetFailure $error) {
|
||||
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
|
||||
@@ -70,12 +96,15 @@ if (($argv[2] ?? '') === 'write') {
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
if (! in_array($argv[2] ?? '', ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
|
||||
throw new InvalidArgumentException('Invalid landed-cost worker mode.');
|
||||
}
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
|
||||
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepareMode = match ($argv[2] ?? '') {
|
||||
'race-estimate-reconcile' => 'prepare-reconcile', 'race-estimate' => 'prepare-estimate', default => 'prepare'
|
||||
};
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$workers = [];
|
||||
@@ -88,7 +117,7 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
|
||||
if ($index === 1 && $scenario !== 'same_operation') {
|
||||
$contender['operation'] = (string) Str::uuid();
|
||||
if ($scenario === 'same_source_different_plan') {
|
||||
$contender['plan'] = (string) Str::uuid();
|
||||
$contender[($input['reconciliation'] ?? false) ? 'actual_plan' : 'plan'] = (string) Str::uuid();
|
||||
} else {
|
||||
$contender['version'] = 2;
|
||||
}
|
||||
@@ -121,13 +150,13 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
|
||||
$statuses = array_column($results, 'status');
|
||||
sort($statuses);
|
||||
$commands = $db->table('budget_landed_commands')->where('tenant_id', $input['tenant'])->count();
|
||||
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.landed_reserve')->count();
|
||||
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', ($input['reconciliation'] ?? false) ? 'budget.landed_estimate_reconcile' : (($input['estimate'] ?? false) ? 'budget.landed_estimate_reserve' : 'budget.landed_reserve'))->count();
|
||||
$reserved = (int) $db->table('budget_landed_entries')->where('tenant_id', $input['tenant'])->sum('reserved_minor');
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1 || $reserved !== 2000
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== (($input['reconciliation'] ?? false) ? 3 : 1) || $audits !== 1 || $reserved !== (($input['reconciliation'] ?? false) ? 3000 : 2000)
|
||||
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
|
||||
throw new RuntimeException('Contention must retain exactly one source, budget effect and audit.');
|
||||
}
|
||||
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
echo json_encode(['scenario' => $scenario, 'estimate' => $input['estimate'] ?? false, 'reconciliation' => $input['reconciliation'] ?? false, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
if ($scenario === 'same_operation') {
|
||||
$artifact = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
@@ -149,6 +178,19 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
|
||||
throw new RuntimeException('The earlier whole-command runtime must refuse the new per-origin data.');
|
||||
}
|
||||
echo $whole->getOutput();
|
||||
if ($input['estimate'] ?? false) {
|
||||
$prior = base_path('storage/framework/testing/budget-import-estimate-prior-qa-20261127');
|
||||
if (hash_file('sha256', $prior.'/src/BudgetControl.php') !== 'd81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa') {
|
||||
throw new RuntimeException('Preserve the private prior runtime used for estimate downgrade verification.');
|
||||
}
|
||||
$oldEstimate = new Process([PHP_BINARY, __FILE__, $database, 'legacy-estimate', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $prior], timeout: 30);
|
||||
$oldEstimate->mustRun();
|
||||
$receipt = json_decode($oldEstimate->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($receipt['old_estimate_runtime_rejected'] ?? false) !== true || ($receipt['runtime_landed_version'] ?? null) !== CommonBudget::LANDED_COSTS_CONTRACT) {
|
||||
throw new RuntimeException('The prior per-origin runtime must refuse estimate effects before balance access.');
|
||||
}
|
||||
echo $oldEstimate->getOutput();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
|
||||
@@ -23,6 +23,7 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
|
||||
$amendmentMode = in_array($argv[2] ?? '', ['prepare-amend', 'write-amend', 'race-amend'], true);
|
||||
if (($argv[2] ?? '') === 'legacy') {
|
||||
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
|
||||
auth()->guard()->setUser($actor);
|
||||
@@ -37,7 +38,7 @@ if (($argv[2] ?? '') === 'legacy') {
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'prepare') {
|
||||
if (in_array($argv[2] ?? '', ['prepare', 'prepare-amend'], true)) {
|
||||
$f = receiptFixture();
|
||||
$source = unissuedOrderPartsSource($f, 10000);
|
||||
$line = $source->items()->sole();
|
||||
@@ -52,20 +53,36 @@ if (($argv[2] ?? '') === 'prepare') {
|
||||
$engine = app(CommonBudget::class)->for($f['issuer']);
|
||||
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
|
||||
$plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
|
||||
if ($amendmentMode) {
|
||||
$plan = [[...$plan[0], 'allocation_key' => 'a', 'subtotal_minor' => 5000, 'total_minor' => 5000],
|
||||
[...$plan[0], 'allocation_key' => 'b', 'subtotal_minor' => 5000, 'total_minor' => 5000]];
|
||||
}
|
||||
$engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
|
||||
$award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
|
||||
$input = ['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
|
||||
'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0,
|
||||
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR);
|
||||
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]];
|
||||
if ($amendmentMode) {
|
||||
$input['sources'][0]['allocations'] = [['allocation_key' => 'a', 'subtotal_minor' => 2000, 'total_minor' => 2000],
|
||||
['allocation_key' => 'b', 'subtotal_minor' => 2000, 'total_minor' => 2000]];
|
||||
$engine->commitOrderParts($input['order'], $input['sources'], (string) Str::uuid());
|
||||
$input['actor'] = $finance->id;
|
||||
$input['sources'][0]['version'] = 1;
|
||||
$input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1000;
|
||||
$input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 3000;
|
||||
}
|
||||
echo json_encode($input, JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') === 'write') {
|
||||
if (in_array($argv[2] ?? '', ['write', 'write-amend'], true)) {
|
||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']);
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$result = $amendmentMode ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic concurrent Finance amendment.', $input['operation'])
|
||||
: $engine->commitOrderParts($input['order'], $input['sources'], $input['operation']);
|
||||
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
|
||||
} catch (BudgetFailure $error) {
|
||||
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
|
||||
@@ -74,13 +91,13 @@ if (($argv[2] ?? '') === 'write') {
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (($argv[2] ?? '') !== 'race') {
|
||||
if (! in_array($argv[2] ?? '', ['race', 'race-amend'], true)) {
|
||||
throw new InvalidArgumentException('Invalid order-part worker mode.');
|
||||
}
|
||||
budgetDistributionFixtureSchema();
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
|
||||
foreach (['same_operation', 'conflicting_version'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'prepare-amend' : 'prepare'], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$workers = [];
|
||||
@@ -91,11 +108,16 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
|
||||
for ($index = 0; $index < 2; $index++) {
|
||||
if ($index === 1 && $scenario === 'conflicting_version') {
|
||||
$input['operation'] = (string) Str::uuid();
|
||||
$input['order'] = (string) Str::uuid();
|
||||
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
|
||||
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
|
||||
if ($amendmentMode) {
|
||||
$input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1500;
|
||||
$input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 2500;
|
||||
} else {
|
||||
$input['order'] = (string) Str::uuid();
|
||||
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
|
||||
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
|
||||
}
|
||||
}
|
||||
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||
$worker = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'write-amend' : 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||
$workers[] = $worker;
|
||||
$worker->start();
|
||||
}
|
||||
@@ -125,14 +147,14 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
|
||||
$entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']);
|
||||
$reserved = (int) (clone $entries)->sum('reserved_minor');
|
||||
$committed = (int) (clone $entries)->sum('committed_minor');
|
||||
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count();
|
||||
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count();
|
||||
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->where('kind', $amendmentMode ? 'amend' : 'commit')->count();
|
||||
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $amendmentMode ? 'budget.order_parts_amended' : 'budget.orders_committed')->count();
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1
|
||||
|| $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true)
|
||||
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
|
||||
throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.');
|
||||
}
|
||||
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
echo json_encode(['scenario' => $scenario, 'amendment' => $amendmentMode, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
if ($scenario === 'same_operation') {
|
||||
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportDossier;
|
||||
use App\Services\ImportEvidence;
|
||||
use App\Services\ImportParties;
|
||||
use App\Services\SupplyPlanning;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$database = $argv[1] ?? '';
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
|
||||
}
|
||||
config(['import-dossier.qa_enabled' => true]);
|
||||
Storage::set('local', Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/dossier-contention-'.$database), 'throw' => true]));
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
$file = static fn () => UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic concurrent packing list\n%%EOF");
|
||||
$partyMode = in_array($argv[2] ?? '', ['prepare-party', 'write-party', 'race-party'], true);
|
||||
$recordKind = $partyMode ? 'import_party' : 'import_document';
|
||||
$auditAction = $partyMode ? 'import.party_selected' : 'import.document_recorded';
|
||||
if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
|
||||
$f = receiptFixture();
|
||||
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
|
||||
auth()->guard()->setUser($f['issuer']);
|
||||
$import = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput(['purchase_order_id' => $f['order']->id,
|
||||
'purpose' => 'internal', 'jurisdiction' => 'Synthetic contention jurisdiction', 'origin_country' => 'Synthetic A',
|
||||
'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
|
||||
$data = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-PARALLEL',
|
||||
'issuer_reference' => 'Synthetic supplier', 'reason' => 'Synthetic concurrent original document registration.'];
|
||||
$actor = $f['issuer'];
|
||||
if ($partyMode) {
|
||||
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||
supplyGrant($actor, ['procurement', 'import_prepare']);
|
||||
auth()->guard()->setUser($actor);
|
||||
$instructions = app(ImportDossier::class)->record($actor, $import, [...$data, 'type' => 'written_instructions'], $file());
|
||||
$supplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
|
||||
$supplier->name = 'Synthetic concurrent broker';
|
||||
$supplier->nuit = '987654321';
|
||||
$supplier->save();
|
||||
$data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
|
||||
'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
|
||||
'reason' => 'Explicit synthetic concurrent independent buyer selection.'];
|
||||
if (($argv[3] ?? '') === 'same_version') {
|
||||
app(ImportParties::class)->select($actor, $import, $data);
|
||||
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'role' => 'broker'];
|
||||
}
|
||||
} elseif (($argv[3] ?? '') === 'same_version') {
|
||||
$old = app(ImportDossier::class)->record($f['issuer'], $import, $data, $file());
|
||||
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1,
|
||||
'reference' => 'PACK-CORRECTED'];
|
||||
}
|
||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'data' => $data,
|
||||
'records_before' => SupplyRecord::query()->where('kind', $recordKind)->count(),
|
||||
'audits_before' => DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', $auditAction)->count(),
|
||||
'files_before' => count(Storage::disk('local')->allFiles())], JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if (in_array($argv[2] ?? '', ['write', 'write-party'], true)) {
|
||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_dossier_write_'.getmypid()]);
|
||||
$actor = User::query()->findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
try {
|
||||
$import = SupplyRecord::query()->findOrFail($input['import']);
|
||||
$record = $partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
|
||||
: app(ImportDossier::class)->record($actor, $import, $input['data'], $file());
|
||||
echo json_encode(['status' => 200, 'id' => $record->id], JSON_THROW_ON_ERROR);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
exit;
|
||||
}
|
||||
if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party'], true)) {
|
||||
throw new InvalidArgumentException('Unknown dossier worker mode.');
|
||||
}
|
||||
foreach (['same_operation', 'same_version'] as $scenario) {
|
||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'prepare-party' : 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
|
||||
$prepare->mustRun();
|
||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$db = DB::connection();
|
||||
$workers = [];
|
||||
$db->beginTransaction();
|
||||
try {
|
||||
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
|
||||
for ($index = 0; $index < 2; $index++) {
|
||||
$workerInput = $input;
|
||||
if ($scenario === 'same_version' && $index === 1) {
|
||||
$workerInput['data']['operation_key'] = (string) Str::uuid();
|
||||
}
|
||||
$worker = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'write-party' : 'write', json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||
$workers[] = $worker;
|
||||
$worker->start();
|
||||
}
|
||||
$deadline = microtime(true) + 10;
|
||||
do {
|
||||
$db->select('select pg_stat_clear_snapshot()');
|
||||
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_dossier_write_%' and wait_event_type='Lock'", [$database])->n;
|
||||
if ($blocked >= 2) {
|
||||
break;
|
||||
}
|
||||
usleep(50000);
|
||||
} while (microtime(true) < $deadline);
|
||||
if ($blocked < 2) {
|
||||
throw new RuntimeException('Both dossier writers must demonstrably wait on the company lock.');
|
||||
}
|
||||
$db->commit();
|
||||
$results = [];
|
||||
foreach ($workers as $worker) {
|
||||
$worker->wait();
|
||||
if (! $worker->isSuccessful()) {
|
||||
throw new RuntimeException($worker->getErrorOutput());
|
||||
}
|
||||
$results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
$statuses = array_column($results, 'status');
|
||||
sort($statuses);
|
||||
$records = DB::table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', $recordKind)->count() - $input['records_before'];
|
||||
$audits = DB::table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $auditAction)->count() - $input['audits_before'];
|
||||
$files = count(Storage::disk('local')->allFiles()) - $input['files_before'];
|
||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($partyMode ? 0 : 1)) {
|
||||
throw new RuntimeException('Dossier contention must preserve one document version, one original and one audit.');
|
||||
}
|
||||
auth()->guard()->setUser(User::query()->findOrFail($input['actor']));
|
||||
foreach (SupplyRecord::query()->where('kind', 'import_document')->get() as $record) {
|
||||
app(ImportEvidence::class)->bytes($record);
|
||||
}
|
||||
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||
'documents_created' => $records, 'audits' => $audits, 'files_created' => $files, 'all_originals_verified' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} finally {
|
||||
if ($db->transactionLevel() > 0) {
|
||||
$db->rollBack();
|
||||
}
|
||||
foreach ($workers as $worker) {
|
||||
if ($worker->isRunning()) {
|
||||
$worker->stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user