1435 lines
102 KiB
PHP
1435 lines
102 KiB
PHP
<?php
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\AdmissionAdoption;
|
|
use App\Models\AdmissionDecision;
|
|
use App\Models\AuditLog;
|
|
use App\Models\AwardCancellation;
|
|
use App\Models\Budget;
|
|
use App\Models\BudgetEntry;
|
|
use App\Models\CostCenter;
|
|
use App\Models\CriticalityLevel;
|
|
use App\Models\Department;
|
|
use App\Models\Equipment;
|
|
use App\Models\EquipmentSparePart;
|
|
use App\Models\InvestmentPolicy;
|
|
use App\Models\PurchaseAward;
|
|
use App\Models\PurchaseControlPolicy;
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\PurchaseRevision;
|
|
use App\Models\QualificationSet;
|
|
use App\Models\Quotation;
|
|
use App\Models\Requisition;
|
|
use App\Models\SparePart;
|
|
use App\Models\StockItem;
|
|
use App\Models\StockMovement;
|
|
use App\Models\Supplier;
|
|
use App\Models\Tenant;
|
|
use App\Models\User;
|
|
use App\Models\Warehouse;
|
|
use App\Services\AgreementOrderLimits;
|
|
use App\Services\BudgetWorkflow;
|
|
use App\Services\CommonBudget;
|
|
use App\Services\ComparisonPolicy;
|
|
use App\Services\ConflictGuard;
|
|
use App\Services\DocumentaryQualificationWorkflow;
|
|
use App\Services\EquipmentWorkflow;
|
|
use App\Services\FormalAdmission;
|
|
use App\Services\OrderCancellationPolicyWorkflow;
|
|
use App\Services\OrderCancellationWorkflow;
|
|
use App\Services\OrderPartsPreparation;
|
|
use App\Services\ProcurementReviewCsv;
|
|
use App\Services\ProcurementReviewReport;
|
|
use App\Services\ProposalComparison;
|
|
use App\Services\ProposalOpeningWorkflow;
|
|
use App\Services\PurchaseControlPolicyWorkflow;
|
|
use App\Services\PurchaseRevisionWorkflow;
|
|
use App\Services\PurchaseWorkflow;
|
|
use App\Services\QuotationExchange;
|
|
use App\Services\RequisitionBudgetDistributions;
|
|
use App\Services\RequisitionCatalogue;
|
|
use App\Services\RequisitionWorkflow;
|
|
use App\Services\SupplyPlanning;
|
|
use App\Services\WorkflowTaskInbox;
|
|
use Illuminate\Database\QueryException;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Inertia\Testing\AssertableInertia as Assert;
|
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
use Tempo\Finance\Budget\BudgetControl;
|
|
|
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
|
|
|
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
|
|
if (! method_exists(BudgetControl::class, 'recordDistribution')) {
|
|
$this->markTestSkipped('Unpublished common source requires explicit QA selection.');
|
|
}
|
|
budgetDistributionFixtureSchema();
|
|
config(['budget-distributions.qa_enabled' => true]);
|
|
$this->withoutVite();
|
|
$second = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'QA-SPLIT', 'name' => 'Segundo centro sintético']);
|
|
$adapter = app(CommonBudget::class);
|
|
foreach ([$this->r->cost_center_id, $second->id] as $centre) {
|
|
$this->actingAs($this->finance);
|
|
$id = $adapter->for($this->finance)->create(['cost_center_id' => $centre, 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true,
|
|
'amount_minor' => 20000, 'reason' => 'Dotação sintética do percurso distribuído.']);
|
|
$this->actingAs($this->admin);
|
|
$adapter->for($this->admin)->approve($id);
|
|
}
|
|
$host = app(RequisitionBudgetDistributions::class);
|
|
$allocations = array_map(fn ($centre) => ['allocation_key' => (string) Str::uuid(), 'line_id' => $this->item->id, 'centre_id' => $centre,
|
|
'subtotal_minor' => 5000, 'total_minor' => 5000], [$this->r->cost_center_id, $second->id]);
|
|
// The approved source is the existing fixture; preparation/submission have their separate native tests.
|
|
$this->r->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
|
|
'source_revision' => $host->revision($this->r, $host->requestLines($this->r)), 'prepared_by' => $this->owner->id, 'reason' => 'Distribuição da fonte sintética aprovada.']])->save();
|
|
$this->actingAs($this->finance);
|
|
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
|
|
$this->selection['reason'] = 'Confirmação explícita das parcelas da proposta seleccionada.';
|
|
$this->selection['budget_distribution_preparation'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'], 'subtotal' => '50.00', 'total' => '50.00'], $allocations);
|
|
$this->actingAs($this->buyer)->get($this->awardUrl)->assertOk()->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true);
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->snapshot['budget_control']['phase'])->toBe('commit')
|
|
->and(DB::table('budget_distribution_entries')->where('kind', 'commit')->count())->toBe(2)
|
|
->and(DB::table('budget_entries')->where('requisition_id', $this->r->id)->count())->toBe(0);
|
|
$before = DB::table('budget_distribution_entries')->count();
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect();
|
|
expect(DB::table('budget_distribution_entries')->count())->toBe($before)->and(PurchaseOrder::query()->count())->toBe(1);
|
|
});
|
|
|
|
function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $quantity = '1.000', ?string $stockUnit = null): array
|
|
{
|
|
config(['agreement_order_limits.qa_enabled' => true]);
|
|
expect(app(AgreementOrderLimits::class)->ready())->toBeTrue();
|
|
foreach (User::query()->where('tenant_id', $test->tenant->id)->get() as $user) {
|
|
$permissions = [$user->purchasing_role->value];
|
|
if ($user->id === $test->buyer->id) {
|
|
$permissions = [...$permissions, 'supply_prepare', 'supply_read'];
|
|
}
|
|
if ($user->id === $test->finance->id) {
|
|
$permissions = [...$permissions, 'supply_review'];
|
|
}
|
|
supplyGrant($user, $permissions);
|
|
}
|
|
$stock = StockItem::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-ORDER-LIMIT', 'name' => 'Artigo contratual sintético', 'unit' => $stockUnit ?? $test->item->unit]);
|
|
$warehouse = Warehouse::query()->create(['tenant_id' => $test->tenant->id, 'created_by' => $test->buyer->id, 'code' => 'QA-LIMIT', 'name' => 'Armazém contratual sintético']);
|
|
// Explicit synthetic catalogue identity, prepared before selecting/approving the award. Never match by name.
|
|
$test->item->update(['catalogue_snapshot' => ['stock_item_id' => $stock->id]]);
|
|
$test->actingAs($test->buyer);
|
|
$planning = app(SupplyPlanning::class);
|
|
$draft = $planning->save($test->buyer, 'agreement', supplyInput(['stock_item_id' => $stock->id, 'warehouse_id' => $warehouse->id, 'supplier_id' => $test->quotes[0]->supplier_id,
|
|
'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'origin' => 'local', 'currency' => 'MZN',
|
|
'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'QA-PER-ORDER', 'order_limit_amount' => $amount, 'order_limit_quantity' => $quantity]));
|
|
$test->actingAs($test->finance);
|
|
$agreement = $planning->save($test->finance, 'agreement', supplyInput([], 'approve', $draft));
|
|
$binding = ['requisition_item_id' => $test->item->id, 'agreement_id' => $agreement->id];
|
|
|
|
return compact('agreement', 'binding', 'stock', 'warehouse');
|
|
}
|
|
|
|
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed) {
|
|
$f = perOrderAgreement($this, '100.00', '1.000');
|
|
$planning = app(SupplyPlanning::class);
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-GLOBAL-CONTRACT',
|
|
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => $cap]));
|
|
$this->actingAs($this->finance);
|
|
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
|
$bindings = [];
|
|
foreach ([false, true] as $second) {
|
|
$stock = $f['stock'];
|
|
$item = $this->item;
|
|
if ($second) {
|
|
$stock = $stock->replicate();
|
|
$stock->forceFill(['code' => 'QA-SECOND-ARTICLE', 'unit' => 'kg'])->save();
|
|
$item = $this->item->replicate();
|
|
$item->forceFill(['catalogue_snapshot' => ['stock_item_id' => $stock->id], 'unit' => 'kg'])->save();
|
|
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
|
|
foreach ($this->quotes as $quote) {
|
|
$line = $quote->items()->sole()->replicate();
|
|
$line->forceFill(['requisition_item_id' => $item->id])->save();
|
|
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
|
|
}
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'stock_item_id' => $stock->id,
|
|
'contract_key' => $contract->record_key, 'reference' => 'QA-CONTRACT-ARTICLE-'.($second ? '2' : '1')]));
|
|
$this->actingAs($this->finance);
|
|
$agreement = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
|
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
|
|
}
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => $bindings]);
|
|
if (! $allowed) {
|
|
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
|
|
return;
|
|
}
|
|
$response->assertRedirect();
|
|
$order = PurchaseOrder::query()->sole();
|
|
foreach ($order->snapshot['agreement_bindings'] as $row) {
|
|
expect($row['contract']['checked_order_value_minor'])->toBe(20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
|
|
->and($row['contract']['version'])->toBe($contract->version)->and($row['checked_order_value_minor'])->toBe(10000);
|
|
}
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Contrato global: QA-GLOBAL-CONTRACT');
|
|
$this->withoutVite()->get('/compras/fornecimento?view=contracts')->assertOk();
|
|
$this->get('/compras/fornecimento?view=agreements&linked_contract_key='.$contract->record_key)
|
|
->assertOk()->assertInertia(fn (Assert $page) => $page->component('supply/index')->has('records', 2)->where('linkedContractKey', $contract->record_key));
|
|
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false]]);
|
|
|
|
test('per order contract rejects incompatible association and stale approval without changing earlier versions', function () {
|
|
$f = perOrderAgreement($this);
|
|
$planning = app(SupplyPlanning::class);
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-HEADER',
|
|
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
|
|
expect(fn () => $planning->save($this->buyer, 'contract', supplyInput([], 'approve', $draft)))->toThrow(HttpException::class);
|
|
$this->actingAs($this->finance);
|
|
$tasks = collect(app(WorkflowTaskInbox::class)->build($this->finance, 'procurement'))->where('task', 'contract_review');
|
|
expect($tasks->pluck('href')->all())->toContain('/compras/fornecimento?view=contracts&record_id='.$draft->id.'#supply-record-'.$draft->id);
|
|
expect($tasks->sole()['reference'])->toBe('QA-HEADER');
|
|
$contract = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
|
foreach ([['currency' => 'USD'], ['supplier_id' => 0], ['contract_version' => 999], ['valid_until' => today()->addMonths(2)->toDateString()]] as $change) {
|
|
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key, ...$change], $this->tenant->id))->toThrow(ValidationException::class);
|
|
}
|
|
expect(fn () => app(AgreementOrderLimits::class)->contract([...$f['agreement']->data, 'contract_key' => $contract->record_key], $this->tenant->id + 999))->toThrow(ValidationException::class);
|
|
$this->actingAs($this->buyer);
|
|
$article = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
|
|
expect($article->data['contract_version'])->toBe($contract->version);
|
|
$this->actingAs($this->finance);
|
|
$approved = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $article));
|
|
$this->actingAs($this->buyer);
|
|
$policyDraft = $planning->save($this->buyer, 'policy', supplyInput([...supplyPolicy($f), 'agreement_key' => $approved->record_key]));
|
|
$this->actingAs($this->finance);
|
|
$policy = $planning->save($this->finance, 'policy', supplyInput([], 'approve', $policyDraft));
|
|
$this->actingAs($this->buyer);
|
|
$pending = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $contract->record_key]));
|
|
$this->actingAs($this->finance);
|
|
$planning->save($this->finance, 'contract', supplyInput([], 'suspend', $contract));
|
|
expect($planning->calendar($policy, today()->toDateString())['lead_time_available'])->toBeFalse();
|
|
expect(fn () => $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $pending)))->toThrow(ValidationException::class);
|
|
expect($contract->fresh()->state)->toBe('approved')->and($article->fresh()->state)->toBe('draft');
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $this->item->id, 'agreement_id' => $approved->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('per order limits preserve equality and each independent order can use the full limit again', function (bool $global) {
|
|
$f = perOrderAgreement($this);
|
|
if ($global) {
|
|
$planning = app(SupplyPlanning::class);
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'contract', supplyInput(['supplier_id' => $this->quotes[0]->supplier_id, 'reference' => 'QA-FULL-AGAIN',
|
|
'currency' => 'MZN', 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'order_limit_amount' => '100.00']));
|
|
$this->actingAs($this->finance);
|
|
$header = $planning->save($this->finance, 'contract', supplyInput([], 'approve', $draft));
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'contract_key' => $header->record_key]));
|
|
$this->actingAs($this->finance);
|
|
$f['agreement'] = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
|
$f['binding']['agreement_id'] = $f['agreement']->id;
|
|
}
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors()->assertRedirect();
|
|
$first = PurchaseOrder::query()->sole();
|
|
$snapshot = $first->snapshot;
|
|
expect($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBe(10000)
|
|
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_quantity_milli'])->toBe(1000)
|
|
->and($snapshot['agreement_bindings'][$this->item->id]['basis'])->toBe('per_order');
|
|
$request = $this->r->replicate();
|
|
$request->forceFill(['number' => 'REQ-ORDER-SECOND'])->save();
|
|
foreach ($this->r->steps()->get() as $step) {
|
|
$copy = $step->replicate();
|
|
$copy->forceFill(['requisition_id' => $request->id])->save();
|
|
}
|
|
$item = $this->item->replicate();
|
|
$item->forceFill(['requisition_id' => $request->id])->save();
|
|
$quotes = [];
|
|
foreach ($this->quotes as $quote) {
|
|
$copy = $quote->replicate();
|
|
$copy->forceFill(['requisition_id' => $request->id])->save();
|
|
foreach ($quote->items()->get() as $line) {
|
|
$new = $line->replicate();
|
|
$new->forceFill(['quotation_id' => $copy->id, 'requisition_item_id' => $item->id])->save();
|
|
}
|
|
foreach ($quote->evaluations()->get() as $evaluation) {
|
|
$new = $evaluation->replicate();
|
|
$new->forceFill(['quotation_id' => $copy->id])->save();
|
|
}
|
|
$quotes[] = $copy;
|
|
}
|
|
$this->r = $request;
|
|
$this->item = $item;
|
|
$this->quotes = $quotes;
|
|
$this->selection['quotation_id'] = $quotes[0]->id;
|
|
$this->awardUrl = '/requisicoes/'.$request->id.'/adjudicacao';
|
|
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasNoErrors();
|
|
$secondAward = PurchaseAward::query()->where('requisition_id', $request->id)->sole();
|
|
approvePurchaseAward($this, $secondAward);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$secondAward->id.'/emitir', ['agreement_bindings' => [['requisition_item_id' => $item->id, 'agreement_id' => $f['agreement']->id]]])->assertSessionHasNoErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(2)->and((int) PurchaseOrder::query()->sum('total_minor'))->toBe(20000)
|
|
->and($first->fresh()->snapshot)->toBe($snapshot)->and($f['agreement']->fresh()->data['max_order_value_minor'])->toBe(10000);
|
|
if (DB::getDriverName() === 'sqlite') {
|
|
// PostgreSQL report snapshots are exercised outside Pest's outer transaction by the existing report worker.
|
|
$report = app(ProcurementReviewReport::class)->build($this->buyer, $first->requisition_id);
|
|
expect($report['agreement_limits'])->toBe($snapshot['agreement_bindings']);
|
|
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Acordo por ordem')->toContain('QA-PER-ORDER');
|
|
if ($global) {
|
|
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Contrato global por ordem')->toContain('QA-FULL-AGAIN');
|
|
expect(array_values($first->snapshot['agreement_bindings'])[0]['contract']['checked_order_value_minor'])->toBe(10000);
|
|
}
|
|
}
|
|
})->with([false, true]);
|
|
|
|
test('per order limits reject excess and explicit zero before committing any order', function (?string $value, ?string $quantity) {
|
|
$f = perOrderAgreement($this, $value, $quantity);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$before = BudgetEntry::query()->get()->toArray();
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0)->and(BudgetEntry::query()->get()->toArray())->toBe($before);
|
|
})->with([['99.99', '1.000'], ['100.00', '0.999'], ['0', null], [null, '0']]);
|
|
|
|
test('per order limits keep an absent limit distinct from zero and recover issue without another effect', function () {
|
|
$f = perOrderAgreement($this, null, null);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$payload = ['agreement_bindings' => [$f['binding']]];
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
|
|
$order = PurchaseOrder::query()->sole();
|
|
$snapshot = $order->snapshot;
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir', $payload)->assertSessionHasNoErrors();
|
|
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $f['agreement']->id + 100]]])->assertConflict();
|
|
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->fresh()->snapshot)->toBe($snapshot)
|
|
->and($snapshot['agreement_bindings'][$this->item->id]['max_order_value_minor'])->toBeNull()
|
|
->and(AuditLog::query()->where('action', 'purchase_order.issued')->count())->toBe(1);
|
|
});
|
|
|
|
test('per order limits refuse suspended stale foreign source data and omitted source read permission', function () {
|
|
$f = perOrderAgreement($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->finance);
|
|
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
|
|
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'requisition_item_id' => 999999]]])->assertUnprocessable();
|
|
DB::table('organization_profiles')->whereIn('id', DB::table('organization_memberships')->where('user_id', $this->buyer->id)->select('profile_id'))->update(['permissions' => json_encode(['procurement'])]);
|
|
$this->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertForbidden();
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('per order quantity limits use the explicit frozen conversion without changing commercial prices', function () {
|
|
$f = perOrderAgreement($this, '100.00', '12.000', 'pcs');
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$body = $f['binding'];
|
|
$body['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem contratual sintética', 'version' => 'QA-PACK-1'];
|
|
$bad = $body;
|
|
$bad['conversion']['denominator'] = '7';
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$bad]])->assertUnprocessable();
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertUnprocessable();
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$body]])->assertSessionHasNoErrors();
|
|
$order = PurchaseOrder::query()->sole();
|
|
expect($order->total_minor)->toBe(10000)->and($order->items()->sole()->quantity)->toBe('1.000')
|
|
->and($order->snapshot['agreement_bindings'][$this->item->id]['agreement_quantity_milli'])->toBe('12000')
|
|
->and($order->snapshot['agreement_bindings'][$this->item->id]['conversion'])->toBe($body['conversion']);
|
|
});
|
|
|
|
test('per order limit preparation is exact rejects cumulative modes and is unavailable outside its qa switch', function () {
|
|
config(['agreement_order_limits.qa_enabled' => true]);
|
|
$limits = app(AgreementOrderLimits::class);
|
|
expect($limits->terms(['order_limit_amount' => '123.45', 'order_limit_quantity' => '12.345']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 12345, 'max_order_quantity_milli' => 12345]);
|
|
expect($limits->terms(['order_limit_amount' => '', 'order_limit_quantity' => ' ']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => null, 'max_order_quantity_milli' => null]);
|
|
expect($limits->terms(['order_limit_amount' => '10000000000.00', 'order_limit_quantity' => '1000000000.000']))->toBe(['order_limit_basis' => 'per_order', 'max_order_value_minor' => 1000000000000, 'max_order_quantity_milli' => 1000000000000]);
|
|
foreach ([['order_limit_amount' => '1.001'], ['order_limit_quantity' => '1.0001'], ['order_limit_amount' => '-1'], ['order_limit_amount' => '1', 'order_limit_basis' => 'cumulative']] as $body) {
|
|
expect(fn () => $limits->terms($body))->toThrow(ValidationException::class);
|
|
}
|
|
config(['agreement_order_limits.qa_enabled' => false]);
|
|
expect(fn () => $limits->terms(['order_limit_amount' => '1']))->toThrow(HttpException::class)
|
|
->and($limits->terms(['reference' => 'legacy']))->toBe([]);
|
|
});
|
|
|
|
test('per order limits aggregate all covered lines of the same agreement instead of granting a limit to each line', function (string $amount, string $quantity, bool $allowed) {
|
|
$f = perOrderAgreement($this, $amount, $quantity);
|
|
$second = $this->item->replicate();
|
|
$second->save();
|
|
$this->r->update(['subtotal_minor' => 20000, 'total_minor' => 20000]);
|
|
foreach ($this->quotes as $quote) {
|
|
$line = $quote->items()->sole()->replicate();
|
|
$line->forceFill(['requisition_item_id' => $second->id])->save();
|
|
$quote->update(['subtotal_minor' => $quote->subtotal_minor * 2, 'total_minor' => $quote->total_minor * 2]);
|
|
}
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$payload = ['agreement_bindings' => [$f['binding'], ['requisition_item_id' => $second->id, 'agreement_id' => $f['agreement']->id]]];
|
|
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', $payload);
|
|
if (! $allowed) {
|
|
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
|
|
return;
|
|
}
|
|
$response->assertRedirect();
|
|
$order = PurchaseOrder::query()->sole();
|
|
expect($order->total_minor)->toBe(20000)->and($order->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(20000)
|
|
->and($order->snapshot['agreement_bindings'][$second->id]['checked_order_quantity_milli'])->toBe('2000');
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Acordos e limites preservados por ordem')->assertSee('QA-PER-ORDER');
|
|
})->with([['200.00', '1.500', false], ['150.00', '2.000', false], ['200.00', '2.000', true]]);
|
|
|
|
test('per order value limit includes taxes rather than only the net amount', function (string $amount, bool $allowed) {
|
|
$f = perOrderAgreement($this, $amount, '1.000');
|
|
awardPrices($this, 10000, 16);
|
|
$this->r->update(['tax_minor' => 1600, 'total_minor' => 11600]);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]]);
|
|
if (! $allowed) {
|
|
$response->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
|
|
return;
|
|
}
|
|
$response->assertRedirect();
|
|
expect(PurchaseOrder::query()->sole()->snapshot['agreement_bindings'][$this->item->id]['checked_order_value_minor'])->toBe(11600);
|
|
})->with([['100.00', false], ['116.00', true]]);
|
|
|
|
test('per order frozen article and warehouse are reused by receipt without changing documentary quantities', function () {
|
|
$f = perOrderAgreement($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [$f['binding']]])->assertSessionHasNoErrors();
|
|
$order = PurchaseOrder::query()->sole();
|
|
$original = $order->snapshot;
|
|
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
|
supplyGrant($receiver, ['warehouse']);
|
|
$this->actingAs($receiver);
|
|
$body = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'QA-CONTRACT-RECEIPT', 'received_on' => today()->toDateString(), 'warehouse_id' => null,
|
|
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => null]]];
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertUnprocessable();
|
|
$body['warehouse_id'] = $f['warehouse']->id;
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
|
|
expect(StockMovement::query()->sole()->stock_item_id)->toBe($f['stock']->id)->and(StockMovement::query()->sole()->quantity_milli)->toBe(1000)
|
|
->and($order->fresh()->snapshot)->toBe($original)->and($f['agreement']->fresh()->data['max_order_quantity_milli'])->toBe(1000);
|
|
});
|
|
|
|
test('per order agreement search retains selected eligible sources beyond the hundred row window without reviving suspension', function () {
|
|
$f = perOrderAgreement($this);
|
|
$this->actingAs($this->buyer);
|
|
for ($index = 0; $index < 101; $index++) {
|
|
$copy = $f['agreement']->replicate();
|
|
$copy->forceFill(['record_key' => (string) Str::uuid(), 'version' => 1, 'operation_key' => (string) Str::uuid(),
|
|
'created_at' => now(),
|
|
'input_hash' => hash('sha256', 'synthetic-pagination-agreement:'.$index),
|
|
'reason' => 'Fixture sintética de paginação; não representa aprovação empresarial.',
|
|
'data' => [...$f['agreement']->data, 'reference' => 'NEWER-QA-'.$index]])->save();
|
|
}
|
|
$limits = app(AgreementOrderLimits::class);
|
|
expect($limits->options($this->buyer, $this->r, $this->quotes[0]))->toHaveCount(100);
|
|
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toHaveCount(1);
|
|
$this->actingAs($this->finance);
|
|
app(SupplyPlanning::class)->save($this->finance, 'agreement', supplyInput([], 'suspend', $f['agreement']));
|
|
$this->actingAs($this->buyer);
|
|
expect($limits->options($this->buyer, $this->r, $this->quotes[0], 'NO-MATCH', [$f['agreement']->id]))->toBe([]);
|
|
});
|
|
|
|
test('per order source from another company cannot be bound even when its identity is known', function () {
|
|
$f = perOrderAgreement($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$foreign = receiptFixture();
|
|
supplyGrant($foreign['issuer'], ['supply_prepare']);
|
|
supplyGrant($foreign['receiver'], ['supply_review']);
|
|
$this->actingAs($foreign['issuer']);
|
|
$planning = app(SupplyPlanning::class);
|
|
$draft = $planning->save($foreign['issuer'], 'agreement', supplyInput(['stock_item_id' => $foreign['stock']->id, 'warehouse_id' => $foreign['warehouse']->id,
|
|
'supplier_id' => $foreign['order']->supplier_id, 'habitual' => false, 'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(),
|
|
'origin' => 'local', 'currency' => 'MZN', 'price_minor' => 10000, 'lead_days' => 4, 'reference' => 'FOREIGN-QA', 'order_limit_amount' => '100.00']));
|
|
$this->actingAs($foreign['receiver']);
|
|
$other = $planning->save($foreign['receiver'], 'agreement', supplyInput([], 'approve', $draft));
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $other->id]]])->assertUnprocessable();
|
|
expect(PurchaseOrder::query()->where('tenant_id', $this->tenant->id)->count())->toBe(0);
|
|
});
|
|
|
|
test('per order limits refuse an agreement in another currency without inventing a conversion', function () {
|
|
$f = perOrderAgreement($this);
|
|
$planning = app(SupplyPlanning::class);
|
|
$this->actingAs($this->buyer);
|
|
$draft = $planning->save($this->buyer, 'agreement', supplyInput([...$f['agreement']->data, 'currency' => 'USD', 'reference' => 'WRONG-CURRENCY-QA']));
|
|
$this->actingAs($this->finance);
|
|
$wrong = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => [[...$f['binding'], 'agreement_id' => $wrong->id]]])->assertUnprocessable()->assertJsonValidationErrors('agreement_bindings');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('mixed currency comparison ranks the frozen mzn reference rather than raw foreign amounts', function () {
|
|
$this->actingAs($this->finance);
|
|
app(QuotationExchange::class)->record($this->finance, $this->r, [
|
|
'operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
|
'quoted_on' => today()->toDateString(), 'source' => 'Fonte sintética para comparação multimoeda',
|
|
]);
|
|
$quote = $this->quotes[0];
|
|
$quote->update(['currency' => 'USD', 'exchange_basis' => app(QuotationExchange::class)->basis($this->r, 'USD')]);
|
|
$result = app(ProposalComparison::class)->inspect($this->r);
|
|
expect($result['ready'])->toBeTrue()->and($result['top_ids'])->toBe([$this->quotes[1]->id])
|
|
->and($result['rows'][0]['total_minor'])->toBe(10000)
|
|
->and($result['rows'][0]['reference_amounts']['total_minor'])->toBe(600000);
|
|
});
|
|
|
|
test('foreign award approves and commits mzn while the immutable order keeps original currency and rate', function () {
|
|
$this->actingAs($this->finance);
|
|
$exchange = app(QuotationExchange::class);
|
|
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
|
'quoted_on' => today()->toDateString(), 'source' => 'Fonte sintética congelada antes da proposta']);
|
|
$quote = $this->quotes[0];
|
|
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
|
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->total_minor)->toBe(6000);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->currency)->toBe('USD')->and($order->total_minor)->toBe(100)
|
|
->and($order->items()->sole()->unit_price_minor)->toBe(100)
|
|
->and($order->snapshot['reference_amounts']['total_minor'])->toBe(6000)
|
|
->and($order->snapshot['exchange_basis'])->toBe($quote->exchange_basis);
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('USD')->assertSee('60.0000000000')->assertSee('Referência orçamental');
|
|
});
|
|
|
|
test('foreign currency conversion determines final approval thresholds without changing estimate approvals', function () {
|
|
$this->actingAs($this->finance);
|
|
$exchange = app(QuotationExchange::class);
|
|
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '40000',
|
|
'quoted_on' => today()->toDateString(), 'source' => 'Taxa exclusivamente sintética para testar alçadas']);
|
|
awardPrices($this, 5000000);
|
|
$quote = $this->quotes[0];
|
|
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
|
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
|
$before = $this->r->steps()->get()->toArray();
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->total_minor)->toBe(4000000)->and($award->approvals()->count())->toBe(2)
|
|
->and($this->r->steps()->get()->toArray())->toBe($before);
|
|
});
|
|
|
|
test('foreign order cancellation reverses the mzn commitment while preserving the original foreign document', function () {
|
|
$this->actingAs($this->finance);
|
|
$exchange = app(QuotationExchange::class);
|
|
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '60',
|
|
'quoted_on' => today()->toDateString(), 'source' => 'Taxa sintética para testar reversão do compromisso']);
|
|
$quote = $this->quotes[0];
|
|
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
|
|
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100, 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
|
|
Budget::query()->create(['tenant_id' => $this->tenant->id, 'cost_center_id' => $this->r->cost_center_id, 'year' => now()->year,
|
|
'amount_minor' => 20000, 'includes_tax' => true, 'created_by' => $this->finance->id, 'approved_by' => $this->admin->id, 'reason' => 'Dotação sintética para cancelamento multimoeda']);
|
|
DB::transaction(function () {
|
|
app(ConflictGuard::class)->lockCompany($this->finance);
|
|
app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000);
|
|
});
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
expect((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->sum('committed_minor'))->toBe(6000);
|
|
$original = $order->getAttributes();
|
|
config(['order_cancellation.enabled' => true]);
|
|
$admins = [$this->admin];
|
|
foreach (range(1, 2) as $index) {
|
|
$admins[] = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
|
|
}
|
|
$this->actingAs($admins[0]);
|
|
$policyWorkflow = app(OrderCancellationPolicyWorkflow::class);
|
|
$policy = $policyWorkflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
|
|
'valid_from' => today()->toDateString(), 'valid_until' => today()->addWeek()->toDateString(), 'reason' => 'Política exclusivamente sintética para cancelamento']);
|
|
foreach (array_slice($admins, 1) as $reviewer) {
|
|
$this->actingAs($reviewer);
|
|
$policyWorkflow->review($reviewer, $policy, 'approved', 'Conferência sintética independente');
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$flow = app(OrderCancellationWorkflow::class);
|
|
$cancellation = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
|
|
'reason' => 'Cancelamento sintético antes de qualquer execução', 'evidence' => 'Evidência documental exclusivamente sintética']);
|
|
$this->actingAs($this->finance);
|
|
$flow->decide($this->finance, $cancellation, 'approved', 'Conferência financeira sintética independente');
|
|
expect((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->sum('committed_minor'))->toBe(0)
|
|
->and((int) DB::table('budget_entries')->where('requisition_id', $this->r->id)->where('kind', 'order-cancel-'.$order->id)->value('committed_minor'))->toBe(-6000)
|
|
->and($order->fresh()->getAttributes())->toBe($original);
|
|
});
|
|
|
|
function awardPrices(object $test, int $firstPrice, int $taxRate = 0): void
|
|
{
|
|
$test->r->items()->update(['tax_rate' => $taxRate]);
|
|
foreach ($test->quotes as $index => $quote) {
|
|
$price = $firstPrice + $index * 10000;
|
|
$tax = intdiv($price * $taxRate + 50, 100);
|
|
$quote->items()->update(['unit_price_minor' => $price, 'tax_rate' => $taxRate, 'subtotal_minor' => $price, 'tax_minor' => $tax, 'total_minor' => $price + $tax]);
|
|
$quote->update(['subtotal_minor' => $price, 'tax_minor' => $tax, 'total_minor' => $price + $tax]);
|
|
}
|
|
}
|
|
|
|
function selectPurchaseAward(object $test): PurchaseAward
|
|
{
|
|
$test->actingAs($test->buyer)->post($test->awardUrl, $test->selection)->assertSessionHasNoErrors()->assertRedirect($test->awardUrl);
|
|
|
|
return PurchaseAward::query()->firstOrFail();
|
|
}
|
|
|
|
function prepareFormalAwardAdmission(object $test): void
|
|
{
|
|
$workflow = app(FormalAdmission::class);
|
|
$test->actingAs($test->admin);
|
|
$policy = $workflow->policy($test->admin, ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance', 'department_head'], 'required_count' => 2, 'reason' => 'Política fictícia para adjudicação']);
|
|
$test->actingAs($test->buyer);
|
|
$workflow->adopt($test->buyer, $test->r, $policy->id, 0, 'Adopção fictícia antes da adjudicação');
|
|
$opening = app(ProposalOpeningWorkflow::class);
|
|
$documentary = app(DocumentaryQualificationWorkflow::class);
|
|
$set = $documentary->define($test->buyer, $test->r, ['previous_id' => 0, 'basis_hash' => $opening->basis($opening->proposals($test->r)), 'reason' => 'Requisito exclusivamente fictício', 'criteria' => [['label' => 'Conformidade documentada', 'category' => 'technical', 'required' => true]]]);
|
|
foreach ($test->quotes as $quote) {
|
|
$test->actingAs($test->finance);
|
|
$documentary->assess($test->finance, $set, ['previous_id' => 0, 'quotation_id' => $quote->id, 'reason' => 'Análise exclusivamente fictícia', 'answers' => [['criterion_id' => 1, 'result' => 'met', 'evidence' => 'Documento fictício', 'reason' => 'Conformidade confirmada no teste']]]);
|
|
$test->actingAs($test->buyer);
|
|
$decision = $workflow->propose($test->buyer, $test->r, ['quotation_id' => $quote->id, 'previous_id' => 0, 'basis_hash' => $workflow->basis($test->r, $quote->id)['hash'], 'outcome' => 'admit', 'reason' => 'Proposta fundamentada no teste']);
|
|
foreach ([$test->finance, $test->head] as $reviewer) {
|
|
$test->actingAs($reviewer);
|
|
$workflow->review($reviewer, $decision, 'approved', 'Conferência independente fictícia');
|
|
}
|
|
}
|
|
$test->actingAs($test->buyer);
|
|
}
|
|
|
|
function approvePurchaseAward(object $test, PurchaseAward $award): void
|
|
{
|
|
foreach ($award->approvals()->get() as $step) {
|
|
$user = match ($step->role) {
|
|
'department_head' => $test->head, 'procurement' => $test->secondBuyer, 'finance' => $test->finance,
|
|
};
|
|
$test->actingAs($user)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors()->assertRedirect();
|
|
}
|
|
}
|
|
|
|
function issuePurchaseOrder(object $test, PurchaseAward $award): PurchaseOrder
|
|
{
|
|
approvePurchaseAward($test, $award);
|
|
$test->actingAs($test->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors()->assertRedirect();
|
|
|
|
return PurchaseOrder::query()->firstOrFail();
|
|
}
|
|
|
|
test('catalogue origin survives order issue and automatically identifies received stock without remapping', function () {
|
|
$this->actingAs($this->admin);
|
|
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'CAT-ORDER', 'name' => $this->item->description, 'unit' => $this->item->unit]);
|
|
app(RequisitionCatalogue::class)->save($this->admin, $stock->id, ['version' => 0, 'stock_basis' => app(RequisitionCatalogue::class)->basis($stock), 'category' => $this->item->category,
|
|
'purchase_type' => 'consumable', 'published' => true, 'reason' => 'Fonte fictícia da linha antes de emitir.']);
|
|
$entry = DB::table('requisition_catalogue')->where('stock_item_id', $stock->id)->sole();
|
|
// Bind the synthetic fixture's source before exercising the real issue workflow.
|
|
$resolved = app(RequisitionCatalogue::class)->line($this->owner, ['catalogue_entry_id' => $entry->id, 'catalogue_version' => 1], []);
|
|
$this->item->update(['catalogue_entry_id' => $entry->id, 'catalogue_snapshot' => $resolved['catalogue_snapshot']]);
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
expect($order->snapshot['catalogue_sources'][$this->item->id]['stock_item_id'])->toBe($stock->id);
|
|
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
|
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'REC-CAT', 'name' => 'Armazém fictício']);
|
|
$wrong = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'WRONG-CAT', 'name' => 'Artigo distinto', 'unit' => $stock->unit]);
|
|
$line = $order->items()->sole();
|
|
$body = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GUIA-CAT-1', 'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
|
|
'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant']]];
|
|
$bad = $body;
|
|
$bad['items'][0]['stock_item_id'] = $wrong->id;
|
|
$this->actingAs($receiver)->postJson('/ordens/'.$order->id.'/recepcoes', $bad)->assertUnprocessable();
|
|
$this->get('/ordens/'.$order->id.'/recepcoes')->assertInertia(fn (Assert $p) => $p->where('progress.lines.0.stock_item_id', $stock->id));
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertOk()->assertJsonPath('created', false);
|
|
expect(StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
|
|
});
|
|
|
|
function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
|
|
{
|
|
require_once __DIR__.'/../Support/InvestmentFixture.php';
|
|
$test->item->update(['purchase_type' => 'equipment', 'production_area' => 'Linha fictícia de investimento']);
|
|
$test->r->update(['status' => 'draft']);
|
|
$test->r->refresh();
|
|
$test->actingAs($test->head);
|
|
$technical = app(EquipmentWorkflow::class);
|
|
$technical->review($test->head, $test->r, $technical->basis($test->r), 'approved', 'Validação técnica fictícia independente.');
|
|
$test->r->update(['status' => 'approved']);
|
|
$test->r->steps()->create(['tenant_id' => $test->tenant->id, 'position' => 2, 'role' => 'finance', 'decision' => 'approved', 'approver_id' => $test->finance->id, 'decided_at' => now()]);
|
|
$test->actingAs($test->owner);
|
|
Budget::query()->create(['tenant_id' => $test->tenant->id, 'cost_center_id' => $test->r->cost_center_id, 'year' => now()->year, 'kind' => 'investment', 'amount_minor' => 100000, 'includes_tax' => true, 'created_by' => $test->admin->id, 'approved_by' => $test->finance->id, 'reason' => 'Dotação fictícia de investimento']);
|
|
DB::transaction(function () use ($test) {
|
|
app(ConflictGuard::class)->lockCompany($test->owner);
|
|
app(BudgetWorkflow::class)->record($test->owner, $test->r, 'reserve', $test->r->total_minor, $test->r->subtotal_minor);
|
|
});
|
|
|
|
return publishInvestmentFixture($test->tenant->id, $ceiling, $includesTax);
|
|
}
|
|
|
|
beforeEach(function () {
|
|
$this->tenant = Tenant::query()->create(['name' => 'Empresa das ordens']);
|
|
$this->department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Produção']);
|
|
$center = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'code' => 'PROD', 'name' => 'Produção']);
|
|
foreach (['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'secondBuyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin] as $key => $role) {
|
|
$this->{$key} = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => $role]);
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$this->r = Requisition::query()->create([
|
|
'tenant_id' => $this->tenant->id, 'requester_id' => $this->owner->id, 'department_id' => $this->department->id, 'cost_center_id' => $center->id,
|
|
'number' => 'REQ-ORDER', 'priority' => 'normal', 'needed_by' => now()->addMonth(), 'justification' => 'Necessidade de materiais para produção.',
|
|
'status' => 'approved', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000,
|
|
'approval_snapshot' => ['first_limit_minor' => 2500000, 'second_limit_minor' => 15000000, 'approval_includes_tax' => true, 'rules_provisional' => true],
|
|
]);
|
|
$this->r->steps()->create(['tenant_id' => $this->tenant->id, 'position' => 1, 'role' => 'department_head', 'decision' => 'approved', 'approver_id' => $this->head->id, 'decided_at' => now()]);
|
|
$this->item = $this->r->items()->create(['tenant_id' => $this->tenant->id, 'description' => 'Material de teste', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1', 'unit' => 'un', 'unit_price_minor' => 10000, 'tax_rate' => '0', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
|
$this->quotes = [];
|
|
$this->suppliers = [];
|
|
foreach (['111222333', '222333444', '333444555'] as $index => $nuit) {
|
|
$supplier = Supplier::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'name' => 'Fornecedor '.$index, 'nuit' => $nuit, 'contact' => 'Contacto', 'email' => 'fornecedor'.$index.'@example.test', 'phone' => '123456789', 'address' => 'Maputo', 'category' => 'Material', 'beneficiaries' => 'Beneficiário', 'document_references' => 'Alvará conferido.', 'diligence_notes' => 'Documentação regular no teste.', 'status' => 'active', 'next_review' => now()->addYear()]);
|
|
$this->suppliers[] = $supplier;
|
|
$this->actingAs($this->buyer)->post('/requisicoes/'.$this->r->id.'/cotacoes', ['supplier_id' => $supplier->id, 'reference' => 'PROP-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'), 'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $this->item->id, 'unit_price' => (string) (100 + $index * 100)]]])->assertSessionHasNoErrors();
|
|
$quote = Quotation::query()->latest('id')->firstOrFail();
|
|
$this->quotes[] = $quote;
|
|
foreach ([$this->buyer, $this->finance] as $evaluator) {
|
|
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8', 'comment' => 'Avaliação independente fundamentada.', 'no_conflict' => true])->assertSessionHasNoErrors();
|
|
}
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$this->awardUrl = '/requisicoes/'.$this->r->id.'/adjudicacao';
|
|
$this->selection = ['quotation_id' => $this->quotes[0]->id, 'justification' => 'Proposta com melhor pontuação técnica e comercial.', 'delivery_date' => now()->addWeek()->format('Y-m-d'), 'delivery_location' => 'Armazém central de Maputo'];
|
|
});
|
|
|
|
test('award starts a new approval cycle and order freezes all agreed data', function () {
|
|
$sourceSteps = $this->r->steps()->get()->toArray();
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->status)->toBe('pending')->and($award->approvals()->count())->toBe(1);
|
|
expect($award->approvals()->firstOrFail()->decision)->toBe('pending');
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->number)->toMatch('/^OC-\d{4}-\d{6}$/')->and($order->total_minor)->toBe(10000);
|
|
expect($order->snapshot['supplier']['name'])->toBe('Fornecedor 0')->and($order->snapshot['quotation']['payment_terms'])->toBe('30 dias');
|
|
expect($order->snapshot['budget_checked'])->toBeFalse()->and($order->snapshot['development_only'])->toBeTrue();
|
|
expect($order->snapshot['award']['delivery_date'])->toBe($this->selection['delivery_date']);
|
|
expect($order->items()->count())->toBe(1)->and($order->snapshot['decision_matrix'])->toHaveCount(3);
|
|
expect($this->r->steps()->get()->toArray())->toBe($sourceSteps);
|
|
$this->get('/ordens/'.$order->id)->assertInertia(fn (Assert $page) => $page->component('purchases/show')->where('order.number', $order->number)->has('history', 3));
|
|
$this->get('/ordens')->assertInertia(fn (Assert $page) => $page->has('orders.data', 1)->has('awards.data', 1));
|
|
});
|
|
|
|
test('discount evidence and net prices survive award order and printable report', function () {
|
|
$quote = $this->quotes[0];
|
|
$terms = ['version' => 1, 'discount_basis' => 'unit_before_vat', 'rounding' => 'net_unit_half_up_cent',
|
|
'lines' => [['requisition_item_id' => $this->item->id, 'gross_unit_minor' => 12500, 'discount_type' => 'percent', 'discount_value' => '20.00', 'net_unit_minor' => 10000]]];
|
|
$quote->update(['commercial_terms' => $terms]);
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->items()->sole()->unit_price_minor)->toBe(10000)
|
|
->and($order->snapshot['decision_matrix'][0]['commercial_terms'])->toBe($terms)
|
|
->and($order->total_minor)->toBe(10000);
|
|
$this->actingAs($this->buyer)->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('20.00%');
|
|
});
|
|
|
|
test('comparison rule is printed with the order and policy tampering invalidates an approved award', function () {
|
|
$policy = [...ComparisonPolicy::DEFAULTS, 'revision' => 1, 'configured' => true];
|
|
$this->r->update(['comparison_policy' => $policy]);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->r->update(['comparison_policy' => [...$policy, 'minimum_proposals' => 1]]);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('comparison');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
$this->r->update(['comparison_policy' => $policy]);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
$order = PurchaseOrder::query()->sole();
|
|
expect($order->snapshot['comparison_policy'])->toBe($policy);
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Regra de comparação preservada: revisão 1');
|
|
});
|
|
|
|
test('final approval tier uses inclusive boundaries of the stored process rules', function (int $priceMinor, int $count) {
|
|
awardPrices($this, $priceMinor);
|
|
$this->tenant->update(['first_limit_minor' => 1, 'second_limit_minor' => 2]);
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->approvals()->count())->toBe($count);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->total_minor)->toBe($priceMinor)->and($order->snapshot['approval_rules']['first_limit_minor'])->toBe(2500000);
|
|
})->with([[2500000, 1], [2500001, 2], [15000000, 2], [15000001, 3]]);
|
|
|
|
test('stored tax basis governs the final approval tier', function (bool $includesTax, int $count) {
|
|
awardPrices($this, 2500000, 16);
|
|
$rules = $this->r->approval_snapshot;
|
|
$rules['approval_includes_tax'] = $includesTax;
|
|
$this->r->update(['approval_snapshot' => $rules]);
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->approvals()->count())->toBe($count)->and($award->tax_minor)->toBe(400000)->and($award->total_minor)->toBe(2900000);
|
|
})->with([[true, 2], [false, 1]]);
|
|
|
|
test('fractional quantities and VAT remain exact in issued lines and totals', function () {
|
|
$this->item->update(['quantity' => '1.125', 'tax_rate' => '16']);
|
|
foreach ([[123, 138, 22, 160], [223, 251, 40, 291], [323, 363, 58, 421]] as $index => [$unit, $subtotal, $tax, $total]) {
|
|
$q = $this->quotes[$index];
|
|
$q->items()->update(['quantity' => '1.125', 'tax_rate' => '16', 'unit_price_minor' => $unit, 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $total]);
|
|
$q->update(['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $total]);
|
|
}
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
expect($order->subtotal_minor)->toBe(138)->and($order->tax_minor)->toBe(22)->and($order->total_minor)->toBe(160);
|
|
expect($order->items()->firstOrFail()->quantity)->toBe('1.125');
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1,60 MZN')->assertSee('Não autoriza compras reais');
|
|
});
|
|
|
|
test('ties allow a justified choice between top scoring proposals', function () {
|
|
foreach ($this->quotes as $q) {
|
|
$q->items()->update(['unit_price_minor' => 10000, 'subtotal_minor' => 10000, 'total_minor' => 10000]);
|
|
$q->update(['subtotal_minor' => 10000, 'total_minor' => 10000]);
|
|
}
|
|
$this->selection['quotation_id'] = $this->quotes[2]->id;
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->quotation_id)->toBe($this->quotes[2]->id);
|
|
});
|
|
|
|
test('non top selection and quote exemptions remain blocked without policy', function () {
|
|
$this->post($this->awardUrl, [...$this->selection, 'quotation_id' => $this->quotes[2]->id])->assertSessionHasErrors('quotation_id');
|
|
$this->post($this->awardUrl, [...$this->selection, 'override' => true])->assertSessionHasErrors('override');
|
|
$this->quotes[2]->update(['valid_until' => now()->subDay()]);
|
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('comparison');
|
|
expect(PurchaseAward::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('two currently eligible independent evaluators are required for every proposal', function (string $change) {
|
|
if ($change === 'role') {
|
|
$this->finance->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
|
} elseif ($change === 'absence') {
|
|
$this->quotes[0]->evaluations()->where('evaluator_id', $this->finance->id)->update(['no_conflict' => false]);
|
|
} elseif ($change === 'requester') {
|
|
$this->quotes[0]->evaluations()->where('evaluator_id', $this->finance->id)->update(['evaluator_id' => $this->owner->id]);
|
|
$this->owner->forceFill(['purchasing_role' => PurchasingRole::Finance])->save();
|
|
} else {
|
|
$this->quotes[0]->evaluations()->where('evaluator_id', $this->finance->id)->delete();
|
|
}
|
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('comparison');
|
|
})->with(['role', 'absence', 'requester', 'missing']);
|
|
|
|
test('invalid source policy approval or unsupported purchase type cannot be presumed valid', function (string $change, string $error) {
|
|
if ($change === 'snapshot') {
|
|
$this->r->update(['approval_snapshot' => null]);
|
|
} elseif ($change === 'approval') {
|
|
$this->r->steps()->update(['decision' => 'pending']);
|
|
} else {
|
|
$this->item->update(['purchase_type' => $change]);
|
|
}
|
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors($error);
|
|
expect(PurchaseAward::query()->count())->toBe(0);
|
|
})->with([['snapshot', 'policy'], ['approval', 'approvals'], ['equipment', 'purchase_type'], ['spare_part', 'purchase_type']]);
|
|
|
|
test('award approvals enforce role order department distinct people and no self approval', function () {
|
|
awardPrices($this, 15000001);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->finance)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
$this->actingAs($this->admin)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
$otherDepartment = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro']);
|
|
$otherHead = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $otherDepartment->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
|
$this->actingAs($otherHead)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
$this->actingAs($this->head)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
|
$this->head->forceFill(['purchasing_role' => PurchasingRole::Procurement])->save();
|
|
$this->actingAs($this->head)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
$this->actingAs($this->secondBuyer)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
|
$this->actingAs($this->finance)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
|
|
});
|
|
|
|
test('rejection requires a reason and prevents issuance', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->head)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'rejected'])->assertSessionHasErrors('comment');
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'rejected', 'comment' => 'Necessário rever a necessidade e a proposta.'])->assertSessionHasNoErrors();
|
|
expect($award->refresh()->status)->toBe('rejected');
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
|
|
});
|
|
|
|
test('issuer revalidates suspension expiry conflicts and evaluator eligibility after approval', function (string $change) {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
if ($change === 'suspension') {
|
|
$this->suppliers[0]->update(['status' => 'suspended']);
|
|
} elseif ($change === 'expiry') {
|
|
$this->quotes[0]->update(['valid_until' => now()->subDay()]);
|
|
} elseif ($change === 'role') {
|
|
$this->finance->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
|
|
} else {
|
|
$user = $change === 'conflict_evaluator' ? $this->finance : $this->head;
|
|
$this->actingAs($user)->post('/conflitos', ['scope' => 'supplier', 'supplier_id' => $this->suppliers[0]->id, 'has_conflict' => true, 'known_since' => now()->format('Y-m-d'), 'reason' => 'Conflito conhecido após a avaliação e aprovação.'])->assertSessionHasNoErrors();
|
|
}
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
})->with(['suspension', 'expiry', 'role', 'conflict_evaluator', 'conflict_approver']);
|
|
|
|
test('changed prices or matrix after award cannot reuse approvals', function () {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
awardPrices($this, 10001);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('comparison');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('invalid line totals are rejected instead of trusting stored totals', function () {
|
|
$this->quotes[0]->items()->update(['tax_minor' => 99]);
|
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('comparison');
|
|
});
|
|
|
|
test('repeated issuance returns the same order and does not duplicate audit or lines', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect('/ordens/'.$order->id);
|
|
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->items()->count())->toBe(1);
|
|
expect(AuditLog::query()->where('action', 'purchase_order.issued')->count())->toBe(1);
|
|
$this->post($this->awardUrl, $this->selection)->assertSessionHasErrors('award');
|
|
});
|
|
|
|
test('database uniqueness prevents a second document for the same process', function () {
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
$duplicate = $order->getAttributes();
|
|
unset($duplicate['id']);
|
|
$duplicate['number'] = 'OC-DUPLICATE';
|
|
expect(fn () => DB::table('purchase_orders')->insert($duplicate))->toThrow(QueryException::class);
|
|
});
|
|
|
|
test('changes after issuance cannot rewrite supplier terms evaluations or printed content', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
$snapshot = $order->snapshot;
|
|
$this->suppliers[0]->update(['name' => 'Nome posterior', 'address' => 'Morada posterior']);
|
|
$this->quotes[0]->update(['payment_terms' => 'Pagamento posterior']);
|
|
$this->quotes[0]->evaluations()->update(['quality' => 1]);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertRedirect('/ordens/'.$order->id);
|
|
expect($order->refresh()->snapshot)->toBe($snapshot);
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Fornecedor 0')->assertDontSee('Nome posterior')->assertDontSee('Pagamento posterior');
|
|
expect(fn () => $order->update(['total_minor' => 1]))->toThrow(LogicException::class);
|
|
});
|
|
|
|
test('new quotations and evaluations cannot change a selected comparison', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$this->post('/requisicoes/'.$this->r->id.'/cotacoes', ['supplier_id' => $this->suppliers[0]->id, 'reference' => 'Nova', 'delivery_days' => 1, 'valid_until' => now()->addWeek()->format('Y-m-d'), 'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $this->item->id, 'unit_price' => '1']]])->assertSessionHasErrors('award');
|
|
$this->actingAs($this->secondBuyer)->post('/cotacoes/'.$this->quotes[0]->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8', 'comment' => 'Nova avaliação depois da selecção.', 'no_conflict' => true])->assertSessionHasErrors('award');
|
|
expect($award->approvals()->firstOrFail()->decision)->toBe('pending');
|
|
});
|
|
|
|
test('browser cannot set award or order money status or override rules', function () {
|
|
$this->post($this->awardUrl, [...$this->selection, 'total_minor' => 1, 'status' => 'approved'])->assertSessionHasErrors(['total_minor', 'status']);
|
|
$award = selectPurchaseAward($this);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir', ['total_minor' => 1, 'status' => 'paid', 'override' => true])->assertSessionHasErrors(['total_minor', 'status', 'override']);
|
|
});
|
|
|
|
test('award and order operations restrict profiles and departments', function (PurchasingRole $role) {
|
|
$award = selectPurchaseAward($this);
|
|
$user = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => $role]);
|
|
$this->actingAs($user)->post($this->awardUrl, $this->selection)->assertForbidden();
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertForbidden();
|
|
if (in_array($role, [PurchasingRole::Requester, PurchasingRole::Warehouse])) {
|
|
$this->get('/ordens')->assertForbidden();
|
|
$this->get($this->awardUrl)->assertForbidden();
|
|
}
|
|
})->with([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::DepartmentHead, PurchasingRole::Requester, PurchasingRole::Warehouse]);
|
|
|
|
test('other companies cannot select approve issue list read or print documents', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
$tenant = Tenant::query()->create(['name' => 'Outra empresa']);
|
|
$user = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
|
$this->actingAs($user)->get('/ordens')->assertInertia(fn (Assert $page) => $page->has('orders.data', 0)->has('awards.data', 0));
|
|
$this->get($this->awardUrl)->assertNotFound();
|
|
$this->post($this->awardUrl, $this->selection)->assertNotFound();
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertNotFound();
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertNotFound();
|
|
$this->get('/ordens/'.$order->id)->assertNotFound();
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertNotFound();
|
|
});
|
|
|
|
test('audit failure rolls back issuance including document lines and number', function () {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->mock(RequisitionWorkflow::class, function ($mock) {
|
|
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Falha de auditoria da emissão.'));
|
|
});
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertStatus(500);
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
$this->assertDatabaseCount('purchase_order_items', 0);
|
|
expect($award->refresh()->status)->toBe('approved');
|
|
});
|
|
|
|
test('audit failure rolls back award and its approval cycle', function () {
|
|
$this->mock(RequisitionWorkflow::class, function ($mock) {
|
|
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Falha de auditoria da adjudicação.'));
|
|
});
|
|
$this->post($this->awardUrl, $this->selection)->assertStatus(500);
|
|
expect(PurchaseAward::query()->count())->toBe(0);
|
|
$this->assertDatabaseCount('purchase_award_approvals', 0);
|
|
});
|
|
|
|
test('supplier names are frozen at issuance rather than read from live records', function () {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->suppliers[0]->update(['name' => 'Nome validado antes de emitir']);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
$order = PurchaseOrder::query()->firstOrFail();
|
|
expect($order->snapshot['supplier']['name'])->toBe('Nome validado antes de emitir');
|
|
expect($order->snapshot['decision_matrix'][0]['supplier']['name'])->toBe('Nome validado antes de emitir');
|
|
});
|
|
|
|
test('print escapes supplied HTML and keeps the development and budget notices', function () {
|
|
$this->selection['justification'] = 'Fundamento escrito <script>alert(1)</script> para teste de impressão.';
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('<script>', false)->assertDontSee('<script>alert(1)</script>', false)->assertSee('Orçamento não verificado')->assertSee('Não autoriza compras reais');
|
|
});
|
|
|
|
test('department heads cannot read or print another departments order', function () {
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
$other = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Departamento distinto']);
|
|
$head = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $other->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
|
$this->actingAs($head)->get('/ordens')->assertInertia(fn (Assert $page) => $page->has('orders.data', 0)->has('awards.data', 0));
|
|
$this->get('/ordens/'.$order->id)->assertNotFound();
|
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertNotFound();
|
|
$this->get($this->awardUrl)->assertNotFound();
|
|
});
|
|
|
|
test('quotation from a different process cannot be selected', function () {
|
|
$other = $this->r->replicate();
|
|
$other->number = 'REQ-OTHER';
|
|
$other->save();
|
|
$q = $this->quotes[0]->replicate();
|
|
$q->requisition_id = $other->id;
|
|
$q->save();
|
|
$this->post($this->awardUrl, [...$this->selection, 'quotation_id' => $q->id])->assertNotFound();
|
|
});
|
|
|
|
test('a conflict recorded after selection blocks the remaining approvals', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->head)->post('/conflitos', ['scope' => 'process', 'requisition_id' => $this->r->id, 'has_conflict' => true, 'known_since' => now()->format('Y-m-d'), 'reason' => 'Conflito identificado antes da decisão final.'])->assertSessionHasNoErrors();
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
expect($award->approvals()->firstOrFail()->decision)->toBe('pending');
|
|
});
|
|
|
|
test('delivery dates that expire before emission are not silently replaced', function () {
|
|
$this->selection['delivery_date'] = now()->format('Y-m-d');
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->travel(1)->days();
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('delivery_date');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('spare purchase flows through award order receipt and issue with equipment trace', function () {
|
|
$level = CriticalityLevel::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->admin->id, 'code' => 'PART-TEST', 'name' => 'Normal de teste', 'criteria' => 'Critério explícito da fixture', 'is_critical' => false, 'created_at' => now()]);
|
|
$asset = Equipment::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'department_id' => $this->department->id, 'criticality_level_id' => $level->id, 'code' => 'EQ-FLOW', 'description' => 'Máquina da fixture', 'area' => 'Produção', 'status' => 'active']);
|
|
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'code' => 'PART-FLOW', 'name' => 'Peça da fixture', 'unit' => 'un']);
|
|
$part = SparePart::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'stock_item_id' => $stock->id, 'criticality_level_id' => $level->id, 'minimum_milli' => 500]);
|
|
EquipmentSparePart::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $this->buyer->id, 'equipment_id' => $asset->id, 'spare_part_id' => $part->id, 'created_at' => now()]);
|
|
$this->item->update(['purchase_type' => 'spare_part', 'spare_part_id' => $part->id, 'equipment_id' => $asset->id]);
|
|
$award = selectPurchaseAward($this);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->items()->firstOrFail()->spare_part_id)->toBe($part->id)->and($order->snapshot['equipment_context'][0]['equipment']['description'])->toBe('Máquina da fixture');
|
|
$asset->update(['description' => 'Nome actualizado']);
|
|
expect($order->refresh()->snapshot['equipment_context'][0]['equipment']['description'])->toBe('Máquina da fixture');
|
|
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
|
$this->actingAs($receiver);
|
|
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FLOW', 'name' => 'Armazém de teste']);
|
|
$receipt = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-FLOW', 'received_on' => today()->format('Y-m-d'), 'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->firstOrFail()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', $receipt)->assertCreated();
|
|
$this->postJson('/stock/operacoes', ['kind' => 'issue', 'reference' => 'SAI-FLOW', 'idempotency_key' => (string) Str::uuid(), 'warehouse_id' => $warehouse->id, 'stock_item_id' => $stock->id, 'responsible_id' => $receiver->id, 'destination' => 'Produção', 'reason' => 'Montagem no equipamento', 'quantity' => '0.500', 'equipment_id' => $asset->id])->assertCreated();
|
|
expect((int) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(500)->and(StockMovement::query()->where('equipment_id', $asset->id)->count())->toBe(2);
|
|
});
|
|
|
|
test('equipment within the explicit inclusive investment ceiling requires finance and flows through receipt', function () {
|
|
$policy = prepareEquipmentInvestment($this);
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->approvals()->pluck('role')->all())->toBe(['department_head', 'finance']);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->snapshot['investment_rules']['id'])->toBe($policy->id)
|
|
->and($order->snapshot['investment_rules']['ceiling_minor'])->toBe(10000)
|
|
->and($order->snapshot['equipment_requests'][0]['production_area'])->toBe('Linha fictícia de investimento');
|
|
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
|
$this->actingAs($receiver);
|
|
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'INV', 'name' => 'Armazém fictício']);
|
|
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'EQ-INV', 'name' => 'Equipamento recebido fictício', 'unit' => 'un']);
|
|
$this->postJson('/ordens/'.$order->id.'/recepcoes', ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-INV', 'received_on' => today()->format('Y-m-d'), 'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->firstOrFail()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]])->assertCreated();
|
|
expect((int) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000);
|
|
publishInvestmentFixture($this->tenant->id, '200.00');
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->refresh()->snapshot['investment_rules']['ceiling_minor'])->toBe(10000);
|
|
});
|
|
|
|
test('equipment above the company investment ceiling cannot be awarded', function () {
|
|
prepareEquipmentInvestment($this, '99.99');
|
|
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors('investment');
|
|
expect(PurchaseAward::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('investment tax basis is explicit and independent of ordinary approval tiers', function (bool $includesTax) {
|
|
awardPrices($this, 10000, 16);
|
|
prepareEquipmentInvestment($this, '100.00', $includesTax);
|
|
if ($includesTax) {
|
|
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors('investment');
|
|
} else {
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
expect($order->total_minor)->toBe(11600)->and($order->snapshot['investment_rules']['includes_tax'])->toBeFalse();
|
|
}
|
|
})->with([true, false]);
|
|
|
|
test('a newly published investment policy cannot reuse an existing final approval cycle', function () {
|
|
prepareEquipmentInvestment($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
publishInvestmentFixture($this->tenant->id, '200.00');
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('investment');
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('equipment cannot bypass technical finance or investment budget requirements', function (string $missing) {
|
|
prepareEquipmentInvestment($this);
|
|
if ($missing === 'technical') {
|
|
DB::table('technical_reviews')->where('requisition_id', $this->r->id)->delete();
|
|
} elseif ($missing === 'finance') {
|
|
$this->r->steps()->where('role', 'finance')->delete();
|
|
} else {
|
|
DB::table('budgets')->where('tenant_id', $this->tenant->id)->update(['kind' => 'operating']);
|
|
}
|
|
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors($missing === 'technical' ? 'technical' : ($missing === 'finance' ? 'approvals' : 'investment'));
|
|
expect(PurchaseAward::query()->count())->toBe(0);
|
|
})->with(['technical', 'finance', 'budget']);
|
|
|
|
test('purchase issuance rechecks a revoked procurement role inside transaction', function () {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer);
|
|
DB::table('users')->where('id', $this->buyer->id)->update(['purchasing_role' => 'warehouse']);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertForbidden();
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('final approval rechecks a department head who moved departments', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$department = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro departamento fictício']);
|
|
$this->actingAs($this->head);
|
|
DB::table('users')->where('id', $this->head->id)->update(['department_id' => $department->id]);
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
expect($award->approvals()->where('decision', 'approved')->count())->toBe(0);
|
|
});
|
|
|
|
function enablePurchaseCancellation(object $test): PurchaseControlPolicy
|
|
{
|
|
$admins = [$test->admin, User::factory()->create(['tenant_id' => $test->tenant->id, 'purchasing_role' => PurchasingRole::Admin]), User::factory()->create(['tenant_id' => $test->tenant->id, 'purchasing_role' => PurchasingRole::Admin])];
|
|
$test->actingAs($admins[0]);
|
|
$workflow = app(PurchaseControlPolicyWorkflow::class);
|
|
$policy = $workflow->propose($admins[0], ['previous_id' => 0, 'mode' => 'unissued_award', 'enabled' => true, 'valid_from' => today()->format('Y-m-d'), 'valid_until' => today()->addMonth()->format('Y-m-d'), 'reason' => 'Regra fictícia para teste isolado']);
|
|
foreach ([$admins[1], $admins[2]] as $admin) {
|
|
$test->actingAs($admin);
|
|
$workflow->review($admin, $policy, 'approved', 'Validação independente fictícia');
|
|
}
|
|
|
|
return $policy->refresh();
|
|
}
|
|
|
|
test('cancellation requires an explicitly published company policy', function () {
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasErrors('cancellation');
|
|
expect(AwardCancellation::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('pending cancellation freezes final approval and rejection resumes the original process', function () {
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
|
|
$this->actingAs($this->head)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasErrors('cancellation');
|
|
$cancel = AwardCancellation::query()->firstOrFail();
|
|
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'rejected', 'reason' => 'Manter o processo original fictício'])->assertSessionHasNoErrors();
|
|
issuePurchaseOrder($this, $award);
|
|
expect(PurchaseOrder::query()->count())->toBe(1);
|
|
});
|
|
|
|
test('approved cancellation preserves history and creates exactly one fresh requester draft', function () {
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$steps = $award->approvals()->count();
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('cancellation');
|
|
$cancel = AwardCancellation::query()->firstOrFail();
|
|
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'approved', 'reason' => 'Cancelamento independente fictício'])->assertSessionHasNoErrors();
|
|
expect($award->refresh()->status)->toBe('cancelled')->and($this->r->refresh()->status)->toBe('cancelled')->and($award->approvals()->count())->toBe($steps)->and(Quotation::query()->count())->toBe(3);
|
|
$this->actingAs($this->owner);
|
|
$data = ['needed_by' => today()->addWeek()->format('Y-m-d'), 'justification' => 'Nova necessidade fictícia actualizada'];
|
|
$this->post('/cancelamentos/'.$cancel->id.'/revisao', $data)->assertSessionHasNoErrors();
|
|
$this->post('/cancelamentos/'.$cancel->id.'/revisao', $data)->assertSessionHasNoErrors();
|
|
$link = PurchaseRevision::query()->sole();
|
|
$draft = Requisition::query()->findOrFail($link->requisition_id);
|
|
expect($draft->status)->toBe('draft')->and($draft->steps()->count())->toBe(0)->and($draft->items()->count())->toBe(1)->and($draft->total_minor)->toBe($this->r->total_minor)->and(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('issued orders cannot enter the cancellation circuit', function () {
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
issuePurchaseOrder($this, $award);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Tentativa fictícia após emissão'])->assertSessionHasErrors('cancellation');
|
|
expect(AwardCancellation::query()->count())->toBe(0)->and(PurchaseOrder::query()->count())->toBe(1);
|
|
});
|
|
|
|
test('cancellation cannot be self reviewed after a role change', function () {
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
|
|
$cancel = AwardCancellation::query()->firstOrFail();
|
|
DB::table('users')->where('id', $this->buyer->id)->update(['purchasing_role' => 'finance']);
|
|
$this->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'approved', 'reason' => 'Tentativa de auto aprovação fictícia'])->assertForbidden();
|
|
expect($cancel->refresh()->status)->toBe('pending');
|
|
});
|
|
|
|
test('cancellation releases the unused budget reservation exactly once', function () {
|
|
prepareEquipmentInvestment($this);
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
|
|
$cancel = AwardCancellation::query()->firstOrFail();
|
|
$data = ['decision' => 'approved', 'reason' => 'Libertação independente fictícia'];
|
|
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', $data)->assertSessionHasNoErrors();
|
|
$this->post('/cancelamentos/'.$cancel->id.'/decidir', $data)->assertSessionHasNoErrors();
|
|
expect(BudgetEntry::query()->where('requisition_id', $this->r->id)->sum('reserved_minor'))->toBe(0)
|
|
->and(BudgetEntry::query()->where('requisition_id', $this->r->id)->where('kind', 'release')->count())->toBe(1);
|
|
});
|
|
|
|
test('cancellation and reservation release roll back together if audit fails', function () {
|
|
prepareEquipmentInvestment($this);
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade alterada para teste'])->assertSessionHasNoErrors();
|
|
$cancel = AwardCancellation::query()->firstOrFail();
|
|
$this->actingAs($this->finance);
|
|
AuditLog::creating(function (AuditLog $entry) {
|
|
if ($entry->action === 'cancellation.approved') {
|
|
throw new RuntimeException('Falha fictícia de auditoria');
|
|
}
|
|
});
|
|
try {
|
|
expect(fn () => app(PurchaseRevisionWorkflow::class)->review($this->finance, $cancel, 'approved', 'Teste de atomicidade fictício'))->toThrow(RuntimeException::class);
|
|
} finally {
|
|
AuditLog::flushEventListeners();
|
|
}
|
|
expect($cancel->refresh()->status)->toBe('pending')->and($award->refresh()->status)->toBe('pending')
|
|
->and(BudgetEntry::query()->where('kind', 'release')->count())->toBe(0)
|
|
->and((int) BudgetEntry::query()->sum('reserved_minor'))->toBeGreaterThan(0);
|
|
});
|
|
|
|
test('documentary noncompliance does not silently exclude an otherwise eligible award', function () {
|
|
$opening = app(ProposalOpeningWorkflow::class);
|
|
$comparison = app(ProposalComparison::class)->inspect($this->r);
|
|
$this->actingAs($this->buyer)->post('/requisicoes/'.$this->r->id.'/qualificacao', ['previous_id' => 0, 'basis_hash' => $opening->basis($opening->proposals($this->r)), 'reason' => 'Requisito documental fictício do processo', 'criteria' => [['label' => 'Requisito documental para conferência', 'category' => 'administrative', 'required' => true]]])->assertSessionHasNoErrors();
|
|
$set = QualificationSet::query()->sole();
|
|
$this->actingAs($this->finance)->post('/qualificacoes/'.$set->id.'/analises', ['previous_id' => 0, 'quotation_id' => $this->quotes[0]->id, 'reason' => 'Registo documental sem decisão formal', 'answers' => [['criterion_id' => 1, 'result' => 'not_met', 'evidence' => 'Referência de teste fictícia', 'reason' => 'Não conformidade registada para apreciação']]])->assertSessionHasNoErrors();
|
|
expect(app(ProposalComparison::class)->inspect($this->r))->toBe($comparison);
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
expect($order->total_minor)->toBe(10000)->and(PurchaseOrder::query()->count())->toBe(1);
|
|
});
|
|
|
|
test('review report reflects tied source scores and existing frozen orders without deciding a winner', function () {
|
|
foreach ($this->quotes as $quote) {
|
|
$quote->items()->update(['unit_price_minor' => 10000, 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
|
$quote->update(['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$comparison = app(ProposalComparison::class)->inspect($this->r);
|
|
$report = app(ProcurementReviewReport::class)->build($this->buyer, $this->r->id);
|
|
expect($report['comparison']['ready'])->toBeTrue()->and($report['comparison']['top_count'])->toBe(3)
|
|
->and(array_column($report['comparison']['rows'], 'score_minor'))->toBe(array_column($comparison['rows'], 'score_minor'))
|
|
->and($report)->not->toHaveKey('recommended_supplier_id');
|
|
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
|
$report = app(ProcurementReviewReport::class)->build($this->buyer, $this->r->id);
|
|
expect($report['order']['number'])->toBe($order->number)->and($report['order']['total_minor'])->toBe(10000);
|
|
});
|
|
|
|
test('adopted formal admission preserves scoring and binds award and issued order', function () {
|
|
$before = app(ProposalComparison::class)->inspect($this->r);
|
|
prepareFormalAwardAdmission($this);
|
|
$after = app(ProposalComparison::class)->inspect($this->r);
|
|
expect($after['ready'])->toBeTrue()->and(array_column($after['rows'], 'score_minor'))->toBe(array_column($before['rows'], 'score_minor'));
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->admission_snapshot['review_ids'])->toHaveCount(2)->and($award->admission_snapshot['adoption_id'])->toBeGreaterThan(0);
|
|
$order = issuePurchaseOrder($this, $award);
|
|
expect($order->snapshot['admission'])->toBe($award->admission_snapshot);
|
|
$this->suppliers[0]->update(['name' => 'Alteração posterior à emissão']);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(1)->and($order->refresh()->snapshot['supplier']['name'])->toBe('Fornecedor 0');
|
|
$this->post('/requisicoes/'.$this->r->id.'/admissao/adoptar', ['policy_id' => 1, 'previous_id' => 1, 'reason' => 'Tentativa após a emissão'])->assertSessionHasErrors('admission');
|
|
});
|
|
|
|
test('formal exclusions cannot enter selection and minimum three eligible suppliers remains', function () {
|
|
prepareFormalAwardAdmission($this);
|
|
$workflow = app(FormalAdmission::class);
|
|
$adoption = $workflow->adoption($this->r);
|
|
$previous = AdmissionDecision::query()->where('quotation_id', $this->quotes[0]->id)->latest('id')->firstOrFail();
|
|
$decision = $workflow->propose($this->buyer, $this->r, ['quotation_id' => $this->quotes[0]->id, 'previous_id' => $previous->id, 'basis_hash' => $previous->basis_hash, 'outcome' => 'exclude', 'reason' => 'Exclusão fictícia fundamentada']);
|
|
foreach ([$this->finance, $this->head] as $reviewer) {
|
|
$this->actingAs($reviewer);
|
|
$workflow->review($reviewer, $decision, 'approved', 'Conferência de exclusão fictícia');
|
|
}
|
|
expect($workflow->status($decision, $adoption))->toBe('confirmed')->and(app(ProposalComparison::class)->inspect($this->r)['ready'])->toBeFalse();
|
|
$this->actingAs($this->buyer)->post($this->awardUrl, $this->selection)->assertSessionHasErrors();
|
|
expect(PurchaseAward::query()->count())->toBe(0)->and(BudgetEntry::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('admission basis changes block emission and existing legacy award cannot adopt retroactively', function () {
|
|
prepareFormalAwardAdmission($this);
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->suppliers[0]->update(['name' => 'Nome alterado antes de emitir']);
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('legacy award keeps null admission basis and refuses later adoption', function () {
|
|
$award = selectPurchaseAward($this);
|
|
expect($award->admission_snapshot)->toBeNull();
|
|
$this->actingAs($this->admin);
|
|
$policy = app(FormalAdmission::class)->policy($this->admin, ['previous_id' => 0, 'enabled' => true, 'roles' => ['finance'], 'required_count' => 1, 'reason' => 'Política fictícia posterior']);
|
|
$this->actingAs($this->buyer)->post('/requisicoes/'.$this->r->id.'/admissao/adoptar', ['policy_id' => $policy->id, 'previous_id' => 0, 'reason' => 'Adopção retroactiva impedida'])->assertSessionHasErrors('admission');
|
|
expect(AdmissionAdoption::query()->count())->toBe(0);
|
|
issuePurchaseOrder($this, $award);
|
|
});
|
|
|
|
test('task inbox follows every final award approval and hands approved issuance back to procurement', function () {
|
|
awardPrices($this, 30000000);
|
|
$award = selectPurchaseAward($this);
|
|
$this->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
foreach ([$this->head, $this->secondBuyer, $this->finance] as $reviewer) {
|
|
$this->actingAs($reviewer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)
|
|
->where('tasks.data.0.task', 'award_approve')->where('tasks.data.0.href', $this->awardUrl));
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
|
$this->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
}
|
|
$this->actingAs($this->buyer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)->where('tasks.data.0.task', 'order_issue_review'));
|
|
$this->get($this->awardUrl)->assertInertia(fn (Assert $page) => $page->where('canIssue', true));
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(1);
|
|
$this->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
});
|
|
|
|
test('task inbox respects pending cancellation and consultation leaves award budget and audit untouched', function () {
|
|
enablePurchaseCancellation($this);
|
|
$award = selectPurchaseAward($this);
|
|
$this->actingAs($this->head)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1));
|
|
$this->actingAs($this->buyer)->post('/adjudicacoes/'.$award->id.'/cancelamento', ['reason' => 'Necessidade fictícia em conferência'])->assertSessionHasNoErrors();
|
|
$before = [$award->fresh()->toArray(), $award->approvals()->get()->toArray(), BudgetEntry::query()->get()->toArray(), AuditLog::query()->count()];
|
|
$this->actingAs($this->head)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
$this->get($this->awardUrl)->assertInertia(fn (Assert $page) => $page->where('canDecide', false));
|
|
expect([$award->fresh()->toArray(), $award->approvals()->get()->toArray(), BudgetEntry::query()->get()->toArray(), AuditLog::query()->count()])->toEqual($before);
|
|
$cancel = AwardCancellation::query()->sole();
|
|
$this->actingAs($this->finance)->post('/cancelamentos/'.$cancel->id.'/decidir', ['decision' => 'rejected', 'reason' => 'Manter o processo sintético original'])->assertSessionHasNoErrors();
|
|
$this->actingAs($this->head)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1));
|
|
});
|
|
|
|
test('task inbox cannot grant an award decision to maintenance or a revoked department role', function () {
|
|
$award = selectPurchaseAward($this);
|
|
supplyGrant($this->head, ['department_head']);
|
|
DB::table('organization_memberships')->where('user_id', $this->head->id)->update(['maintenance' => true, 'expires_at' => now()->addHour()]);
|
|
$this->actingAs($this->head)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
$this->get($this->awardUrl)->assertInertia(fn (Assert $page) => $page->where('canDecide', false));
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
|
DB::table('organization_memberships')->where('user_id', $this->head->id)->update(['maintenance' => false, 'expires_at' => now()->subMinute()]);
|
|
$this->actingAs($this->head->fresh())->get('/requisicoes/tarefas?module=purchases')->assertForbidden();
|
|
expect($award->fresh()->status)->toBe('pending')->and(PurchaseOrder::query()->count())->toBe(0);
|
|
});
|
|
|
|
test('task inbox issuance review does not override a proposal that expired after approval', function () {
|
|
$award = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $award);
|
|
$this->quotes[0]->update(['valid_until' => today()->subDay()]);
|
|
$this->actingAs($this->buyer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)->where('tasks.data.0.task', 'order_issue_review'));
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors();
|
|
expect(PurchaseOrder::query()->count())->toBe(0)->and($award->fresh()->status)->toBe('approved');
|
|
});
|
|
|
|
test('quotation tasks hand a ready comparison to adjudication without reopening rejected awards', function () {
|
|
$this->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)->where('tasks.data.0.task', 'comparison_review'));
|
|
$award = selectPurchaseAward($this);
|
|
$this->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
$this->actingAs($this->head)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 1)->where('tasks.data.0.task', 'award_approve'));
|
|
$this->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'rejected', 'comment' => 'Devolver ao percurso autorizado de revisão.'])->assertSessionHasNoErrors();
|
|
$this->actingAs($this->buyer)->get('/requisicoes/tarefas?module=purchases')->assertInertia(fn (Assert $page) => $page->where('tasks.total', 0));
|
|
$this->get('/requisicoes/'.$this->r->id.'/cotacoes')->assertInertia(fn (Assert $page) => $page->where('canCreate', false)->where('canEvaluate', false));
|
|
});
|
|
|
|
test('optional partial-order preparation reuses native final approvals and preserves all documents and financial effects', function () {
|
|
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
|
$this->markTestSkipped('Explicit unpublished common source required.');
|
|
}
|
|
config(['order-parts.qa_enabled' => true]);
|
|
$award = selectPurchaseAward($this);
|
|
$service = app(OrderPartsPreparation::class);
|
|
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
|
|
$this->actingAs($this->buyer);
|
|
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
|
|
approvePurchaseAward($this, $award);
|
|
$this->actingAs($this->buyer);
|
|
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
|
|
$result = $service->prepare($this->buyer, $input);
|
|
expect($result)->toMatchArray(['currency' => 'MZN', 'subtotal_minor' => 4000, 'tax_minor' => 0, 'total_minor' => 4000, 'issued' => false, 'budget_effects' => false])
|
|
->and($result['sources'][0]['items'][0]['quantity_offset_milli'])->toBe(0)
|
|
->and($service->prepare($this->buyer, $input)['fingerprint'])->toBe($result['fingerprint'])
|
|
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
|
|
$this->actingAs($this->finance);
|
|
expect(fn () => $service->prepare($this->finance, $input))->toThrow(HttpException::class);
|
|
$this->actingAs($this->buyer);
|
|
$bad = $input;
|
|
$bad['sources'][0]['items'][0]['quantity'] = '1.001';
|
|
expect(fn () => $service->prepare($this->buyer, $bad))->toThrow(ValidationException::class);
|
|
config(['order-parts.qa_enabled' => false]);
|
|
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(HttpException::class);
|
|
config(['order-parts.qa_enabled' => true]);
|
|
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors();
|
|
expect(fn () => $service->prepare($this->buyer, $input))->toThrow(ValidationException::class);
|
|
});
|
|
|
|
test('optional partial-order preparation consolidates two independently approved native origins without issuing or averaging data', function () {
|
|
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
|
$this->markTestSkipped('Explicit unpublished common source required.');
|
|
}
|
|
config(['order-parts.qa_enabled' => true]);
|
|
$first = selectPurchaseAward($this);
|
|
approvePurchaseAward($this, $first);
|
|
$this->actingAs($this->buyer);
|
|
$secondRequest = $this->r->fresh()->replicate();
|
|
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
|
|
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
|
|
$secondRequest->save();
|
|
$line = $this->item->replicate();
|
|
$line->requisition_id = $secondRequest->id;
|
|
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
|
|
$line->save();
|
|
foreach ($this->r->steps()->get() as $step) {
|
|
$copy = $step->replicate();
|
|
$copy->requisition_id = $secondRequest->id;
|
|
$copy->save();
|
|
}
|
|
$quotes = [];
|
|
foreach ($this->suppliers as $index => $supplier) {
|
|
$this->actingAs($this->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
|
|
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
|
|
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
|
|
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
|
|
$quotes[] = $quote;
|
|
foreach ([$this->buyer, $this->finance] as $evaluator) {
|
|
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
|
|
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
|
|
}
|
|
}
|
|
$this->actingAs($this->buyer);
|
|
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
|
|
approvePurchaseAward($this, $second);
|
|
$this->actingAs($this->buyer);
|
|
$before = [PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()];
|
|
$input = ['sources' => [
|
|
['award_id' => $second->id, 'items' => [['quotation_item_id' => $quotes[0]->items()->sole()->id, 'quantity' => '0.500']]],
|
|
['award_id' => $first->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]],
|
|
]];
|
|
$result = app(OrderPartsPreparation::class)->prepare($this->buyer, $input);
|
|
expect($result)->toMatchArray(['currency' => 'MZN', 'total_minor' => 14000, 'issued' => false, 'budget_effects' => false])
|
|
->and($result['sources'])->toHaveCount(2)
|
|
->and(array_column($result['sources'], 'requisition_id'))->toBe([$this->r->id, $secondRequest->id])
|
|
->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null])
|
|
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
|
|
});
|