$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; }); } }