Add stock items, groups and movements at a moving average cost

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:18:59 +02:00
co-authored by Claude Sonnet 5.5
parent 361a2974cf
commit 30132deb0e
81 changed files with 4968 additions and 115 deletions
@@ -0,0 +1,63 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->management()->create(['name' => 'Johtaja']);
$this->actingAs($this->user);
ServiceUnitModel::factory()->usingStock()->create(['name' => 'Painotuotanto']);
$group = StockItemGroupModel::factory()->create(['name' => 'Paperit']);
$this->item = StockItemModel::factory()->create([
'stock_item_group_id' => $group->id,
'name' => 'Valokuvapaperi',
'unit' => 'sheet',
'reorder_level_milli' => 50_000,
'average_cost_hundredths' => 5_000,
]);
StockMovementModel::query()->create([
'stock_item_id' => $this->item->id, 'kind' => 'purchase', 'quantity_milli' => 40_000, 'unit_cost_hundredths' => 5_000,
'value_cents' => 2_000, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->user->id,
]);
});
it('has no accessibility issues on the stock pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
$url = match ($page) {
'index' => route('inventory.index'),
'item' => route('inventory.items.show', $this->item->id),
'form' => route('inventory.items.edit', $this->item->id),
'groups' => route('inventory.groups'),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee(match ($page) {
'groups' => 'Paperit', 'form' => __('inventory.form.edit_title'), default => 'Valokuvapaperi'
})
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['index', 'item', 'form', 'groups'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('reverses a movement in a dialog that returns focus', function () {
visit(route('inventory.items.show', $this->item->id))
->assertSee(__('inventory.status.reorder'))
->click(__('inventory.item.reverse'))
->assertSee(__('inventory.item.reverse_title'))
->assertNoAccessibilityIssues(level: 2)
->click(__('inventory.item.reverse_confirm'))
->assertSee('Vastakirjaus kirjattu')
->assertScript('document.activeElement.id', 'item-status');
});
@@ -0,0 +1,216 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->manager = User::factory()->management()->create(['name' => 'Maija Johto']);
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
$this->papers = StockItemGroupModel::factory()->create(['name' => 'Paperit', 'sort_order' => 1]);
$this->paper = StockItemModel::factory()->create([
'stock_item_group_id' => $this->papers->id,
'name' => 'Valokuvapaperi 10×15',
'unit' => 'sheet',
'code' => '6417000123',
'reorder_level_milli' => 20_000,
]);
});
function purchaseStock(int $itemId, string $quantity, string $total = '', string $unitPrice = ''): mixed
{
return Livewire::test('inventory::item', ['item' => $itemId])
->set('purchaseQuantity', $quantity)
->set('purchaseTotal', $total)
->set('purchaseUnitPrice', $unitPrice)
->call('recordPurchase');
}
it('shows the stock menu link only when a service unit uses stock', function () {
$this->actingAs($this->employee);
$this->get(route('home'))->assertDontSee(__('layout.inventory'));
ServiceUnitModel::factory()->usingStock()->create();
$this->get(route('home'))->assertSee(__('layout.inventory'));
$this->get(route('inventory.index'))->assertOk()->assertSee('Valokuvapaperi 10×15');
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('inventory.index'))->assertForbidden();
});
it('records purchases at a moving average cost and shows costs only to management', function () {
$this->actingAs($this->manager);
purchaseStock($this->paper->id, '100', total: '50,00')->assertHasNoErrors();
purchaseStock($this->paper->id, '100', unitPrice: '0,70')
->assertHasNoErrors()
->assertSet('message', fn (string $message) => str_contains($message, "Saldo nyt 200\u{00A0}arkki, keskihinta 0,60\u{00A0}€"));
expect($this->paper->fresh()->average_cost_hundredths)->toBe(6_000)
->and(StockMovementModel::query()->where('kind', 'purchase')->sum('value_cents'))->toBe(12_000);
Livewire::test('inventory::index')->assertSee(__('inventory.columns.average_cost'))->assertSee("120,00\u{00A0}€", false);
$this->actingAs($this->employee);
Livewire::test('inventory::index')
->assertSee("200\u{00A0}arkki", false)
->assertDontSee(__('inventory.columns.average_cost'))
->assertDontSee("120,00\u{00A0}€", false);
Livewire::test('inventory::item', ['item' => $this->paper->id])
->assertDontSee(__('inventory.purchase.title'))
->call('recordPurchase')
->assertForbidden();
});
it('requires a price and a positive quantity for a purchase', function () {
$this->actingAs($this->manager);
purchaseStock($this->paper->id, '10')->assertHasErrors('purchaseTotal');
purchaseStock($this->paper->id, '0', total: '5')->assertHasErrors('purchaseQuantity');
purchaseStock($this->paper->id, '10', unitPrice: '0,12345')->assertHasErrors('purchaseUnitPrice');
expect(StockMovementModel::query()->count())->toBe(0);
});
it('lets anyone using stock record use with a reason, going negative with a warning, and undo it the same day', function () {
$this->actingAs($this->employee);
Livewire::test('inventory::item', ['item' => $this->paper->id])
->set('useQuantity', '3')
->call('recordUse')
->assertHasErrors('useReason')
->set('useReason', 'Koeajo')
->call('recordUse')
->assertHasNoErrors()
->assertSee(__('inventory.status.negative'))
->assertSee(__('inventory.use.negative_warning'));
$use = StockMovementModel::query()->sole();
expect($use->kind)->toBe(StockMovementKind::Consumption)->and($use->quantity_milli)->toBe(-3_000);
Livewire::test('inventory::index', ['onlyReorder' => true])->assertSee('Valokuvapaperi 10×15');
Livewire::test('inventory::item', ['item' => $this->paper->id])
->call('confirmReverse', $use->id)
->call('reverse')
->assertSet('message', fn (string $message) => str_contains($message, 'Vastakirjaus kirjattu'));
expect(StockMovementModel::query()->where('reverses_movement_id', $use->id)->sole()->quantity_milli)->toBe(3_000);
$this->travel(1)->day();
Livewire::test('inventory::item', ['item' => $this->paper->id])->call('confirmReverse', $use->id)->assertForbidden();
$other = StockMovementModel::query()->create([
'stock_item_id' => $this->paper->id, 'kind' => 'consumption', 'quantity_milli' => -1000, 'unit_cost_hundredths' => 0,
'value_cents' => 0, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->manager->id, 'reason' => 'Testi',
]);
Livewire::test('inventory::item', ['item' => $this->paper->id])->call('confirmReverse', $other->id)->assertForbidden();
});
it('records write-offs with a reason for management only', function () {
$this->actingAs($this->manager);
Livewire::test('inventory::item', ['item' => $this->paper->id])
->set('writeOffQuantity', '2,5')
->call('recordWriteOff')
->assertHasErrors('writeOffReason')
->set('writeOffReason', 'Vaurioitunut')
->call('recordWriteOff')
->assertHasNoErrors();
expect(StockMovementModel::query()->sole()->only(['kind', 'quantity_milli', 'reason']))
->toBe(['kind' => StockMovementKind::WriteOff, 'quantity_milli' => -2_500, 'reason' => 'Vaurioitunut']);
});
it('does not let an item out of use be used', function () {
$this->actingAs($this->manager);
Livewire::test('inventory::item', ['item' => $this->paper->id])
->call('toggleActive')
->assertSee(__('inventory.item.inactive_note'))
->assertDontSee(__('inventory.use.title'));
Livewire::test('inventory::index')->assertDontSee('Valokuvapaperi 10×15');
Livewire::test('inventory::index')->set('includeInactive', true)->assertSee('Valokuvapaperi 10×15');
});
it('searches items by parts of the name or code', function () {
$this->actingAs($this->employee);
StockItemModel::factory()->create(['stock_item_group_id' => $this->papers->id, 'name' => 'Tarramateriaali kiiltävä']);
Livewire::test('inventory::index')
->set('search', 'KIILTAVA')
->assertSee('Tarramateriaali kiiltävä')
->assertDontSee('Valokuvapaperi')
->set('search', '6417')
->assertSee('Valokuvapaperi');
});
it('adds and edits items and groups, with an image', function () {
Storage::fake('local');
$this->actingAs($this->manager);
Livewire::test('inventory::groups')
->set('newName', 'Musteet')
->call('add')
->assertHasNoErrors()
->set('newName', 'musteet')
->call('add')
->assertHasErrors('newName');
$inks = StockItemGroupModel::query()->where('name', 'Musteet')->sole();
Livewire::test('inventory::groups')
->call('move', $inks->id, 'up')
->assertSet('message', 'Musteet siirretty ylöspäin.')
->call('startRename', $inks->id)
->set('editingName', 'Musteet ja värit')
->call('rename')
->assertHasNoErrors();
expect($inks->fresh()->name)->toBe('Musteet ja värit')
->and($inks->fresh()->sort_order)->toBeLessThan($this->papers->fresh()->sort_order);
Livewire::test('inventory::item-form')
->set('groupId', (string) $inks->id)
->set('name', 'Muste syaani')
->set('unit', 'litre')
->set('reorderLevel', '0,5')
->set('image', UploadedFile::fake()->image('muste.jpg', 300, 200))
->call('save')
->assertHasNoErrors();
$ink = StockItemModel::query()->where('name', 'Muste syaani')->sole();
expect($ink->reorder_level_milli)->toBe(500)
->and($ink->image_path)->not->toBeNull();
Storage::disk('local')->assertExists($ink->thumbnail_path);
$this->get(route('inventory.items.image', [$ink->id, 'thumbnail']))->assertOk();
Livewire::test('inventory::item-form', ['item' => $ink->id])
->set('name', 'Valokuvapaperi 10×15')
->call('save')
->assertHasErrors('name')
->set('name', 'Muste syaani 1 l')
->set('removeImage', true)
->call('save')
->assertHasNoErrors();
expect($ink->fresh()->image_path)->toBeNull();
Storage::disk('local')->assertMissing($ink->thumbnail_path);
$this->actingAs($this->employee);
$this->get(route('inventory.items.create'))->assertForbidden();
$this->get(route('inventory.groups'))->assertForbidden();
});
@@ -77,7 +77,7 @@ it('stores a downscaled image and a thumbnail without metadata and shows them on
});
it('turns a sideways phone photo upright and leaves out its EXIF data', function () {
$stored = (new GdTaskImageFiles)->store(sidewaysJpeg(40, 20), $this->task->id);
$stored = app(GdTaskImageFiles::class)->store(sidewaysJpeg(40, 20), $this->task->id);
$bytes = Storage::disk('local')->get($stored->path);
expect(getimagesizefromstring($bytes)[0])->toBe(20)
@@ -0,0 +1,77 @@
<?php
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Services\StockSearch;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
it('parses and formats quantities with three decimals', function () {
expect(StockQuantity::parsePositive('2,5')->milli)->toBe(2500)
->and(StockQuantity::parsePositive('1 200')->milli)->toBe(1_200_000)
->and(StockQuantity::parsePositive('0.125')->milli)->toBe(125)
->and(StockQuantity::parse(''))->toBeNull()
->and(StockQuantity::format(2500))->toBe('2,5')
->and(StockQuantity::format(-1000))->toBe('-1')
->and(StockQuantity::format(1_234_500))->toBe("1\u{00A0}234,5")
->and(StockQuantity::inputValue(1_234_500))->toBe('1234,5');
});
it('rejects quantities that are zero, negative or too precise', function (string $value) {
StockQuantity::parsePositive($value);
})->with(['0', '-1', '1,2345', 'abc'])->throws(InvalidStockQuantity::class);
it('values stock at the moving average cost', function () {
// 10 sheets for 5,00 € → 0,50 € each (5 000 hundredths of a cent).
$average = StockValuation::averageAfterPurchase(0, 0, 10_000, 500);
expect($average)->toBe(5_000);
// 10 more for 7,00 € → (5,00 + 7,00) / 20 = 0,60 €.
$average = StockValuation::averageAfterPurchase(10_000, $average, 10_000, 700);
expect($average)->toBe(6_000)
->and(StockValuation::valueCents(2_500, $average))->toBe(150)
->and(StockValuation::valueCents(-2_500, $average))->toBe(-150);
// After a negative balance the purchase's own price is the average.
expect(StockValuation::averageAfterPurchase(-3_000, 6_000, 10_000, 1_000))->toBe(10_000)
// Ink at 0,0123 €/ml keeps its precision.
->and(StockValuation::unitCostOf(1_000_000, 1_230))->toBe(123);
});
it('records use and write-offs negated at the average cost, and reverses them once', function () {
$item = StockItem::reconstitute(1, 1, new StockName('Paperi'), StockUnit::Sheet, null, null, null, 5_000, null, null, true);
$day = new DateTimeImmutable('2026-11-26');
$use = StockMovement::consumption($item, StockQuantity::parsePositive('3'), new StockUseTarget(taskId: 4, jobId: 2), $day, $day, 7);
$reversal = StockMovement::reversalOf(StockMovement::reconstitute(9, 1, StockMovementKind::Consumption, $use->quantityMilli(), 5_000, $use->valueCents(), $day, $day, 7, $use->target(), null, null, null, null, null), $day, $day, 7);
expect($use->quantityMilli())->toBe(-3_000)
->and($use->valueCents())->toBe(-150)
->and($use->isOwnUseOf(7, $day))->toBeTrue()
->and($use->isOwnUseOf(8, $day))->toBeFalse()
->and($use->isOwnUseOf(7, $day->modify('+1 day')))->toBeFalse()
->and($reversal->quantityMilli())->toBe(3_000)
->and($reversal->valueCents())->toBe(150)
->and($reversal->reversesMovementId())->toBe(9)
->and($reversal->target()?->taskId)->toBe(4);
StockMovement::reversalOf($reversal, $day, $day, 7);
})->throws(StockMovementNotReversible::class);
it('needs a reason for use without a target', function () {
new StockUseTarget;
})->throws(StockReasonRequired::class);
it('matches searches by words of the name or code regardless of case and dots', function () {
expect(StockSearch::matches('valokuva 10', 'Valokuvapaperi 10×15', null))->toBeTrue()
->and(StockSearch::matches('PAAPERI', 'Pääperi', null))->toBeTrue()
->and(StockSearch::matches('6417', 'Muste', '6417000123'))->toBeTrue()
->and(StockSearch::matches('muste syaani', 'Muste magenta', null))->toBeFalse();
});