Consolida recepcoes, stock, equipamentos e identidade SGC
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\CriticalityLevel;
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\EquipmentSparePart;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SparePart;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\StockOperation;
|
||||
use App\Models\TechnicalReview;
|
||||
use App\Models\User;
|
||||
use App\Services\EquipmentWorkflow;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
function equipmentRequestData(array $f, string $type = 'equipment'): array
|
||||
{
|
||||
return ['cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal', 'needed_by' => today()->addWeek()->format('Y-m-d'), 'justification' => 'Equipamento para uma linha de produção de teste.', 'items' => [['description' => 'Máquina de teste', 'category' => 'Produção', 'purchase_type' => $type, 'quantity' => '1', 'unit' => 'cx', 'unit_price' => '1.00', 'tax_rate' => '0', 'production_area' => 'Linha fictícia', 'equipment_id' => $f['asset']->id, 'spare_part_id' => $f['part']->id]]];
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$f = &$this->f;
|
||||
$f['admin'] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
$f['head'] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$f['finance'] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
$f['level'] = CriticalityLevel::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['admin']->id, 'code' => 'CRIT-TEST', 'name' => 'Categoria de teste', 'criteria' => 'Critério fictício definido explicitamente para teste', 'is_critical' => true, 'created_at' => now()]);
|
||||
$f['asset'] = Equipment::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'department_id' => $f['department']->id, 'criticality_level_id' => $f['level']->id, 'code' => 'EQ-TEST', 'description' => 'Compressor de teste', 'area' => 'Linha A', 'status' => 'stopped']);
|
||||
$f['part'] = SparePart::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'stock_item_id' => $f['stock']->id, 'criticality_level_id' => $f['level']->id, 'minimum_milli' => 2000]);
|
||||
EquipmentSparePart::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'equipment_id' => $f['asset']->id, 'spare_part_id' => $f['part']->id, 'created_at' => now()]);
|
||||
$this->actingAs($f['receiver']);
|
||||
});
|
||||
|
||||
test('criticality requires explicit company criteria and critical flag without defaults', function () {
|
||||
$this->actingAs($this->f['admin']);
|
||||
$this->postJson('/equipamentos/categorias', ['code' => 'NEW', 'name' => 'Nova categoria'])->assertUnprocessable()->assertJsonValidationErrors(['criteria', 'is_critical']);
|
||||
$this->post('/equipamentos/categorias', ['code' => 'NEW', 'name' => 'Nova categoria', 'criteria' => 'Critério decidido pela empresa de teste', 'is_critical' => false])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$level = CriticalityLevel::query()->where('code', 'NEW')->firstOrFail();
|
||||
expect($level->is_critical)->toBeFalse();
|
||||
expect(fn () => $level->update(['criteria' => 'Rewrite']))->toThrow(LogicException::class);
|
||||
});
|
||||
|
||||
test('only administration configures criticality', function ($role) {
|
||||
$this->f['receiver']->forceFill(['purchasing_role' => $role])->save();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->post('/equipamentos/categorias', ['code' => 'X', 'name' => 'X', 'criteria' => 'X', 'is_critical' => true])->assertForbidden();
|
||||
})->with([PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead, PurchasingRole::Requester]);
|
||||
|
||||
test('catalogue requires explicit minimum and supports optimistic audited updates', function () {
|
||||
$payload = ['id' => $this->f['part']->id, 'version' => 1, 'stock_item_id' => $this->f['stock']->id, 'criticality_level_id' => $this->f['level']->id];
|
||||
$this->postJson('/equipamentos/pecas', $payload)->assertUnprocessable()->assertJsonValidationErrors('minimum_quantity');
|
||||
$payload['minimum_quantity'] = '0';
|
||||
$this->post('/equipamentos/pecas', $payload)->assertSessionHasNoErrors();
|
||||
expect($this->f['part']->refresh()->minimum_milli)->toBe(0)->and($this->f['part']->version)->toBe(2);
|
||||
$this->postJson('/equipamentos/pecas', $payload)->assertUnprocessable()->assertJsonValidationErrors('version');
|
||||
});
|
||||
|
||||
test('warehouse stock drives minimum alert without duplicate inventory balances', function () {
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||
$this->get('/equipamentos')->assertInertia(fn (Assert $p) => $p->component('equipment/index')->where('parts.0.balance_milli', 1000)->where('parts.0.below_minimum', true));
|
||||
$this->postJson('/equipamentos/associacoes', ['equipment_id' => $this->f['asset']->id, 'spare_part_id' => $this->f['part']->id])->assertUnprocessable();
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000)->and(EquipmentSparePart::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('parts require compatible destination and snapshot equipment in issue and movement', function () {
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||
$p = ['kind' => 'issue', 'reference' => 'SAI-EQ', 'idempotency_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'responsible_id' => $this->f['receiver']->id, 'destination' => 'Linha A', 'reason' => 'Substituição de rolamento', 'quantity' => '0.500'];
|
||||
$this->postJson('/stock/operacoes', $p)->assertUnprocessable()->assertJsonValidationErrors('equipment_id');
|
||||
$p['equipment_id'] = $this->f['asset']->id;
|
||||
$this->postJson('/stock/operacoes', $p)->assertCreated();
|
||||
$this->postJson('/stock/operacoes', $p)->assertOk();
|
||||
$op = StockOperation::query()->firstOrFail();
|
||||
expect($op->equipment_id)->toBe($this->f['asset']->id)->and($op->spare_part_id)->toBe($this->f['part']->id)->and($op->snapshot['equipment']['description'])->toBe('Compressor de teste');
|
||||
$this->f['asset']->update(['description' => 'Nome novo']);
|
||||
expect($op->refresh()->snapshot['equipment']['description'])->toBe('Compressor de teste');
|
||||
$movement = StockMovement::query()->where('stock_operation_id', $op->id)->firstOrFail();
|
||||
expect($movement->equipment_id)->toBe($op->equipment_id)->and($movement->snapshot['equipment']['description'])->toBe('Compressor de teste');
|
||||
});
|
||||
|
||||
test('cross company associations and catalogue references are rejected', function ($resource) {
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
if ($resource === 'equipment') {
|
||||
$this->postJson('/equipamentos/activos', ['code' => 'OTHER', 'description' => 'Test', 'area' => 'A', 'status' => 'active', 'department_id' => $other['department']->id, 'criticality_level_id' => $this->f['level']->id])->assertUnprocessable()->assertJsonValidationErrors('department_id');
|
||||
} else {
|
||||
$this->postJson('/equipamentos/pecas', ['stock_item_id' => $other['stock']->id, 'minimum_quantity' => '0', 'criticality_level_id' => $this->f['level']->id])->assertUnprocessable()->assertJsonValidationErrors('stock_item_id');
|
||||
}
|
||||
})->with(['equipment', 'stock']);
|
||||
|
||||
test('unrelated and foreign equipment cannot receive a designated spare part', function () {
|
||||
$asset = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['receiver']->id, 'department_id' => $this->f['department']->id, 'criticality_level_id' => $this->f['level']->id, 'code' => 'UNLINKED', 'description' => 'Other', 'area' => 'A', 'status' => 'active']);
|
||||
expect(fn () => app(EquipmentWorkflow::class)->linkedPart($this->f['part']->id, $asset->id))->toThrow(ValidationException::class);
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['receiver']);
|
||||
$this->get('/equipamentos')->assertInertia(fn (Assert $p) => $p->has('equipment', 0)->has('parts', 0)->has('history.data', 0));
|
||||
$this->postJson('/equipamentos/associacoes', ['equipment_id' => $this->f['asset']->id, 'spare_part_id' => $this->f['part']->id])->assertUnprocessable()->assertJsonValidationErrors(['equipment_id', 'spare_part_id']);
|
||||
});
|
||||
|
||||
test('equipment requisition demands technical validation and adds finance for every value', function () {
|
||||
$data = equipmentRequestData($this->f);
|
||||
$this->post('/requisicoes', $data)->assertSessionHasNoErrors();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
$this->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable()->assertJsonValidationErrors('technical');
|
||||
$basis = app(EquipmentWorkflow::class)->basis($r);
|
||||
$this->actingAs($this->f['head'])->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => $basis, 'decision' => 'approved', 'reason' => 'Especificações adequadas à linha de teste'])->assertSessionHasNoErrors();
|
||||
$this->actingAs($this->f['receiver'])->post('/requisicoes/'.$r->id.'/submeter')->assertSessionHasNoErrors();
|
||||
expect($r->refresh()->status)->toBe('pending')->and($r->steps()->pluck('role')->all())->toBe(['department_head', 'finance']);
|
||||
$this->actingAs($this->f['head'])->post('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
||||
expect($r->refresh()->status)->toBe('pending');
|
||||
$this->actingAs($this->f['finance'])->post('/requisicoes/'.$r->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors();
|
||||
$this->actingAs($this->f['issuer'])->postJson('/requisicoes/'.$r->id.'/adjudicacao', ['quotation_id' => $this->f['order']->purchase_award_id, 'justification' => 'Justificação de teste', 'delivery_date' => today()->addWeek()->format('Y-m-d'), 'delivery_location' => 'Linha A'])->assertUnprocessable()->assertJsonValidationErrors('purchase_type');
|
||||
});
|
||||
|
||||
test('technical decision cannot be made by requester admin or warehouse', function ($role) {
|
||||
$r = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
$actor = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => $role]);
|
||||
if ($role === PurchasingRole::DepartmentHead) {
|
||||
$r->update(['requester_id' => $actor->id]);
|
||||
}
|
||||
$this->actingAs($actor)->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => app(EquipmentWorkflow::class)->basis($r), 'decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
|
||||
})->with([PurchasingRole::DepartmentHead, PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Finance]);
|
||||
|
||||
test('technical decision is immutable and stale review cannot approve edited request', function () {
|
||||
$r = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
$basis = app(EquipmentWorkflow::class)->basis($r);
|
||||
$this->actingAs($this->f['head'])->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => $basis, 'decision' => 'approved', 'reason' => 'Validação do teste'])->assertSessionHasNoErrors();
|
||||
$review = TechnicalReview::query()->firstOrFail();
|
||||
expect(fn () => $review->delete())->toThrow(LogicException::class);
|
||||
$data = equipmentRequestData($this->f);
|
||||
$data['justification'] = 'Mudança da finalidade técnica do equipamento';
|
||||
$this->actingAs($this->f['receiver'])->put('/requisicoes/'.$r->id, $data)->assertSessionHasNoErrors();
|
||||
$this->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable()->assertJsonValidationErrors('technical');
|
||||
$this->actingAs($this->f['head'])->postJson('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => $basis, 'decision' => 'approved', 'reason' => 'Teste'])->assertUnprocessable()->assertJsonValidationErrors('basis_hash');
|
||||
expect(TechnicalReview::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('rejected technical review does not permit submission', function () {
|
||||
$r = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
$this->actingAs($this->f['head'])->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => app(EquipmentWorkflow::class)->basis($r), 'decision' => 'rejected', 'reason' => 'Não cumpre a especificação técnica'])->assertSessionHasNoErrors();
|
||||
$this->actingAs($this->f['receiver'])->postJson('/requisicoes/'.$r->id.'/submeter')->assertUnprocessable()->assertJsonValidationErrors('technical');
|
||||
});
|
||||
|
||||
test('urgent critical spare parts require downtime without granting quotation exceptions', function () {
|
||||
$data = equipmentRequestData($this->f, 'spare_part');
|
||||
$data['priority'] = 'urgent';
|
||||
$this->postJson('/requisicoes', $data)->assertUnprocessable()->assertJsonValidationErrors('items');
|
||||
$data['items'][0]['downtime_started_at'] = now()->subHour()->format('Y-m-d\TH:i');
|
||||
$this->post('/requisicoes', $data)->assertSessionHasNoErrors();
|
||||
$r = Requisition::query()->latest('id')->firstOrFail();
|
||||
expect($r->items()->firstOrFail()->equipment_id)->toBe($this->f['asset']->id)->and($r->items()->firstOrFail()->downtime_started_at)->not->toBeNull();
|
||||
});
|
||||
|
||||
test('spare receipts preserve authorised item and equipment traceability', function () {
|
||||
$f = receiptFixture('1.000', 'spare_part');
|
||||
$this->actingAs($f['receiver']);
|
||||
// Attach already authorised links only inside the isolated fixture.
|
||||
$level = CriticalityLevel::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'code' => 'PART', 'name' => 'Test', 'criteria' => 'Fixture', 'is_critical' => false, 'created_at' => now()]);
|
||||
$asset = Equipment::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'department_id' => $f['department']->id, 'criticality_level_id' => $level->id, 'code' => 'EQ', 'description' => 'Test', 'area' => 'A', 'status' => 'active']);
|
||||
$part = SparePart::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'stock_item_id' => $f['stock']->id, 'criticality_level_id' => $level->id, 'minimum_milli' => 1000]);
|
||||
EquipmentSparePart::query()->create(['tenant_id' => $f['tenant']->id, 'created_by' => $f['receiver']->id, 'equipment_id' => $asset->id, 'spare_part_id' => $part->id, 'created_at' => now()]);
|
||||
DB::table('purchase_order_items')->where('id', $f['line']->id)->update(['equipment_id' => $asset->id, 'spare_part_id' => $part->id]);
|
||||
$this->postJson('/ordens/'.$f['order']->id.'/recepcoes', receiptPayload($f, '1.000'))->assertCreated();
|
||||
$movement = StockMovement::query()->firstOrFail();
|
||||
expect($movement->equipment_id)->toBe($asset->id)->and($movement->spare_part_id)->toBe($part->id);
|
||||
});
|
||||
|
||||
test('public equipment page has fictional props only', function () {
|
||||
$this->get('/consulta/equipamentos')->assertInertia(fn (Assert $p) => $p->component('preview/index')->where('initialScreen', 'equipment')->where('auth.user', null)->missing('equipment')->missing('parts'));
|
||||
});
|
||||
|
||||
test('technical reviewer of another department and foreign company cannot decide', function () {
|
||||
$r = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
$dept = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outra área']);
|
||||
$this->f['head']->forceFill(['department_id' => $dept->id])->save();
|
||||
$this->actingAs($this->f['head'])->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => app(EquipmentWorkflow::class)->basis($r), 'decision' => 'approved', 'reason' => 'Teste'])->assertForbidden();
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['receiver']);
|
||||
$this->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => app(EquipmentWorkflow::class)->basis($r), 'decision' => 'approved', 'reason' => 'Teste'])->assertNotFound();
|
||||
});
|
||||
|
||||
test('technical audit failure rolls back decision', function () {
|
||||
$r = app(RequisitionWorkflow::class)->save($this->f['receiver'], equipmentRequestData($this->f));
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Audit failed'));
|
||||
$this->actingAs($this->f['head']);
|
||||
$this->withoutExceptionHandling();
|
||||
try {
|
||||
$this->post('/requisicoes/'.$r->id.'/validacao-tecnica', ['basis_hash' => app(EquipmentWorkflow::class)->basis($r), 'decision' => 'approved', 'reason' => 'Teste']);
|
||||
$this->fail('Expected exception');
|
||||
} catch (RuntimeException $e) {
|
||||
expect($e->getMessage())->toBe('Audit failed');
|
||||
}
|
||||
expect(TechnicalReview::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('foreign classifications cannot be used in equipment or part configuration', function () {
|
||||
$other = receiptFixture();
|
||||
$level = CriticalityLevel::query()->create(['tenant_id' => $other['tenant']->id, 'created_by' => $other['receiver']->id, 'code' => 'FOREIGN', 'name' => 'Outra', 'criteria' => 'Fixture', 'is_critical' => false, 'created_at' => now()]);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->postJson('/equipamentos/activos', ['code' => 'FOREIGN', 'description' => 'Máquina', 'area' => 'Linha', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id])->assertUnprocessable()->assertJsonValidationErrors('criticality_level_id');
|
||||
$this->postJson('/equipamentos/pecas', ['id' => $this->f['part']->id, 'version' => 1, 'stock_item_id' => $this->f['stock']->id, 'criticality_level_id' => $level->id, 'minimum_quantity' => '1'])->assertUnprocessable()->assertJsonValidationErrors('criticality_level_id');
|
||||
});
|
||||
|
||||
test('classification and minimum edits do not erase earlier movement snapshots', function () {
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||
$p = ['kind' => 'issue', 'reference' => 'SNAP', 'idempotency_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'responsible_id' => $this->f['receiver']->id, 'destination' => 'Produção', 'reason' => 'Reposição', 'quantity' => '0.001', 'equipment_id' => $this->f['asset']->id];
|
||||
$this->postJson('/stock/operacoes', $p)->assertCreated();
|
||||
$this->post('/equipamentos/pecas', ['id' => $this->f['part']->id, 'version' => 1, 'stock_item_id' => $this->f['stock']->id, 'criticality_level_id' => $this->f['level']->id, 'minimum_quantity' => '5.000'])->assertSessionHasNoErrors();
|
||||
expect(StockOperation::query()->firstOrFail()->snapshot['spare_part']['minimum_milli'])->toBe(2000);
|
||||
});
|
||||
|
||||
test('finance can consult but cannot change equipment or parts', function () {
|
||||
$this->actingAs($this->f['finance'])->get('/equipamentos')->assertOk();
|
||||
$this->post('/equipamentos/pecas', ['stock_item_id' => $this->f['stock']->id, 'criticality_level_id' => $this->f['level']->id, 'minimum_quantity' => '1'])->assertForbidden();
|
||||
});
|
||||
|
||||
test('new catalogue forms accept empty optional identity and version fields', function () {
|
||||
$this->post('/equipamentos/activos', ['id' => '', 'version' => '', 'stock_item_id' => '', 'serial_number' => '', 'code' => 'NEW-FORM', 'description' => 'Equipamento novo', 'area' => 'Linha B', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $this->f['level']->id])->assertSessionHasNoErrors();
|
||||
expect(Equipment::query()->where('code', 'NEW-FORM')->count())->toBe(1);
|
||||
});
|
||||
@@ -3,5 +3,5 @@
|
||||
test('returns a successful response', function () {
|
||||
$response = $this->get(route('home'));
|
||||
|
||||
$response->assertRedirect('/consulta');
|
||||
$response->assertOk();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
test('home is a distinct public entry point without business data', function () {
|
||||
$this->get('/')->assertOk()->assertInertia(fn (Assert $page) => $page->component('home')->where('auth.user', null)->missing('orders')->missing('receipts')->missing('balances'));
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
test('each demo area has a dedicated address without exposing operational data', function (string $path, string $screen) {
|
||||
$this->get($path)->assertOk()->assertInertia(fn (Assert $page) => $page->component('preview/index')->where('initialScreen', $screen)->where('auth.user', null)->missing('orders')->missing('receipts')->missing('movements')->missing('balances'));
|
||||
})->with([['/consulta', 'overview'], ['/consulta/requisicoes', 'requests'], ['/consulta/fornecedores', 'suppliers'], ['/consulta/cotacoes', 'quotes'], ['/consulta/ordens', 'orders'], ['/consulta/recepcoes', 'receipts'], ['/consulta/stock', 'stock'], ['/consulta/conflitos', 'conflicts'], ['/consulta/aparencia', 'appearance']]);
|
||||
|
||||
test('home and public navigation preserve authenticated accounts without exposing identity', function () {
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user)->get('/')->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
|
||||
$this->get('/consulta/recepcoes')->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
|
||||
$this->assertAuthenticatedAs($user);
|
||||
});
|
||||
|
||||
test('public receiving and stock demos provide no mutation endpoints', function () {
|
||||
$this->post('/consulta/recepcoes', [])->assertStatus(405);
|
||||
$this->post('/consulta/stock', [])->assertStatus(405);
|
||||
$this->get('/consulta/desconhecido')->assertNotFound();
|
||||
$this->get('/recepcoes')->assertRedirect('/login');
|
||||
$this->get('/stock')->assertRedirect('/login');
|
||||
});
|
||||
@@ -3,17 +3,25 @@
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\CriticalityLevel;
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\EquipmentSparePart;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
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\RequisitionWorkflow;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
function awardPrices(object $test, int $firstPrice, int $taxRate = 0): void
|
||||
@@ -373,3 +381,24 @@ test('delivery dates that expire before emission are not silently replaced', fun
|
||||
$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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Department;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\User;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->url = '/ordens/'.$this->f['order']->id.'/recepcoes';
|
||||
$this->payload = receiptPayload($this->f);
|
||||
});
|
||||
|
||||
test('partial then total receipts preserve pending quantities and credit only accepted stock', function () {
|
||||
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertCreated()->assertJsonPath('status', 'partial');
|
||||
$first = GoodsReceipt::query()->firstOrFail();
|
||||
$this->postJson($this->url, receiptPayload($this->f, '0.600'))->assertCreated()->assertJsonPath('status', 'complete');
|
||||
$progress = app(ReceiptWorkflow::class)->progress($this->f['order']);
|
||||
expect($progress['state'])->toBe('complete')->and($progress['lines'][0]['delivery_pending_milli'])->toBe(0)->and($progress['lines'][0]['accepted_milli'])->toBe(1000);
|
||||
expect(StockMovement::query()->count())->toBe(2)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000);
|
||||
expect($first->refresh()->status)->toBe('partial');
|
||||
expect(AuditLog::query()->where('action', 'receipt.confirmed')->count())->toBe(2);
|
||||
$this->get('/stock')->assertInertia(fn (Assert $page) => $page->component('stock/index')->where('balances.0.quantity_milli', 1000)->has('movements.data', 2));
|
||||
});
|
||||
|
||||
test('overreceipt is rejected against cumulative delivered quantities', function () {
|
||||
$this->postJson($this->url, receiptPayload($this->f, '0.700'))->assertCreated();
|
||||
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertUnprocessable()->assertJsonValidationErrors('items');
|
||||
expect(GoodsReceipt::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(700);
|
||||
});
|
||||
|
||||
test('idempotent retries preserve one receipt and movement but changed payload cannot reuse the key', function () {
|
||||
$first = $this->postJson($this->url, $this->payload)->assertCreated()->json('id');
|
||||
$this->postJson($this->url, $this->payload)->assertOk()->assertJsonPath('id', $first)->assertJsonPath('created', false);
|
||||
$changed = $this->payload;
|
||||
$changed['items'][0]['received_quantity'] = '0.500';
|
||||
$changed['items'][0]['accepted_quantity'] = '0.500';
|
||||
$this->postJson($this->url, $changed)->assertUnprocessable()->assertJsonValidationErrors('idempotency_key');
|
||||
expect(GoodsReceipt::query()->count())->toBe(1)->and(StockMovement::query()->count())->toBe(1);
|
||||
expect(AuditLog::query()->where('action', 'receipt.confirmed')->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('another token cannot duplicate the same normalized delivery note', function () {
|
||||
$this->payload['delivery_note'] = 'gr teste 001';
|
||||
$this->postJson($this->url, $this->payload)->assertCreated();
|
||||
$this->payload['idempotency_key'] = (string) Str::uuid();
|
||||
$this->payload['delivery_note'] = ' GR TESTE 001 ';
|
||||
$this->postJson($this->url, $this->payload)->assertUnprocessable()->assertJsonValidationErrors('delivery_note');
|
||||
expect(StockMovement::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('reservations and rejections record divergences without crediting rejected goods or authorizing replacements', function () {
|
||||
$body = receiptPayload($this->f, '0.600');
|
||||
$body['items'][0] = [...$body['items'][0], 'accepted_quantity' => '0.400', 'quality_status' => 'reservations', 'notes' => 'Duas décimas danificadas.'];
|
||||
$this->postJson($this->url, $body)->assertCreated();
|
||||
$rejected = receiptPayload($this->f, '0.400');
|
||||
$rejected['warehouse_id'] = null;
|
||||
$rejected['items'][0] = [...$rejected['items'][0], 'accepted_quantity' => '0', 'quality_status' => 'nonconforming', 'stock_item_id' => null, 'notes' => 'Material não conforme.'];
|
||||
$this->postJson($this->url, $rejected)->assertCreated()->assertJsonPath('status', 'rejected');
|
||||
expect(StockMovement::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(400);
|
||||
$progress = app(ReceiptWorkflow::class)->progress($this->f['order']);
|
||||
expect($progress['state'])->toBe('quality_pending')->and($progress['has_divergences'])->toBeTrue();
|
||||
expect($progress['lines'][0]['delivery_pending_milli'])->toBe(0)->and($progress['lines'][0]['acceptance_pending_milli'])->toBe(600);
|
||||
$this->postJson($this->url, receiptPayload($this->f, '0.100'))->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('quality and quantity inconsistencies cannot confirm stock', function (string $received, string $accepted, string $quality, ?string $notes) {
|
||||
$this->payload['items'][0] = [...$this->payload['items'][0], 'received_quantity' => $received, 'accepted_quantity' => $accepted, 'quality_status' => $quality, 'notes' => $notes];
|
||||
$this->postJson($this->url, $this->payload)->assertUnprocessable();
|
||||
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
|
||||
})->with([['0.500', '0.600', 'reservations', 'Excesso inválido'], ['0.500', '0.400', 'compliant', null], ['0.500', '0.100', 'nonconforming', 'Não conforme'], ['0.500', '0.400', 'reservations', null], ['-1', '0', 'nonconforming', 'Negativo'], ['0.0001', '0.0001', 'compliant', null], ['0', '0', 'compliant', null]]);
|
||||
|
||||
test('stock items require the correct warehouse and unit', function (string $missing) {
|
||||
if ($missing === 'warehouse') {
|
||||
$this->payload['warehouse_id'] = null;
|
||||
} elseif ($missing === 'item') {
|
||||
$this->payload['items'][0]['stock_item_id'] = null;
|
||||
} else {
|
||||
$this->f['stock']->update(['unit' => 'kg']);
|
||||
}
|
||||
$this->postJson($this->url, $this->payload)->assertUnprocessable()->assertJsonValidationErrors('items');
|
||||
expect(StockMovement::query()->count())->toBe(0);
|
||||
})->with(['warehouse', 'item', 'unit']);
|
||||
|
||||
test('services can be accepted without creating physical stock', function () {
|
||||
$f = receiptFixture('1.000', 'service');
|
||||
$this->actingAs($f['receiver']);
|
||||
$body = receiptPayload($f, '1.000');
|
||||
$body['warehouse_id'] = null;
|
||||
$body['items'][0]['stock_item_id'] = null;
|
||||
$this->postJson('/ordens/'.$f['order']->id.'/recepcoes', $body)->assertCreated()->assertJsonPath('status', 'complete');
|
||||
expect(StockMovement::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('an issuer cannot receive their order even after becoming warehouse staff', function () {
|
||||
$this->f['issuer']->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
|
||||
$this->actingAs($this->f['issuer'])->postJson($this->url, $this->payload)->assertForbidden();
|
||||
});
|
||||
|
||||
test('confirmation is exclusive to warehouse staff', function (PurchasingRole $role) {
|
||||
$user = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => $role]);
|
||||
$this->actingAs($user)->postJson($this->url, $this->payload)->assertForbidden();
|
||||
})->with([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement, PurchasingRole::Requester, PurchasingRole::DepartmentHead]);
|
||||
|
||||
test('warehouse order view exposes receiving quantities without the financial snapshot', function () {
|
||||
$this->get($this->url)->assertInertia(fn (Assert $page) => $page->component('receipts/order')->where('canConfirm', true)->where('progress.lines.0.ordered_milli', 1000)->missing('order.snapshot')->missing('order.total_minor')->missing('order.currency'));
|
||||
$this->get('/recepcoes')->assertInertia(fn (Assert $page) => $page->has('orders.data', 1));
|
||||
});
|
||||
|
||||
test('companies cannot consult or confirm another company receipt or stock', function () {
|
||||
$id = $this->postJson($this->url, $this->payload)->assertCreated()->json('id');
|
||||
$foreign = receiptFixture();
|
||||
$this->actingAs($foreign['receiver'])->get($this->url)->assertNotFound();
|
||||
$this->postJson($this->url, $this->payload)->assertNotFound();
|
||||
$this->get('/recepcoes/'.$id)->assertNotFound();
|
||||
$this->get('/stock')->assertInertia(fn (Assert $page) => $page->has('balances', 0)->has('movements.data', 0)->has('items', 1)->where('items.0.id', $foreign['stock']->id));
|
||||
$body = receiptPayload($foreign);
|
||||
$body['warehouse_id'] = $this->f['warehouse']->id;
|
||||
$body['items'][0]['stock_item_id'] = $this->f['stock']->id;
|
||||
$this->postJson('/ordens/'.$foreign['order']->id.'/recepcoes', $body)->assertUnprocessable()->assertJsonValidationErrors(['warehouse_id', 'items.0.stock_item_id']);
|
||||
});
|
||||
|
||||
test('department heads see only their department receipts and cannot inspect stock', function () {
|
||||
$id = $this->postJson($this->url, $this->payload)->assertCreated()->json('id');
|
||||
$dept = Department::query()->create(['tenant_id' => $this->f['tenant']->id, 'name' => 'Outro departamento']);
|
||||
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $dept->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
$this->actingAs($head)->get('/recepcoes')->assertInertia(fn (Assert $page) => $page->has('orders.data', 0)->has('receipts.data', 0));
|
||||
$this->get('/recepcoes/'.$id)->assertForbidden();
|
||||
$this->get('/stock')->assertForbidden();
|
||||
$head->forceFill(['department_id' => $this->f['department']->id])->save();
|
||||
$this->actingAs($head)->get('/recepcoes/'.$id)->assertOk();
|
||||
});
|
||||
|
||||
test('a line from another order and duplicate lines are rejected', function () {
|
||||
$foreign = receiptFixture();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->payload['items'][0]['purchase_order_item_id'] = $foreign['line']->id;
|
||||
$this->postJson($this->url, $this->payload)->assertUnprocessable()->assertJsonValidationErrors('items');
|
||||
$body = receiptPayload($this->f);
|
||||
$body['items'][] = $body['items'][0];
|
||||
$this->postJson($this->url, $body)->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('receipts items and movements are append only and unsupported HTTP edits are absent', function () {
|
||||
$id = $this->postJson($this->url, $this->payload)->assertCreated()->json('id');
|
||||
$receipt = GoodsReceipt::query()->findOrFail($id);
|
||||
$item = GoodsReceiptItem::query()->firstOrFail();
|
||||
$movement = StockMovement::query()->firstOrFail();
|
||||
foreach ([$receipt, $item, $movement] as $record) {
|
||||
expect(fn () => $record->delete())->toThrow(LogicException::class);
|
||||
}
|
||||
expect(fn () => $receipt->update(['delivery_note' => 'Outra']))->toThrow(LogicException::class);
|
||||
expect(fn () => $item->update(['accepted_milli' => 1000]))->toThrow(LogicException::class);
|
||||
expect(fn () => $movement->update(['quantity_milli' => 1000]))->toThrow(LogicException::class);
|
||||
$this->put('/recepcoes/'.$id, [])->assertStatus(405);
|
||||
$this->delete('/recepcoes/'.$id)->assertStatus(405);
|
||||
});
|
||||
|
||||
test('stock is derived from receipts not initial balances supplied by browser', function () {
|
||||
$this->post('/stock/artigos', ['code' => ' novo-art ', 'name' => 'Novo artigo', 'unit' => ' CX ', 'quantity_milli' => 999999, 'tenant_id' => 999])->assertSessionHasNoErrors();
|
||||
$item = StockItem::query()->where('code', 'NOVO-ART')->firstOrFail();
|
||||
expect($item->tenant_id)->toBe($this->f['tenant']->id)->and($item->unit)->toBe('cx');
|
||||
expect(StockMovement::query()->count())->toBe(0);
|
||||
$this->post('/stock/artigos', ['code' => 'novo-art', 'name' => 'Duplicado', 'unit' => 'cx'])->assertSessionHasErrors('code');
|
||||
$this->post('/stock/movimentos', [])->assertNotFound();
|
||||
});
|
||||
|
||||
test('audit failure rolls back receipt lines and all stock entries', function () {
|
||||
$this->mock(RequisitionWorkflow::class, function ($mock) {
|
||||
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Falha simulada de auditoria da recepção.'));
|
||||
});
|
||||
$this->postJson($this->url, $this->payload)->assertStatus(500);
|
||||
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0)->and(GoodsReceiptItem::query()->count())->toBe(0);
|
||||
expect(app(ReceiptWorkflow::class)->progress($this->f['order'])['lines'][0]['delivery_pending_milli'])->toBe(1000);
|
||||
});
|
||||
|
||||
test('receipt dates and server controlled fields are enforced', function () {
|
||||
$this->postJson($this->url, [...$this->payload, 'received_on' => now()->subDay()->format('Y-m-d')])->assertUnprocessable()->assertJsonValidationErrors('received_on');
|
||||
$this->postJson($this->url, [...$this->payload, 'received_on' => now()->addDay()->format('Y-m-d')])->assertUnprocessable();
|
||||
$this->postJson($this->url, [...$this->payload, 'received_by' => $this->f['issuer']->id, 'status' => 'complete'])->assertUnprocessable()->assertJsonValidationErrors(['received_by', 'status']);
|
||||
});
|
||||
|
||||
test('guests cannot access receiving and stock operations', function () {
|
||||
auth()->logout();
|
||||
$this->get('/recepcoes')->assertRedirect('/login');
|
||||
$this->get('/stock')->assertRedirect('/login');
|
||||
$this->post($this->url, $this->payload)->assertRedirect('/login');
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\StockOperation;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Support\Str;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->f = receiptFixture();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||
$this->dest = Warehouse::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['receiver']->id, 'code' => 'DEST', 'name' => 'Destino']);
|
||||
$this->p = ['kind' => 'issue', 'reference' => 'SAI-001', 'idempotency_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'stock_item_id' => $this->f['stock']->id, 'responsible_id' => $this->f['issuer']->id, 'destination' => 'Produção / REQ-001', 'reason' => 'Consumo de produção', 'quantity' => '0.600'];
|
||||
});
|
||||
|
||||
test('issues are exact, idempotent and cannot make stock negative', function () {
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertOk()->assertJsonPath('created', false);
|
||||
$this->p['quantity'] = '0.500';
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable();
|
||||
$this->p['reference'] = 'SAI-002';
|
||||
$this->p['idempotency_key'] = (string) Str::uuid();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable()->assertJsonValidationErrors('quantity');
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(400)->and(StockOperation::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('transfer creates exactly two opposite ledger entries and rejects repeated references', function () {
|
||||
$this->p['kind'] = 'transfer';
|
||||
$this->p['destination_warehouse_id'] = $this->dest->id;
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$op = StockOperation::query()->firstOrFail();
|
||||
$moves = StockMovement::query()->where('stock_operation_id', $op->id);
|
||||
expect($moves->count())->toBe(2)->and((int) $moves->sum('quantity_milli'))->toBe(0);
|
||||
expect((int) StockMovement::query()->where('warehouse_id', $this->dest->id)->sum('quantity_milli'))->toBe(600);
|
||||
$this->p['idempotency_key'] = (string) Str::uuid();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable()->assertJsonValidationErrors('reference');
|
||||
$this->p['reference'] = 'OTHER';
|
||||
$this->p['destination_warehouse_id'] = $this->f['warehouse']->id;
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable();
|
||||
});
|
||||
|
||||
test('counts preserve theoretical quantities and adjustments apply a justified difference once', function () {
|
||||
$this->p['kind'] = 'count';
|
||||
$this->p['quantity'] = '0';
|
||||
$this->p['ledger_version'] = StockMovement::query()->max('id');
|
||||
$id = $this->postJson('/stock/operacoes', $this->p)->assertCreated()->json('id');
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000);
|
||||
$this->p['kind'] = 'adjustment';
|
||||
$this->p['count_id'] = $id;
|
||||
$this->p['reference'] = 'AJ-001';
|
||||
$this->p['idempotency_key'] = (string) Str::uuid();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertOk();
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(0);
|
||||
$this->p['reference'] = 'AJ-002';
|
||||
$this->p['idempotency_key'] = (string) Str::uuid();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable();
|
||||
expect(StockOperation::query()->findOrFail($id)->theoretical_milli)->toBe(1000);
|
||||
});
|
||||
|
||||
test('intervening receipts and issues invalidate counts and stale count forms', function () {
|
||||
$count = [...$this->p, 'kind' => 'count', 'quantity' => '0.800', 'ledger_version' => StockMovement::query()->max('id')];
|
||||
$id = $this->postJson('/stock/operacoes', $count)->assertCreated()->json('id');
|
||||
$this->p['reference'] = 'SAI-NEW';
|
||||
$this->p['idempotency_key'] = (string) Str::uuid();
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$this->postJson('/stock/operacoes', [...$count, 'reference' => 'COUNT-NEW', 'idempotency_key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('ledger_version');
|
||||
$this->postJson('/stock/operacoes', [...$this->p, 'kind' => 'adjustment', 'reference' => 'AJ-NEW', 'count_id' => $id, 'idempotency_key' => (string) Str::uuid()])->assertUnprocessable()->assertJsonValidationErrors('count_id');
|
||||
});
|
||||
|
||||
test('operational role cannot be replaced by administration or other profiles', function ($role) {
|
||||
$this->f['receiver']->forceFill(['purchasing_role' => $role])->save();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertForbidden();
|
||||
})->with([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement, PurchasingRole::DepartmentHead, PurchasingRole::Requester]);
|
||||
|
||||
test('foreign company resources cannot be used', function ($field) {
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$values = ['warehouse_id' => $other['warehouse']->id, 'destination_warehouse_id' => $other['warehouse']->id, 'stock_item_id' => $other['stock']->id, 'responsible_id' => $other['receiver']->id];
|
||||
if ($field === 'destination_warehouse_id') {
|
||||
$this->p['kind'] = 'transfer';
|
||||
}
|
||||
$this->p[$field] = $values[$field];
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable()->assertJsonValidationErrors($field);
|
||||
})->with(['warehouse_id', 'destination_warehouse_id', 'stock_item_id', 'responsible_id']);
|
||||
|
||||
test('audit failure rolls back both halves of transfer and operation', function () {
|
||||
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Audit unavailable'));
|
||||
$this->p['kind'] = 'transfer';
|
||||
$this->p['destination_warehouse_id'] = $this->dest->id;
|
||||
$this->withoutExceptionHandling();
|
||||
try {
|
||||
$this->postJson('/stock/operacoes', $this->p);
|
||||
$this->fail('Expected exception');
|
||||
} catch (RuntimeException $e) {
|
||||
expect($e->getMessage())->toBe('Audit unavailable');
|
||||
}
|
||||
expect(StockOperation::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('operations are immutable and new public screen contains only demonstration props', function () {
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$op = StockOperation::query()->firstOrFail();
|
||||
expect(fn () => $op->update(['reason' => 'rewrite']))->toThrow(LogicException::class);
|
||||
expect(fn () => $op->delete())->toThrow(LogicException::class);
|
||||
$this->get('/stock/operacoes')->assertInertia(fn (Assert $p) => $p->component('stock/operations')->has('operations.data', 1)->where('canOperate', true));
|
||||
$this->get('/consulta/operacoes-stock')->assertInertia(fn (Assert $p) => $p->component('preview/index')->where('initialScreen', 'operations')->missing('operations')->where('auth.user', null));
|
||||
});
|
||||
|
||||
test('invalid precision and missing justification or destination do not write', function ($field, $value) {
|
||||
$this->p[$field] = $value;
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertUnprocessable()->assertJsonValidationErrors($field);
|
||||
expect(StockOperation::query()->count())->toBe(0);
|
||||
})->with([['quantity', '-1'], ['quantity', '0'], ['quantity', '0.0001'], ['reason', ' '], ['destination', ''], ['responsible_id', null]]);
|
||||
|
||||
test('positive adjustments credit only the difference and matching counts create no movements', function () {
|
||||
$count = [...$this->p, 'kind' => 'count', 'quantity' => '1.250', 'ledger_version' => StockMovement::query()->max('id')];
|
||||
$id = $this->postJson('/stock/operacoes', $count)->assertCreated()->json('id');
|
||||
$adjustment = [...$this->p, 'kind' => 'adjustment', 'count_id' => $id, 'reference' => 'AJ-POS', 'idempotency_key' => (string) Str::uuid()];
|
||||
$this->postJson('/stock/operacoes', $adjustment)->assertCreated();
|
||||
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(1250);
|
||||
$id = $this->postJson('/stock/operacoes', [...$count, 'reference' => 'MATCH', 'idempotency_key' => (string) Str::uuid(), 'ledger_version' => StockMovement::query()->max('id')])->assertCreated()->json('id');
|
||||
$this->postJson('/stock/operacoes', [...$adjustment, 'reference' => 'NOOP', 'count_id' => $id, 'idempotency_key' => (string) Str::uuid()])->assertUnprocessable();
|
||||
expect(StockMovement::query()->count())->toBe(2);
|
||||
});
|
||||
|
||||
test('failure creating transfer credit rolls back its debit', function () {
|
||||
StockMovement::creating(function (StockMovement $movement) {
|
||||
if ($movement->movement_type === 'transfer_in') {
|
||||
throw new RuntimeException('Credit failed');
|
||||
}
|
||||
});
|
||||
$this->withoutExceptionHandling();
|
||||
try {
|
||||
$this->postJson('/stock/operacoes', [...$this->p, 'kind' => 'transfer', 'destination_warehouse_id' => $this->dest->id]);
|
||||
$this->fail('Expected failure');
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('Credit failed');
|
||||
}
|
||||
expect(StockOperation::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('stock views isolate operations and counts from other companies', function () {
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$other = receiptFixture();
|
||||
$this->actingAs($other['receiver']);
|
||||
$this->get('/stock/operacoes')->assertInertia(fn (Assert $p) => $p->has('operations.data', 0)->has('counts', 0));
|
||||
});
|
||||
|
||||
test('form encoded retry identifiers and equivalent quantities retain idempotency', function () {
|
||||
$id = $this->postJson('/stock/operacoes', $this->p)->assertCreated()->json('id');
|
||||
foreach (['warehouse_id', 'stock_item_id', 'responsible_id'] as $key) {
|
||||
$this->p[$key] = (string) $this->p[$key];
|
||||
}
|
||||
$this->p['quantity'] = '0.6';
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertOk()->assertJsonPath('id', $id);
|
||||
});
|
||||
Reference in New Issue
Block a user