Files
compras/tests/Concurrency/requisition-account-worker.php
T
nala 448948a487
tests / ci (push) Waiting to run
commit compras1 2911
2026-11-29 05:28:30 +02:00

364 lines
21 KiB
PHP

<?php
use App\Models\ConflictDeclaration;
use App\Models\ConflictRelease;
use App\Models\OrderCancellation;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\OrderCancellationWorkflow;
use App\Services\ProposalComparison;
use App\Services\RequisitionAccountAssignments;
use App\Services\UrgentQuotationBasis;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
if (in_array($argv[2] ?? '', ['prepare-native-review', 'read-office-purchase', 'describe-private-audit-schema', 'read-native-conflict-release', 'read-native-urgent-stock', 'read-native-cancellation'], true)) {
$privateRoot = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$databaseName = getenv('DB_DATABASE') ?: '';
if ($privateRoot === false || $boundary === false || ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $databaseName, $matches)
|| str_replace('\\', '/', $privateRoot) !== str_replace('\\', '/', $boundary).'/rq01-ledger-qa-'.$matches[1]) {
throw new LogicException('Private native review root refused.');
}
$app->useStoragePath($privateRoot.'/storage');
}
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
$source = requisitionLedgerQaSource();
if (! $app->environment('testing') || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $source === null) {
throw new LogicException('Owned common-ledger QA composition required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
config(['requisition-accounts.qa_enabled' => true]);
require_once __DIR__.'/../Support/ReceiptFixture.php';
if ($mode === 'prepare-native-review') {
require_once __DIR__.'/../Support/RequisitionAccountsNativeReview.php';
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1', getenv('RQ01_QA_LEGAL_REFERENCE') === '1', getenv('RQ01_QA_PRINT_PAGINATION') === '1'), JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'describe-private-audit-schema') {
$columns = DB::transaction(function () {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$schema = DB::getSchemaBuilder();
$result = [];
foreach ($schema->getTableListing() as $table) {
$result[$table] = $schema->getColumnListing($table);
}
ksort($result);
return $result;
});
echo json_encode(['schema_only' => true, 'no_business_values' => true, 'tables' => $columns], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-office-purchase') {
if (getenv('RQ01_NATIVE_OFFICE_JOURNEY') !== '1') {
throw new LogicException('Office HTTP assertions require their explicit synthetic composition.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
Carbon::setTestNow($fixture['clock']);
CarbonImmutable::setTestNow($fixture['clock']);
require_once __DIR__.'/../Support/NativeOfficePurchaseState.php';
try {
$state = DB::transaction(function () use ($fixture) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return nativeOfficePurchaseState($fixture);
});
echo json_encode($state, JSON_THROW_ON_ERROR);
} catch (Throwable $error) {
fwrite(STDERR, get_class($error).': '.$error->getMessage().PHP_EOL);
exit(1);
}
exit;
}
if ($mode === 'read-native-conflict-release') {
if (getenv('RQ01_QA_CONFLICT_RELEASE') !== '1') {
throw new LogicException('Conflict assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['conflict_review'];
config(['conflict-releases.qa_enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['author_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$originals = ConflictDeclaration::query()->where('user_id', $context['author_id'])->orderBy('id')->get();
if (hash('sha256', $originals->toJson()) !== $context['originals_sha256']) {
throw new LogicException('Native release must preserve both original declarations.');
}
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Native release changed protected financial, stock or authority frame: '.$table);
}
}
$release = ConflictRelease::query()->sole();
$guard = app(ConflictGuard::class);
$supplierBlocked = $guard->hasConflict($context['author_id'], $context['supplier_id'], null);
$otherProcessBlocked = $guard->hasConflict($context['author_id'], $context['supplier_id'], $context['requisition_id']);
if ($release->declaration_id !== $context['declaration_id'] || $release->authorised_by !== $context['direction_id']
|| Arr::sortRecursive($release->snapshot) !== Arr::sortRecursive($originals->first()->toArray()) || $supplierBlocked || ! $otherProcessBlocked
|| DB::table('audit_logs')->where('action', 'conflict.release_authorised')->count() !== 1) {
throw new LogicException('Native direction decision must release only the selected chain once.');
}
return ['release_id' => $release->id, 'declaration_id' => $release->declaration_id,
'direction_id' => $release->authorised_by, 'originals_preserved' => true,
'financial_stock_and_authority_frames_preserved' => count($context['protected_frames']),
'selected_supplier_impediment_released' => ! $supplierBlocked, 'other_process_impediment_still_blocks' => $otherProcessBlocked,
'release_audit_count' => 1, 'readonly_transaction' => DB::selectOne('SHOW transaction_read_only')->transaction_read_only === 'on',
'synthetic_only' => true, 'operational_changes' => false];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-native-urgent-stock') {
if (getenv('RQ01_QA_URGENT_STOCK') !== '1') {
throw new LogicException('Urgent stock assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['urgent_stock_review'];
config(['urgent-quotations.qa_enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['actor_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Urgent evidence changed a protected frame: '.$table);
}
}
$request = Requisition::query()->findOrFail($context['request_id']);
$eligible = app(UrgentQuotationBasis::class)->eligible($request);
$policy = app(ProposalComparison::class)->inspect($request)['policy'];
if (count($eligible) !== 1 || $policy['minimum_proposals'] !== 1 || $policy['normal_minimum_proposals'] !== 3 || $policy['minimum_evaluators'] !== 2
|| DB::table('audit_logs')->where('action', 'urgent.stock_minimum_recorded')->where('requisition_id', $request->id)->count() !== 1) {
throw new LogicException('Native urgent conference must preserve one valid evidence and independent evaluations.');
}
return ['eligible_evidence' => 1, 'minimum_proposals' => 1, 'normal_minimum_proposals' => 3, 'minimum_evaluators' => 2,
'protected_frames_preserved' => count($context['protected_frames']), 'single_audit' => true, 'readonly_transaction' => true, 'synthetic_only' => true];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'read-native-cancellation') {
if (getenv('RQ01_QA_ORDER_CANCELLATION') !== '1') {
throw new LogicException('Cancellation assertions require their own synthetic preview.');
}
$fixture = json_decode(file_get_contents($privateRoot.'/native-review.json'), true, 64, JSON_THROW_ON_ERROR);
$context = $fixture['cancellation_review'];
config(['order_cancellation.enabled' => true]);
auth()->guard()->setUser(User::query()->findOrFail($context['finance_id']));
$state = DB::transaction(function () use ($context) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
foreach ($context['protected_frames'] as $table => $expected) {
$rows = DB::table($table)->when($table === 'users', fn ($query) => $query->select(['id', 'tenant_id', 'department_id', 'purchasing_role']))->orderBy('id')->get();
if (hash('sha256', $rows->toJson()) !== $expected) {
throw new LogicException('Legacy cancellation changed a protected frame: '.$table);
}
}
$order = PurchaseOrder::query()->findOrFail($context['order_id']);
$request = Requisition::query()->findOrFail($context['request_id']);
$record = OrderCancellation::query()->where('purchase_order_id', $order->id)->sole();
$currentSource = Arr::except($request->getAttributes(), ['status', 'updated_at']);
$originalSource = Arr::except($context['original_request'], ['status', 'updated_at']);
if ($record->status !== 'approved' || $record->created_by !== $context['author_id'] || $record->reviewed_by !== $context['finance_id']
|| $request->status !== 'cancelled' || $currentSource !== $originalSource || $order->status !== 'issued'
|| hash('sha256', json_encode($order->getAttributes(), JSON_THROW_ON_ERROR)) !== $context['original_order_sha256']
|| app(OrderCancellationWorkflow::class)->state($order) !== 'cancelled') {
throw new LogicException('Native cancellation must preserve the issued original and independent decision.');
}
foreach (['requested', 'approved'] as $action) {
if (DB::table('audit_logs')->where('action', 'order_cancellation.'.$action)->where('requisition_id', $request->id)->count() !== 1) {
throw new LogicException('Native cancellation must create one request and one decision audit.');
}
}
return ['original_order_preserved' => true, 'original_status' => 'issued', 'operational_status' => 'cancelled',
'source_request_cancelled_only' => true, 'independent_finance_decision' => true, 'protected_frames_preserved' => count($context['protected_frames']),
'no_fabricated_legacy_reversal' => true, 'one_request_one_decision' => true, 'readonly_transaction' => true, 'synthetic_only' => true];
});
echo json_encode($state, JSON_THROW_ON_ERROR);
exit;
}
$financial = static function (): string {
$rows = [];
foreach (['gl_accounts', 'gl_journals', 'gl_lines', 'requisitions', 'requisition_items', 'invoices', 'invoice_items', 'external_payments', 'budget_entries', 'stock_movements'] as $table) {
$rows[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
};
$snapshot = static function (): array {
$frames = [];
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
$name = str_replace('"', '""', $table->tablename);
$rows = DB::select('select row_to_json(t)::text as row from "'.$name.'" t order by row_to_json(t)::text');
$frames[$table->tablename] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($table->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
return $frames;
};
if ($mode === 'read-native-sources') {
$frames = DB::transaction(function () use ($snapshot) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
return $snapshot();
});
echo json_encode(['snapshot' => $frames], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'prepare-recovery') {
LedgerSchema::install(DB::connection());
$composition = null;
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') {
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
$composition = integratedPurchasingQaSchema();
}
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
auth()->guard()->setUser($actor);
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
$service = app(RequisitionAccountAssignments::class);
$first = $service->save($actor, $request, $payload['input']);
$payload['input']['operation_key'] = (string) Str::uuid();
$payload['input']['version'] = 1;
$payload['input']['reason'] = 'Segunda versão explícita preservada no restauro';
$second = $service->save($actor, $request, $payload['input']);
echo json_encode(['payload' => $payload, 'first' => $first->id, 'second' => $second->id, 'snapshot' => $snapshot(), 'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'verify-recovery') {
$fixture = json_decode($argv[3], true, 64, JSON_THROW_ON_ERROR);
$composition = $fixture['integrated_optional_schema'] ?? null;
if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1'
&& (! is_array($composition) || count($composition['migrations'] ?? []) !== 5
|| count($composition['verified_tables'] ?? []) !== 12)) {
throw new RuntimeException('Integrated recovery requires the complete optional schema manifest.');
}
if ($snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Restored account composition differs in tables, columns or rows.');
}
$payload = $fixture['payload'];
$actor = User::query()->whereKey($payload['actor'])->firstOrFail();
auth()->guard()->setUser($actor);
$request = Requisition::query()->whereKey($payload['request'])->firstOrFail();
$service = app(RequisitionAccountAssignments::class);
$replay = $service->save($actor, $request, $payload['input']);
$frozen = $service->freezeForItems($actor, [$payload['input']['item_id']]);
if ($replay->id !== $fixture['second'] || $frozen[$payload['input']['item_id']]['id'] !== $fixture['second']
|| DB::table('supply_records')->where('kind', 'req_account')->count() !== 2 || $snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Restored account versions, audited origin or replay changed.');
}
echo json_encode(['tables_equal' => count($fixture['snapshot']), 'versions' => 2, 'audited_account_source_verified' => true,
'replay_without_effects' => true, 'chart_and_native_financial_sources_preserved' => true,
'integrated_optional_schema' => $composition], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if ($mode === 'prepare') {
$f = receiptFixture();
$f['r']->update(['status' => 'draft']);
auth()->guard()->setUser($f['issuer']);
DB::table('gl_accounts')->insert(['tenant_id' => $f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'QA-RACE-ACCOUNT', 'label' => 'Conta fictícia de concorrência', 'currency' => 'MZN', 'is_movement' => true]);
$space = app(RequisitionAccountAssignments::class)->workspace($f['issuer'], $f['r']);
$line = $space['items'][0];
$account = $space['accounts']['data'][0];
echo json_encode(['actor' => $f['issuer']->id, 'tenant' => $f['tenant']->id, 'request' => $f['r']->id, 'fingerprint' => $financial(),
'input' => ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'],
'reason' => 'Imputação explícita num ensaio de contenção real', 'allocations' => [['account_id' => $account['id'], 'source_hash' => $account['source_hash'],
'subtotal' => '100.00', 'total' => '100.00']]]], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'write') {
$payload = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_req_account_'.getmypid()]);
$actor = User::query()->findOrFail($payload['actor']);
auth()->guard()->setUser($actor);
try {
$record = app(RequisitionAccountAssignments::class)->save($actor, Requisition::query()->findOrFail($payload['request']), $payload['input']);
echo json_encode(['status' => 200, 'id' => $record->id]);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()]);
}
exit;
}
if ($mode !== 'race') {
throw new InvalidArgumentException('Unknown QA account mode.');
}
LedgerSchema::install(DB::connection());
foreach (['same_operation', 'same_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$payload = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
DB::beginTransaction();
try {
DB::table('tenants')->where('id', $payload['tenant'])->lockForUpdate()->firstOrFail();
for ($i = 0; $i < 2; $i++) {
$input = $payload;
if ($scenario === 'same_version' && $i === 1) {
$input['input']['operation_key'] = (string) Str::uuid();
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, 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(*) n from pg_stat_activity where datname=? and application_name like 'sgc_req_account_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked === 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked !== 2) {
throw new RuntimeException('Both account writers must demonstrably wait on the company lock.');
}
DB::commit();
$statuses = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException('Synthetic account writer failed: '.$worker->getErrorOutput());
}
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
}
sort($statuses);
$count = DB::table('supply_records')->where('tenant_id', $payload['tenant'])->where('kind', 'req_account')->count();
$audits = DB::table('audit_logs')->where('tenant_id', $payload['tenant'])->where('action', 'requisition.accounts_assigned')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $count !== 1 || $audits !== 1 || $financial() !== $payload['fingerprint']) {
throw new RuntimeException('Account contention lost replay/version/source guarantees.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers' => $blocked, 'versions' => $count, 'audits' => $audits, 'financial_sources_unchanged' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if (DB::transactionLevel() > 0) {
DB::rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}