commit compras1 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 07:11:35 +02:00
parent d58b75c87a
commit eb32c74c56
202 changed files with 17463 additions and 1526 deletions
@@ -0,0 +1,229 @@
<?php
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionAccountAssignments;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
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;
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'], 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'), 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;
}
$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();
}
}
}
}
@@ -3,6 +3,7 @@
use App\Models\Requisition;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -23,6 +24,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
config(['requisition-expiry.qa_enabled' => true]);
$expenses = ($argv[2] ?? '') === 'recover-expenses';
$urgent = ($argv[2] ?? '') === 'recover-urgent';
require_once __DIR__.'/../Support/ReceiptFixture.php';
receiptFixture();
$fingerprint = static function (Connection $connection): array {
@@ -51,7 +53,7 @@ $pg = static function (string $binary, array $arguments) use ($connectionConfig)
$preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.'/requisition-cycle-worker.php', $database, 'prepare', ...($urgent ? ['urgent'] : [])], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($input['clock']);
@@ -62,7 +64,7 @@ $workflow = app(RequisitionWorkflow::class);
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
$request->refresh();
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version,
'cost_center_id' => $request->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'cost_center_id' => $request->cost_center_id, 'priority' => $urgent ? 'urgent' : 'normal', 'needed_by' => today()->addWeek()->toDateString(),
'justification' => 'Synthetic revised request retained through recovery',
'items' => [['description' => 'Synthetic revised item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '120.00', 'tax_rate' => '0.00']]], $request);
$submission = (string) Str::uuid();
@@ -105,6 +107,15 @@ 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 ($urgent) {
$deadline = app(RequisitionExpiry::class)->deadline($request->fresh());
if (($deadline['timing'] ?? null) !== 'urgent_override'
|| Carbon::parse($deadline['started_at'])->diffInSeconds(Carbon::parse($deadline['expires_at'])) != 300
|| $request->fresh()->approval_snapshot['approval_expiry']['request_priority'] !== 'urgent') {
throw new RuntimeException('Restored urgent submission lost its explicit frozen timing.');
}
echo json_encode(['urgent_policy_frozen_restored' => true, 'urgent_expire_seconds_restored' => 300], JSON_THROW_ON_ERROR).PHP_EOL;
}
if ($expenses) {
$expenseActor = User::query()->whereKey($expenseFixture['f']['validator']->id)->firstOrFail();
auth()->guard()->setUser($expenseActor);
@@ -95,6 +95,7 @@ if ($mode === 'legacy-cycles') {
}
if ($mode === 'prepare') {
$urgent = ($argv[3] ?? '') === 'urgent';
if (! $db->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
@@ -107,16 +108,17 @@ if ($mode === 'prepare') {
Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating',
'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Synthetic concurrent cycle budget', 'created_by' => $admin->id, 'approved_by' => $finance->id]);
app(RequisitionExpiry::class)->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => []]],
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => null, 'escalation_minutes' => null, 'profile_ids' => [],
...($urgent ? ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => null, 'urgent_escalation_minutes' => null] : [])]],
'reason' => 'Explicit synthetic concurrent expiry policy']);
auth()->guard()->setUser($owner);
$workflow = app(RequisitionWorkflow::class);
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => $urgent ? 'urgent' : 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic simultaneous expiry and decision',
'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
Carbon::setTestNow(now()->addMinutes(31));
Carbon::setTestNow(now()->addMinutes($urgent ? 6 : 31));
echo json_encode(['tenant' => $owner->tenant_id, 'owner' => $owner->id, 'head' => $head->id, 'request' => $request->id,
'version' => $request->process_version, 'clock' => now()->toIso8601String(),
'basis' => app(RequisitionExpiry::class)->deadline($request)['basis_hash'], 'operation' => (string) Str::uuid()], JSON_THROW_ON_ERROR);