commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
@@ -3,9 +3,16 @@
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportLandedCosts;
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;
require __DIR__.'/../../vendor/autoload.php';
@@ -18,8 +25,10 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
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]);
@@ -63,24 +72,96 @@ $pg = static function (string $binary, array $arguments) use ($config): void {
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema();
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();
}
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
$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__.($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, '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) => $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']);
$apply($engine);
$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);
@@ -111,6 +192,31 @@ try {
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)');
@@ -119,8 +225,10 @@ try {
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions')
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
$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');
@@ -128,7 +236,7 @@ try {
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' => $orderParts ? 8 : 4, 'existing_balances_preserved' => true,
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 {