commit compras5 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 20:19:21 +02:00
parent 7486007fcf
commit d58b75c87a
57 changed files with 2803 additions and 116 deletions
@@ -0,0 +1,118 @@
<?php
use App\Models\User;
use App\Services\ExpenseAllocations;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$db = DB::connection();
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|| $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Expense contention requires disposable local PostgreSQL QA.');
}
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]);
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
$financial = static function () use ($db): string {
$rows = [];
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'stock_movements', 'pa_commands'] as $table) {
$rows[$table] = $db->table($table)->orderBy('id')->get()->toJson();
}
return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
};
if ($mode === 'prepare') {
$fixture = expenseAllocationQaFixture();
$f = $fixture['f'];
if (($argv[3] ?? '') === 'same_version') {
$record = app(ExpenseAllocations::class)->save($f['validator'], $fixture['payment']->id, $fixture['input']);
$fixture['input']['version'] = $record->version;
$fixture['input']['operation_key'] = (string) Str::uuid();
}
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['validator']->id, 'alternate' => $f['author']->id,
'payment' => $fixture['payment']->id, 'input' => $fixture['input'], 'financial_fingerprint' => $financial(),
'records_before' => $db->table('supply_records')->where('tenant_id', $f['tenant']->id)->where('kind', 'expense_allocation')->count(),
'audits_before' => $db->table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'expense.allocation_recorded')->count()], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'write') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
$db->select('select set_config(?, ?, false)', ['application_name', 'sgc_expense_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
app(ExpenseAllocations::class)->save($actor, $input['payment'], $input['input']);
echo json_encode(['status' => 200]);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()]);
}
exit;
}
if ($mode !== 'race-expense') {
throw new InvalidArgumentException('Unknown expense contention mode.');
}
foreach (['same_operation', 'same_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
$db->beginTransaction();
try {
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
for ($index = 0; $index < 2; $index++) {
$payload = $input;
if ($scenario === 'same_version' && $index === 1) {
$payload['actor'] = $input['alternate'];
$payload['input']['operation_key'] = (string) Str::uuid();
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($payload, 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_expense_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 Finance writers must demonstrably wait on the company lock.');
}
$db->commit();
$statuses = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
}
sort($statuses);
$records = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'expense_allocation')->count() - $input['records_before'];
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'expense.allocation_recorded')->count() - $input['audits_before'];
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $financial() !== $input['financial_fingerprint']) {
throw new RuntimeException('Expense contention must retain one attribution/audit and unchanged native financial sources.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'expense_versions_created' => $records, '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();
}
}
}
}
+21 -1
View File
@@ -28,7 +28,8 @@ $database = $argv[1] ?? '';
$corpus = realpath($argv[3] ?? '');
$candidateRelative = $argv[4] ?? '';
$candidateHash = $argv[5] ?? '';
$reviewMode = ($argv[2] ?? '') === 'legal-review';
$expiryReview = ($argv[2] ?? '') === 'expiry-review';
$reviewMode = ($argv[2] ?? '') === 'legal-review' || $expiryReview;
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)
|| $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
@@ -180,9 +181,28 @@ try {
'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
$bank = importBankQaFixture($reviewer, $import);
app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
$expiryRequest = null;
if ($expiryReview) {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
supplyGrant($reviewer, ['admin', 'procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
supplyGrant($head, ['department_head']);
app(\App\Services\RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]],
'reason' => 'Política estritamente sintética para revisão visual do ciclo']);
$workflow = app(\App\Services\RequisitionWorkflow::class);
$expiryRequest = $workflow->save($reviewer, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Ensaio visual sintético da devolução e nova submissão',
'items' => [['description' => 'Material sintético do ciclo', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($reviewer, $expiryRequest, (string) Str::uuid(), $expiryRequest->process_version);
// Explicit synthetic clock fixture: no existing request or real timestamp is rewritten.
$expiryRequest->update(['submitted_at' => now()->subMinutes(31)]);
}
$stopFile = $directory.'/stop';
echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
'expiry_request' => $expiryRequest?->id, 'expiry_url' => $expiryRequest === null ? null : $url.'/requisicoes/'.$expiryRequest->id.'/prazos',
'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
$deadline = microtime(true) + 3600;
@@ -2,6 +2,7 @@
use App\Models\Requisition;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -21,6 +22,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
throw new LogicException('Cycle recovery requires disposable local PostgreSQL QA.');
}
config(['requisition-expiry.qa_enabled' => true]);
$expenses = ($argv[2] ?? '') === 'recover-expenses';
require_once __DIR__.'/../Support/ReceiptFixture.php';
receiptFixture();
$fingerprint = static function (Connection $connection): array {
@@ -66,6 +68,16 @@ $request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'pr
$submission = (string) Str::uuid();
$version = $request->process_version;
$workflow->submit($owner, $request, $submission, $version);
$expenseFixture = $expenseInput = null;
if ($expenses) {
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
$expenseFixture = expenseAllocationQaFixture();
$expenseService = app(ExpenseAllocations::class);
$firstExpense = $expenseService->save($expenseFixture['f']['validator'], $expenseFixture['payment']->id, $expenseFixture['input']);
$expenseInput = [...$expenseFixture['input'], 'operation_key' => (string) Str::uuid(), 'version' => $firstExpense->version,
'allocations' => [['category' => 'Material', 'amount' => '10.00'], ['category' => 'Serviços', 'amount' => '30.00']]];
$expenseService->save($expenseFixture['f']['validator'], $expenseFixture['payment']->id, $expenseInput);
}
$after = $fingerprint($db);
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
@@ -93,6 +105,21 @@ try {
|| $restored->table('approval_steps')->where('requisition_id', $request->id)->where('decision', 'expired')->count() !== 1) {
throw new RuntimeException('Restored native expiry/submission replay changed history or reservation.');
}
if ($expenses) {
$expenseActor = User::query()->whereKey($expenseFixture['f']['validator']->id)->firstOrFail();
auth()->guard()->setUser($expenseActor);
$expenseService = app(ExpenseAllocations::class);
$paymentId = $expenseFixture['payment']->id;
$projection = $expenseService->projection($expenseActor, $paymentId);
$replay = $expenseService->save($expenseActor, $paymentId, $expenseInput);
if ($replay->version !== 2 || $projection['state'] !== 'allocated'
|| $projection['allocations'] !== [['category' => 'Material', 'amount_minor' => '1000'], ['category' => 'Serviços', 'amount_minor' => '3000']]
|| $fingerprint($restored) !== $after) {
throw new RuntimeException('Explicit expense versions, audited sources or replay changed after restore.');
}
echo json_encode(['expense_versions_restored' => 2, 'expense_native_sources_verified' => true,
'expense_explicit_amounts_restored' => ['Material' => '1000', 'Serviços' => '3000'], 'expense_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
DB::setDefaultConnection($originalDefault);
DB::purge('cycle_recovery_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
+24 -1
View File
@@ -35,6 +35,29 @@ if ($mode === 'scheduled-cycle') {
if (auth()->check() || request()->hasSession()) {
throw new RuntimeException('Scheduled proof must run without an authenticated session.');
}
$scope = app(RequisitionExpiryRun::class);
$denied = 0;
foreach (['foreign_origin', 'budget_create', 'submit'] as $action) {
try {
$scope->execute($input['request'], function () use ($input, $action) {
$actor = User::query()->findOrFail($input['owner']);
if ($action === 'foreign_origin') {
app(CommonBudget::class)->for($actor, [$input['request'] + 999999 => 1]);
} elseif ($action === 'budget_create') {
app(CommonBudget::class)->for($actor, [$input['request'] => 1])->create([]);
} else {
$request = Requisition::query()->findOrFail($input['request']);
app(RequisitionWorkflow::class)->submit($actor, $request, (string) Str::uuid(), $request->process_version);
}
});
throw new RuntimeException('Scheduled scope unexpectedly allowed '.$action);
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 403 || $scope->tenantId() !== null) {
throw $error;
}
$denied++;
}
}
if (Artisan::call('sgc:approval-deadlines-tick') !== 0) {
throw new RuntimeException('Scheduled deadline tick failed: '.Artisan::output());
}
@@ -53,7 +76,7 @@ if ($mode === 'scheduled-cycle') {
throw new RuntimeException('Scheduled audit must distinguish automatic execution from an interactive act.');
}
echo json_encode(['scheduled_expiry_without_session' => true, 'scheduled_scope_closed' => true, 'scheduled_repeat_without_effects' => true,
'scheduled_audit_explicit' => true], JSON_THROW_ON_ERROR);
'scheduled_audit_explicit' => true, 'scheduled_unrelated_operations_denied' => $denied], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'legacy-cycles') {