diff --git a/app/Modules/Inventory/Application/Contracts/InventoryCountQueries.php b/app/Modules/Inventory/Application/Contracts/InventoryCountQueries.php new file mode 100644 index 0000000..5324958 --- /dev/null +++ b/app/Modules/Inventory/Application/Contracts/InventoryCountQueries.php @@ -0,0 +1,26 @@ + Newest first. + */ + public function counts(): array; + + public function findCount(int $id): ?InventoryCountSummary; + + /** + * The items of the count in group order and by name: those in its + * groups that are in use, and every item counted in it. + * + * @return list + */ + public function lines(int $countId): array; +} diff --git a/app/Modules/Inventory/Application/DTOs/InventoryCountLine.php b/app/Modules/Inventory/Application/DTOs/InventoryCountLine.php new file mode 100644 index 0000000..731a4bd --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/InventoryCountLine.php @@ -0,0 +1,41 @@ +countedMilli !== null; + } + + public function differenceMilli(): ?int + { + return $this->countedMilli === null || $this->bookMilli === null ? null : $this->countedMilli - $this->bookMilli; + } +} diff --git a/app/Modules/Inventory/Application/DTOs/InventoryCountSummary.php b/app/Modules/Inventory/Application/DTOs/InventoryCountSummary.php new file mode 100644 index 0000000..ea7129e --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/InventoryCountSummary.php @@ -0,0 +1,28 @@ + $groupNames + */ + public function __construct( + public int $id, + public string $countedOn, + public bool $isConfirmed, + public array $groupNames, + public string $startedByName, + public ?string $confirmedByName, + public ?string $confirmedAt, + public int $countedItems, + public ?int $valueBeforeCents, + public ?int $valueAfterCents, + ) {} +} diff --git a/app/Modules/Inventory/Application/UseCases/InventoryCounts.php b/app/Modules/Inventory/Application/UseCases/InventoryCounts.php new file mode 100644 index 0000000..82d6478 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/InventoryCounts.php @@ -0,0 +1,129 @@ + $groupIds Empty: the whole stock. + * + * @throws InventoryCountAlreadyOpen + */ + public function start(array $groupIds, int $actorUserId): int + { + return $this->transactions->run(function () use ($groupIds, $actorUserId): int { + if ($this->counts->hasOpen()) { + throw new InventoryCountAlreadyOpen; + } + + return (int) $this->counts->save(InventoryCount::start($this->clock->today(), array_values(array_unique($groupIds)), $actorUserId))->id(); + }); + } + + /** + * Enters a counted quantity with the item's book balance now; an empty + * value takes the item back to not counted. + * + * @return int|null The book balance stored with the count, null when cleared. + * + * @throws InventoryCountNotFound + * @throws InventoryCountConfirmed + * @throws StockItemNotFound + * @throws StockItemNotInCount + * @throws InvalidStockQuantity + */ + public function record(int $countId, int $itemId, string $counted, int $actorUserId): ?int + { + $quantity = StockQuantity::parse($counted); + + return $this->transactions->run(function () use ($countId, $itemId, $quantity, $actorUserId): ?int { + $count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound; + $count->ensureOpen(); + + $item = $this->items->lockById($itemId) ?? throw new StockItemNotFound; + + if (! $count->covers($item->groupId())) { + throw new StockItemNotInCount; + } + + if ($quantity === null) { + $this->counts->removeLine($countId, $itemId); + + return null; + } + + $book = $this->movements->balanceOf($itemId); + $this->counts->recordLine($countId, $itemId, $book, $quantity->milli, $actorUserId, $this->clock->now()); + + return $book; + }); + } + + /** + * @return int The number of adjustments made. + * + * @throws InventoryCountNotFound + * @throws InventoryCountConfirmed + */ + public function confirm(int $countId, int $actorUserId): int + { + return $this->transactions->run(function () use ($countId, $actorUserId): int { + $count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound; + $count->ensureOpen(); + + $valueBefore = $this->items->stockValueCents(); + $now = $this->clock->now(); + $adjustments = 0; + + foreach ($this->counts->lines($countId) as $line) { + $item = $this->items->lockById($line['itemId']) ?? throw new StockItemNotFound; + $this->counts->setLineUnitCost($countId, $line['itemId'], $item->averageCostHundredths()); + + $difference = $line['countedMilli'] - $line['bookMilli']; + + if ($difference !== 0) { + $this->movements->add(StockMovement::adjustment($item, $difference, $countId, $count->countedOn(), $now, $actorUserId)); + $adjustments++; + } + } + + $count->confirm($actorUserId, $now, $valueBefore, $this->items->stockValueCents()); + $this->counts->save($count); + + return $adjustments; + }); + } +} diff --git a/app/Modules/Inventory/Domain/Contracts/InventoryCountRepository.php b/app/Modules/Inventory/Domain/Contracts/InventoryCountRepository.php new file mode 100644 index 0000000..f847c49 --- /dev/null +++ b/app/Modules/Inventory/Domain/Contracts/InventoryCountRepository.php @@ -0,0 +1,37 @@ + + */ + public function lines(int $countId): array; + + public function setLineUnitCost(int $countId, int $itemId, int $unitCostHundredths): void; +} diff --git a/app/Modules/Inventory/Domain/Contracts/StockItemRepository.php b/app/Modules/Inventory/Domain/Contracts/StockItemRepository.php index 16cfe58..47bac22 100644 --- a/app/Modules/Inventory/Domain/Contracts/StockItemRepository.php +++ b/app/Modules/Inventory/Domain/Contracts/StockItemRepository.php @@ -19,4 +19,9 @@ interface StockItemRepository public function save(StockItem $item): StockItem; public function isNameTaken(string $name, ?int $exceptId = null): bool; + + /** + * The value of all stock: each item's balance at its average cost. + */ + public function stockValueCents(): int; } diff --git a/app/Modules/Inventory/Domain/Entities/InventoryCount.php b/app/Modules/Inventory/Domain/Entities/InventoryCount.php new file mode 100644 index 0000000..a1be8e9 --- /dev/null +++ b/app/Modules/Inventory/Domain/Entities/InventoryCount.php @@ -0,0 +1,121 @@ +|null $groupIds Null: the whole stock. + */ + private function __construct( + private ?int $id, + private DateTimeImmutable $countedOn, + private ?array $groupIds, + private int $startedBy, + private ?int $confirmedBy, + private ?DateTimeImmutable $confirmedAt, + private ?int $valueBeforeCents, + private ?int $valueAfterCents, + ) {} + + /** + * @param list|null $groupIds + */ + public static function start(DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy): self + { + return new self(null, $countedOn, $groupIds === [] ? null : $groupIds, $startedBy, null, null, null, null); + } + + /** + * @param list|null $groupIds + */ + public static function reconstitute(int $id, DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy, ?int $confirmedBy, ?DateTimeImmutable $confirmedAt, ?int $valueBeforeCents, ?int $valueAfterCents): self + { + return new self($id, $countedOn, $groupIds, $startedBy, $confirmedBy, $confirmedAt, $valueBeforeCents, $valueAfterCents); + } + + /** + * @throws InventoryCountConfirmed + */ + public function ensureOpen(): void + { + if ($this->isConfirmed()) { + throw new InventoryCountConfirmed; + } + } + + /** + * @throws InventoryCountConfirmed + */ + public function confirm(int $userId, DateTimeImmutable $at, int $valueBeforeCents, int $valueAfterCents): void + { + $this->ensureOpen(); + $this->confirmedBy = $userId; + $this->confirmedAt = $at; + $this->valueBeforeCents = $valueBeforeCents; + $this->valueAfterCents = $valueAfterCents; + } + + public function covers(int $groupId): bool + { + return $this->groupIds === null || in_array($groupId, $this->groupIds, true); + } + + public function isConfirmed(): bool + { + return $this->confirmedAt !== null; + } + + public function id(): ?int + { + return $this->id; + } + + public function countedOn(): DateTimeImmutable + { + return $this->countedOn; + } + + /** + * @return list|null + */ + public function groupIds(): ?array + { + return $this->groupIds; + } + + public function startedBy(): int + { + return $this->startedBy; + } + + public function confirmedBy(): ?int + { + return $this->confirmedBy; + } + + public function confirmedAt(): ?DateTimeImmutable + { + return $this->confirmedAt; + } + + public function valueBeforeCents(): ?int + { + return $this->valueBeforeCents; + } + + public function valueAfterCents(): ?int + { + return $this->valueAfterCents; + } +} diff --git a/app/Modules/Inventory/Domain/Exceptions/InventoryCountAlreadyOpen.php b/app/Modules/Inventory/Domain/Exceptions/InventoryCountAlreadyOpen.php new file mode 100644 index 0000000..af42ebf --- /dev/null +++ b/app/Modules/Inventory/Domain/Exceptions/InventoryCountAlreadyOpen.php @@ -0,0 +1,15 @@ + + */ + protected function casts(): array + { + return [ + 'inventory_count_id' => 'integer', + 'stock_item_id' => 'integer', + 'book_quantity_milli' => 'integer', + 'counted_quantity_milli' => 'integer', + 'unit_cost_hundredths' => 'integer', + 'counted_by' => 'integer', + 'counted_at' => 'immutable_datetime', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/InventoryCountModel.php b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/InventoryCountModel.php new file mode 100644 index 0000000..49a12ab --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/InventoryCountModel.php @@ -0,0 +1,55 @@ +|null $group_ids + * @property int $started_by + * @property int|null $confirmed_by + * @property Carbon|null $confirmed_at + * @property int|null $value_before_cents + * @property int|null $value_after_cents + */ +#[Table('inventory_counts')] +#[Fillable(['counted_on', 'status', 'group_ids', 'started_by', 'confirmed_by', 'confirmed_at', 'value_before_cents', 'value_after_cents'])] +class InventoryCountModel extends Model +{ + public const string OPEN = 'open'; + + public const string CONFIRMED = 'confirmed'; + + /** + * @return HasMany + */ + public function lines(): HasMany + { + return $this->hasMany(InventoryCountLineModel::class, 'inventory_count_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'counted_on' => 'immutable_date', + 'group_ids' => 'array', + 'started_by' => 'integer', + 'confirmed_by' => 'integer', + 'confirmed_at' => 'immutable_datetime', + 'value_before_cents' => 'integer', + 'value_after_cents' => 'integer', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountQueries.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountQueries.php new file mode 100644 index 0000000..362a741 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountQueries.php @@ -0,0 +1,102 @@ +summaries(InventoryCountModel::query()->withCount('lines')->orderByDesc('id')->get()); + } + + public function findCount(int $id): ?InventoryCountSummary + { + $model = InventoryCountModel::query()->withCount('lines')->find($id); + + return $model === null ? null : $this->summaries(collect([$model]))[0]; + } + + public function lines(int $countId): array + { + $count = InventoryCountModel::query()->find($countId); + + if ($count === null) { + return []; + } + + $lines = InventoryCountLineModel::query()->where('inventory_count_id', $countId)->get()->keyBy('stock_item_id'); + $groupIds = $count->group_ids === null ? null : array_map('intval', $count->group_ids); + $names = $this->users->namesByIds($lines->pluck('counted_by')->unique()->values()->all()); + $confirmed = $count->status === InventoryCountModel::CONFIRMED; + + $items = array_filter( + $this->stock->items(includeInactive: true), + fn ($item): bool => $lines->has($item->id) + || (! $confirmed && $item->isActive && ($groupIds === null || in_array($item->groupId, $groupIds, true))), + ); + + return array_values(array_map(function ($item) use ($lines, $names): InventoryCountLine { + /** @var InventoryCountLineModel|null $line */ + $line = $lines->get($item->id); + + return new InventoryCountLine( + itemId: $item->id, + itemName: $item->name, + code: $item->code, + groupId: $item->groupId, + groupName: $item->groupName, + unit: $item->unit, + currentBalanceMilli: $item->balanceMilli, + bookMilli: $line?->book_quantity_milli, + countedMilli: $line?->counted_quantity_milli, + unitCostHundredths: $line->unit_cost_hundredths ?? $item->averageCostHundredths, + countedByName: $line === null ? null : ($names[$line->counted_by] ?? ''), + countedAt: $line === null ? null : $this->localTime($line->counted_at), + ); + }, $items)); + } + + /** + * @param Collection $models + * @return list + */ + private function summaries(Collection $models): array + { + $names = $this->users->namesByIds($models->flatMap(fn (InventoryCountModel $model): array => array_filter([$model->started_by, $model->confirmed_by]))->unique()->values()->all()); + $groupNames = StockItemGroupModel::query()->orderBy('sort_order')->pluck('name', 'id'); + + return $models->map(fn (InventoryCountModel $model): InventoryCountSummary => new InventoryCountSummary( + id: $model->id, + countedOn: $model->counted_on->format('Y-m-d'), + isConfirmed: $model->status === InventoryCountModel::CONFIRMED, + groupNames: $model->group_ids === null ? [] : $groupNames->only(array_map('intval', $model->group_ids))->values()->all(), + startedByName: $names[$model->started_by] ?? '', + confirmedByName: $model->confirmed_by === null ? null : ($names[$model->confirmed_by] ?? ''), + confirmedAt: $model->confirmed_at === null ? null : $this->localTime($model->confirmed_at), + countedItems: (int) $model->getAttribute('lines_count'), + valueBeforeCents: $model->value_before_cents, + valueAfterCents: $model->value_after_cents, + ))->values()->all(); + } + + private function localTime(\DateTimeInterface $moment): string + { + return Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountRepository.php new file mode 100644 index 0000000..8be8d36 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentInventoryCountRepository.php @@ -0,0 +1,99 @@ +find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function lockById(int $id): ?InventoryCount + { + $model = InventoryCountModel::query()->lockForUpdate()->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function hasOpen(): bool + { + return InventoryCountModel::query()->where('status', InventoryCountModel::OPEN)->lockForUpdate()->exists(); + } + + public function save(InventoryCount $count): InventoryCount + { + $model = $count->id() === null ? new InventoryCountModel : InventoryCountModel::query()->findOrFail($count->id()); + + $model->fill([ + 'counted_on' => $count->countedOn()->format('Y-m-d'), + 'status' => $count->isConfirmed() ? InventoryCountModel::CONFIRMED : InventoryCountModel::OPEN, + 'group_ids' => $count->groupIds(), + 'started_by' => $count->startedBy(), + 'confirmed_by' => $count->confirmedBy(), + 'confirmed_at' => $count->confirmedAt()?->format('Y-m-d H:i:s'), + 'value_before_cents' => $count->valueBeforeCents(), + 'value_after_cents' => $count->valueAfterCents(), + ])->save(); + + return $this->toEntity($model); + } + + public function recordLine(int $countId, int $itemId, int $bookMilli, int $countedMilli, int $userId, DateTimeImmutable $at): void + { + InventoryCountLineModel::query()->updateOrCreate( + ['inventory_count_id' => $countId, 'stock_item_id' => $itemId], + ['book_quantity_milli' => $bookMilli, 'counted_quantity_milli' => $countedMilli, 'counted_by' => $userId, 'counted_at' => $at->format('Y-m-d H:i:s')], + ); + } + + public function removeLine(int $countId, int $itemId): void + { + InventoryCountLineModel::query()->where('inventory_count_id', $countId)->where('stock_item_id', $itemId)->delete(); + } + + public function lines(int $countId): array + { + return InventoryCountLineModel::query() + ->where('inventory_count_id', $countId) + ->orderBy('id') + ->get() + ->map(fn (InventoryCountLineModel $line): array => [ + 'itemId' => $line->stock_item_id, + 'bookMilli' => $line->book_quantity_milli, + 'countedMilli' => $line->counted_quantity_milli, + ]) + ->values() + ->all(); + } + + public function setLineUnitCost(int $countId, int $itemId, int $unitCostHundredths): void + { + InventoryCountLineModel::query() + ->where('inventory_count_id', $countId) + ->where('stock_item_id', $itemId) + ->update(['unit_cost_hundredths' => $unitCostHundredths]); + } + + private function toEntity(InventoryCountModel $model): InventoryCount + { + return InventoryCount::reconstitute( + $model->id, + DateTimeImmutable::createFromInterface($model->counted_on), + $model->group_ids === null ? null : array_map('intval', $model->group_ids), + $model->started_by, + $model->confirmed_by, + $model->confirmed_at === null ? null : DateTimeImmutable::createFromInterface($model->confirmed_at), + $model->value_before_cents, + $model->value_after_cents, + ); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php index c819657..01e21e7 100644 --- a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockItemRepository.php @@ -4,8 +4,10 @@ namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories; use App\Modules\Inventory\Domain\Contracts\StockItemRepository; use App\Modules\Inventory\Domain\Entities\StockItem; +use App\Modules\Inventory\Domain\Services\StockValuation; use App\Modules\Inventory\Domain\ValueObjects\StockName; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel; +use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel; class EloquentStockItemRepository implements StockItemRepository { @@ -51,6 +53,18 @@ class EloquentStockItemRepository implements StockItemRepository ->exists(); } + public function stockValueCents(): int + { + return (int) StockItemModel::query() + ->select(['id', 'average_cost_hundredths']) + ->selectSub( + StockMovementModel::query()->selectRaw('COALESCE(SUM(quantity_milli), 0)')->whereColumn('stock_movements.stock_item_id', 'stock_items.id'), + 'balance_milli', + ) + ->get() + ->sum(fn (StockItemModel $model): int => StockValuation::valueCents((int) $model->getAttribute('balance_milli'), $model->average_cost_hundredths)); + } + private function toEntity(StockItemModel $model): StockItem { return StockItem::reconstitute( diff --git a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php index 6ed86c9..7a0fadc 100644 --- a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php +++ b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php @@ -4,10 +4,12 @@ namespace App\Modules\Inventory\Infrastructure\Providers; use App\Models\User; use App\Modules\Catalog\Application\Contracts\CatalogQueries; +use App\Modules\Inventory\Application\Contracts\InventoryCountQueries; use App\Modules\Inventory\Application\Contracts\StockItemImages; use App\Modules\Inventory\Application\Contracts\StockQueries; use App\Modules\Inventory\Application\Contracts\StockTasks; use App\Modules\Inventory\Application\UseCases\TaskMaterials; +use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository; use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository; use App\Modules\Inventory\Domain\Contracts\StockItemRepository; use App\Modules\Inventory\Domain\Contracts\StockMovementRepository; @@ -15,6 +17,8 @@ use App\Modules\Inventory\Domain\Contracts\TaskMaterialSuggestionRepository; use App\Modules\Inventory\Infrastructure\Adapters\TasksForStock; use App\Modules\Inventory\Infrastructure\Adapters\TaskUsageWithStock; use App\Modules\Inventory\Infrastructure\Files\StockItemImageFiles; +use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentInventoryCountQueries; +use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentInventoryCountRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemGroupRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockMovementRepository; @@ -46,6 +50,8 @@ class InventoryServiceProvider extends ServiceProvider StockItemImages::class => StockItemImageFiles::class, TaskMaterialSuggestionRepository::class => EloquentTaskMaterialSuggestionRepository::class, StockTasks::class => TasksForStock::class, + InventoryCountRepository::class => EloquentInventoryCountRepository::class, + InventoryCountQueries::class => EloquentInventoryCountQueries::class, ]; public function register(): void diff --git a/app/Modules/Inventory/Presentation/Http/Controllers/DownloadInventoryCount.php b/app/Modules/Inventory/Presentation/Http/Controllers/DownloadInventoryCount.php new file mode 100644 index 0000000..6c6db98 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Http/Controllers/DownloadInventoryCount.php @@ -0,0 +1,73 @@ +findCount($count) ?? abort(404); + abort_unless($summary->isConfirmed, 404); + $lines = $counts->lines($count); + + return response()->streamDownload(function () use ($lines): void { + $out = fopen('php://output', 'w'); + + if ($out === false) { + return; + } + + fwrite($out, "\u{FEFF}"); + fputcsv($out, array_map(fn (string $key): string => __('inventory.counts.csv.'.$key), [ + 'item', 'code', 'group', 'unit', 'book', 'counted', 'difference', 'unit_cost', 'book_value', 'counted_value', 'difference_value', + ]), ';', '"', ''); + + foreach ($lines as $line) { + if (! $line->isCounted()) { + continue; + } + + $book = (int) $line->bookMilli; + $counted = (int) $line->countedMilli; + + fputcsv($out, [ + self::text($line->itemName), + self::text((string) $line->code), + self::text($line->groupName), + __('inventory.units.'.$line->unit->value), + StockQuantity::inputValue($book), + StockQuantity::inputValue($counted), + StockQuantity::inputValue($counted - $book), + number_format($line->unitCostHundredths / 10_000, 4, ',', ''), + (string) StockValuation::valueCents($book, $line->unitCostHundredths), + (string) StockValuation::valueCents($counted, $line->unitCostHundredths), + (string) StockValuation::valueCents($counted - $book, $line->unitCostHundredths), + ], ';', '"', ''); + } + + fclose($out); + }, __('inventory.counts.csv.file', ['date' => $summary->countedOn]).'.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'no-store, private', + ]); + } + + private static function text(string $value): string + { + return preg_match('/^[=+\-@\t\r\n]/', $value) === 1 ? "'".$value : $value; + } +} diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡count.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡count.blade.php new file mode 100644 index 0000000..aa493c7 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡count.blade.php @@ -0,0 +1,282 @@ +authorize('inventory.count'); + + abort_if(app(InventoryCountQueries::class)->findCount($count) === null, 404); + $this->countId = $count; + } + + #[Computed] + public function count(): InventoryCountSummary + { + return app(InventoryCountQueries::class)->findCount($this->countId) ?? abort(404); + } + + /** + * @return list + */ + #[Computed] + public function lines(): array + { + return app(InventoryCountQueries::class)->lines($this->countId); + } + + /** + * The lines shown, by group name. + * + * @return array> + */ + public function groupedLines(): array + { + $groups = []; + + foreach ($this->lines as $line) { + if (! $this->onlyUncounted || ! $line->isCounted()) { + $groups[$line->groupName][] = $line; + } + } + + return $groups; + } + + public function uncountedCount(): int + { + return count(array_filter($this->lines, fn (InventoryCountLine $line): bool => ! $line->isCounted())); + } + + public function updatedOnlyUncounted(): void + { + $this->authorize('inventory.count'); + } + + public function saveCounted(int $itemId, string $value, InventoryCounts $counts): void + { + $this->authorize('inventory.count'); + $this->resetErrorBag('counted.'.$itemId); + + $line = collect($this->lines)->firstWhere('itemId', $itemId) ?? abort(404); + + try { + $book = $counts->record($this->countId, $itemId, $value, (int) auth()->id()); + } catch (InvalidStockQuantity) { + $this->addError('counted.'.$itemId, __('inventory.counts.errors.quantity')); + + return; + } catch (InventoryCountConfirmed) { + $this->message = __('inventory.counts.errors.confirmed'); + + return; + } catch (InventoryCountNotFound|StockItemNotFound|StockItemNotInCount) { + $this->message = __('inventory.errors.not_found'); + + return; + } + + unset($this->lines); + + if ($book === null) { + $this->message = __('inventory.counts.cleared', ['item' => $line->itemName]); + + return; + } + + $counted = (int) StockQuantity::parse($value)?->milli; + $this->message = __('inventory.counts.saved', [ + 'item' => $line->itemName, + 'counted' => $this->quantity($counted, $line->unit), + 'difference' => $this->signed($counted - $book, $line->unit), + ]); + } + + public function confirmCount(): void + { + $this->authorize('inventory.manage-counts'); + $this->js("document.getElementById('confirm-count-dialog').showModal()"); + } + + public function confirm(InventoryCounts $counts): void + { + $this->authorize('inventory.manage-counts'); + + try { + $adjustments = $counts->confirm($this->countId, (int) auth()->id()); + $this->message = trans_choice('inventory.counts.confirmed_message', $adjustments, ['count' => $adjustments]); + } catch (InventoryCountConfirmed) { + $this->message = __('inventory.counts.errors.confirmed'); + } catch (InventoryCountNotFound|StockItemNotFound) { + $this->message = __('inventory.errors.not_found'); + } + + unset($this->count, $this->lines); + $this->js("document.getElementById('confirm-count-dialog').close(); document.getElementById('count-status').focus()"); + } + + public function signed(int $milli, mixed $unit): string + { + return ($milli > 0 ? '+' : '').$this->quantity($milli, $unit); + } + + public function differenceValue(InventoryCountLine $line): int + { + return StockValuation::valueCents((int) $line->differenceMilli(), $line->unitCostHundredths); + } + + public function render(): mixed + { + return $this->view()->title(__('inventory.counts.name', ['date' => $this->dateLabel($this->count->countedOn)])); + } +}; +?> + +
+ @php($count = $this->count) + +
+

{{ __('inventory.counts.back') }}

+

{{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }}

+

+ {{ $count->groupNames === [] ? __('inventory.counts.whole_stock') : implode(', ', $count->groupNames) }} + · {{ __('inventory.counts.started_by', ['name' => $count->startedByName]) }} +

+ @if ($count->isConfirmed) +

+

+ @can('inventory.see-value') +

{{ __('inventory.counts.values', ['before' => $this->money((int) $count->valueBeforeCents), 'after' => $this->money((int) $count->valueAfterCents)]) }}

+ @endcan + @else +

{{ __('inventory.counts.count_help') }}

+ @endif +
+ +

{{ $message }}

+ +
+ @unless ($count->isConfirmed) + + @endunless +

{{ trans_choice('inventory.counts.uncounted', $this->uncountedCount(), ['count' => $this->uncountedCount()]) }}

+ @if (! $count->isConfirmed) + @can('inventory.manage-counts') + + @endcan + @else + @can('inventory.manage-counts') + + + @endcan + @endif +
+ + @forelse ($this->groupedLines() as $groupName => $lines) +
+

{{ $groupName }}

+
    + @foreach ($lines as $line) + @php($difference = $line->differenceMilli()) +
  • +
    +

    {{ $line->itemName }}

    +

    + @if ($line->isCounted()) + {{ __('inventory.counts.book', ['book' => $this->quantity((int) $line->bookMilli, $line->unit)]) }} + · {{ __('inventory.counts.difference', ['difference' => $this->signed((int) $difference, $line->unit)]) }} + @can('inventory.see-value') + ({{ $this->money($this->differenceValue($line)) }}) + @endcan + · {{ $line->countedByName }}, {{ $this->dateLabel((string) $line->countedAt) }} + @else + + + · {{ __('inventory.counts.current', ['balance' => $this->quantity($line->currentBalanceMilli, $line->unit)]) }} + @endif +

    +
    + @if ($count->isConfirmed) +

    {{ $line->isCounted() ? $this->quantity((int) $line->countedMilli, $line->unit) : '–' }}

    + @else +
    + + itemId) aria-invalid="true" aria-describedby="counted-{{ $line->itemId }}-error" @enderror + class="mt-1 h-10 w-full rounded-md border border-zinc-500 bg-white px-2 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100" + /> + @error('counted.'.$line->itemId) +

    {{ $message }}

    + @enderror +
    + @endif +
  • + @endforeach +
+
+ @empty +

{{ __('inventory.counts.no_lines') }}

+ @endforelse + + @can('inventory.manage-counts') + +

{{ __('inventory.counts.confirm_text') }}

+ @if ($this->uncountedCount() > 0) +

{{ trans_choice('inventory.counts.confirm_uncounted', $this->uncountedCount(), ['count' => $this->uncountedCount()]) }}

+ @endif + + + + +
+ @endcan +
diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡counts.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡counts.blade.php new file mode 100644 index 0000000..d739320 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡counts.blade.php @@ -0,0 +1,144 @@ + + */ + public array $groupIds = []; + + public function mount(): void + { + $this->authorize('inventory.count'); + } + + /** + * @return list + */ + #[Computed] + public function counts(): array + { + return app(InventoryCountQueries::class)->counts(); + } + + /** + * @return list + */ + #[Computed] + public function groupOptions(): array + { + return array_map( + fn ($group): array => ['value' => $group->id, 'label' => $group->name], + app(StockQueries::class)->groups(includeInactive: false), + ); + } + + public function start(InventoryCounts $counts): void + { + $this->authorize('inventory.manage-counts'); + + try { + $id = $counts->start(array_map('intval', $this->groupIds), (int) auth()->id()); + } catch (InventoryCountAlreadyOpen) { + $this->addError('groupIds', __('inventory.counts.errors.already_open')); + + return; + } + + $this->redirectRoute('inventory.counts.show', $id, navigate: true); + } + + public function render(): mixed + { + return $this->view()->title(__('inventory.counts.title')); + } +}; +?> + +
+
+

{{ __('inventory.counts.title') }}

+

{{ __('inventory.counts.intro') }}

+
+ + @can('inventory.manage-counts') +
+

{{ __('inventory.counts.start_title') }}

+
+ @if ($this->groupOptions !== []) + + @endif + @error('groupIds') + + @enderror + + +
+ @endcan + +
+

{{ __('inventory.counts.list') }}

+ + @if ($this->counts === []) +

{{ __('inventory.counts.none') }}

+ @else +
    + @foreach ($this->counts as $count) +
  • +
    +

    + + {{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }} + +

    +

    + {{ $count->groupNames === [] ? __('inventory.counts.whole_stock') : implode(', ', $count->groupNames) }} + · {{ trans_choice('inventory.counts.counted_items', $count->countedItems, ['count' => $count->countedItems]) }} +

    +
    +
    + @if ($count->isConfirmed) + + + @can('inventory.manage-counts') + + + @endcan + @else + + + @endif +
    +
  • + @endforeach +
+ @endif +
+
diff --git a/app/Modules/Inventory/Presentation/Routes/web.php b/app/Modules/Inventory/Presentation/Routes/web.php index f3ab17b..7926ccf 100644 --- a/app/Modules/Inventory/Presentation/Routes/web.php +++ b/app/Modules/Inventory/Presentation/Routes/web.php @@ -1,5 +1,6 @@ whereNumber('item')->name('items.show'); + + Route::middleware('can:inventory.count')->group(function () { + Route::livewire('/counts', 'inventory::counts')->name('counts'); + Route::livewire('/counts/{count}', 'inventory::count')->whereNumber('count')->name('counts.show'); + }); + + Route::get('/counts/{count}/csv', DownloadInventoryCount::class) + ->whereNumber('count') + ->middleware('can:inventory.manage-counts') + ->name('counts.csv'); }); diff --git a/app/View/MainMenu.php b/app/View/MainMenu.php index 45e7ebe..6cfdf0b 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -103,6 +103,7 @@ final class MainMenu 'label' => 'layout.group_maintenance', 'items' => [ ['route' => 'inventory.index', 'pattern' => ['inventory.index', 'inventory.items.*', 'inventory.groups'], 'label' => 'layout.inventory', 'ability' => 'inventory.menu'], + ['route' => 'inventory.counts', 'pattern' => ['inventory.counts*'], 'label' => 'layout.inventory_counts', 'ability' => 'inventory.menu'], ['route' => 'catalog.index', 'pattern' => ['catalog.index', 'catalog.service-units.*', 'catalog.services.*', 'catalog.work-types.*'], 'label' => 'layout.catalog', 'ability' => 'catalog.manage'], ['route' => 'catalog.workflow-templates', 'pattern' => ['catalog.workflow-templates*'], 'label' => 'layout.workflow_templates', 'ability' => 'catalog.manage'], ['route' => 'catalog.prices', 'pattern' => ['catalog.prices', 'catalog.products.*', 'catalog.vat-rates.*'], 'label' => 'layout.price_list_admin', 'ability' => 'catalog.manage'], diff --git a/database/migrations/2026_11_26_142839_create_inventory_counts_tables.php b/database/migrations/2026_11_26_142839_create_inventory_counts_tables.php new file mode 100644 index 0000000..aa6a724 --- /dev/null +++ b/database/migrations/2026_11_26_142839_create_inventory_counts_tables.php @@ -0,0 +1,62 @@ +id(); + $table->date('counted_on'); + $table->string('status', 20); + $table->json('group_ids')->nullable(); + $table->foreignId('started_by')->constrained('users')->restrictOnDelete(); + $table->foreignId('confirmed_by')->nullable()->constrained('users')->restrictOnDelete(); + $table->timestamp('confirmed_at')->nullable(); + $table->bigInteger('value_before_cents')->nullable(); + $table->bigInteger('value_after_cents')->nullable(); + $table->timestamps(); + }); + + Schema::create('inventory_count_lines', function (Blueprint $table) { + $table->id(); + $table->foreignId('inventory_count_id')->constrained()->cascadeOnDelete(); + $table->foreignId('stock_item_id')->constrained()->restrictOnDelete(); + $table->bigInteger('book_quantity_milli'); + $table->bigInteger('counted_quantity_milli'); + $table->bigInteger('unit_cost_hundredths')->nullable(); + $table->foreignId('counted_by')->constrained('users')->restrictOnDelete(); + $table->timestamp('counted_at'); + $table->timestamps(); + + $table->unique(['inventory_count_id', 'stock_item_id']); + }); + + Schema::table('stock_movements', function (Blueprint $table) { + $table->foreign('inventory_count_id', 'stock_movements_count_foreign')->references('id')->on('inventory_counts')->restrictOnDelete(); + }); + } + + public function down(): void + { + // SQLite (tests) cannot drop a foreign key; there the table is dropped by the earlier migration's rollback. + if (Schema::getConnection()->getDriverName() !== 'sqlite') { + Schema::table('stock_movements', function (Blueprint $table) { + $table->dropForeign('stock_movements_count_foreign'); + }); + } + + Schema::dropIfExists('inventory_count_lines'); + Schema::dropIfExists('inventory_counts'); + } +}; diff --git a/lang/en/inventory.php b/lang/en/inventory.php index 80f915b..c5c3653 100644 --- a/lang/en/inventory.php +++ b/lang/en/inventory.php @@ -194,6 +194,61 @@ return [ 'undone_mark' => 'undone', ], + 'counts' => [ + 'title' => 'Stock counts', + 'intro' => 'In a stock count the items are counted and the book balances corrected. One count may be open at a time; several people may count, in several parts.', + 'start_title' => 'Start a stock count', + 'groups' => 'Item groups', + 'groups_hint' => 'Leave all unchecked to count the whole stock.', + 'start' => 'Start stock count', + 'list' => 'Stock counts', + 'none' => 'No stock counts yet.', + 'name' => 'Stock count :date', + 'whole_stock' => 'Whole stock', + 'counted_items' => '{0} no items counted|{1} 1 item counted|[2,*] :count items counted', + 'open' => 'Open', + 'confirmed_by' => 'Confirmed :at (:name)', + 'started_by' => 'started by :name', + 'values' => 'Stock value before corrections :before, after corrections :after.', + 'count_help' => 'Type the counted quantity; it is saved when you leave the field. An empty field takes the item back to not counted. The difference is to the book balance at the moment of counting.', + 'only_uncounted' => 'Show only items not counted', + 'uncounted' => '{0} All items counted.|{1} 1 item not counted.|[2,*] :count items not counted.', + 'counted' => 'Counted (:unit)', + 'book' => 'book balance :book', + 'difference' => 'difference :difference', + 'current' => 'balance now :balance', + 'not_counted' => 'Not counted', + 'saved' => ':item: counted :counted, difference :difference.', + 'cleared' => ':item taken back to not counted.', + 'no_lines' => 'No items in this selection.', + 'confirm' => 'Confirm stock count', + 'confirm_title' => 'Confirm the stock count?', + 'confirm_text' => 'Every difference is recorded as a stock count correction at the average cost. A confirmed count cannot be changed.', + 'confirm_uncounted' => '{1} 1 item is not counted, and its balance is not changed.|[2,*] :count items are not counted, and their balances are not changed.', + 'confirmed_message' => '{0} Stock count confirmed. There were no differences.|{1} Stock count confirmed: 1 correction recorded.|[2,*] Stock count confirmed: :count corrections recorded.', + 'download_csv' => 'Download CSV', + 'csv_named' => 'Download stock count :date as CSV', + 'back' => 'Back to stock counts', + 'csv' => [ + 'file' => 'stock-count-:date', + 'item' => 'Item', + 'code' => 'Code', + 'group' => 'Group', + 'unit' => 'Unit', + 'book' => 'Balance', + 'counted' => 'Counted', + 'difference' => 'Difference', + 'unit_cost' => 'Average cost (€)', + 'book_value' => 'Balance value (cents)', + 'counted_value' => 'Counted value (cents)', + 'difference_value' => 'Difference value (cents)', + ], + 'errors' => [ + 'already_open' => 'Another stock count is open. Confirm it before starting a new one.', + 'confirmed' => 'The stock count has been confirmed and cannot be changed.', + 'quantity' => 'Enter a quantity of zero or more, at most three decimals.', + ], + ], 'errors' => [ 'name' => 'Enter a name (1–150 characters).', 'name_taken' => 'The name is already in use.', diff --git a/lang/fi/inventory.php b/lang/fi/inventory.php index 169433f..fceba93 100644 --- a/lang/fi/inventory.php +++ b/lang/fi/inventory.php @@ -194,6 +194,61 @@ return [ 'undone_mark' => 'peruttu', ], + 'counts' => [ + 'title' => 'Inventaario', + 'intro' => 'Inventaariossa lasketaan varaston nimikkeet ja korjataan kirjanpitosaldot. Kesken voi olla yksi inventaario kerrallaan; laskennan voi tehdä useampi henkilö ja useassa osassa.', + 'start_title' => 'Aloita inventaario', + 'groups' => 'Nimikeryhmät', + 'groups_hint' => 'Jätä kaikki valitsematta, niin inventaario koskee koko varastoa.', + 'start' => 'Aloita inventaario', + 'list' => 'Inventaariot', + 'none' => 'Ei vielä inventaarioita.', + 'name' => 'Inventaario :date', + 'whole_stock' => 'Koko varasto', + 'counted_items' => '{0} ei laskettuja nimikkeitä|{1} 1 laskettu nimike|[2,*] :count laskettua nimikettä', + 'open' => 'Kesken', + 'confirmed_by' => 'Vahvistettu :at (:name)', + 'started_by' => 'aloittanut :name', + 'values' => 'Varaston arvo ennen korjauksia :before, korjausten jälkeen :after.', + 'count_help' => 'Kirjoita laskettu määrä; se tallentuu, kun siirryt pois kentästä. Tyhjä kenttä palauttaa nimikkeen laskemattomaksi. Ero lasketaan laskentahetken kirjanpitosaldosta.', + 'only_uncounted' => 'Näytä vain laskemattomat', + 'uncounted' => '{0} Kaikki nimikkeet laskettu.|{1} 1 nimike laskematta.|[2,*] :count nimikettä laskematta.', + 'counted' => 'Laskettu (:unit)', + 'book' => 'kirjanpitosaldo :book', + 'difference' => 'ero :difference', + 'current' => 'saldo nyt :balance', + 'not_counted' => 'Laskematta', + 'saved' => ':item: laskettu :counted, ero :difference.', + 'cleared' => ':item palautettu laskemattomaksi.', + 'no_lines' => 'Ei nimikkeitä tällä rajauksella.', + 'confirm' => 'Vahvista inventaario', + 'confirm_title' => 'Vahvistetaanko inventaario?', + 'confirm_text' => 'Jokaisesta erosta kirjataan inventaariokorjaus keskihinnalla. Vahvistettua inventaariota ei voi muuttaa.', + 'confirm_uncounted' => '{1} 1 nimike on laskematta, eikä sen saldoa muuteta.|[2,*] :count nimikettä on laskematta, eikä niiden saldoja muuteta.', + 'confirmed_message' => '{0} Inventaario vahvistettu. Eroja ei ollut.|{1} Inventaario vahvistettu: 1 korjaus kirjattu.|[2,*] Inventaario vahvistettu: :count korjausta kirjattu.', + 'download_csv' => 'Lataa CSV', + 'csv_named' => 'Lataa inventaario :date CSV-tiedostona', + 'back' => 'Takaisin inventaarioihin', + 'csv' => [ + 'file' => 'inventaario-:date', + 'item' => 'Nimike', + 'code' => 'Koodi', + 'group' => 'Ryhmä', + 'unit' => 'Yksikkö', + 'book' => 'Saldo', + 'counted' => 'Laskettu', + 'difference' => 'Ero', + 'unit_cost' => 'Keskihinta (€)', + 'book_value' => 'Saldon arvo (snt)', + 'counted_value' => 'Lasketun arvo (snt)', + 'difference_value' => 'Eron arvo (snt)', + ], + 'errors' => [ + 'already_open' => 'Toinen inventaario on kesken. Vahvista se ennen uuden aloittamista.', + 'confirmed' => 'Inventaario on vahvistettu, eikä sitä voi muuttaa.', + 'quantity' => 'Anna määrä nollana tai suurempana lukuna, enintään kolme desimaalia.', + ], + ], 'errors' => [ 'name' => 'Anna nimi (1–150 merkkiä).', 'name_taken' => 'Nimi on jo käytössä.', diff --git a/tests/Browser/InventoryAccessibilityTest.php b/tests/Browser/InventoryAccessibilityTest.php index 532d6d0..a67a6be 100644 --- a/tests/Browser/InventoryAccessibilityTest.php +++ b/tests/Browser/InventoryAccessibilityTest.php @@ -3,6 +3,7 @@ use App\Models\User; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; +use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\InventoryCountModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel; @@ -94,3 +95,28 @@ it('records material on a task card with the keyboard and without accessibility 'desktop, light' => ['desktop', 'light'], 'mobile, dark' => ['mobile', 'dark'], ]); + +it('has no accessibility issues on the stock count pages and saves a counted quantity', function (string $device, string $colorScheme) { + $count = InventoryCountModel::query()->create([ + 'counted_on' => now()->toDateString(), 'status' => 'open', 'started_by' => $this->user->id, + ]); + + foreach ([route('inventory.counts'), route('inventory.counts.show', $count->id)] as $url) { + $visit = visit($url); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee(__('inventory.counts.title'))->assertNoJavaScriptErrors()->assertNoAccessibilityIssues(level: 2); + } + + visit(route('inventory.counts.show', $count->id)) + ->fill('#counted-'.$this->item->id, '38') + ->keys('#counted-'.$this->item->id, 'Tab') + ->assertSee('Valokuvapaperi: laskettu 38') + ->click(__('inventory.counts.confirm')) + ->assertSee(__('inventory.counts.confirm_title')) + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Feature/Modules/Inventory/InventoryCountTest.php b/tests/Feature/Modules/Inventory/InventoryCountTest.php new file mode 100644 index 0000000..7f9e376 --- /dev/null +++ b/tests/Feature/Modules/Inventory/InventoryCountTest.php @@ -0,0 +1,95 @@ +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->inks = StockItemGroupModel::factory()->create(['name' => 'Musteet', 'sort_order' => 2]); + $this->paper = StockItemModel::factory()->create(['stock_item_group_id' => $this->papers->id, 'name' => 'Valokuvapaperi', 'unit' => 'sheet', 'average_cost_hundredths' => 5_000]); + $this->card = StockItemModel::factory()->create(['stock_item_group_id' => $this->papers->id, 'name' => 'Kartonki', 'average_cost_hundredths' => 10_000]); + $this->ink = StockItemModel::factory()->create(['stock_item_group_id' => $this->inks->id, 'name' => 'Muste', 'unit' => 'litre']); + + foreach ([[$this->paper, 100_000], [$this->card, 10_000]] as [$item, $milli]) { + StockMovementModel::query()->create([ + 'stock_item_id' => $item->id, 'kind' => 'purchase', 'quantity_milli' => $milli, 'unit_cost_hundredths' => $item->average_cost_hundredths, + 'value_cents' => intdiv($milli * $item->average_cost_hundredths, 100_000), 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->manager->id, + ]); + } +}); + +it('counts the chosen groups, keeps the book balance of the moment and corrects the differences on confirmation', function () { + $this->actingAs($this->manager); + + Livewire::test('inventory::counts')->set('groupIds', [(string) $this->papers->id])->call('start')->assertHasNoErrors(); + $count = InventoryCountModel::query()->sole(); + + Livewire::test('inventory::counts')->call('start')->assertHasErrors('groupIds'); + + $this->actingAs($this->employee); + Livewire::test('inventory::count', ['count' => $count->id]) + ->assertSee('Valokuvapaperi') + ->assertDontSee('Muste') + ->assertSee('2 nimikettä laskematta.') + ->call('saveCounted', $this->paper->id, '95') + ->assertSet('message', "Valokuvapaperi: laskettu 95\u{00A0}arkki, ero -5\u{00A0}arkki.") + ->call('saveCounted', $this->card->id, 'x') + ->assertHasErrors('counted.'.$this->card->id) + ->set('onlyUncounted', true) + ->assertSee('Kartonki') + ->assertDontSee('kirjanpitosaldo 100'); + + Livewire::test('inventory::count', ['count' => $count->id])->call('saveCounted', $this->ink->id, '1')->assertNotFound(); + + // Use recorded during the count does not change the counted difference. + StockMovementModel::query()->create([ + 'stock_item_id' => $this->paper->id, 'kind' => 'consumption', 'quantity_milli' => -10_000, 'unit_cost_hundredths' => 5_000, + 'value_cents' => -500, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->employee->id, 'reason' => 'Testi', + ]); + + Livewire::test('inventory::count', ['count' => $count->id])->call('confirmCount')->assertForbidden(); + + $this->actingAs($this->manager); + Livewire::test('inventory::count', ['count' => $count->id]) + ->assertSee('1 nimike laskematta.') + ->call('confirmCount') + ->assertSee('1 nimike on laskematta, eikä sen saldoa muuteta.') + ->call('confirm') + ->assertSet('message', 'Inventaario vahvistettu: 1 korjaus kirjattu.'); + + $adjustment = StockMovementModel::query()->where('kind', StockMovementKind::Adjustment)->sole(); + $count->refresh(); + + expect($adjustment->quantity_milli)->toBe(-5_000) + ->and($adjustment->inventory_count_id)->toBe($count->id) + ->and($count->status)->toBe('confirmed') + ->and($count->value_before_cents)->toBe(4_500 + 1_000) + ->and($count->value_after_cents)->toBe(4_250 + 1_000) + ->and((int) StockMovementModel::query()->where('stock_item_id', $this->paper->id)->sum('quantity_milli'))->toBe(85_000); + + Livewire::test('inventory::count', ['count' => $count->id]) + ->call('saveCounted', $this->paper->id, '9') + ->assertSet('message', __('inventory.counts.errors.confirmed')); + + $csv = $this->get(route('inventory.counts.csv', $count->id))->assertOk()->streamedContent(); + expect($csv)->toContain('Valokuvapaperi;;Paperit;arkki;100;95;-5;0,5000;5000;4750;-250'); + + $this->actingAs($this->employee); + $this->get(route('inventory.counts.csv', $count->id))->assertForbidden(); +}); + +it('keeps subcontractors out of stock counts', function () { + $this->actingAs(User::factory()->subcontractor()->create()); + + $this->get(route('inventory.counts'))->assertForbidden(); +});