Count stock and correct the differences on confirmation
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\InventoryCountLine;
|
||||
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
|
||||
|
||||
interface InventoryCountQueries
|
||||
{
|
||||
/**
|
||||
* @return list<InventoryCountSummary> 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<InventoryCountLine>
|
||||
*/
|
||||
public function lines(int $countId): array;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
|
||||
/**
|
||||
* An item on a stock count's list: its current balance and, once counted,
|
||||
* the counted quantity and the book balance at the moment of counting.
|
||||
* The unit cost is the one stored at confirmation, or the current average
|
||||
* cost while the count is open.
|
||||
*/
|
||||
final readonly class InventoryCountLine
|
||||
{
|
||||
public function __construct(
|
||||
public int $itemId,
|
||||
public string $itemName,
|
||||
public ?string $code,
|
||||
public int $groupId,
|
||||
public string $groupName,
|
||||
public StockUnit $unit,
|
||||
public int $currentBalanceMilli,
|
||||
public ?int $bookMilli,
|
||||
public ?int $countedMilli,
|
||||
public int $unitCostHundredths,
|
||||
public ?string $countedByName,
|
||||
public ?string $countedAt,
|
||||
) {}
|
||||
|
||||
public function isCounted(): bool
|
||||
{
|
||||
return $this->countedMilli !== null;
|
||||
}
|
||||
|
||||
public function differenceMilli(): ?int
|
||||
{
|
||||
return $this->countedMilli === null || $this->bookMilli === null ? null : $this->countedMilli - $this->bookMilli;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A stock count as listed. $groupNames is empty for the whole stock;
|
||||
* $confirmedAt is "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class InventoryCountSummary
|
||||
{
|
||||
/**
|
||||
* @param list<string> $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,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\InventoryCount;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountAlreadyOpen;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotInCount;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Stock counts (inventaario, spec 19.3): management starts one for the
|
||||
* whole stock or chosen groups (one open at a time), anyone using stock
|
||||
* enters counted quantities, possibly in parts and on several devices,
|
||||
* and management confirms it: every difference becomes an adjustment at
|
||||
* the average cost, and the stock value before and after is stored.
|
||||
* Items not counted are left as they are.
|
||||
*/
|
||||
final class InventoryCounts
|
||||
{
|
||||
public function __construct(
|
||||
private InventoryCountRepository $counts,
|
||||
private StockItemRepository $items,
|
||||
private StockMovementRepository $movements,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param list<int> $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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Domain\Entities\InventoryCount;
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface InventoryCountRepository
|
||||
{
|
||||
public function findById(int $id): ?InventoryCount;
|
||||
|
||||
/**
|
||||
* The count, locked until the end of the transaction.
|
||||
*/
|
||||
public function lockById(int $id): ?InventoryCount;
|
||||
|
||||
public function hasOpen(): bool;
|
||||
|
||||
public function save(InventoryCount $count): InventoryCount;
|
||||
|
||||
/**
|
||||
* Stores a counted quantity with the book balance of the moment; a
|
||||
* recount replaces the line.
|
||||
*/
|
||||
public function recordLine(int $countId, int $itemId, int $bookMilli, int $countedMilli, int $userId, DateTimeImmutable $at): void;
|
||||
|
||||
public function removeLine(int $countId, int $itemId): void;
|
||||
|
||||
/**
|
||||
* @return list<array{itemId: int, bookMilli: int, countedMilli: int}>
|
||||
*/
|
||||
public function lines(int $countId): array;
|
||||
|
||||
public function setLineUnitCost(int $countId, int $itemId, int $unitCostHundredths): void;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Entities;
|
||||
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A stock count (inventaario, spec 19.3) of the whole stock or of chosen
|
||||
* item groups. It is open while counted and confirmed once by management;
|
||||
* a confirmed count is never changed.
|
||||
*/
|
||||
final class InventoryCount
|
||||
{
|
||||
/**
|
||||
* @param list<int>|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<int>|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<int>|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<int>|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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InventoryCountAlreadyOpen extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Another stock count is open.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InventoryCountConfirmed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock count has been confirmed and cannot be changed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InventoryCountNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock count was not found.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockItemNotInCount extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The item is not in this stock count.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Inventory Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $inventory_count_id
|
||||
* @property int $stock_item_id
|
||||
* @property int $book_quantity_milli
|
||||
* @property int $counted_quantity_milli
|
||||
* @property int|null $unit_cost_hundredths
|
||||
* @property int $counted_by
|
||||
* @property Carbon $counted_at
|
||||
*/
|
||||
#[Table('inventory_count_lines')]
|
||||
#[Fillable(['inventory_count_id', 'stock_item_id', 'book_quantity_milli', 'counted_quantity_milli', 'unit_cost_hundredths', 'counted_by', 'counted_at'])]
|
||||
class InventoryCountLineModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Inventory Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property Carbon $counted_on
|
||||
* @property string $status
|
||||
* @property list<int>|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<InventoryCountLineModel, $this>
|
||||
*/
|
||||
public function lines(): HasMany
|
||||
{
|
||||
return $this->hasMany(InventoryCountLineModel::class, 'inventory_count_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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',
|
||||
];
|
||||
}
|
||||
}
|
||||
+102
@@ -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');
|
||||
}
|
||||
}
|
||||
+99
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\InventoryCountQueries;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* A confirmed stock count as a CSV for the bookkeeping (spec 19.3): item,
|
||||
* unit, book balance, counted quantity, difference, average cost and the
|
||||
* values in cents. Semicolons and a UTF-8 BOM for Excel; quantities with a
|
||||
* decimal comma; text that looks like a formula gets an apostrophe.
|
||||
*/
|
||||
class DownloadInventoryCount
|
||||
{
|
||||
public function __invoke(int $count, InventoryCountQueries $counts): StreamedResponse
|
||||
{
|
||||
Gate::authorize('inventory.manage-counts');
|
||||
|
||||
$summary = $counts->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\InventoryCountQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\InventoryCountLine;
|
||||
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
|
||||
use App\Modules\Inventory\Application\UseCases\InventoryCounts;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotInCount;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A stock count's counting list (spec 19.3): items by group, with a field
|
||||
* for the counted quantity that saves when left (several people may count
|
||||
* at the same time, also on tablets). The difference to the book balance
|
||||
* at the moment of counting is shown as a quantity, and for management as
|
||||
* a value. Management confirms the count in a dialog that tells how many
|
||||
* items are left uncounted.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsStock;
|
||||
|
||||
#[Locked]
|
||||
public int $countId;
|
||||
|
||||
public bool $onlyUncounted = false;
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
public function mount(int $count): void
|
||||
{
|
||||
$this->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<InventoryCountLine>
|
||||
*/
|
||||
#[Computed]
|
||||
public function lines(): array
|
||||
{
|
||||
return app(InventoryCountQueries::class)->lines($this->countId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines shown, by group name.
|
||||
*
|
||||
* @return array<string, list<InventoryCountLine>>
|
||||
*/
|
||||
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)]));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
|
||||
@php($count = $this->count)
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-sm"><x-link :href="route('inventory.counts')" navigate>{{ __('inventory.counts.back') }}</x-link></p>
|
||||
<h1 class="text-2xl font-semibold">{{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }}</h1>
|
||||
<p class="text-sm">
|
||||
{{ $count->groupNames === [] ? __('inventory.counts.whole_stock') : implode(', ', $count->groupNames) }}
|
||||
· {{ __('inventory.counts.started_by', ['name' => $count->startedByName]) }}
|
||||
</p>
|
||||
@if ($count->isConfirmed)
|
||||
<p class="flex items-center gap-2 text-sm font-medium">
|
||||
<x-icon name="lock-closed" class="size-5" aria-hidden="true" />
|
||||
{{ __('inventory.counts.confirmed_by', ['name' => $count->confirmedByName, 'at' => $this->dateLabel((string) $count->confirmedAt)]) }}
|
||||
</p>
|
||||
@can('inventory.see-value')
|
||||
<p class="text-sm">{{ __('inventory.counts.values', ['before' => $this->money((int) $count->valueBeforeCents), 'after' => $this->money((int) $count->valueAfterCents)]) }}</p>
|
||||
@endcan
|
||||
@else
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.counts.count_help') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<p id="count-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-4">
|
||||
@unless ($count->isConfirmed)
|
||||
<x-checkbox id="only-uncounted" wire:model.live="onlyUncounted" :label="__('inventory.counts.only_uncounted')" />
|
||||
@endunless
|
||||
<p class="text-sm">{{ trans_choice('inventory.counts.uncounted', $this->uncountedCount(), ['count' => $this->uncountedCount()]) }}</p>
|
||||
@if (! $count->isConfirmed)
|
||||
@can('inventory.manage-counts')
|
||||
<x-button wire:click="confirmCount" icon="check-badge" :text="__('inventory.counts.confirm')" />
|
||||
@endcan
|
||||
@else
|
||||
@can('inventory.manage-counts')
|
||||
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 text-sm font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
|
||||
<x-icon name="arrow-down-tray" class="size-4" aria-hidden="true" />
|
||||
{{ __('inventory.counts.download_csv') }}
|
||||
</a>
|
||||
@endcan
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@forelse ($this->groupedLines() as $groupName => $lines)
|
||||
<section wire:key="count-group-{{ md5($groupName) }}" aria-label="{{ $groupName }}" class="space-y-2">
|
||||
<h2 class="text-lg font-semibold">{{ $groupName }}</h2>
|
||||
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
|
||||
@foreach ($lines as $line)
|
||||
@php($difference = $line->differenceMilli())
|
||||
<li wire:key="count-line-{{ $line->itemId }}" class="flex flex-wrap items-end justify-between gap-3 p-3">
|
||||
<div class="min-w-0 flex-1 space-y-1">
|
||||
<p class="font-medium break-words">{{ $line->itemName }}</p>
|
||||
<p class="text-sm text-zinc-700 dark:text-zinc-300">
|
||||
@if ($line->isCounted())
|
||||
{{ __('inventory.counts.book', ['book' => $this->quantity((int) $line->bookMilli, $line->unit)]) }}
|
||||
· <span class="font-medium">{{ __('inventory.counts.difference', ['difference' => $this->signed((int) $difference, $line->unit)]) }}</span>
|
||||
@can('inventory.see-value')
|
||||
({{ $this->money($this->differenceValue($line)) }})
|
||||
@endcan
|
||||
· {{ $line->countedByName }}, {{ $this->dateLabel((string) $line->countedAt) }}
|
||||
@else
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<x-icon name="question-mark-circle" class="size-4" aria-hidden="true" />
|
||||
{{ __('inventory.counts.not_counted') }}
|
||||
</span>
|
||||
· {{ __('inventory.counts.current', ['balance' => $this->quantity($line->currentBalanceMilli, $line->unit)]) }}
|
||||
@endif
|
||||
</p>
|
||||
</div>
|
||||
@if ($count->isConfirmed)
|
||||
<p class="text-sm font-medium">{{ $line->isCounted() ? $this->quantity((int) $line->countedMilli, $line->unit) : '–' }}</p>
|
||||
@else
|
||||
<div class="w-36">
|
||||
<label for="counted-{{ $line->itemId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">
|
||||
{{ __('inventory.counts.counted', ['unit' => __('inventory.units.'.$line->unit->value)]) }}
|
||||
<span class="sr-only">: {{ $line->itemName }}</span>
|
||||
</label>
|
||||
<input
|
||||
id="counted-{{ $line->itemId }}"
|
||||
type="text"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
value="{{ $line->isCounted() ? StockQuantity::inputValue((int) $line->countedMilli) : '' }}"
|
||||
wire:change="saveCounted({{ $line->itemId }}, $event.target.value)"
|
||||
@error('counted.'.$line->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)
|
||||
<p id="counted-{{ $line->itemId }}-error" class="mt-1 text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</section>
|
||||
@empty
|
||||
<p class="text-sm">{{ __('inventory.counts.no_lines') }}</p>
|
||||
@endforelse
|
||||
|
||||
@can('inventory.manage-counts')
|
||||
<x-confirm-dialog id="confirm-count-dialog" :title="__('inventory.counts.confirm_title')">
|
||||
<p>{{ __('inventory.counts.confirm_text') }}</p>
|
||||
@if ($this->uncountedCount() > 0)
|
||||
<p class="mt-2 font-medium">{{ trans_choice('inventory.counts.confirm_uncounted', $this->uncountedCount(), ['count' => $this->uncountedCount()]) }}</p>
|
||||
@endif
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="confirm" :text="__('inventory.counts.confirm')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
@endcan
|
||||
</div>
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\InventoryCountQueries;
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
|
||||
use App\Modules\Inventory\Application\UseCases\InventoryCounts;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InventoryCountAlreadyOpen;
|
||||
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* Stock counts (inventaario, spec 19.3): the list of counts, newest first,
|
||||
* and for management the start of a new one for the whole stock or chosen
|
||||
* item groups. Only one count is open at a time.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsStock;
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
public array $groupIds = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('inventory.count');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<InventoryCountSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function counts(): array
|
||||
{
|
||||
return app(InventoryCountQueries::class)->counts();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{value: int, label: string}>
|
||||
*/
|
||||
#[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'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-2xl font-semibold">{{ __('inventory.counts.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.counts.intro') }}</p>
|
||||
</div>
|
||||
|
||||
@can('inventory.manage-counts')
|
||||
<section aria-labelledby="start-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="start-heading" class="text-lg font-semibold">{{ __('inventory.counts.start_title') }}</h2>
|
||||
<form wire:submit="start" class="space-y-4" novalidate>
|
||||
@if ($this->groupOptions !== [])
|
||||
<x-checkbox-group
|
||||
:legend="__('inventory.counts.groups')"
|
||||
model="groupIds"
|
||||
:options="$this->groupOptions"
|
||||
:hint="__('inventory.counts.groups_hint')"
|
||||
/>
|
||||
@endif
|
||||
@error('groupIds')
|
||||
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
<x-button submit icon="clipboard-document-check" :text="__('inventory.counts.start')" />
|
||||
</form>
|
||||
</section>
|
||||
@endcan
|
||||
|
||||
<section aria-labelledby="counts-heading" class="space-y-3">
|
||||
<h2 id="counts-heading" class="text-lg font-semibold">{{ __('inventory.counts.list') }}</h2>
|
||||
|
||||
@if ($this->counts === [])
|
||||
<p class="text-sm">{{ __('inventory.counts.none') }}</p>
|
||||
@else
|
||||
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
|
||||
@foreach ($this->counts as $count)
|
||||
<li wire:key="count-{{ $count->id }}" class="flex flex-wrap items-center justify-between gap-3 p-3">
|
||||
<div class="min-w-0 space-y-1">
|
||||
<p class="font-medium">
|
||||
<x-link :href="route('inventory.counts.show', $count->id)" navigate>
|
||||
{{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }}
|
||||
</x-link>
|
||||
</p>
|
||||
<p class="text-sm">
|
||||
{{ $count->groupNames === [] ? __('inventory.counts.whole_stock') : implode(', ', $count->groupNames) }}
|
||||
· {{ trans_choice('inventory.counts.counted_items', $count->countedItems, ['count' => $count->countedItems]) }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm">
|
||||
@if ($count->isConfirmed)
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<x-icon name="lock-closed" class="size-4" aria-hidden="true" />
|
||||
{{ __('inventory.counts.confirmed_by', ['name' => $count->confirmedByName, 'at' => $this->dateLabel((string) $count->confirmedAt)]) }}
|
||||
</span>
|
||||
@can('inventory.manage-counts')
|
||||
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
|
||||
<x-icon name="arrow-down-tray" class="size-4" aria-hidden="true" />
|
||||
{{ __('inventory.counts.csv_named', ['date' => $this->dateLabel($count->countedOn)]) }}
|
||||
</a>
|
||||
@endcan
|
||||
@else
|
||||
<span class="inline-flex items-center gap-1 font-medium">
|
||||
<x-icon name="pencil-square" class="size-4" aria-hidden="true" />
|
||||
{{ __('inventory.counts.open') }}
|
||||
</span>
|
||||
@endif
|
||||
</div>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</section>
|
||||
</div>
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Presentation\Http\Controllers\DownloadInventoryCount;
|
||||
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
@@ -20,4 +21,14 @@ Route::middleware(['web', 'auth', 'can:inventory.view'])
|
||||
});
|
||||
|
||||
Route::livewire('/items/{item}', 'inventory::item')->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');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user