Files
compras/tests/Feature/DocumentaryQualificationTest.php
T
2026-11-02 20:27:11 +02:00

201 lines
14 KiB
PHP

<?php
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\BudgetEntry;
use App\Models\Department;
use App\Models\PurchaseAward;
use App\Models\QualificationAssessment;
use App\Models\QualificationSet;
use App\Models\Tenant;
use App\Models\User;
use App\Services\DocumentaryQualificationWorkflow;
use App\Services\ProposalComparison;
use App\Services\ProposalOpeningWorkflow;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/QualificationFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
$this->f = qualificationFixture();
$this->url = '/requisicoes/'.$this->f['r']->id.'/qualificacao';
$this->actingAs($this->f['issuer']);
});
function defineDocumentaryQualification(object $test, array $changes = []): QualificationSet
{
$test->actingAs($test->f['issuer'])->post($test->url, [...$test->f['definition'], ...$changes])->assertSessionHasNoErrors();
return QualificationSet::query()->latest('revision')->firstOrFail();
}
function recordDocumentaryAssessment(object $test, QualificationSet $set, array $changes = [], ?User $actor = null): QualificationAssessment
{
$test->actingAs($actor ?? $test->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$test->f['assessment'], ...$changes])->assertSessionHasNoErrors();
return QualificationAssessment::query()->latest('id')->firstOrFail();
}
test('documentary qualification freezes process criteria without financial decisions', function () {
$before = app(ProposalComparison::class)->inspect($this->f['r']);
$set = defineDocumentaryQualification($this);
$answers = $this->f['assessment']['answers'];
$answers[0]['result'] = 'not_met';
recordDocumentaryAssessment($this, $set, ['answers' => $answers]);
expect($set->criteria[0]['id'])->toBe(1)->and($set->snapshot['proposals'][0]['id'])->toBe($this->f['quote']->id)
->and(BudgetEntry::query()->count())->toBe(0)->and(PurchaseAward::query()->count())->toBe(0)
->and(app(ProposalComparison::class)->inspect($this->f['r']))->toBe($before);
$this->get($this->url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->component('purchases/qualification')->where('isCurrent', true)->has('records', 1));
$this->get('/requisicoes/'.$this->f['r']->id.'/processo')->assertInertia(fn (Assert $page) => $page->where('documents', fn ($documents) => collect($documents)->contains('kind', 'Qualificação documental')));
});
test('formal task documentary resumes only my incomplete analysis and reuses the existing answers', function () {
$set = defineDocumentaryQualification($this);
$first = recordDocumentaryAssessment($this, $set);
$path = '/requisicoes/tarefas?module=purchases&search=documental';
$this->get($path)->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)
->where('tasks.data.0.href', $this->url.'?version='.$set->id.'&quotation_id='.$this->f['quote']->id.'#qualification-assess'));
$this->get($this->url.'?version='.$set->id.'&quotation_id='.$this->f['quote']->id)->assertInertia(fn (Assert $page) => $page
->where('focusQuotationId', $this->f['quote']->id)->where('canAssess', true)->where('records.0.id', $first->id)
->where('records.0.answers.0.evidence', $this->f['assessment']['answers'][0]['evidence']));
$this->actingAs($this->f['other_analyst'])->get($path)->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
$answers = $first->answers;
$answers[1] = ['criterion_id' => 2, 'result' => 'not_met', 'evidence' => 'Documento sintético', 'reason' => 'Resultado negativo fundamentado no ensaio.'];
recordDocumentaryAssessment($this, $set, ['previous_id' => $first->id, 'answers' => $answers]);
$this->get($path)->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
expect($first->fresh()->answers[1]['result'])->toBe('pending')->and(QualificationAssessment::query()->count())->toBe(2)->and(BudgetEntry::query()->count())->toBe(0);
});
test('formal task documentary does not continue an old basis or create new analyst assignments', function () {
$set = defineDocumentaryQualification($this);
$first = recordDocumentaryAssessment($this, $set);
$before = [QualificationAssessment::query()->count(), AuditLog::query()->count()];
$this->get('/requisicoes/tarefas?module=purchases&search=documental')->assertOk();
expect([QualificationAssessment::query()->count(), AuditLog::query()->count()])->toBe($before);
$this->f['quote']->update(['reference' => 'REFERÊNCIA-ALTERADA']);
$this->get('/requisicoes/tarefas?module=purchases&search=documental')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
$this->get($this->url.'?quotation_id='.$this->f['quote']->id)->assertInertia(fn (Assert $page) => $page->where('isCurrent', false)->where('canAssess', false));
$this->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'previous_id' => $first->id])->assertSessionHasErrors('qualification');
$this->getJson($this->url.'?quotation_id=999999')->assertUnprocessable();
});
test('formal task documentary does not let an administrative reading grant authorise another department analysis', function () {
$set = defineDocumentaryQualification($this);
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro departamento sintético']);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $department->id]);
supplyGrant($head, ['admin', 'department_head']);
$this->actingAs($head)->get($this->url)->assertInertia(fn (Assert $page) => $page->where('canAssess', false));
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertForbidden();
expect(QualificationAssessment::query()->count())->toBe(0);
});
test('documentary criteria versions and analyst corrections never overwrite earlier records', function () {
$set = defineDocumentaryQualification($this);
$first = recordDocumentaryAssessment($this, $set);
$second = recordDocumentaryAssessment($this, $set, ['previous_id' => $first->id, 'reason' => 'Correcção fictícia identificada']);
expect($second->revision)->toBe(2)->and($first->refresh()->reason)->toBe('Análise exclusivamente fictícia');
$new = defineDocumentaryQualification($this, ['previous_id' => $set->id, 'reason' => 'Nova versão sem apagar requisitos']);
expect($new->revision)->toBe(2)->and(QualificationAssessment::query()->where('qualification_set_id', $new->id)->count())->toBe(0);
$this->actingAs($this->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'previous_id' => $second->id])->assertSessionHasErrors('qualification');
$this->get($this->url.'?version='.$set->id)->assertInertia(fn (Assert $page) => $page->where('isCurrent', false)->where('canAssess', false)->where('records.0.id', $second->id)->has('history.data', 2));
});
test('different documentary analysts retain independent records and cannot replace another analyst', function () {
$set = defineDocumentaryQualification($this);
$first = recordDocumentaryAssessment($this, $set);
$this->actingAs($this->f['other_analyst'])->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'previous_id' => $first->id])->assertSessionHasErrors('previous_id');
$other = recordDocumentaryAssessment($this, $set, [], $this->f['other_analyst']);
expect($other->revision)->toBe(1)->and($other->analyst_id)->not->toBe($first->analyst_id);
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->has('records', 2)->has('history.data', 2));
});
test('documentary results require exact criteria and appropriate evidence and reasons', function () {
$set = defineDocumentaryQualification($this);
$data = $this->f['assessment'];
$data['answers'][0]['evidence'] = '';
$this->actingAs($this->f['analyst'])->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
$data['answers'][0]['result'] = 'not_applicable';
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasNoErrors();
$data['previous_id'] = QualificationAssessment::query()->sole()->id;
$data['answers'][0]['reason'] = '';
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
$data['answers'][0]['criterion_id'] = 99;
$this->post('/qualificacoes/'.$set->id.'/analises', $data)->assertSessionHasErrors('answers');
$this->post('/qualificacoes/'.$set->id.'/analises', [...$this->f['assessment'], 'analyst_id' => $this->f['other_analyst']->id])->assertSessionHasErrors('analyst_id');
});
test('documentary requirements reject duplicates forged snapshots and stale versions', function () {
$data = $this->f['definition'];
$data['criteria'][1]['label'] = mb_strtoupper($data['criteria'][0]['label']);
$this->post($this->url, $data)->assertSessionHasErrors('criteria');
$this->post($this->url, [...$this->f['definition'], 'snapshot' => ['approved' => true]])->assertSessionHasErrors('snapshot');
defineDocumentaryQualification($this);
$this->post($this->url, $this->f['definition'])->assertSessionHasErrors('previous_id');
expect(QualificationSet::query()->count())->toBe(1);
});
test('changed documentary proposal bases block new analysis and require fresh requirements', function () {
$set = defineDocumentaryQualification($this);
recordDocumentaryAssessment($this, $set);
$this->f['quote']->update(['reference' => 'Referência posterior fictícia']);
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertSessionHasErrors('qualification');
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('isCurrent', false)->where('canAssess', false));
$this->actingAs($this->f['issuer'])->post($this->url, [...$this->f['definition'], 'previous_id' => $set->id])->assertSessionHasErrors('basis_hash');
$opening = app(ProposalOpeningWorkflow::class);
$fresh = defineDocumentaryQualification($this, ['previous_id' => $set->id, 'basis_hash' => $opening->basis($opening->proposals($this->f['r']))]);
expect($fresh->snapshot['proposals'][0]['reference'])->toBe('Referência posterior fictícia')->and($set->refresh()->snapshot['proposals'][0]['reference'])->toBe('PROP-TEST');
});
test('documentary requester and revoked analysts cannot write while admin only reads', function () {
$set = defineDocumentaryQualification($this);
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertForbidden();
$this->actingAs($this->f['analyst']);
DB::table('users')->where('id', $this->f['analyst']->id)->update(['purchasing_role' => 'requester']);
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertForbidden();
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($admin)->get($this->url)->assertInertia(fn (Assert $page) => $page->where('canDefine', false)->where('canAssess', false));
$this->post($this->url, [...$this->f['definition'], 'previous_id' => $set->id])->assertForbidden();
});
test('documentary qualification enforces company department and guest access', function () {
$set = defineDocumentaryQualification($this);
$this->actingAs($this->f['receiver'])->get($this->url)->assertForbidden();
$department = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro departamento']);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head)->get($this->url)->assertNotFound();
$other = Tenant::query()->create(['name' => 'Outra empresa fictícia']);
$this->actingAs(User::factory()->create(['tenant_id' => $other->id, 'purchasing_role' => PurchasingRole::Finance]))->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertNotFound();
auth()->logout();
$this->get($this->url)->assertRedirect('/login');
});
test('documentary qualification stops new records after award without removing history', function () {
$set = defineDocumentaryQualification($this);
recordDocumentaryAssessment($this, $set);
PurchaseAward::query()->create($this->f['award_attributes']);
$this->post('/qualificacoes/'.$set->id.'/analises', $this->f['assessment'])->assertSessionHasErrors('qualification');
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->where('canDefine', false)->where('canAssess', false)->has('records', 1));
});
test('documentary qualification versions are immutable and audit failure rolls back an assessment', function () {
$set = defineDocumentaryQualification($this);
$this->actingAs($this->f['analyst']);
AuditLog::creating(function (AuditLog $event) {
if ($event->action === 'qualification.assessed') {
throw new RuntimeException('Falha fictícia de auditoria');
}
});
try {
expect(fn () => app(DocumentaryQualificationWorkflow::class)->assess($this->f['analyst'], $set, $this->f['assessment']))->toThrow(RuntimeException::class);
} finally {
AuditLog::flushEventListeners();
}
expect(QualificationAssessment::query()->count())->toBe(0);
$assessment = recordDocumentaryAssessment($this, $set);
expect(fn () => $assessment->update(['reason' => 'Alterar passado']))->toThrow(LogicException::class);
expect(fn () => $set->delete())->toThrow(LogicException::class);
});