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

This commit is contained in:
2026-11-27 19:13:31 +02:00
parent 9cf9764710
commit 7486007fcf
41 changed files with 1270 additions and 66 deletions
@@ -0,0 +1,122 @@
<?php
use App\Models\Requisition;
use App\Models\User;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$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('Cycle recovery requires disposable local PostgreSQL QA.');
}
config(['requisition-expiry.qa_enabled' => true]);
require_once __DIR__.'/../Support/ReceiptFixture.php';
receiptFixture();
$fingerprint = static function (Connection $connection): array {
$result = [];
foreach ($connection->select("select tablename from pg_tables where schemaname='public' order by tablename") as $row) {
$table = str_replace('"', '""', $row->tablename);
$rows = $connection->select('select row_to_json(t)::text as row from "'.$table.'" t order by row_to_json(t)::text');
$result[$row->tablename] = hash('sha256', json_encode([$connection->getSchemaBuilder()->getColumnListing($row->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
return $result;
};
$before = $fingerprint($db);
$connectionConfig = $db->getConfig();
unset($connectionConfig['name']);
$directory = storage_path('framework/testing/cycle-recovery-'.$database);
File::ensureDirectoryExists($directory, 0700);
$pg = static function (string $binary, array $arguments) use ($connectionConfig): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
['PGHOST' => $connectionConfig['host'], 'PGPORT' => (string) $connectionConfig['port'], 'PGUSER' => $connectionConfig['username'], 'PGPASSWORD' => $connectionConfig['password']], timeout: 60);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Synthetic cycle backup/restore failed.');
}
};
$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->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($input['clock']);
$owner = User::query()->findOrFail($input['owner']);
auth()->guard()->setUser($owner);
$request = Requisition::query()->findOrFail($input['request']);
$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(),
'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();
$version = $request->process_version;
$workflow->submit($owner, $request, $submission, $version);
$after = $fingerprint($db);
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
$originalDefault = DB::getDefaultConnection();
config(['database.connections.cycle_recovery_admin' => [...$connectionConfig, 'database' => 'postgres'],
'database.connections.cycle_recovery_restore' => [...$connectionConfig, 'database' => $restore]]);
$admin = DB::connection('cycle_recovery_admin');
$created = false;
try {
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $postDump]);
$restored = DB::connection('cycle_recovery_restore');
if ($fingerprint($restored) !== $after) {
throw new RuntimeException('Restored cycle schema or complete table contents differ.');
}
DB::setDefaultConnection('cycle_recovery_restore');
$owner = User::query()->findOrFail($input['owner']);
auth()->guard()->setUser($owner);
$request = Requisition::query()->findOrFail($input['request']);
$workflow->expire($owner, $request, $input['basis'], $input['operation'], $input['version']);
$workflow->submit($owner, $request, $submission, $version);
if ($fingerprint($restored) !== $after || $request->fresh()->approval_cycle !== 2
|| (int) $restored->table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor') !== 12000
|| $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.');
}
DB::setDefaultConnection($originalDefault);
DB::purge('cycle_recovery_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
$created = false;
$admin->statement('CREATE DATABASE "'.$restore.'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('cycle_recovery_restore');
if ($fingerprint($restored) !== $before || $restored->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
throw new RuntimeException('Pre-extension restore did not preserve its exact original schema and records.');
}
echo json_encode(['cycle_post_extension_all_tables_equal' => true, 'cycle_native_replays_without_effects' => true,
'cycle_history_and_reserve_restored' => true, 'cycle_reserved_minor' => 12000,
'cycle_pre_extension_all_tables_equal' => true, 'pre_extension_tables' => count($before), 'post_extension_tables' => count($after)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
DB::setDefaultConnection($originalDefault);
DB::purge('cycle_recovery_restore');
if ($created) {
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
}
echo json_encode(['restore_database' => $restore, 'isolated_restore_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
$resolved = realpath($directory);
$testingRoot = realpath(storage_path('framework/testing'));
if ($resolved !== false && $testingRoot !== false && str_starts_with($resolved, $testingRoot.DIRECTORY_SEPARATOR)) {
File::deleteDirectory($resolved);
}
}
@@ -0,0 +1,210 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Requisition;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionExpiryRun;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
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('Cycle contention requires disposable local PostgreSQL QA.');
}
config(['requisition-expiry.qa_enabled' => true]);
require_once __DIR__.'/../Support/ReceiptFixture.php';
if ($mode === 'scheduled-cycle') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($input['clock']);
if (auth()->check() || request()->hasSession()) {
throw new RuntimeException('Scheduled proof must run without an authenticated session.');
}
if (Artisan::call('sgc:approval-deadlines-tick') !== 0) {
throw new RuntimeException('Scheduled deadline tick failed: '.Artisan::output());
}
$request = $db->table('requisitions')->where('id', $input['request'])->sole();
$count = $db->table('supply_records')->count();
$audits = $db->table('audit_logs')->count();
if (Artisan::call('sgc:approval-deadlines-tick') !== 0 || $db->table('supply_records')->count() !== $count || $db->table('audit_logs')->count() !== $audits
|| $request->status !== 'draft' || $request->approval_cycle !== 2 || auth()->check()
|| app(RequisitionExpiryRun::class)->tenantId() !== null
|| (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor') !== 0) {
throw new RuntimeException('Scheduled expiry must close the scope and replay without effects.');
}
$audit = $db->table('audit_logs')->where('requisition_id', $input['request'])->where('action', 'requisition.expired_returned')->sole();
$data = json_decode($audit->after, true, 32, JSON_THROW_ON_ERROR);
if (($data['execution']['mode'] ?? null) !== 'scheduled_approval_deadline' || $audit->ip_address !== null) {
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);
exit;
}
if ($mode === 'legacy-cycles') {
$actor = User::query()->findOrFail((int) $argv[3]);
auth()->guard()->setUser($actor);
try {
app(CommonBudget::class)->for($actor)->balance((int) $argv[4]);
throw new RuntimeException('Old runtime unexpectedly exposed a balance after a new cycle.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503) {
throw $error;
}
echo json_encode(['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503]);
}
exit;
}
if ($mode === 'prepare') {
if (! $db->getSchemaBuilder()->hasTable('budget_requisition_cycles')) {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
$f = receiptFixture();
$owner = $f['issuer'];
$admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$finance = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Finance]);
auth()->guard()->setUser($admin);
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' => []]],
'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',
'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));
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);
exit;
}
// Re-enter the native submission route before checking an older installed composition.
$verifyLegacy = function (array $input) use ($db, $database): void {
$owner = User::query()->findOrFail($input['owner']);
auth()->guard()->setUser($owner);
$request = Requisition::query()->findOrFail($input['request']);
app(RequisitionWorkflow::class)->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$before = $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson();
$budget = $db->table('budgets')->where('tenant_id', $owner->tenant_id)->where('cost_center_id', $request->cost_center_id)->sole();
$legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy-cycles', (string) $owner->id, (string) $budget->id],
dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => base_path('packages/budget-control')], timeout: 30);
$legacy->mustRun();
$receipt = json_decode($legacy->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($receipt['old_cycle_runtime_rejected_before_balance'] ?? false) !== true
|| $before !== $db->table('budget_entries')->where('requisition_id', $request->id)->orderBy('id')->get()->toJson()) {
throw new RuntimeException('Legacy cycle refusal must precede all balance exposure and financial writes.');
}
echo $legacy->getOutput().PHP_EOL;
};
if ($mode === 'write') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
Carbon::setTestNow($input['clock']);
$db->select('select set_config(?, ?, false)', ['application_name', 'sgc_cycle_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['decision'] ? $input['head'] : $input['owner']);
auth()->guard()->setUser($actor);
try {
$request = Requisition::query()->findOrFail($input['request']);
$workflow = app(RequisitionWorkflow::class);
if ($input['decision']) {
$workflow->decide($actor, $request, 'approved', 'Synthetic decision after configured deadline', $input['operation'], $input['version']);
} else {
$workflow->expire($actor, $request, $input['basis'], $input['operation'], $input['version']);
}
echo json_encode(['status' => 200]);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()]);
}
exit;
}
if ($mode !== 'race-cycles') {
throw new InvalidArgumentException('Unknown cycle worker mode.');
}
foreach (['same_operation', 'different_operations', 'late_decision'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], 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 + ['decision' => $scenario === 'late_decision' && $index === 1];
if ($scenario !== 'same_operation' && $index === 1) {
$payload['operation'] = (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_cycle_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 cycle 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);
$request = $db->table('requisitions')->where('id', $input['request'])->sole();
$returns = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'req_expiration')->count();
$reserve = (int) $db->table('budget_entries')->where('requisition_id', $input['request'])->sum('reserved_minor');
$approved = $db->table('approval_steps')->where('requisition_id', $input['request'])->where('decision', 'approved')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $returns !== 1 || $reserve !== 0
|| $request->status !== 'draft' || $request->approval_cycle !== 2 || $approved !== 0) {
throw new RuntimeException('Concurrent expiry must preserve one return, zero reserve and no late approval: '.json_encode($statuses));
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'returns' => $returns, 'reserve_minor' => $reserve, 'late_approvals' => $approved], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
$verifyLegacy($input);
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$scheduled = new Process([PHP_BINARY, __FILE__, $database, 'scheduled-cycle', $prepare->getOutput()], dirname(__DIR__, 2), timeout: 30);
$scheduled->mustRun();
echo $scheduled->getOutput().PHP_EOL;
+22 -2
View File
@@ -1794,12 +1794,32 @@ test('native partial-order Finance amendment exposes a recoverable form and pres
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
});
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function (int $cycle) {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
if ($cycle === 2) {
if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) {
$this->markTestSkipped('Explicit cycle-capable common QA source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
$engine = app(CommonBudget::class)->for($this->buyer, [$this->r->id => 1]);
$engine->beginRequisitionCycle($this->r->id, 1, (string) Str::uuid());
$engine->closeRequisitionCycle($this->r->id, 1, (string) Str::uuid());
$this->r->setAttribute('approval_cycle', 2);
$this->r->save();
$step = $this->r->steps()->make(['tenant_id' => $this->tenant->id, 'position' => 1, 'role' => 'department_head',
'decision' => 'approved', 'approver_id' => $this->head->id, 'decided_at' => now()]);
$step->setAttribute('approval_cycle', 2);
$step->save();
app(CommonBudget::class)->for($this->buyer, [$this->r->id => 2])->beginRequisitionCycle($this->r->id, 2, (string) Str::uuid());
}
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$workflow = app(OrderPartsWorkflow::class);
@@ -1824,7 +1844,7 @@ test('native partial-order issuance commits only forty then sixty and preserves
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
});
})->with([1, 2]);
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
@@ -159,6 +159,40 @@ test('import assumptions release in the old cycle before a separately identified
->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old);
});
test('configured escalation alerts respect current membership and never delegate the pending approval', function () {
$owner = $this->f['issuer'];
$head = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
$viewer = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Configured]);
$profiles = [];
foreach ([[$owner, ['admin', 'requester']], [$head, ['department_head']], [$viewer, ['procurement']]] as [$person, $permissions]) {
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Synthetic profile '.$person->id,
'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $owner->tenant_id, 'user_id' => $person->id, 'profile_id' => $profile, 'maintenance' => false]);
$profiles[$person->id] = $profile;
}
DB::table('organization_access')->insert(['tenant_id' => $owner->tenant_id, 'active' => true, 'version' => 1]);
$this->actingAs($owner);
$expiry = app(RequisitionExpiry::class);
$expiry->savePolicy($owner, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => 20, 'profile_ids' => [$profiles[$viewer->id]]]],
'reason' => 'Explicit synthetic escalation to an existing viewer profile']);
$workflow = app(RequisitionWorkflow::class);
$request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id,
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic configured deadline and notification recipients',
'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();
$this->travel(20)->minutes();
$result = $expiry->check($owner, $request, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version]);
expect($result['escalation_eligible'])->toBe(1)->and($result['notices_created'])->toBe(2);
$this->actingAs($viewer);
expect(array_column(app(WorkflowNotices::class)->visible($viewer), 'kind'))->toContain('escalation')
->and($request->canDecide($viewer))->toBeFalse();
DB::table('organization_memberships')->where('user_id', $viewer->id)->update(['expires_at' => now()->subSecond()]);
expect(app(WorkflowNotices::class)->visible($viewer))->toBe([]);
$this->travelBack();
});
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
@@ -179,6 +213,13 @@ test('native expiry returns the same request and preserves the approved stage be
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->actingAs($head);
$this->travel(10)->minutes();
$check = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$firstCheck = $expiry->check($head, $request, $check);
expect($firstCheck['notices_created'])->toBe(1)
->and($expiry->check($head, $request, $check))->toBe($firstCheck)
->and($expiry->check($head, $request, ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version])['notices_created'])->toBe(0)
->and(array_column(app(WorkflowNotices::class)->visible($head), 'kind'))->toContain('reminder');
$workflow->decide($head, $request, 'approved', 'Conferência sintética do primeiro nível', (string) Str::uuid(), $request->process_version);
$request->refresh();
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
@@ -216,5 +257,13 @@ test('native expiry returns the same request and preserves the approved stage be
$notices = app(WorkflowNotices::class)->visible($owner);
expect(array_column($notices, 'outcome'))->toContain('expired')
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
$this->travel(31)->minutes();
$check = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson('/requisicoes/'.$request->id.'/prazos/verificar', $check)->assertRedirect();
$this->postJson('/requisicoes/'.$request->id.'/prazos/verificar', $check)->assertRedirect();
$request->refresh();
expect($request->status)->toBe('draft')->and($request->approval_cycle)->toBe(3)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(2);
$this->travelBack();
});
+19
View File
@@ -24,6 +24,25 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return false;
};
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
if ($mode === 'recover-cycles') {
return $contains(fn ($row) => ($row['cycle_post_extension_all_tables_equal'] ?? false) === true
&& ($row['cycle_native_replays_without_effects'] ?? false) === true && ($row['cycle_history_and_reserve_restored'] ?? false) === true
&& ($row['cycle_reserved_minor'] ?? null) === 12000 && ($row['cycle_pre_extension_all_tables_equal'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
if ($mode === 'race-cycles') {
foreach (['same_operation', 'different_operations', 'late_decision'] as $scenario) {
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|| ($matches[0]['returns'] ?? null) !== 1 || ($matches[0]['reserve_minor'] ?? null) !== 0
|| ($matches[0]['late_approvals'] ?? null) !== 0
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
return $contains(fn ($row) => ($row['old_cycle_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? null) === 503);
}
if ($mode === 'capital') {
if (! $contains(fn ($row) => ($row['capital_register_versions_restored'] ?? null) === 2
&& ($row['capital_assignment_source_version_restored'] ?? null) === 1 && ($row['capital_archived_head_preserved'] ?? false) === true
+17
View File
@@ -1,5 +1,22 @@
<?php
test('cycle contention requires all three real lock and single-effect receipts', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-cycles'];
$rows = [];
foreach (['same_operation' => [200, 200], 'different_operations' => [200, 409], 'late_decision' => [200, 409]] as $scenario => $statuses) {
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'returns' => 1, 'reserve_minor' => 0, 'late_approvals' => 0];
}
$rows[] = ['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503];
$output = function () use (&$rows) {
return implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
};
expect(landedQaReceiptsVerified($command, $output()))->toBeTrue();
$rows[2]['late_approvals'] = 1;
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
array_pop($rows);
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
});
test('capital register contention requires both actual lock receipts and one immutable version per scenario', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-capital'];
$rows = [];
@@ -0,0 +1,85 @@
import { App } from "@inertiajs/react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, test } from "vitest";
import Expiry from "../../resources/js/pages/requisitions/expiry";
function render(extra: object) {
return renderToStaticMarkup(
<App
initialComponent={Expiry}
initialPage={{
component: "requisitions/expiry",
url: "/requisicoes/1/prazos",
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
requisition: {
id: 1,
number: "REQ-QA",
status: "draft",
process_version: 4,
approval_cycle: 2,
},
deadline: {
state: "inactive",
step_id: null,
expires_at: null,
basis_hash: null,
},
canExpire: false,
canCheck: false,
canEdit: true,
actorId: 1,
tenantId: 1,
history: {
data: [
{
id: 1,
data: { cycle: 1, next_cycle: 2 },
reason: "<script>synthetic</script>",
request: { number: "REQ-QA" },
steps: [
{
id: 1,
position: 1,
role: "department_head",
decision: "approved",
},
],
},
],
prev_page_url: null,
next_page_url: null,
},
...extra,
},
}}
/>,
);
}
test("returned owner sees the same draft and preserved approval without expiry controls", () => {
const html = render({});
expect(html).toContain("/requisicoes/1/editar");
expect(html).toContain("Aprovação preservada");
expect(html).toContain("&lt;script&gt;synthetic&lt;/script&gt;");
expect(html).not.toContain("<form");
});
test("a pending configured deadline exposes due actions only when allowed", () => {
const html = render({
canEdit: false,
canCheck: true,
deadline: {
state: "running",
step_id: 2,
expires_at: "2026-11-27T12:30:00Z",
basis_hash: "a".repeat(64),
},
});
expect(html).toContain("Verificar e executar acções devidas");
expect(html).not.toContain("Rever rascunho");
expect(html).not.toContain("Devolver ao requisitante</button>");
});