commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
+382 -3
View File
@@ -27,12 +27,16 @@ 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\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\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
use App\Services\ProposalOpeningWorkflow;
@@ -41,12 +45,387 @@ use App\Services\PurchaseRevisionWorkflow;
use App\Services\QuotationExchange;
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;
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
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);
@@ -97,7 +476,7 @@ test('foreign currency conversion determines final approval thresholds without c
test('foreign order cancellation reverses the mzn commitment while preserving the original foreign document', function () {
$this->actingAs($this->finance);
$exchange = app(\App\Services\QuotationExchange::class);
$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];
@@ -118,7 +497,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
$admins[] = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
}
$this->actingAs($admins[0]);
$policyWorkflow = app(\App\Services\OrderCancellationPolicyWorkflow::class);
$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) {
@@ -126,7 +505,7 @@ test('foreign order cancellation reverses the mzn commitment while preserving th
$policyWorkflow->review($reviewer, $policy, 'approved', 'Conferência sintética independente');
}
$this->actingAs($this->buyer);
$flow = app(\App\Services\OrderCancellationWorkflow::class);
$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);