@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user