Files
compras/tests/Feature/ReceiptQuantityConversionTest.php
T
nala 12dd6df28a
tests / ci (push) Waiting to run
commit melhorias compras1
2026-11-21 21:04:40 +02:00

184 lines
12 KiB
PHP

<?php
use App\Enums\PurchasingRole;
use App\Models\GoodsReceipt;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\StockMovement;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptStockMovement;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StockWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['inventory_conversion.qa_enabled' => true]);
$this->f = receiptFixture();
// New consistent synthetic process: 2 boxes x 100 MZN = 200 MZN. Original fixture is untouched.
$request = $this->f['r']->replicate();
$request->forceFill(['number' => 'QA-CONVERSION-REQUEST', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$requested = $this->f['r']->items()->sole()->replicate();
$requested->forceFill(['requisition_id' => $request->id, 'quantity' => '2.000', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$oldAward = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id);
$quote = Quotation::query()->findOrFail($oldAward->quotation_id)->replicate();
$quote->forceFill(['requisition_id' => $request->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$award = $oldAward->replicate();
$award->forceFill(['requisition_id' => $request->id, 'quotation_id' => $quote->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$order = $this->f['order']->replicate();
$order->forceFill(['number' => 'QA-CONVERSION-ORDER', 'requisition_id' => $request->id, 'purchase_award_id' => $award->id, 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$line = $this->f['line']->replicate();
$line->forceFill(['purchase_order_id' => $order->id, 'requisition_item_id' => $requested->id, 'quantity' => '2.000', 'subtotal_minor' => 20000, 'total_minor' => 20000])->save();
$this->f['line'] = $line;
$this->f['order'] = $order;
$this->f['r'] = $request;
$this->f['stock']->update(['unit' => 'un']);
$this->actingAs($this->f['receiver']);
$this->url = '/ordens/'.$order->id.'/recepcoes';
$this->conversion = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de teste', 'version' => 'QA-1'];
$this->body = receiptPayload($this->f, '2.000');
$this->body['items'][0]['conversion'] = $this->conversion;
});
test('two boxes retain two documentary units and 200 MZN while crediting exactly 24 physical units once', function () {
$id = $this->postJson($this->url, $this->body)->assertCreated()->json('id');
$this->postJson($this->url, $this->body)->assertOk()->assertJsonPath('id', $id);
$line = GoodsReceipt::query()->findOrFail($id)->items()->sole();
$movement = StockMovement::query()->sole();
expect($line->accepted_milli)->toBe(2000)->and($movement->quantity_milli)->toBe(24000)
->and($this->f['order']->fresh()->total_minor)->toBe(20000)
->and($this->f['line']->fresh()->unit_price_minor)->toBe(10000)
->and($movement->snapshot['quantity_conversion']['source'])->toBe($this->conversion['source']);
$result = DB::transaction(function () use ($line, $movement) {
app(ConflictGuard::class)->lockCompany($this->f['receiver']);
return app(ReceiptStockMovement::class)->for($this->f['receiver'])->write($line->id, $movement->snapshot['inventory_source_hash']);
});
expect($result['replayed'])->toBeTrue()->and(StockMovement::query()->count())->toBe(1);
$this->get('/recepcoes/'.$id.'/imprimir')->assertOk()->assertSee('Stock: 24,000')->assertSee('versão QA-1');
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance);
$invoice = app(InvoiceWorkflow::class)->register($finance, $this->f['order'], [
'number' => 'QA-BOXES', 'issued_on' => today()->toDateString(), 'subtotal' => '200.00', 'tax' => '0.00', 'total' => '200.00',
'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '2.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']],
]);
expect($invoice->total_minor)->toBe(20000)->and($invoice->items()->sole()->quantity_milli)->toBe(2000);
});
test('partial receipts freeze the factor article units source and version of the order line', function () {
$body = $this->body;
$body['items'][0]['received_quantity'] = $body['items'][0]['accepted_quantity'] = '1.500';
$this->postJson($this->url, $body)->assertCreated();
$next = receiptPayload($this->f, '0.500');
$next['items'][0]['conversion'] = $this->conversion;
$bad = $next;
$bad['items'][0]['conversion']['numerator'] = '24';
$this->postJson($this->url, $bad)->assertUnprocessable();
$bad = $next;
$bad['items'][0]['conversion']['version'] = 'QA-2';
$this->postJson($this->url, $bad)->assertUnprocessable();
$this->postJson($this->url, $next)->assertCreated();
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(24000)
->and(app(ReceiptWorkflow::class)->progress($this->f['order'])['state'])->toBe('complete');
});
test('missing source factor and nonrepresentable physical quantities never create a receipt', function () {
$bad = $this->body;
unset($bad['items'][0]['conversion']);
$this->postJson($this->url, $bad)->assertUnprocessable();
$bad = $this->body;
$bad['items'][0]['conversion']['source'] = '';
$this->postJson($this->url, $bad)->assertUnprocessable();
$bad = $this->body;
$bad['items'][0]['received_quantity'] = $bad['items'][0]['accepted_quantity'] = '0.001';
$bad['items'][0]['conversion']['numerator'] = '1';
$bad['items'][0]['conversion']['denominator'] = '2';
$this->postJson($this->url, $bad)->assertUnprocessable();
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
test('conversion is not enabled by its presence in a request and cannot escape the QA guard', function () {
config(['inventory_conversion.qa_enabled' => false]);
$this->postJson($this->url, $this->body)->assertUnprocessable();
expect(StockMovement::query()->count())->toBe(0);
});
test('legacy receipt facts retain the exact v1 hash and compatible replay without a conversion basis', function () {
$this->f['stock']->update(['unit' => 'cx']);
$body = $this->body;
unset($body['items'][0]['conversion']);
$this->postJson($this->url, $body)->assertCreated();
$line = GoodsReceipt::query()->sole()->items()->sole();
$movement = StockMovement::query()->sole();
$facts = DB::table('goods_receipt_items AS l')->join('goods_receipts AS r', fn ($j) => $j->on('r.id', '=', 'l.goods_receipt_id')->on('r.tenant_id', '=', 'l.tenant_id'))
->where('l.id', $line->id)->where('l.tenant_id', $this->f['tenant']->id)
->select(['l.id', 'l.tenant_id', 'l.stock_item_id', 'l.received_milli', 'l.accepted_milli', 'l.rejected_milli', 'l.quality_status', 'l.notes',
'l.snapshot AS line_snapshot', 'r.id AS receipt_id', 'r.purchase_order_id', 'r.received_by', 'r.warehouse_id', 'r.delivery_note', 'r.received_on', 'r.confirmed_at', 'r.snapshot AS receipt_snapshot'])->first();
expect($movement->snapshot['inventory_source_hash'])->toBe(hash('sha256', json_encode((array) $facts, JSON_THROW_ON_ERROR)))
->and($movement->quantity_milli)->toBe(2000)->and($line->snapshot)->not->toHaveKey('quantity_conversion');
DB::transaction(function () use ($line, $movement) {
app(ConflictGuard::class)->lockCompany($this->f['receiver']);
expect(app(ReceiptStockMovement::class)->for($this->f['receiver'])->write($line->id, $movement->snapshot['inventory_source_hash'])['replayed'])->toBeTrue();
});
});
test('conversion cannot bypass actor eligibility and a failed audit rolls back the physical effect', function () {
$this->actingAs($this->f['issuer'])->postJson($this->url, $this->body)->assertForbidden();
$this->actingAs($this->f['receiver']);
$this->mock(RequisitionWorkflow::class, function ($mock) {
$mock->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
});
expect(fn () => app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $this->body))->toThrow(RuntimeException::class, 'Synthetic audit failure');
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
test('a supplier return uses physical units and subtracts the exact documentary equivalent for invoicing', function () {
$this->postJson($this->url, $this->body)->assertCreated();
$source = GoodsReceipt::query()->sole()->items()->sole();
supplyGrant($this->f['receiver'], ['warehouse', 'inventory_disposition_prepare']);
supplyGrant($this->f['issuer'], ['procurement', 'inventory_disposition_review']);
$data = ['kind' => 'supplier_return', 'reference' => 'QA-RETURN-BOX', 'stock_item_id' => $this->f['stock']->id,
'warehouse_id' => $this->f['warehouse']->id, 'receipt_item_id' => $source->id, 'quantity' => '6.000'];
$workflow = app(InventoryDispositions::class);
$this->actingAs($this->f['receiver']);
$draft = $workflow->save($this->f['receiver'], supplyInput($data));
expect($draft->data['document_quantity_milli'])->toBe(500);
$this->actingAs($this->f['issuer']);
$approved = $workflow->save($this->f['issuer'], supplyInput([], 'approve', $draft));
$this->actingAs($this->f['receiver']);
$workflow->save($this->f['receiver'], supplyInput(['event_on' => today()->toDateString(), 'evidence' => 'Guia sintética assinada para teste.'], 'execute', $approved));
expect($workflow->returnedForReceipt($source->id))->toBe(6000)
->and($workflow->returnedForOrderLine($this->f['line']->id))->toBe(500)
->and(app(StockWorkflow::class)->balance($this->f['stock']->id, $this->f['warehouse']->id)['quantity'])->toBe(18000)
->and(app(ReceiptWorkflow::class)->progress($this->f['order'])['lines'][0]['effective_accepted_milli'])->toBe(1500);
expect(fn () => $workflow->basis([...$data, 'quantity_milli' => 1]))->toThrow(ValidationException::class);
});
test('lot allocation and quality follow converted physical quantities rather than boxes', function () {
supplyGrant($this->f['issuer'], ['inventory_lot_prepare']);
supplyGrant($this->f['receiver'], ['warehouse', 'inventory_lot_review']);
$this->actingAs($this->f['issuer']);
$lots = app(InventoryLots::class);
$draft = $lots->save($this->f['issuer'], supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
'requires_expiry' => true, 'minimum_remaining_days' => 0, 'lots' => []], 'prepare'));
$this->actingAs($this->f['receiver']);
$lots->save($this->f['receiver'], supplyInput([], 'activate', $draft));
$bad = $this->body;
$bad['items'][0]['lots'] = [['code' => 'QA-BOX', 'expires_on' => today()->addYear()->toDateString(), 'quantity' => '2.000']];
$this->postJson($this->url, $bad)->assertUnprocessable();
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
$bad['items'][0]['lots'][0]['quantity'] = '24.000';
$this->postJson($this->url, $bad)->assertCreated();
$context = $lots->context($this->f['stock']->id, $this->f['warehouse']->id);
expect($context['reconciled'])->toBeTrue()->and($context['lots'][0]['quantity_milli'])->toBe(24000)
->and($context['usable_milli'])->toBe(0);
});