committedUrgentReviewFixture ?? false) { if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) { throw new LogicException('Urgent review cleanup requires its disposable committed QA fixture.'); } DB::statement('DROP SCHEMA public CASCADE'); DB::statement('CREATE SCHEMA public'); } }); beforeEach(function () { if (! method_exists(BudgetControl::class, 'beginRequisitionCycle')) { $this->markTestSkipped('The optional cycle contract uses the explicitly authorised common QA source, never the installed kernel.'); } $this->f = receiptFixture(); $this->actingAs($this->f['issuer']); $this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]); $this->budget = Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Dotação aprovada estritamente sintética para ciclos', 'created_by' => $this->f['issuer']->id, 'approved_by' => $this->reviewer->id]); if (getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1') { $source = requisitionLedgerQaSource(); if ($source === null) { throw new LogicException('Integrated cycles require the dedicated actual-ledger QA runner.'); } require_once $source.'/bootstrap.php'; LedgerSchema::install(DB::connection()); require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php'; $composition = integratedPurchasingQaSchema(); expect($composition['verified_tables'])->toHaveCount(12); } else { budgetDistributionFixtureSchema(); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up(); (require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up(); } config(['requisition-expiry.qa_enabled' => true]); }); test('ordinary budget cycles release and reserve a revised amount without replaying or rewriting the original cycle', function () { $origin = $this->f['r']->id; $service = app(CommonBudget::class); $first = $service->for($this->f['issuer'], [$origin => 1]); $open = (string) Str::uuid(); $first->beginRequisitionCycle($origin, 1, $open); $first->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000); expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class); $first->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'); $close = (string) Str::uuid(); $first->closeRequisitionCycle($origin, 1, $close); $old = DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson(); expect($first->closeRequisitionCycle($origin, 1, $close)['replayed'])->toBeTrue(); $second = $service->for($this->f['issuer'], [$origin => 2]); $second->beginRequisitionCycle($origin, 2, (string) Str::uuid()); $second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000); $second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000); expect(DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson())->toBe($old) ->and(DB::table('budget_entries')->where('requisition_cycle', 2)->count())->toBe(1) ->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(12000); $this->actingAs($this->reviewer); expect($service->for($this->reviewer)->balance($this->budget->id)['available_minor'])->toBe(88000); $this->actingAs($this->f['issuer']); expect(fn () => $service->for($this->f['issuer'])->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'))->toThrow(BudgetFailure::class); $second->record($origin, $this->f['r']->cost_center_id, 'operating', 'release'); expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0); }); test('a current committed cycle cannot expire or open another cycle and malformed operations cannot establish identity', function () { $origin = $this->f['r']->id; $engine = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]); expect(fn () => $engine->beginRequisitionCycle($origin, 1, str_repeat('-', 36)))->toThrow(BudgetFailure::class); $engine->beginRequisitionCycle($origin, 1, (string) Str::uuid()); $engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000); $engine->record($origin, $this->f['r']->cost_center_id, 'operating', 'commit', 10000, 10000); expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(fn () => app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2])->beginRequisitionCycle($origin, 2, (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(DB::table('budget_requisition_cycles')->count())->toBe(1) ->and((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(10000); $invoice = Invoice::query()->create(['tenant_id' => $this->f['tenant']->id, 'purchase_order_id' => $this->f['order']->id, 'supplier_id' => $this->f['order']->supplier_id, 'created_by' => $this->f['issuer']->id, 'number' => 'CYCLE-CONSUMPTION-QA', 'issued_on' => today(), 'status' => 'validated', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'snapshot' => ['synthetic' => true]]); $this->actingAs($this->reviewer); app(CommonBudget::class)->for($this->reviewer, [$origin => 1])->consume($origin, $invoice->id, 10000, 10000); $this->actingAs($this->f['issuer']); expect((int) DB::table('budget_entries')->sum('committed_minor'))->toBe(0); expect(fn () => $engine->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class); }); test('current approval relations select the new cycle during eager loading and keep all original decisions addressable', function () { $request = $this->f['r']->fresh(); $old = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 1, 'position' => 1, 'role' => 'department_head', 'decision' => 'approved', 'approver_id' => $this->reviewer->id, 'decided_at' => now()]); $request->setAttribute('approval_cycle', 2); $request->setAttribute('status', 'pending'); $request->save(); expect((int) DB::table('requisitions')->where('id', $request->id)->value('approval_cycle'))->toBe(2); $current = $request->allSteps()->create(['tenant_id' => $request->tenant_id, 'approval_cycle' => 2, 'position' => 1, 'role' => 'department_head', 'decision' => 'pending']); $loaded = Requisition::query()->with('steps')->whereKey($request->id)->firstOrFail(); expect($loaded->steps->pluck('id')->all())->toBe([$current->id]) ->and($loaded->allSteps()->count())->toBe(2)->and($old->fresh()->decision)->toBe('approved') ->and(InternalRequisitions::nextStep($loaded->toArray(), $this->reviewer->id)['id'])->toBe($current->id); }); test('distributed reservations use a fresh cycle header and preserve the released original allocations', function () { $origin = $this->f['r']->id; $line = $this->f['r']->items()->sole(); $allocations = [['allocation_key' => 'A', 'line_id' => $line->id, 'centre_id' => $this->f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]]; $lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']]; $revision = hash('sha256', 'synthetic cycle-one native source'); $first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]); $first->beginRequisitionCycle($origin, 1, (string) Str::uuid()); $first->recordDistribution($origin, 'reserve', $allocations, $lines, $revision, (string) Str::uuid()); $first->recordDistribution($origin, 'release', $allocations, $lines, $revision, (string) Str::uuid()); $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()); $old = DB::table('budget_distributions')->where('requisition_cycle', 1)->sole(); $this->f['r']->setAttribute('approval_cycle', 2); $this->f['r']->save(); $line->update(['unit_price_minor' => 12000, 'subtotal_minor' => 12000, 'total_minor' => 12000]); $this->f['r']->update(['subtotal_minor' => 12000, 'total_minor' => 12000]); $allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 12000; $lines[$line->id]['subtotal_minor'] = $lines[$line->id]['total_minor'] = 12000; $second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]); $second->beginRequisitionCycle($origin, 2, (string) Str::uuid()); $second->recordDistribution($origin, 'reserve', $allocations, $lines, hash('sha256', 'synthetic cycle-two native source'), (string) Str::uuid()); expect(DB::table('budget_distributions')->where('id', $old->id)->sole())->toEqual($old) ->and(DB::table('budget_distributions')->where('requisition_id', $origin)->count())->toBe(2) ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(12000) ->and(app(RequisitionBudgetDistributions::class)->source($this->f['r'])->requisition_cycle)->toBe(2); }); test('import assumptions release in the old cycle before a separately identified new plan can reserve', function () { $origin = $this->f['r']->id; $first = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 1]); $first->beginRequisitionCycle($origin, 1, (string) Str::uuid()); $goods = ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]; $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable', 'basis' => 'Explicit synthetic assumption; not a real import or exemption', 'subtotal_minor' => $kind === 'duty' ? 1000 : null, 'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 1000 : null], BudgetImportEstimate::KINDS); $plan = (string) Str::uuid(); $first->reserveImportEstimate($plan, 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid()); expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class); $hash = BudgetImportEstimate::reconcile($goods, $components, true)['fingerprint']; $first->releaseImportEstimate($plan, 1, $hash, (string) Str::uuid()); $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()); $old = DB::table('budget_landed_entries')->orderBy('id')->get()->toJson(); $second = app(CommonBudget::class)->for($this->f['issuer'], [$origin => 2]); $second->beginRequisitionCycle($origin, 2, (string) Str::uuid()); foreach ($components as &$component) { if ($component['kind'] === 'duty') { $component['subtotal_minor'] = $component['total_minor'] = 1500; } } unset($component); $second->reserveImportEstimate((string) Str::uuid(), 1, $this->budget->id, $origin, $goods, $components, (string) Str::uuid()); expect((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1500) ->and(DB::table('budget_landed_entries')->orderBy('id')->limit(2)->get()->toJson())->toBe($old); }); test('urgent deadlines are explicitly configured frozen per submission and expire only the selected request', function () { $owner = $this->f['issuer']; $admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]); User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]); $profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Destinatário sintético configurável', 'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]); $this->actingAs($admin); $expiry = app(RequisitionExpiry::class); $policy = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Prazos sintéticos explícitos para conferir urgências', 'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => 20, 'profile_ids' => [$profile], 'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2]]]; $first = $expiry->savePolicy($admin, $policy); expect($expiry->savePolicy($admin, $policy)->id)->toBe($first->id); $this->actingAs($owner); $workflow = app(RequisitionWorkflow::class); $make = function (string $priority) use ($owner, $workflow) { $request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => $priority, 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com prioridade expressamente indicada', 'items' => [['description' => 'Material sintético', '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); return $request->fresh(); }; $normal = $make('normal'); $urgent = $make('urgent'); $normalDeadline = $expiry->deadline($normal); $urgentDeadline = $expiry->deadline($urgent); expect($normalDeadline['timing'])->toBe('standard')->and($urgentDeadline['timing'])->toBe('urgent_override') ->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['expires_at'])))->toEqual(300) ->and(CarbonImmutable::parse($normalDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($normalDeadline['expires_at'])))->toEqual(1800) ->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['reminder_at'])))->toEqual(60) ->and(CarbonImmutable::parse($urgentDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($urgentDeadline['escalation_at'])))->toEqual(120); $policy['operation_key'] = (string) Str::uuid(); $policy['version'] = 1; $policy['levels'][0]['urgent_expire_minutes'] = 4; $this->actingAs($admin); $expiry->savePolicy($admin, $policy); $this->actingAs($owner); expect($expiry->deadline($urgent)['expires_at'])->toBe($urgentDeadline['expires_at']); $later = $make('urgent'); $laterDeadline = $expiry->deadline($later); expect(CarbonImmutable::parse($laterDeadline['started_at'])->diffInSeconds(CarbonImmutable::parse($laterDeadline['expires_at'])))->toEqual(240); $this->travel(2)->minutes(); $check = $expiry->check($owner, $urgent, ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version]); expect($check['notices_created'])->toBe(1)->and($check['escalation_eligible'])->toBe(0); $this->travel(3)->minutes(); $deadline = $expiry->deadline($urgent); expect($deadline['state'])->toBe('expired')->and($expiry->deadline($normal)['state'])->toBe('running'); $this->postJson('/requisicoes/'.$urgent->id.'/expiracao', ['operation_key' => (string) Str::uuid(), 'process_version' => $urgent->process_version, 'basis_hash' => $deadline['basis_hash']])->assertRedirect(); expect($urgent->fresh()->status)->toBe('draft')->and($normal->fresh()->status)->toBe('pending') ->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(20000); $this->travelBack(); }); test('urgent configuration rejects missing slower or unordered deadlines and preserves legacy replay inputs', function () { $owner = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]); $this->actingAs($owner); $expiry = app(RequisitionExpiry::class); $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'reason' => 'Política sintética sem alteração dos pedidos antigos', 'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]]]; $record = $expiry->savePolicy($owner, $input); expect($record->data['levels'][0])->not->toHaveKey('urgent_expire_minutes') ->and($expiry->savePolicy($owner, $input)->id)->toBe($record->id); foreach ([['urgent_expire_minutes' => 30, 'urgent_reminder_minutes' => 1], ['urgent_expire_minutes' => 5], ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 5], ['urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => 1, 'urgent_escalation_minutes' => 2], ['urgent_reminder_minutes' => 1]] as $changes) { $bad = $input; $bad['operation_key'] = (string) Str::uuid(); $bad['version'] = 1; $bad['levels'][0] = [...$bad['levels'][0], ...$changes]; expect(fn () => $expiry->savePolicy($owner, $bad))->toThrow(ValidationException::class); } expect(SupplyRecord::query()->where('kind', 'req_expiry_policy')->count())->toBe(1); }); test('posterior urgent review follows final decisions and preserves each concluded cycle without changing financial sources', function (string $outcome) { config(['urgent-reviews.qa_enabled' => true]); $owner = $this->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]); $reviewer = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Procurement]); $profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $owner->tenant_id, 'name' => 'Direcção de Compras sintética', 'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]); DB::table('organization_memberships')->insert(['tenant_id' => $owner->tenant_id, 'profile_id' => $profile, 'user_id' => $reviewer->id, 'maintenance' => false]); $service = app(UrgentRequisitionReviews::class); $this->actingAs($admin); $policyInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$profile], 'reason' => 'Designação expressa para a revisão posterior sintética']; $policy = $service->savePolicy($admin, $policyInput); expect($service->savePolicy($admin, $policyInput)->id)->toBe($policy->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' => [], 'urgent_expire_minutes' => 5, 'urgent_reminder_minutes' => null, 'urgent_escalation_minutes' => null]], 'reason' => 'Prazo sintético explícito para conferir expiração e revisão']); $this->actingAs($owner); $workflow = app(RequisitionWorkflow::class); $input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'urgent', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Urgência sintética que exige revisão posterior do ciclo concluído', 'items' => [['description' => 'Material urgente original', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]; $request = $workflow->save($owner, $input); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); $this->actingAs($reviewer); expect($service->queue($reviewer)['records']['total'])->toBe(0) ->and(fn () => $service->workspace($reviewer, $request->id, 1))->toThrow(HttpException::class); if ($outcome === 'expired') { $this->travel(6)->minutes(); $this->actingAs($owner); $proof = app(RequisitionExpiry::class)->deadline($request); $workflow->expire($owner, $request, $proof['basis_hash'], (string) Str::uuid(), $request->process_version); $request->refresh(); $input['operation_key'] = (string) Str::uuid(); $input['process_version'] = $request->process_version; $input['priority'] = 'normal'; $input['items'][0]['description'] = 'Nova preparação deliberadamente diferente'; $input['items'][0]['unit_price'] = '120.00'; $request = $workflow->save($owner, $input, $request); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); expect($request->status)->toBe('pending')->and($request->approval_cycle)->toBe(2) ->and((int) DB::table('budget_entries')->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000); } else { $this->actingAs($head); $workflow->decide($head, $request, $outcome, 'Decisão final sintética independente', (string) Str::uuid(), $request->process_version); } $this->actingAs($reviewer); $space = $service->workspace($reviewer, $request->id, 1); expect($space['source']['outcome'])->toBe($outcome)->and($space['source']['request']['total_minor'])->toBe('10000') ->and($space['source']['items'][0]['description'])->toBe('Material urgente original')->and($space['canReview'])->toBeTrue() ->and($service->queue($reviewer)['coverage']['pending'])->toBe(1); $this->withoutVite(); $path = '/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia'; if ($outcome === 'approved' && DB::getDriverName() === 'pgsql') { if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) { throw new LogicException('Urgent review native task snapshot requires the guarded QA transaction.'); } DB::commit(); $this->committedUrgentReviewFixture = true; $this->get('/requisicoes/tarefas?module=purchases')->assertOk()->assertInertia(fn (Assert $page) => $page ->where('urgentReviewsReady', true)->where('tasks.data', fn ($rows) => collect($rows)->contains('task', 'urgent_requisition_review'))); } $this->get($path)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page ->component('requisitions/urgent-review')->where('source.outcome', $outcome)->where('canReview', true)); $tasks = app(WorkflowTaskInbox::class)->build($reviewer, 'procurement'); expect(array_column($tasks, 'task'))->toContain('urgent_requisition_review'); $before = []; foreach (['requisitions', 'requisition_items', 'approval_steps', 'budget_entries', 'stock_movements', 'invoices'] as $table) { $before[$table] = DB::table($table)->orderBy('id')->get()->toJson(); } $body = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'source_hash' => $space['source']['fingerprint'], 'notes' => 'Conferência posterior sintética, sem alterar a decisão ou os movimentos']; $this->postJson($path, $body)->assertRedirect(); $this->postJson($path, $body)->assertRedirect(); expect($service->queue($reviewer)['coverage']['reviewed'])->toBe(1) ->and(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(1) ->and(array_column(app(WorkflowTaskInbox::class)->build($reviewer, 'procurement'), 'task'))->not->toContain('urgent_requisition_review'); $firstReview = SupplyRecord::query()->where('kind', 'urgent_review')->sole(); $this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'source_hash' => str_repeat('0', 64)])->assertConflict(); $correction = [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'notes' => 'Correcção expressa da revisão, com a primeira versão preservada']; $this->postJson($path, $correction)->assertRedirect(); $this->postJson($path, $correction)->assertRedirect(); $this->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 1])->assertConflict(); expect(SupplyRecord::query()->where('kind', 'urgent_review')->count())->toBe(2) ->and($firstReview->fresh()->data['notes'])->toBe($body['notes']) ->and(DB::table('audit_logs')->where('action', 'urgent.review_recorded')->count())->toBe(2); if ($outcome === 'expired') { $latestAudit = DB::table('audit_logs')->where('action', 'urgent.review_recorded')->latest('id')->value('id'); DB::table('audit_logs')->where('id', $latestAudit)->delete(); expect($service->workspace($reviewer, $request->id, 1)['currentVerified'])->toBeFalse() ->and($service->queue($reviewer, null, 'all')['coverage']['indeterminate'])->toBe(1) ->and($service->queue($reviewer, null, 'all')['coverage']['reviewed'])->toBe(0); $expiration = SupplyRecord::query()->where('kind', 'req_expiration')->sole(); expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $expiration->id) ->update(['snapshot' => json_encode([...$expiration->snapshot, 'items' => []], JSON_THROW_ON_ERROR)])))->toThrow(QueryException::class) ->and($firstReview->fresh()->snapshot['items'][0]['description'])->toBe('Material urgente original'); } foreach ($before as $table => $rows) { expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows); } $this->actingAs($owner)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden(); $this->actingAs($admin)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden(); DB::table('organization_memberships')->where('user_id', $reviewer->id)->update(['expires_at' => now()->subSecond()]); $this->actingAs($reviewer)->postJson($path, [...$body, 'operation_key' => (string) Str::uuid(), 'version' => 2])->assertForbidden(); $this->travelBack(); })->with(['approved', 'rejected', 'expired']); test('urgent review keeps indeterminate coverage and rejects a foreign profile without changing an accepted outcome', function () { config(['urgent-reviews.qa_enabled' => true]); $request = $this->f['r']; $request->update(['priority' => 'urgent']); $owner = $this->f['issuer']; $service = app(UrgentRequisitionReviews::class); $this->actingAs($owner); $queue = $service->queue($owner, null, 'all'); expect($queue['coverage'])->toBe(['pending' => 0, 'reviewed' => 0, 'indeterminate' => 1]) ->and($queue['records']['data'][0]['href'])->toBe('/requisicoes/'.$request->id) ->and(fn () => $service->workspace($owner, $request->id, 1))->toThrow(HttpException::class) ->and($request->fresh()->status)->toBe('approved'); $admin = User::factory()->create(['tenant_id' => $owner->tenant_id, 'department_id' => $owner->department_id, 'purchasing_role' => PurchasingRole::Admin]); $foreign = receiptFixture(); $foreignProfile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $foreign['tenant']->id, 'name' => 'Perfil de outra empresa sintética', 'permissions' => json_encode(['procurement']), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1]); $this->actingAs($admin); $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'profile_ids' => [$foreignProfile], 'reason' => 'Tentativa sintética de designação fora da empresa']; expect(fn () => $service->savePolicy($admin, $input))->toThrow(HttpException::class); $this->withoutVite(); $this->get('/administracao/revisao-urgencias')->assertOk()->assertInertia(fn (Assert $page) => $page->component('organization/urgent-review-policy')->has('profiles', 0)); $this->actingAs($foreign['issuer'])->getJson('/requisicoes/'.$request->id.'/ciclos/1/revisao-urgencia')->assertNotFound(); expect(SupplyRecord::query()->where('kind', 'urgent_review_policy')->count())->toBe(0); }); 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 (string $secondOutcome) { $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]); $buyer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]); $this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]); $expiry = app(RequisitionExpiry::class); $this->actingAs($admin); $expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true, 'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement']), 'reason' => 'Prazos corridos expressamente sintéticos deste teste de expiração']); $owner = $this->f['issuer']; $this->actingAs($owner); $workflow = app(RequisitionWorkflow::class); $input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Requisição sintética para duas submissões independentes', 'items' => [['description' => 'Bem de ensaio', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]; $request = $workflow->save($owner, $input); $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(); $this->travel(31)->minutes(); $deadline = $expiry->deadline($request); expect($deadline['state'])->toBe('expired'); $this->actingAs($buyer); expect(fn () => $workflow->decide($buyer, $request, 'approved', 'Aprovação fora do prazo', (string) Str::uuid(), $request->process_version))->toThrow(HttpException::class); $this->actingAs($owner); $operation = (string) Str::uuid(); $version = $request->process_version; $this->withoutVite(); $body = ['basis_hash' => $deadline['basis_hash'], 'operation_key' => $operation, 'process_version' => $version]; $this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect(); $this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect(); $request->refresh(); expect($request->status)->toBe('draft')->and($request->approval_cycle)->toBe(2)->and($request->steps()->count())->toBe(0) ->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved) ->and($request->allSteps()->where('decision', 'expired')->count())->toBe(1) ->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(1); $this->actingAs($head)->get('/requisicoes?view=decided')->assertInertia(fn (Assert $page) => $page ->where('requisitions.total', 1)->where('requisitions.data.0.id', $request->id) ->has('requisitions.data.0.steps', 0)); $this->actingAs($owner); $this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private') ->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true) ->assertInertia(fn (Assert $page) => $page->component('requisitions/expiry')->where('requisition.approval_cycle', 2)->where('canEdit', true)->has('history.data', 1)); $input['operation_key'] = (string) Str::uuid(); $input['process_version'] = $request->process_version; $input['items'][0]['unit_price'] = '120.00'; $request = $workflow->save($owner, $input, $request); $workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version); $request->refresh(); expect($request->status)->toBe('pending')->and($request->steps()->count())->toBe(2) ->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4) ->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000) ->and(SupplyRecord::query()->where('kind', 'req_expiration')->sole()->snapshot['request']['total_minor'])->toBe(10000); $this->f['tenant']->update(['first_limit_minor' => 9000]); $beforeHistoryRead = []; foreach (['requisitions', 'approval_steps', 'supply_records', 'audit_logs', 'budget_entries', 'budget_requisition_cycles', 'stock_movements'] as $table) { $beforeHistoryRead[$table] = DB::table($table)->orderBy('id')->get()->toJson(); } $this->get('/requisicoes/'.$request->id.'/prazos')->assertOk()->assertInertia(fn (Assert $page) => $page ->where('history.data.0.request.total_minor', 10000)->where('history.data.0.request.priority', 'normal') ->where('history.data.0.items.0.description', 'Bem de ensaio')->where('history.data.0.items.0.total_minor', 10000) ->where('history.data.0.rules.first_limit_minor', 5000)->where('history.data.0.rules.approval_includes_tax', true) ->where('history.data.0.approval_amount_minor', 10000)->where('history.data.0.approval_uses_separate_basis', false) ->where('history.data.0.steps.0.approver_id', $head->id)->where('history.data.0.steps.0.comment', 'Conferência sintética do primeiro nível') ->missing('history.data.0.rules.timing')->missing('history.data.0.items.0.category_context')); foreach ($beforeHistoryRead as $table => $rows) { expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows); } $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); if ($secondOutcome === 'approved') { $this->travel(2)->minutes(); $this->actingAs($head); $workflow->decide($head, $request, 'approved', 'Conferência sintética do novo ciclo', (string) Str::uuid(), $request->process_version); $request->refresh(); $this->travel(3)->minutes(); $this->actingAs($buyer); $workflow->decide($buyer, $request, 'approved', 'Conferência final sintética do novo ciclo', (string) Str::uuid(), $request->process_version); $insights = app(ProcurementOperationalInsights::class)->build(Requisition::query()->whereKey($request->id), CarbonImmutable::now()); expect($request->fresh()->status)->toBe('approved')->and($insights['approval_times'])->toMatchArray([ 'measured' => 1, 'unknown' => 0, 'total_seconds' => 300, 'min_seconds' => 300, 'max_seconds' => 300]); $this->travelBack(); return; } if ($secondOutcome === 'rejected') { $this->actingAs($head); $workflow->decide($head, $request, 'rejected', 'Rejeição sintética da revisão no novo ciclo', (string) Str::uuid(), $request->process_version); expect($request->fresh()->status)->toBe('rejected') ->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0) ->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved) ->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1); $this->travelBack(); return; } $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(); })->with(['expired', 'rejected', 'approved']);