f['tenant']->forceFill(['requisition_approval_policy' => ['enabled' => false, 'levels' => []]])->save(); expect(fn () => $migration->down())->toThrow(LogicException::class); expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBe(['enabled' => false, 'levels' => []]); $this->f['tenant']->forceFill(['requisition_approval_policy' => null])->save(); $step = $this->f['r']->steps()->create(['tenant_id' => $this->f['tenant']->id, 'position' => 1, 'role' => 'configured_1', 'decision' => 'pending', 'routing' => ['name' => 'QA preserved route']]); expect(fn () => $migration->down())->toThrow(LogicException::class); expect($step->fresh()->routing)->toBe(['name' => 'QA preserved route']); }); test('installed capability is explicitly enabled independently from the isolated QA flag', function () { config(['requisition_approval.qa_enabled' => false, 'requisition_approval.enabled' => false]); expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse(); config(['requisition_approval.enabled' => true]); expect(app(RequisitionApprovalLevels::class)->ready())->toBeTrue(); $this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect(); expect($this->f['tenant']->fresh()->requisition_approval_policy['quorum'])->toBe('one_eligible'); config(['requisition_approval.enabled' => false]); expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse(); }); test('approval schema upgrade adds empty fields without rewriting existing company or approval data', function () { $migration = require database_path('migrations/2026_11_22_000003_add_configured_requisition_levels.php'); $columns = fn ($table) => array_values(array_diff(DB::connection()->getSchemaBuilder()->getColumnListing($table), ['requisition_approval_policy', 'routing'])); $tenantColumns = $columns('tenants'); $stepColumns = $columns('approval_steps'); $beforeTenants = DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson(); $beforeSteps = DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson(); $migration->down(); expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse(); $migration->up(); expect(DB::table('tenants')->orderBy('id')->get($tenantColumns)->toJson())->toBe($beforeTenants) ->and(DB::table('approval_steps')->orderBy('id')->get($stepColumns)->toJson())->toBe($beforeSteps) ->and(DB::table('tenants')->whereNotNull('requisition_approval_policy')->exists())->toBeFalse() ->and(DB::table('approval_steps')->whereNotNull('routing')->exists())->toBeFalse() ->and(app(RequisitionApprovalLevels::class)->ready())->toBeTrue(); }); function approvalLevelProfile(int $tenant, string $name, array $permissions): int { return DB::table('organization_profiles')->insertGetId(['tenant_id' => $tenant, 'name' => $name, 'permissions' => json_encode($permissions), 'work_contexts' => json_encode(['procurement.internal']), 'version' => 1, 'created_at' => now(), 'updated_at' => now()]); } function approvalLevelMember(User $actor, int $profile): void { DB::table('organization_memberships')->insert(['tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'profile_id' => $profile, 'maintenance' => false, 'created_at' => now(), 'updated_at' => now()]); } beforeEach(function () { $this->withoutVite(); config(['requisition_approval.qa_enabled' => true]); $this->f = receiptFixture(); $tenant = $this->f['tenant']->id; $this->admin = $this->f['issuer']; $this->f['tenant']->update(['first_limit_minor' => 0, 'second_limit_minor' => 0, 'approval_includes_tax' => true, 'rules_provisional' => false]); $this->head = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]); $this->buyer = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]); $this->financier = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]); $secondAdmin = User::factory()->create(['tenant_id' => $tenant, 'purchasing_role' => PurchasingRole::Configured]); $adminProfile = approvalLevelProfile($tenant, 'Administração QA', ['admin', 'requester']); approvalLevelMember($this->admin, $adminProfile); approvalLevelMember($secondAdmin, $adminProfile); approvalLevelMember($this->head, approvalLevelProfile($tenant, 'Chefia QA', ['department_head'])); approvalLevelMember($this->buyer, approvalLevelProfile($tenant, 'Compras QA', ['procurement'])); approvalLevelMember($this->financier, approvalLevelProfile($tenant, 'Finanças QA', ['finance'])); $this->pool = approvalLevelProfile($tenant, 'Aprovadores adicionais QA', ['requisition_approve']); $this->approvers = []; foreach (range(1, 6) as $index) { $actor = User::factory()->create(['tenant_id' => $tenant, 'department_id' => $this->admin->department_id, 'purchasing_role' => PurchasingRole::Configured]); approvalLevelMember($actor, $this->pool); $this->approvers[] = $actor; } DB::table('organization_access')->insert(['tenant_id' => $tenant, 'active' => true, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]); Budget::query()->create(['tenant_id' => $tenant, 'cost_center_id' => $this->f['r']->cost_center_id, 'year' => now()->year, 'amount_minor' => 1000000, 'includes_tax' => true, 'reason' => 'Dotação exclusivamente sintética.', 'created_by' => $this->admin->id, 'approved_by' => $this->financier->id]); $this->plan = ['version' => 1, 'enabled' => true, 'reason' => 'Plano de níveis adicionais para ensaio isolado.', 'levels' => array_map(fn ($number) => ['name' => 'Nível adicional '.$number, 'profile_ids' => [(string) $this->pool], 'scope' => 'company', 'min_amount' => null, 'categories' => [], 'cost_center_ids' => []], range(1, 5))]; $this->body = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade sintética com oito níveis.', 'items' => [['description' => 'Material QA', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00']]]; $this->actingAs($this->admin); }); function submitConfiguredRequest($test): Requisition { $test->actingAs($test->admin)->postJson('/administracao/parametrizacao/approval_levels', $test->plan)->assertRedirect(); $test->postJson('/requisicoes', $test->body)->assertRedirect(); $record = Requisition::query()->latest('id')->firstOrFail(); $test->postJson('/requisicoes/'.$record->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect(); return $record->fresh(); } function configuredDecision($test, User $actor, Requisition $record, string $decision = 'approved'): void { $test->actingAs($actor)->postJson('/requisicoes/'.$record->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $record->fresh()->process_version, 'decision' => $decision, 'comment' => 'Fundamento sintético da decisão.'])->assertRedirect(); } test('native three controls and five configured levels progress sequentially with one eligible person per level', function () { $r = submitConfiguredRequest($this); expect($r->steps()->count())->toBe(8)->and($r->approval_snapshot['routing_quorum'])->toBe('one_eligible'); foreach ([$this->head, $this->buyer, $this->financier] as $actor) { configuredDecision($this, $actor, $r); } $first = $this->approvers[0]; $this->actingAs($first)->get('/requisicoes/'.$r->id)->assertOk()->assertInertia(fn (Assert $page) => $page->where('canDecide', true)->where('approvalRouting.label', 'Nível adicional 1')); expect(collect(app(WorkflowNotices::class)->visible($first))->contains('role_label', 'Nível adicional 1'))->toBeTrue(); $this->get('/facturas')->assertForbidden(); expect(collect(app(WorkflowTaskInbox::class)->build($first, 'procurement'))->contains('reference', $r->number))->toBeTrue(); expect($r->fresh()->canDecide($this->approvers[1]))->toBeTrue(); foreach (array_slice($this->approvers, 0, 5) as $actor) { configuredDecision($this, $actor, $r); } expect($r->fresh()->status)->toBe('approved')->and($r->steps()->where('decision', 'approved')->count())->toBe(8) ->and($r->steps()->where('position', 4)->sole()->approver_id)->toBe($first->id); expect($r->fresh()->canDecide($this->approvers[5]))->toBeFalse(); }); test('conditions use exact amount category and cost centre and current rules do not rewrite a submitted route', function () { $this->plan['levels'][0]['min_amount'] = '116.01'; $this->plan['levels'][1]['categories'] = ['Outra categoria']; $this->plan['levels'][2]['categories'] = ['MATERIAL']; $this->plan['levels'][2]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id]; $this->plan['levels'][4]['min_amount'] = '116.00'; $r = submitConfiguredRequest($this); expect($r->steps()->count())->toBe(6)->and($r->steps()->where('role', 'configured_3')->sole()->routing['profile_ids'])->toBe([$this->pool]); $snapshot = $r->approval_snapshot; $this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect(); expect($r->fresh()->approval_snapshot)->toBe($snapshot); foreach ([$this->head, $this->buyer, $this->financier, ...array_slice($this->approvers, 0, 3)] as $actor) { configuredDecision($this, $actor, $r); } expect($r->fresh()->status)->toBe('approved'); }); test('explicit RQ01 category conditions combine with native filters and remain frozen through the full approval journey', function () { $this->plan['levels'] = [$this->plan['levels'][0]]; $this->plan['levels'][0] += ['procurement_categories' => ['office_equipment']]; $this->plan['levels'][0]['categories'] = ['Material']; $this->plan['levels'][0]['min_amount'] = '116.00'; $this->plan['levels'][0]['cost_center_ids'] = [(string) $this->f['r']->cost_center_id]; $this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.']; $matched = submitConfiguredRequest($this); expect($matched->steps()->count())->toBe(4) ->and($matched->approval_snapshot['additional_levels']['configured_1']['procurement_categories'])->toBe(['office_equipment']); $next = $this->body; $next['operation_key'] = (string) Str::uuid(); $next['items'][0]['procurement_category'] = 'other'; $this->postJson('/requisicoes', $next)->assertRedirect(); $different = Requisition::query()->latest('id')->firstOrFail(); $this->postJson('/requisicoes/'.$different->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertRedirect(); expect($different->steps()->count())->toBe(3); $snapshot = $matched->approval_snapshot; $this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2, 'enabled' => false])->assertRedirect(); expect($matched->fresh()->approval_snapshot)->toBe($snapshot); foreach ([$this->head, $this->buyer, $this->financier, $this->approvers[0]] as $actor) { configuredDecision($this, $actor, $matched); } expect($matched->fresh()->status)->toBe('approved'); }); test('RQ01 filtered plans refuse an absent classification schema instead of dropping a required approval', function () { $this->plan['levels'] = [$this->plan['levels'][0] + ['procurement_categories' => ['office_equipment']]]; $this->postJson('/administracao/parametrizacao/approval_levels', $this->plan)->assertRedirect(); $this->body['items'][0] += ['procurement_category' => 'office_equipment', 'category_reason' => 'Artigo sintético de escritório fora do catálogo.']; $this->postJson('/requisicoes', $this->body)->assertRedirect(); $request = Requisition::query()->latest('id')->firstOrFail(); $policy = $this->f['tenant']->fresh()->requisition_approval_policy; DB::getSchemaBuilder()->table('requisition_items', fn ($table) => $table->dropColumn('category_context')); $this->postJson('/requisicoes/'.$request->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertServiceUnavailable(); $this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'version' => 2])->assertUnprocessable(); expect($request->fresh()->status)->toBe('draft')->and($request->steps()->count())->toBe(0) ->and(DB::table('budget_entries')->where('requisition_id', $request->id)->count())->toBe(0) ->and($this->f['tenant']->fresh()->requisition_approval_policy)->toBe($policy); }); test('revoked membership and expired maintenance do not approve or expose assigned requests and repeated identity cannot decide two stages', function () { $r = submitConfiguredRequest($this); foreach ([$this->head, $this->buyer, $this->financier] as $actor) { configuredDecision($this, $actor, $r); } configuredDecision($this, $this->approvers[0], $r); $this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden(); DB::table('organization_memberships')->where('user_id', $this->approvers[1]->id)->update(['expires_at' => now()->subMinute()]); $this->actingAs($this->approvers[1])->get('/requisicoes/'.$r->id)->assertForbidden(); $this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden(); expect($r->fresh()->status)->toBe('pending'); approvalLevelMember($this->approvers[2], approvalLevelProfile($r->tenant_id, 'Solicitação sem poderes de aprovação', ['requester'])); DB::table('organization_memberships')->where('user_id', $this->approvers[2]->id)->where('profile_id', $this->pool)->update(['maintenance' => true]); $this->actingAs($this->approvers[2])->get('/requisicoes/'.$r->id)->assertNotFound(); }); test('QA capability is opt in and a configured plan never silently falls back when capability is unavailable', function () { $r = submitConfiguredRequest($this); config(['requisition_approval.qa_enabled' => false]); expect(app(RequisitionApprovalLevels::class)->ready())->toBeFalse(); $this->body['operation_key'] = (string) Str::uuid(); $this->postJson('/requisicoes', $this->body)->assertRedirect(); $new = Requisition::query()->latest('id')->firstOrFail(); $before = DB::table('budget_entries')->count(); $this->postJson('/requisicoes/'.$new->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertStatus(503); expect(DB::table('budget_entries')->count())->toBe($before)->and($new->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(8); }); test('parallel candidates are bound to the version they reviewed and cannot advance another level with an old decision', function () { $r = submitConfiguredRequest($this); $this->actingAs($this->head)->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable(); foreach ([$this->head, $this->buyer, $this->financier] as $actor) { configuredDecision($this, $actor, $r); } $version = $r->fresh()->process_version; $this->actingAs($this->approvers[0])->postJson('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertUnprocessable(); configuredDecision($this, $this->approvers[0], $r); $this->actingAs($this->approvers[1])->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $version, 'decision' => 'approved'])->assertStatus(409); expect($r->steps()->where('role', 'like', 'configured_%')->where('decision', 'approved')->count())->toBe(1); }); test('invalid foreign pools and too many levels do not change the plan or its organisation version', function () { $this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => array_fill(0, 6, $this->plan['levels'][0])])->assertUnprocessable(); $this->postJson('/administracao/parametrizacao/approval_levels', [...$this->plan, 'levels' => ['invalid_key' => $this->plan['levels'][0]]])->assertUnprocessable(); $bad = $this->plan; $bad['levels'][0]['min_amount'] = '-1'; $this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable(); $bad = $this->plan; $bad['levels'][0]['profile_ids'] = [approvalLevelProfile($this->admin->tenant_id, 'Consulta sem aprovação', ['requester'])]; $this->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable(); $other = receiptFixture(); $bad['levels'][0]['profile_ids'] = [approvalLevelProfile($other['tenant']->id, 'Perfil de outra empresa', ['requisition_approve'])]; $this->actingAs($this->admin)->postJson('/administracao/parametrizacao/approval_levels', $bad)->assertUnprocessable(); expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull() ->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1); }); test('department levels revalidate the department and the request owner never approves an assigned level', function () { foreach ($this->plan['levels'] as &$level) { $level['scope'] = 'department'; } unset($level); $r = submitConfiguredRequest($this); foreach ([$this->head, $this->buyer, $this->financier] as $actor) { configuredDecision($this, $actor, $r); } approvalLevelMember($this->admin, $this->pool); $this->actingAs($this->admin)->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden(); $other = Department::query()->create(['tenant_id' => $r->tenant_id, 'name' => 'Outro departamento QA']); DB::table('users')->where('id', $this->approvers[0]->id)->update(['department_id' => $other->id]); $this->actingAs($this->approvers[0])->get('/requisicoes/'.$r->id)->assertNotFound(); $this->postJson('/requisicoes/'.$r->id.'/decidir', ['operation_key' => (string) Str::uuid(), 'process_version' => $r->fresh()->process_version, 'decision' => 'approved'])->assertForbidden(); expect($r->fresh()->status)->toBe('pending'); }); test('a plan update and its version roll back when audit cannot be recorded', function () { $this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->once()->andThrow(new RuntimeException('Injected audit failure')); $this->withoutExceptionHandling(); expect(fn () => $this->postJson('/administracao/parametrizacao/approval_levels', $this->plan))->toThrow(RuntimeException::class); expect($this->f['tenant']->fresh()->requisition_approval_policy)->toBeNull() ->and(DB::table('organization_access')->where('tenant_id', $this->admin->tenant_id)->value('version'))->toBe(1); }); test('an invalid stored plan cannot leave a reservation or partial approval queue behind', function () { $plan = app(RequisitionApprovalLevels::class)->prepare($this->admin, $this->plan); $plan['levels'][] = $plan['levels'][0]; $this->f['tenant']->update(['requisition_approval_policy' => $plan]); $this->postJson('/requisicoes', $this->body)->assertRedirect(); $r = Requisition::query()->latest('id')->firstOrFail(); $before = DB::table('budget_entries')->count(); $this->postJson('/requisicoes/'.$r->id.'/submeter', ['operation_key' => (string) Str::uuid(), 'process_version' => 1])->assertUnprocessable(); expect($r->fresh()->status)->toBe('draft')->and($r->steps()->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe($before); });