Count stock and correct the differences on confirmation

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:34:08 +02:00
co-authored by Claude Sonnet 5.5
parent bca1eed166
commit 0de0e332b2
27 changed files with 1568 additions and 0 deletions
@@ -0,0 +1,102 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Application\Contracts\InventoryCountQueries;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\InventoryCountLine;
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\InventoryCountLineModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\InventoryCountModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class EloquentInventoryCountQueries implements InventoryCountQueries
{
public function __construct(
private StockQueries $stock,
private UserAccountQueries $users,
) {}
public function counts(): array
{
return $this->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<int, InventoryCountModel> $models
* @return list<InventoryCountSummary>
*/
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');
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository;
use App\Modules\Inventory\Domain\Entities\InventoryCount;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\InventoryCountLineModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\InventoryCountModel;
use DateTimeImmutable;
class EloquentInventoryCountRepository implements InventoryCountRepository
{
public function findById(int $id): ?InventoryCount
{
$model = InventoryCountModel::query()->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,
);
}
}
@@ -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(