181 lines
15 KiB
PHP
181 lines
15 KiB
PHP
<?php
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\AuditLog;
|
|
use App\Models\CostCenter;
|
|
use App\Models\Department;
|
|
use App\Models\Quotation;
|
|
use App\Models\Requisition;
|
|
use App\Models\Supplier;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use App\Services\ComparisonPolicy;
|
|
use App\Services\ProposalComparison;
|
|
use App\Services\RequisitionWorkflow;
|
|
use Inertia\Testing\AssertableInertia as Assert;
|
|
|
|
function supplierPayload(string $nuit = '123456789'): array
|
|
{
|
|
return ['name' => 'Fornecedor de teste', 'nuit' => $nuit, 'contact' => 'Contacto', 'email' => 'test@example.com', 'phone' => '123456789', 'address' => 'Maputo', 'category' => 'Material', 'beneficiaries' => 'Beneficiário teste', 'document_references' => 'Alvará e declaração verificados no processo 123.', 'diligence_notes' => 'Documentação conferida e sem impedimentos.', 'blocked' => false, 'next_review' => now()->addYear()->format('Y-m-d')];
|
|
}
|
|
|
|
beforeEach(function () {
|
|
$this->tenant = Tenant::query()->create(['name' => 'Cotação A']);
|
|
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
|
|
$this->center = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'name' => 'Produção', 'code' => 'P']);
|
|
$this->buyer = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
|
$this->finance = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Finance]);
|
|
$this->owner = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Requester]);
|
|
$this->actingAs($this->buyer);
|
|
$this->supplier = Supplier::query()->create([...supplierPayload(), 'tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'status' => 'active']);
|
|
$this->r = Requisition::query()->create(['tenant_id' => $this->tenant->id, 'requester_id' => $this->owner->id, 'department_id' => $this->department->id, 'cost_center_id' => $this->center->id, 'number' => 'REQ-TEST', 'priority' => 'normal', 'needed_by' => now()->addWeek(), 'justification' => 'Pedido aprovado para testes.', 'status' => 'approved', 'subtotal_minor' => 15, 'tax_minor' => 2, 'total_minor' => 17]);
|
|
$this->item = $this->r->items()->create(['tenant_id' => $this->tenant->id, 'description' => 'Material', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '3', 'unit' => 'un', 'unit_price_minor' => 5, 'tax_rate' => '16', 'subtotal_minor' => 15, 'tax_minor' => 2, 'total_minor' => 17]);
|
|
$this->quote = ['supplier_id' => $this->supplier->id, 'reference' => 'PROP-01', 'delivery_days' => 10, 'valid_until' => now()->addMonth()->format('Y-m-d'), 'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $this->item->id, 'unit_price' => '0.05']]];
|
|
});
|
|
|
|
test('supplier creation enforces role tenant and unique nuit', function () {
|
|
$this->actingAs($this->owner)->post('/fornecedores', supplierPayload('987654321'))->assertForbidden();
|
|
$this->actingAs($this->buyer)->post('/fornecedores', [...supplierPayload('987654321'), 'status' => 'active', 'tenant_id' => 999])->assertSessionHasNoErrors()->assertRedirect();
|
|
$s = Supplier::query()->where('nuit', '987654321')->firstOrFail();
|
|
expect($s->status)->toBe('pending')->and($s->tenant_id)->toBe($this->tenant->id);
|
|
$this->post('/fornecedores', supplierPayload('987654321'))->assertSessionHasErrors('nuit');
|
|
$this->post('/fornecedores', supplierPayload('invalid'))->assertSessionHasErrors('nuit');
|
|
});
|
|
|
|
test('supplier review is independent and prevents blocked activation', function () {
|
|
$body = ['status' => 'active', 'comment' => 'Documentação verificada por Finanças.', 'version' => $this->supplier->version];
|
|
$this->post("/fornecedores/{$this->supplier->id}/validar", $body)->assertForbidden();
|
|
$this->buyer->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
|
$this->actingAs($this->buyer)->post("/fornecedores/{$this->supplier->id}/validar", $body)->assertForbidden();
|
|
$this->actingAs($this->finance)->post("/fornecedores/{$this->supplier->id}/validar", $body)->assertSessionHasNoErrors()->assertRedirect();
|
|
$this->supplier->update(['blocked' => true]);
|
|
$this->post("/fornecedores/{$this->supplier->id}/validar", [...$body, 'version' => $this->supplier->fresh()->version])->assertSessionHasErrors('status');
|
|
});
|
|
|
|
test('quotes calculate decimal totals inherit tax and reject duplicates', function () {
|
|
$this->get('/requisicoes/criar')->assertInertia(fn (Assert $page) => $page->where('defaultTaxRate', '16.00'));
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", [...$this->quote, 'total_minor' => 999, 'tenant_id' => 999])->assertSessionHasNoErrors()->assertRedirect();
|
|
$q = Quotation::query()->firstOrFail();
|
|
expect($q->subtotal_minor)->toBe(15)->and($q->tax_minor)->toBe(2)->and($q->total_minor)->toBe(17)->and($q->tenant_id)->toBe($this->tenant->id);
|
|
expect((float) $q->items()->first()->tax_rate)->toBe(16.0);
|
|
$result = app(ProposalComparison::class)->inspect($this->r);
|
|
$basis = array_map(fn ($row) => [
|
|
'quotation' => array_intersect_key($row, array_flip(['id', 'supplier_id', 'reference', 'delivery_days', 'valid_until', 'payment_terms', 'subtotal_minor', 'tax_minor', 'total_minor', 'currency', 'weights'])),
|
|
'items' => $row['items'], 'evaluations' => $row['evaluations'], 'qualified_ids' => array_column($row['qualified_evaluations'], 'id'),
|
|
'eligible' => $row['eligible'], 'score_minor' => $row['score_minor'],
|
|
], $result['rows']);
|
|
expect($result['fingerprint'])->toBe(hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR)));
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", $this->quote)->assertSessionHasErrors('supplier_id');
|
|
expect(Quotation::query()->count())->toBe(1);
|
|
expect(AuditLog::query()->where('action', 'quotation.created')->count())->toBe(1);
|
|
});
|
|
|
|
test('unit discounts are explicit calculated before vat and preserved for comparison', function (string $type, string $discount, int $net, int $tax) {
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", [...$this->quote, 'items' => [['requisition_item_id' => $this->item->id, 'unit_price' => '10.00', 'discount_type' => $type, 'discount_value' => $discount]]])->assertSessionHasNoErrors();
|
|
$quote = Quotation::query()->sole();
|
|
expect($quote->items()->sole()->unit_price_minor)->toBe($net)
|
|
->and($quote->subtotal_minor)->toBe(3 * $net)->and($quote->tax_minor)->toBe($tax)
|
|
->and($quote->commercial_terms['lines'][0]['gross_unit_minor'])->toBe(1000)
|
|
->and($quote->commercial_terms['lines'][0]['discount_type'])->toBe($type);
|
|
$result = app(ProposalComparison::class)->inspect($this->r);
|
|
expect($result['rows'][0]['eligible'])->toBeTrue();
|
|
$terms = $quote->commercial_terms;
|
|
$terms['lines'][0]['discount_value'] = '99.00';
|
|
$quote->update(['commercial_terms' => $terms]);
|
|
expect(app(ProposalComparison::class)->inspect($this->r)['rows'][0]['eligible'])->toBeFalse();
|
|
})->with([['percent', '12.50', 875, 420], ['amount', '1.25', 875, 420]]);
|
|
|
|
test('missing prices invalid discounts and free units cannot become comparison minima', function (array $line) {
|
|
$this->postJson("/requisicoes/{$this->r->id}/cotacoes", [...$this->quote, 'items' => [['requisition_item_id' => $this->item->id, ...$line]]])->assertUnprocessable();
|
|
expect(Quotation::query()->count())->toBe(0);
|
|
})->with([
|
|
[['unit_price' => '']],
|
|
[['unit_price' => '0']],
|
|
[['unit_price' => '10', 'discount_type' => 'percent', 'discount_value' => '100']],
|
|
[['unit_price' => '10', 'discount_type' => 'percent', 'discount_value' => '101']],
|
|
[['unit_price' => '10', 'discount_type' => 'amount', 'discount_value' => '11']],
|
|
[['unit_price' => '10', 'discount_type' => 'none', 'discount_value' => '1']],
|
|
[['unit_price' => '10', 'discount_type' => 'percent']],
|
|
[['unit_price' => '0.01', 'discount_type' => 'percent', 'discount_value' => '50.01']],
|
|
]);
|
|
|
|
test('quotes require approval active suppliers valid dates and exact request items', function () {
|
|
$url = "/requisicoes/{$this->r->id}/cotacoes";
|
|
$this->r->update(['status' => 'draft']);
|
|
$this->post($url, $this->quote)->assertForbidden();
|
|
$this->r->update(['status' => 'approved']);
|
|
$this->supplier->update(['status' => 'pending']);
|
|
$this->post($url, $this->quote)->assertSessionHasErrors('supplier_id');
|
|
$this->supplier->update(['status' => 'active']);
|
|
$this->post($url, [...$this->quote, 'valid_until' => now()->subDay()->format('Y-m-d')])->assertSessionHasErrors('valid_until');
|
|
$this->post($url, [...$this->quote, 'items' => [['requisition_item_id' => 999, 'unit_price' => '1']]])->assertSessionHasErrors('items');
|
|
$this->post($url, [...$this->quote, 'no_conflict' => false])->assertSessionHasErrors('no_conflict');
|
|
expect(Quotation::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('two independent evaluations and three eligible suppliers complete comparison', function () {
|
|
foreach (['123456789', '123456788', '123456787'] as $index => $nuit) {
|
|
$s = $index === 0 ? $this->supplier : Supplier::query()->create([...supplierPayload($nuit), 'tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'status' => 'active']);
|
|
$this->actingAs($this->buyer)->post("/requisicoes/{$this->r->id}/cotacoes", [...$this->quote, 'supplier_id' => $s->id])->assertSessionHasNoErrors();
|
|
$q = Quotation::query()->latest('id')->firstOrFail();
|
|
$ev = ['quality' => 8, 'history' => 5, 'payment' => 8, 'comment' => 'Avaliação técnica independente.', 'no_conflict' => true];
|
|
$this->post("/cotacoes/{$q->id}/avaliar", $ev)->assertSessionHasNoErrors();
|
|
$this->post("/cotacoes/{$q->id}/avaliar", $ev)->assertSessionHasErrors('evaluation');
|
|
$this->actingAs($this->finance)->post("/cotacoes/{$q->id}/avaliar", $ev)->assertSessionHasNoErrors();
|
|
}
|
|
$this->get("/requisicoes/{$this->r->id}/cotacoes")->assertInertia(fn (Assert $page) => $page->component('quotations/show')->where('ready', true)->has('quotations', 3)->where('quotations.0.score', 8.65));
|
|
expect(app(ProposalComparison::class)->inspect($this->r)['top_ids'])->toHaveCount(3);
|
|
$this->supplier->update(['status' => 'suspended']);
|
|
$this->get("/requisicoes/{$this->r->id}/cotacoes")->assertInertia(fn (Assert $page) => $page->where('ready', false)->where('quotations.0.eligible', false));
|
|
});
|
|
|
|
test('requester cannot evaluate own purchase after role change', function () {
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", $this->quote);
|
|
$q = Quotation::query()->firstOrFail();
|
|
$this->owner->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
|
$this->actingAs($this->owner)->post("/cotacoes/{$q->id}/avaliar", ['quality' => 8, 'history' => 5, 'payment' => 8, 'comment' => 'Avaliação de pedido próprio.', 'no_conflict' => true])->assertForbidden();
|
|
});
|
|
|
|
test('configured comparison uses the preserved minimum and weights and retains independent evaluators', function () {
|
|
$policy = app(ComparisonPolicy::class)->checked(['revision' => 1, 'configured' => true, 'minimum_proposals' => 1, 'minimum_evaluators' => 1,
|
|
'weights' => ['price' => 100, 'quality' => 0, 'delivery' => 0, 'history' => 0, 'payment' => 0]]);
|
|
$this->r->update(['comparison_policy' => $policy]);
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", $this->quote)->assertSessionHasNoErrors();
|
|
$quote = Quotation::query()->sole();
|
|
expect($quote->weights)->toBe($policy['weights'])->and(app(ProposalComparison::class)->inspect($this->r)['ready'])->toBeFalse();
|
|
$this->post("/cotacoes/{$quote->id}/avaliar", ['quality' => 8, 'history' => 5, 'payment' => 8, 'comment' => 'Conferência independente da proposta.', 'no_conflict' => true])->assertSessionHasNoErrors();
|
|
$before = app(ProposalComparison::class)->inspect($this->r);
|
|
expect($before['ready'])->toBeTrue()->and($before['rows'][0]['score_minor'])->toBe(1000);
|
|
$this->tenant->update(['comparison_policy' => ComparisonPolicy::DEFAULTS]);
|
|
expect(app(ProposalComparison::class)->inspect($this->r)['fingerprint'])->toBe($before['fingerprint']);
|
|
$this->get("/requisicoes/{$this->r->id}/cotacoes")->assertInertia(fn (Assert $page) => $page->where('comparisonPolicy.minimum_evaluators', 1)->where('ready', true));
|
|
$this->owner->update(['purchasing_role' => PurchasingRole::Finance]);
|
|
$this->actingAs($this->owner)->post("/cotacoes/{$quote->id}/avaliar", ['quality' => 8, 'history' => 5, 'payment' => 8, 'comment' => 'O solicitante continua impedido.', 'no_conflict' => true])->assertForbidden();
|
|
});
|
|
|
|
test('new requests freeze company comparison rules and edits cannot replace that snapshot', function () {
|
|
$policy = [...ComparisonPolicy::DEFAULTS, 'revision' => 1, 'configured' => true, 'minimum_proposals' => 2];
|
|
$this->tenant->update(['comparison_policy' => $policy]);
|
|
$this->actingAs($this->owner);
|
|
$data = ['cost_center_id' => $this->center->id, 'priority' => 'normal', 'needed_by' => now()->addWeek()->format('Y-m-d'), 'justification' => 'Nova requisição com regra da empresa.',
|
|
'items' => [['description' => 'Material', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1', 'unit' => 'un', 'unit_price' => '10.00', 'tax_rate' => '16']]];
|
|
$workflow = app(RequisitionWorkflow::class);
|
|
$created = $workflow->save($this->owner, [...$data, 'comparison_policy' => ['minimum_proposals' => 0]]);
|
|
expect($created->comparison_policy)->toBe($policy)->and($this->r->fresh()->comparison_policy)->toBeNull();
|
|
$next = [...$policy, 'revision' => 2, 'minimum_proposals' => 1];
|
|
$this->tenant->update(['comparison_policy' => $next]);
|
|
$workflow->save($this->owner, [...$data, 'comparison_policy' => $next], $created);
|
|
expect($created->fresh()->comparison_policy)->toBe($policy)->and($workflow->save($this->owner, $data)->comparison_policy)->toBe($next);
|
|
});
|
|
|
|
test('supplier quote and evaluation routes isolate companies', function () {
|
|
$this->post("/requisicoes/{$this->r->id}/cotacoes", $this->quote);
|
|
$q = Quotation::query()->firstOrFail();
|
|
$tenant = Tenant::query()->create(['name' => 'Empresa B']);
|
|
$other = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
|
|
$this->actingAs($other)->get('/fornecedores')->assertInertia(fn (Assert $p) => $p->has('suppliers.data', 0));
|
|
$this->post("/fornecedores/{$this->supplier->id}/validar", ['status' => 'active', 'comment' => 'Tentativa de outro inquilino.'])->assertNotFound();
|
|
$this->get("/requisicoes/{$this->r->id}/cotacoes")->assertNotFound();
|
|
$this->post("/cotacoes/{$q->id}/avaliar", ['quality' => 8, 'history' => 5, 'payment' => 8, 'comment' => 'Tentativa de outro inquilino.', 'no_conflict' => true])->assertNotFound();
|
|
});
|