Add stock items, groups and movements at a moving average cost
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
|
||||
|
||||
/**
|
||||
* Keeps the image files of stock items, which help recognise them on a
|
||||
* touch screen: an upright JPEG without metadata and its thumbnail.
|
||||
*/
|
||||
interface StockItemImages
|
||||
{
|
||||
/**
|
||||
* @return array{path: string, thumbnailPath: string}
|
||||
*
|
||||
* @throws InvalidStockImage
|
||||
*/
|
||||
public function store(string $uploadedFilePath, int $itemId): array;
|
||||
|
||||
/**
|
||||
* @param list<string> $paths
|
||||
*/
|
||||
public function delete(array $paths): void;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
|
||||
|
||||
/**
|
||||
* Reads stock items, groups and movements. Other modules (machines, quick
|
||||
* sales, jobs' task material) read stock through this contract.
|
||||
*/
|
||||
interface StockQueries
|
||||
{
|
||||
/**
|
||||
* @return list<StockGroupSummary> In order.
|
||||
*/
|
||||
public function groups(bool $includeInactive = true): array;
|
||||
|
||||
/**
|
||||
* Items in group order and then by name. $search matches parts of the
|
||||
* name or code regardless of case and Finnish letters.
|
||||
*
|
||||
* @return list<StockItemSummary>
|
||||
*/
|
||||
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array;
|
||||
|
||||
public function findItem(int $id): ?StockItemSummary;
|
||||
|
||||
/**
|
||||
* @param list<int> $ids
|
||||
* @return array<int, StockItemSummary> By id.
|
||||
*/
|
||||
public function itemsByIds(array $ids): array;
|
||||
|
||||
/**
|
||||
* The item's movements, newest first, with the balance after each.
|
||||
*
|
||||
* @return list<StockMovementSummary>
|
||||
*/
|
||||
public function movementsOf(int $itemId, int $limit = 200): array;
|
||||
|
||||
public function findMovement(int $id): ?StockMovementSummary;
|
||||
|
||||
/**
|
||||
* The private-disk path of the item's image or its thumbnail.
|
||||
*/
|
||||
public function imagePathOf(int $itemId, bool $thumbnail): ?string;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A purchase (hankinta) as entered: the day (Y-m-d), the quantity, and the
|
||||
* price without VAT either in total or per unit (the other left empty).
|
||||
*/
|
||||
final readonly class PurchaseData
|
||||
{
|
||||
public function __construct(
|
||||
public int $itemId,
|
||||
public string $occurredOn,
|
||||
public string $quantity,
|
||||
public string $totalPrice = '',
|
||||
public string $unitPrice = '',
|
||||
public ?string $supplier = null,
|
||||
public ?string $documentNumber = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
final readonly class StockGroupSummary
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
public bool $isActive,
|
||||
public int $itemCount = 0,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A stock item's details as entered: the unit key and the reorder level
|
||||
* as typed ("2,5"; empty for none).
|
||||
*/
|
||||
final readonly class StockItemData
|
||||
{
|
||||
public function __construct(
|
||||
public int $groupId,
|
||||
public string $name,
|
||||
public string $unit,
|
||||
public ?string $code = null,
|
||||
public ?string $supplier = null,
|
||||
public string $reorderLevel = '',
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
|
||||
/**
|
||||
* A stock item with its balance (in thousandths), moving average cost (in
|
||||
* hundredths of a cent per unit) and stock value (in cents). Costs and
|
||||
* values are shown only to those who may see them.
|
||||
*/
|
||||
final readonly class StockItemSummary
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public int $groupId,
|
||||
public string $groupName,
|
||||
public string $name,
|
||||
public StockUnit $unit,
|
||||
public ?string $code,
|
||||
public ?string $supplier,
|
||||
public ?int $reorderLevelMilli,
|
||||
public int $balanceMilli,
|
||||
public int $averageCostHundredths,
|
||||
public int $valueCents,
|
||||
public bool $hasImage,
|
||||
public bool $isActive,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* At or below the reorder level: to be ordered (tilattava).
|
||||
*/
|
||||
public function needsReorder(): bool
|
||||
{
|
||||
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
|
||||
}
|
||||
|
||||
public function isNegative(): bool
|
||||
{
|
||||
return $this->balanceMilli < 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
|
||||
|
||||
/**
|
||||
* A stock movement in an item's history: signed quantity and the balance
|
||||
* after it (in thousandths), its value in cents, when and by whom, and
|
||||
* what it was for. $recordedAt is "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class StockMovementSummary
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public int $itemId,
|
||||
public StockMovementKind $kind,
|
||||
public int $quantityMilli,
|
||||
public int $balanceAfterMilli,
|
||||
public int $valueCents,
|
||||
public string $occurredOn,
|
||||
public string $recordedAt,
|
||||
public int $userId,
|
||||
public string $userName,
|
||||
public ?int $taskId,
|
||||
public ?int $jobId,
|
||||
public ?int $machineId,
|
||||
public ?int $orderLineId,
|
||||
public ?int $maintenanceRecordId,
|
||||
public ?int $inventoryCountId,
|
||||
public ?string $reason,
|
||||
public ?string $supplier,
|
||||
public ?string $documentNumber,
|
||||
public ?int $reversesMovementId,
|
||||
public ?int $reversedByMovementId,
|
||||
) {}
|
||||
|
||||
public function canBeReversed(): bool
|
||||
{
|
||||
return $this->reversedByMovementId === null
|
||||
&& $this->kind !== StockMovementKind::Reversal
|
||||
&& $this->kind !== StockMovementKind::Adjustment;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
/**
|
||||
* Stock used (käyttö) as entered: the quantity as typed and what it was
|
||||
* used for; use without a target needs a reason.
|
||||
*/
|
||||
final readonly class StockUseData
|
||||
{
|
||||
public function __construct(
|
||||
public int $itemId,
|
||||
public string $quantity,
|
||||
public ?int $taskId = null,
|
||||
public ?int $jobId = null,
|
||||
public ?int $machineId = null,
|
||||
public ?int $orderLineId = null,
|
||||
public ?int $maintenanceRecordId = null,
|
||||
public ?string $reason = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\DTOs;
|
||||
|
||||
/**
|
||||
* Recorded use or write-off: the movement, the item's name, the quantity
|
||||
* taken and the item's new balance (in thousandths).
|
||||
*/
|
||||
final readonly class StockUseResult
|
||||
{
|
||||
public function __construct(
|
||||
public int $movementId,
|
||||
public string $itemName,
|
||||
public int $quantityMilli,
|
||||
public int $balanceMilli,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemData;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockItem;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Adds a stock item with a zero balance; stock comes in with purchases.
|
||||
*/
|
||||
final class AddStockItem
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockItemFields $fields,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockName
|
||||
* @throws InvalidStockQuantity
|
||||
* @throws StockItemGroupNotFound
|
||||
* @throws StockNameTaken
|
||||
*/
|
||||
public function execute(StockItemData $data): int
|
||||
{
|
||||
$fields = $this->fields->parse($data);
|
||||
|
||||
return $this->transactions->run(function () use ($data, $fields): int {
|
||||
$this->fields->check($data, $fields['name']);
|
||||
|
||||
$item = StockItem::create($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
|
||||
|
||||
return (int) $this->items->save($item)->id();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Adds a stock item group last in order.
|
||||
*/
|
||||
final class AddStockItemGroup
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemGroupRepository $groups,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockName
|
||||
* @throws StockNameTaken
|
||||
*/
|
||||
public function execute(string $name): int
|
||||
{
|
||||
$name = new StockName($name);
|
||||
|
||||
return $this->transactions->run(function () use ($name): int {
|
||||
if ($this->groups->isNameTaken($name->value)) {
|
||||
throw new StockNameTaken;
|
||||
}
|
||||
|
||||
return (int) $this->groups->save(StockItemGroup::create($name, $this->groups->nextSortOrder()))->id();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Renames a stock item group, moves it one place up or down, or takes it
|
||||
* out of use or back. Groups are never deleted.
|
||||
*/
|
||||
final class ChangeStockItemGroup
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemGroupRepository $groups,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockName
|
||||
* @throws StockNameTaken
|
||||
* @throws StockItemGroupNotFound
|
||||
*/
|
||||
public function rename(int $groupId, string $name): void
|
||||
{
|
||||
$name = new StockName($name);
|
||||
|
||||
$this->transactions->run(function () use ($groupId, $name): void {
|
||||
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
|
||||
|
||||
if ($this->groups->isNameTaken($name->value, $groupId)) {
|
||||
throw new StockNameTaken;
|
||||
}
|
||||
|
||||
$group->rename($name);
|
||||
$this->groups->save($group);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool False when the group already was first (up) or last.
|
||||
*
|
||||
* @throws StockItemGroupNotFound
|
||||
*/
|
||||
public function move(int $groupId, bool $up): bool
|
||||
{
|
||||
return $this->transactions->run(function () use ($groupId, $up): bool {
|
||||
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
|
||||
$neighbour = $this->groups->neighbour($group, $up);
|
||||
|
||||
if ($neighbour === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$group->swapOrderWith($neighbour);
|
||||
$this->groups->save($group);
|
||||
$this->groups->save($neighbour);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StockItemGroupNotFound
|
||||
*/
|
||||
public function setActive(int $groupId, bool $active): void
|
||||
{
|
||||
$this->transactions->run(function () use ($groupId, $active): void {
|
||||
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
|
||||
$active ? $group->activate() : $group->deactivate();
|
||||
$this->groups->save($group);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockItemImages;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Sets or removes a stock item's image; the replaced files are deleted.
|
||||
*/
|
||||
final class ChangeStockItemImage
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockItemImages $images,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param string|null $uploadedFilePath Null removes the image.
|
||||
*
|
||||
* @throws StockItemNotFound
|
||||
* @throws InvalidStockImage
|
||||
*/
|
||||
public function execute(int $itemId, ?string $uploadedFilePath): void
|
||||
{
|
||||
$this->items->findById($itemId) ?? throw new StockItemNotFound;
|
||||
$stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId);
|
||||
|
||||
/** @var list<string> $old */
|
||||
$old = $this->transactions->run(function () use ($itemId, $stored): array {
|
||||
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
|
||||
$old = array_values(array_filter([$item->imagePath(), $item->thumbnailPath()]));
|
||||
|
||||
if ($stored === null) {
|
||||
$item->removeImage();
|
||||
} else {
|
||||
$item->setImage($stored['path'], $stored['thumbnailPath']);
|
||||
}
|
||||
|
||||
$this->items->save($item);
|
||||
|
||||
return $old;
|
||||
});
|
||||
|
||||
$this->images->delete($old);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\PurchaseData;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Records a purchase (hankinta): stock comes in at its price without VAT,
|
||||
* given in total or per unit, and the item's moving average cost is
|
||||
* updated (spec 19.2).
|
||||
*/
|
||||
final class RecordStockPurchase
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockMovementRepository $movements,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The movement's id.
|
||||
*
|
||||
* @throws StockItemNotFound
|
||||
* @throws InvalidStockQuantity
|
||||
* @throws InvalidStockCost
|
||||
* @throws InvalidStockDay
|
||||
*/
|
||||
public function execute(PurchaseData $data, int $actorUserId): int
|
||||
{
|
||||
$quantity = StockQuantity::parsePositive($data->quantity);
|
||||
$valueCents = $this->valueCents($data, $quantity);
|
||||
$occurredOn = $this->day($data->occurredOn);
|
||||
|
||||
return $this->transactions->run(function () use ($data, $quantity, $valueCents, $occurredOn, $actorUserId): int {
|
||||
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
|
||||
$balance = $this->movements->balanceOf($data->itemId);
|
||||
|
||||
$movement = StockMovement::purchase($item, $quantity, $valueCents, $occurredOn, $this->clock->now(), $actorUserId, $data->supplier ?? $item->supplier(), $data->documentNumber);
|
||||
|
||||
$item->receive($balance, $quantity->milli, $valueCents);
|
||||
$this->items->save($item);
|
||||
|
||||
return (int) $this->movements->add($movement)->id();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockCost
|
||||
*/
|
||||
private function valueCents(PurchaseData $data, StockQuantity $quantity): int
|
||||
{
|
||||
try {
|
||||
$total = Money::parse($data->totalPrice);
|
||||
} catch (InvalidMoneyAmount) {
|
||||
throw new InvalidStockCost;
|
||||
}
|
||||
|
||||
if ($total !== null) {
|
||||
return $total->cents;
|
||||
}
|
||||
|
||||
return StockValuation::valueCents($quantity->milli, $this->unitCostHundredths($data->unitPrice));
|
||||
}
|
||||
|
||||
/**
|
||||
* A unit price with up to four decimals ("0,0123") in hundredths of a cent.
|
||||
*
|
||||
* @throws InvalidStockCost
|
||||
*/
|
||||
private function unitCostHundredths(string $value): int
|
||||
{
|
||||
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? '');
|
||||
|
||||
if (preg_match('/^(\d{1,7})(?:\.(\d{1,4}))?$/', $value, $matches) !== 1) {
|
||||
throw new InvalidStockCost;
|
||||
}
|
||||
|
||||
return (int) $matches[1] * 10_000 + (int) str_pad($matches[2] ?? '', 4, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockDay
|
||||
*/
|
||||
private function day(string $value): DateTimeImmutable
|
||||
{
|
||||
if ($value === '') {
|
||||
return $this->clock->today();
|
||||
}
|
||||
|
||||
$day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
|
||||
if ($day === false || $day->format('Y-m-d') !== $value) {
|
||||
throw new InvalidStockDay;
|
||||
}
|
||||
|
||||
return $day;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseData;
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseResult;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Records stock used (käyttö) today at the moving average cost, for a
|
||||
* task, a machine, a quick sale order or a maintenance, or with a reason.
|
||||
* Use is never refused for a low balance: a machine must not stop for the
|
||||
* record, so the balance may go negative, which the stock list warns of
|
||||
* (spec 19.2).
|
||||
*/
|
||||
final class RecordStockUse
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockMovementRepository $movements,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws StockItemNotFound
|
||||
* @throws StockItemInactive
|
||||
* @throws InvalidStockQuantity
|
||||
* @throws StockReasonRequired
|
||||
*/
|
||||
public function execute(StockUseData $data, int $actorUserId): StockUseResult
|
||||
{
|
||||
$quantity = StockQuantity::parsePositive($data->quantity);
|
||||
$target = new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $data->reason);
|
||||
|
||||
return $this->transactions->run(function () use ($data, $quantity, $target, $actorUserId): StockUseResult {
|
||||
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
|
||||
$item->ensureUsable();
|
||||
|
||||
$movement = $this->movements->add(StockMovement::consumption($item, $quantity, $target, $this->clock->today(), $this->clock->now(), $actorUserId));
|
||||
|
||||
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseData;
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseResult;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Records a write-off (hävikki / poisto) with its reason, e.g. damaged or
|
||||
* expired stock, or a reprint in production; possibly for a target too.
|
||||
*/
|
||||
final class RecordStockWriteOff
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockMovementRepository $movements,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws StockItemNotFound
|
||||
* @throws InvalidStockQuantity
|
||||
* @throws StockReasonRequired
|
||||
*/
|
||||
public function execute(StockUseData $data, int $actorUserId): StockUseResult
|
||||
{
|
||||
$quantity = StockQuantity::parsePositive($data->quantity);
|
||||
$reason = trim((string) $data->reason);
|
||||
|
||||
if ($reason === '') {
|
||||
throw new StockReasonRequired;
|
||||
}
|
||||
|
||||
$target = $data->taskId === null && $data->machineId === null && $data->orderLineId === null && $data->maintenanceRecordId === null
|
||||
? null
|
||||
: new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $reason);
|
||||
|
||||
return $this->transactions->run(function () use ($data, $quantity, $reason, $target, $actorUserId): StockUseResult {
|
||||
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
|
||||
|
||||
$movement = $this->movements->add(StockMovement::writeOff($item, $quantity, $reason, $this->clock->today(), $this->clock->now(), $actorUserId, $target));
|
||||
|
||||
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Reverses a movement (vastakirjaus): the same movement negated, referring
|
||||
* to the original, recorded today. Users may reverse their own use on the
|
||||
* day it was recorded; other corrections need the right to correct any
|
||||
* movement (management). Reversing a purchase also takes it out of the
|
||||
* moving average cost.
|
||||
*/
|
||||
final class ReverseStockMovement
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockMovementRepository $movements,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The reversal's id.
|
||||
*
|
||||
* @throws StockMovementNotFound
|
||||
* @throws StockMovementNotReversible
|
||||
* @throws StockMovementAlreadyReversed
|
||||
* @throws StockReversalNotAllowed
|
||||
*/
|
||||
public function execute(int $movementId, int $actorUserId, bool $mayReverseAny): int
|
||||
{
|
||||
$today = $this->clock->today();
|
||||
|
||||
return $this->transactions->run(function () use ($movementId, $actorUserId, $mayReverseAny, $today): int {
|
||||
$original = $this->movements->findById($movementId) ?? throw new StockMovementNotFound;
|
||||
|
||||
if (! $mayReverseAny && ! $original->isOwnUseOf($actorUserId, $today)) {
|
||||
throw new StockReversalNotAllowed;
|
||||
}
|
||||
|
||||
$item = $this->items->lockById($original->itemId()) ?? throw new StockItemNotFound;
|
||||
|
||||
if ($this->movements->isReversed($movementId)) {
|
||||
throw new StockMovementAlreadyReversed;
|
||||
}
|
||||
|
||||
$reversal = StockMovement::reversalOf($original, $today, $this->clock->now(), $actorUserId);
|
||||
|
||||
if ($original->kind() === StockMovementKind::Purchase) {
|
||||
$item->receive($this->movements->balanceOf($item->id() ?? 0), $reversal->quantityMilli(), $reversal->valueCents());
|
||||
$this->items->save($item);
|
||||
}
|
||||
|
||||
return (int) $this->movements->add($reversal)->id();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Takes a stock item out of use, or back. An item out of use cannot be
|
||||
* used, but its movements stay.
|
||||
*/
|
||||
final class SetStockItemActive
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws StockItemNotFound
|
||||
*/
|
||||
public function execute(int $itemId, bool $active): void
|
||||
{
|
||||
$this->transactions->run(function () use ($itemId, $active): void {
|
||||
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
|
||||
$active ? $item->activate() : $item->deactivate();
|
||||
$this->items->save($item);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemData;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
|
||||
/**
|
||||
* Checks a stock item's entered details, shared by adding and updating.
|
||||
*/
|
||||
final class StockItemFields
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockItemGroupRepository $groups,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{name: StockName, unit: StockUnit, reorderLevelMilli: ?int}
|
||||
*
|
||||
* @throws InvalidStockName
|
||||
* @throws InvalidStockQuantity
|
||||
*/
|
||||
public function parse(StockItemData $data): array
|
||||
{
|
||||
return [
|
||||
'name' => new StockName($data->name),
|
||||
'unit' => StockUnit::tryFrom($data->unit) ?? StockUnit::Piece,
|
||||
'reorderLevelMilli' => StockQuantity::parse($data->reorderLevel)?->milli,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A new item needs a group in use; an existing item may stay in its
|
||||
* group after the group is taken out of use.
|
||||
*
|
||||
* @throws StockItemGroupNotFound
|
||||
* @throws StockNameTaken
|
||||
*/
|
||||
public function check(StockItemData $data, StockName $name, ?int $exceptItemId = null): void
|
||||
{
|
||||
$group = $this->groups->findById($data->groupId);
|
||||
|
||||
if ($group === null || ($exceptItemId === null && ! $group->isActive())) {
|
||||
throw new StockItemGroupNotFound;
|
||||
}
|
||||
|
||||
if ($this->items->isNameTaken($name->value, $exceptItemId)) {
|
||||
throw new StockNameTaken;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Application\UseCases;
|
||||
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemData;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Changes a stock item's details. Its movements and balance stay.
|
||||
*/
|
||||
final class UpdateStockItem
|
||||
{
|
||||
public function __construct(
|
||||
private StockItemRepository $items,
|
||||
private StockItemFields $fields,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockName
|
||||
* @throws InvalidStockQuantity
|
||||
* @throws StockItemGroupNotFound
|
||||
* @throws StockItemNotFound
|
||||
* @throws StockNameTaken
|
||||
*/
|
||||
public function execute(int $itemId, StockItemData $data): void
|
||||
{
|
||||
$fields = $this->fields->parse($data);
|
||||
|
||||
$this->transactions->run(function () use ($itemId, $data, $fields): void {
|
||||
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
|
||||
$this->fields->check($data, $fields['name'], $itemId);
|
||||
|
||||
$item->change($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
|
||||
$this->items->save($item);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
|
||||
|
||||
interface StockItemGroupRepository
|
||||
{
|
||||
public function findById(int $id): ?StockItemGroup;
|
||||
|
||||
public function save(StockItemGroup $group): StockItemGroup;
|
||||
|
||||
public function isNameTaken(string $name, ?int $exceptId = null): bool;
|
||||
|
||||
public function nextSortOrder(): int;
|
||||
|
||||
/**
|
||||
* The group just before ($up) or after it in order, if any.
|
||||
*/
|
||||
public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Domain\Entities\StockItem;
|
||||
|
||||
interface StockItemRepository
|
||||
{
|
||||
public function findById(int $id): ?StockItem;
|
||||
|
||||
/**
|
||||
* The item, locked until the end of the transaction, so that its
|
||||
* balance and average cost change one movement at a time.
|
||||
*/
|
||||
public function lockById(int $id): ?StockItem;
|
||||
|
||||
public function save(StockItem $item): StockItem;
|
||||
|
||||
public function isNameTaken(string $name, ?int $exceptId = null): bool;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Contracts;
|
||||
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
|
||||
interface StockMovementRepository
|
||||
{
|
||||
public function add(StockMovement $movement): StockMovement;
|
||||
|
||||
public function findById(int $id): ?StockMovement;
|
||||
|
||||
public function isReversed(int $movementId): bool;
|
||||
|
||||
/**
|
||||
* The item's balance in thousandths: the sum of its movements.
|
||||
*/
|
||||
public function balanceOf(int $itemId): int;
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Entities;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
|
||||
/**
|
||||
* A stock item (nimike), e.g. a photo paper or an ink, counted in its unit.
|
||||
* Its balance is the sum of its movements and is not kept here; the item
|
||||
* keeps its moving average cost, which only purchases change. Items are
|
||||
* never deleted: one taken out of use cannot be used, but its movements
|
||||
* stay.
|
||||
*/
|
||||
final class StockItem
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private int $groupId,
|
||||
private StockName $name,
|
||||
private StockUnit $unit,
|
||||
private ?string $code,
|
||||
private ?string $supplier,
|
||||
private ?int $reorderLevelMilli,
|
||||
private int $averageCostHundredths,
|
||||
private ?string $imagePath,
|
||||
private ?string $thumbnailPath,
|
||||
private bool $active,
|
||||
) {}
|
||||
|
||||
public static function create(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): self
|
||||
{
|
||||
return new self(null, $groupId, $name, $unit, self::text($code), self::text($supplier), $reorderLevelMilli, 0, null, null, true);
|
||||
}
|
||||
|
||||
public static function reconstitute(
|
||||
int $id,
|
||||
int $groupId,
|
||||
StockName $name,
|
||||
StockUnit $unit,
|
||||
?string $code,
|
||||
?string $supplier,
|
||||
?int $reorderLevelMilli,
|
||||
int $averageCostHundredths,
|
||||
?string $imagePath,
|
||||
?string $thumbnailPath,
|
||||
bool $active,
|
||||
): self {
|
||||
return new self($id, $groupId, $name, $unit, $code, $supplier, $reorderLevelMilli, $averageCostHundredths, $imagePath, $thumbnailPath, $active);
|
||||
}
|
||||
|
||||
public function change(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): void
|
||||
{
|
||||
$this->groupId = $groupId;
|
||||
$this->name = $name;
|
||||
$this->unit = $unit;
|
||||
$this->code = self::text($code);
|
||||
$this->supplier = self::text($supplier);
|
||||
$this->reorderLevelMilli = $reorderLevelMilli;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the moving average cost for a purchase (or, with a negative
|
||||
* quantity and value, the reversal of one) received on top of the
|
||||
* given balance.
|
||||
*/
|
||||
public function receive(int $balanceMilli, int $quantityMilli, int $valueCents): void
|
||||
{
|
||||
$this->averageCostHundredths = StockValuation::averageAfterPurchase($balanceMilli, $this->averageCostHundredths, $quantityMilli, $valueCents);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StockItemInactive
|
||||
*/
|
||||
public function ensureUsable(): void
|
||||
{
|
||||
if (! $this->active) {
|
||||
throw new StockItemInactive;
|
||||
}
|
||||
}
|
||||
|
||||
public function setImage(string $imagePath, string $thumbnailPath): void
|
||||
{
|
||||
$this->imagePath = $imagePath;
|
||||
$this->thumbnailPath = $thumbnailPath;
|
||||
}
|
||||
|
||||
public function removeImage(): void
|
||||
{
|
||||
$this->imagePath = null;
|
||||
$this->thumbnailPath = null;
|
||||
}
|
||||
|
||||
public function activate(): void
|
||||
{
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
public function deactivate(): void
|
||||
{
|
||||
$this->active = false;
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function groupId(): int
|
||||
{
|
||||
return $this->groupId;
|
||||
}
|
||||
|
||||
public function name(): StockName
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function unit(): StockUnit
|
||||
{
|
||||
return $this->unit;
|
||||
}
|
||||
|
||||
public function code(): ?string
|
||||
{
|
||||
return $this->code;
|
||||
}
|
||||
|
||||
public function supplier(): ?string
|
||||
{
|
||||
return $this->supplier;
|
||||
}
|
||||
|
||||
public function reorderLevelMilli(): ?int
|
||||
{
|
||||
return $this->reorderLevelMilli;
|
||||
}
|
||||
|
||||
public function averageCostHundredths(): int
|
||||
{
|
||||
return $this->averageCostHundredths;
|
||||
}
|
||||
|
||||
public function imagePath(): ?string
|
||||
{
|
||||
return $this->imagePath;
|
||||
}
|
||||
|
||||
public function thumbnailPath(): ?string
|
||||
{
|
||||
return $this->thumbnailPath;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->active;
|
||||
}
|
||||
|
||||
private static function text(?string $value): ?string
|
||||
{
|
||||
$value = $value === null ? '' : trim($value);
|
||||
|
||||
return $value === '' ? null : mb_substr($value, 0, 150);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Entities;
|
||||
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
|
||||
/**
|
||||
* A group of stock items (nimikeryhmä), e.g. Paperit ja kartongit. Groups
|
||||
* are ordered, and never deleted, only taken out of use.
|
||||
*/
|
||||
final class StockItemGroup
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private StockName $name,
|
||||
private int $sortOrder,
|
||||
private bool $active,
|
||||
) {}
|
||||
|
||||
public static function create(StockName $name, int $sortOrder): self
|
||||
{
|
||||
return new self(null, $name, $sortOrder, true);
|
||||
}
|
||||
|
||||
public static function reconstitute(int $id, StockName $name, int $sortOrder, bool $active): self
|
||||
{
|
||||
return new self($id, $name, $sortOrder, $active);
|
||||
}
|
||||
|
||||
public function rename(StockName $name): void
|
||||
{
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
public function activate(): void
|
||||
{
|
||||
$this->active = true;
|
||||
}
|
||||
|
||||
public function deactivate(): void
|
||||
{
|
||||
$this->active = false;
|
||||
}
|
||||
|
||||
public function swapOrderWith(self $other): void
|
||||
{
|
||||
[$this->sortOrder, $other->sortOrder] = [$other->sortOrder, $this->sortOrder];
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function name(): StockName
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function sortOrder(): int
|
||||
{
|
||||
return $this->sortOrder;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->active;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Entities;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A change in an item's balance (varastotapahtuma, spec 19.2). Movements
|
||||
* are never changed or deleted: a mistake is corrected with a reversal,
|
||||
* the same movement negated, which refers to the original. The quantity
|
||||
* is signed (in thousandths) and the value is at the unit cost of the
|
||||
* moment: the purchase price for a purchase, the moving average cost
|
||||
* otherwise.
|
||||
*/
|
||||
final class StockMovement
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private int $itemId,
|
||||
private StockMovementKind $kind,
|
||||
private int $quantityMilli,
|
||||
private int $unitCostHundredths,
|
||||
private int $valueCents,
|
||||
private DateTimeImmutable $occurredOn,
|
||||
private DateTimeImmutable $recordedAt,
|
||||
private int $userId,
|
||||
private ?StockUseTarget $target,
|
||||
private ?string $reason,
|
||||
private ?string $supplier,
|
||||
private ?string $documentNumber,
|
||||
private ?int $inventoryCountId,
|
||||
private ?int $reversesMovementId,
|
||||
) {}
|
||||
|
||||
public static function purchase(StockItem $item, StockQuantity $quantity, int $valueCents, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?string $supplier, ?string $documentNumber): self
|
||||
{
|
||||
return new self(
|
||||
null, (int) $item->id(), StockMovementKind::Purchase, $quantity->milli,
|
||||
StockValuation::unitCostOf($quantity->milli, $valueCents), $valueCents,
|
||||
$occurredOn, $recordedAt, $userId, null, null, self::text($supplier), self::text($documentNumber), null, null,
|
||||
);
|
||||
}
|
||||
|
||||
public static function consumption(StockItem $item, StockQuantity $quantity, StockUseTarget $target, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
|
||||
{
|
||||
return self::outgoing(StockMovementKind::Consumption, $item, $quantity, $target, $target->reason, $occurredOn, $recordedAt, $userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StockReasonRequired
|
||||
*/
|
||||
public static function writeOff(StockItem $item, StockQuantity $quantity, string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?StockUseTarget $target = null): self
|
||||
{
|
||||
$reason = self::text($reason) ?? throw new StockReasonRequired;
|
||||
|
||||
return self::outgoing(StockMovementKind::WriteOff, $item, $quantity, $target, $reason, $occurredOn, $recordedAt, $userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* A stock count's correction: a signed difference at the average cost.
|
||||
*/
|
||||
public static function adjustment(StockItem $item, int $differenceMilli, int $inventoryCountId, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
|
||||
{
|
||||
$cost = $item->averageCostHundredths();
|
||||
|
||||
return new self(
|
||||
null, (int) $item->id(), StockMovementKind::Adjustment, $differenceMilli, $cost,
|
||||
StockValuation::valueCents($differenceMilli, $cost),
|
||||
$occurredOn, $recordedAt, $userId, null, null, null, null, $inventoryCountId, null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StockMovementNotReversible
|
||||
*/
|
||||
public static function reversalOf(self $original, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
|
||||
{
|
||||
if (! $original->isReversible()) {
|
||||
throw new StockMovementNotReversible;
|
||||
}
|
||||
|
||||
return new self(
|
||||
null, $original->itemId, StockMovementKind::Reversal, -$original->quantityMilli,
|
||||
$original->unitCostHundredths, -$original->valueCents,
|
||||
$occurredOn, $recordedAt, $userId, $original->target, $original->reason, null, null, null, $original->id,
|
||||
);
|
||||
}
|
||||
|
||||
public static function reconstitute(
|
||||
int $id,
|
||||
int $itemId,
|
||||
StockMovementKind $kind,
|
||||
int $quantityMilli,
|
||||
int $unitCostHundredths,
|
||||
int $valueCents,
|
||||
DateTimeImmutable $occurredOn,
|
||||
DateTimeImmutable $recordedAt,
|
||||
int $userId,
|
||||
?StockUseTarget $target,
|
||||
?string $reason,
|
||||
?string $supplier,
|
||||
?string $documentNumber,
|
||||
?int $inventoryCountId,
|
||||
?int $reversesMovementId,
|
||||
): self {
|
||||
return new self($id, $itemId, $kind, $quantityMilli, $unitCostHundredths, $valueCents, $occurredOn, $recordedAt, $userId, $target, $reason, $supplier, $documentNumber, $inventoryCountId, $reversesMovementId);
|
||||
}
|
||||
|
||||
public function isReversible(): bool
|
||||
{
|
||||
return $this->kind !== StockMovementKind::Reversal && $this->kind !== StockMovementKind::Adjustment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user may reverse this movement without the right to
|
||||
* correct anyone's: their own use, on the day it was recorded.
|
||||
*/
|
||||
public function isOwnUseOf(int $userId, DateTimeImmutable $today): bool
|
||||
{
|
||||
return $this->kind === StockMovementKind::Consumption
|
||||
&& $this->userId === $userId
|
||||
&& $this->occurredOn->format('Y-m-d') === $today->format('Y-m-d');
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function itemId(): int
|
||||
{
|
||||
return $this->itemId;
|
||||
}
|
||||
|
||||
public function kind(): StockMovementKind
|
||||
{
|
||||
return $this->kind;
|
||||
}
|
||||
|
||||
public function quantityMilli(): int
|
||||
{
|
||||
return $this->quantityMilli;
|
||||
}
|
||||
|
||||
public function unitCostHundredths(): int
|
||||
{
|
||||
return $this->unitCostHundredths;
|
||||
}
|
||||
|
||||
public function valueCents(): int
|
||||
{
|
||||
return $this->valueCents;
|
||||
}
|
||||
|
||||
public function occurredOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->occurredOn;
|
||||
}
|
||||
|
||||
public function recordedAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->recordedAt;
|
||||
}
|
||||
|
||||
public function userId(): int
|
||||
{
|
||||
return $this->userId;
|
||||
}
|
||||
|
||||
public function target(): ?StockUseTarget
|
||||
{
|
||||
return $this->target;
|
||||
}
|
||||
|
||||
public function reason(): ?string
|
||||
{
|
||||
return $this->reason;
|
||||
}
|
||||
|
||||
public function supplier(): ?string
|
||||
{
|
||||
return $this->supplier;
|
||||
}
|
||||
|
||||
public function documentNumber(): ?string
|
||||
{
|
||||
return $this->documentNumber;
|
||||
}
|
||||
|
||||
public function inventoryCountId(): ?int
|
||||
{
|
||||
return $this->inventoryCountId;
|
||||
}
|
||||
|
||||
public function reversesMovementId(): ?int
|
||||
{
|
||||
return $this->reversesMovementId;
|
||||
}
|
||||
|
||||
private static function outgoing(StockMovementKind $kind, StockItem $item, StockQuantity $quantity, ?StockUseTarget $target, ?string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
|
||||
{
|
||||
$cost = $item->averageCostHundredths();
|
||||
|
||||
return new self(
|
||||
null, (int) $item->id(), $kind, -$quantity->milli, $cost,
|
||||
StockValuation::valueCents(-$quantity->milli, $cost),
|
||||
$occurredOn, $recordedAt, $userId, $target, $reason, null, null, null, null,
|
||||
);
|
||||
}
|
||||
|
||||
private static function text(?string $value): ?string
|
||||
{
|
||||
$value = $value === null ? '' : trim($value);
|
||||
|
||||
return $value === '' ? null : mb_substr($value, 0, 255);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Enums;
|
||||
|
||||
/**
|
||||
* What a stock movement is (spec 19.2): a purchase adds stock, use and a
|
||||
* write-off take it, a stock count adjusts it either way, and a reversal
|
||||
* cancels an earlier movement with the opposite quantity.
|
||||
*/
|
||||
enum StockMovementKind: string
|
||||
{
|
||||
case Purchase = 'purchase';
|
||||
case Consumption = 'consumption';
|
||||
case WriteOff = 'write_off';
|
||||
case Adjustment = 'adjustment';
|
||||
case Reversal = 'reversal';
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Enums;
|
||||
|
||||
/**
|
||||
* The unit a stock item is counted in (spec 19.1). Labels are in
|
||||
* lang/*\/inventory.php under units.
|
||||
*/
|
||||
enum StockUnit: string
|
||||
{
|
||||
case Piece = 'piece';
|
||||
case Sheet = 'sheet';
|
||||
case Roll = 'roll';
|
||||
case Metre = 'metre';
|
||||
case SquareMetre = 'square_metre';
|
||||
case Litre = 'litre';
|
||||
case Package = 'package';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidStockCost extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A purchase price must be zero or more, with at most four decimals for a unit price.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidStockDay extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The day must be a valid date.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidStockImage extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The file is not a supported image.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidStockName extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A stock name must be 1-150 characters.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidStockQuantity extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A stock quantity must be a number with at most three decimals.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockItemGroupNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock item group 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 StockItemInactive extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock item is no longer in use.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockItemNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock item 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 StockMovementAlreadyReversed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock movement has already been reversed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockMovementNotFound extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The stock movement 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 StockMovementNotReversible extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Reversals and stock count adjustments cannot be reversed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockNameTaken extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The name is already in use.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockReasonRequired extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A reason is required.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class StockReversalNotAllowed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Only your own use recorded today may be reversed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Services;
|
||||
|
||||
/**
|
||||
* Matches stock items to a search typed on a keyboard or touch screen, or
|
||||
* read by a barcode scanner: every word of the search must be found in the
|
||||
* name or the code, regardless of case and of the dots of å, ä and ö
|
||||
* (spec 19.6).
|
||||
*/
|
||||
final class StockSearch
|
||||
{
|
||||
public static function matches(string $search, string $name, ?string $code): bool
|
||||
{
|
||||
$words = preg_split('/\s+/u', self::normalize($search), -1, PREG_SPLIT_NO_EMPTY) ?: [];
|
||||
$haystack = self::normalize($name.' '.($code ?? ''));
|
||||
|
||||
foreach ($words as $word) {
|
||||
if (! str_contains($haystack, $word)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function normalize(string $value): string
|
||||
{
|
||||
return strtr(mb_strtolower(trim($value)), ['å' => 'a', 'ä' => 'a', 'ö' => 'o', 'é' => 'e', 'ü' => 'u']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\Services;
|
||||
|
||||
/**
|
||||
* Valuation of stock at a moving average cost (liukuva keskihinta, spec
|
||||
* 19.2). Unit costs are in hundredths of a cent per whole unit, so that
|
||||
* cheap units such as a millilitre of ink keep their precision; values
|
||||
* are in cents, rounded half away from zero.
|
||||
*/
|
||||
final class StockValuation
|
||||
{
|
||||
/**
|
||||
* The value of a quantity (in thousandths) at a unit cost.
|
||||
*/
|
||||
public static function valueCents(int $quantityMilli, int $unitCostHundredths): int
|
||||
{
|
||||
return self::divideRounded($quantityMilli * $unitCostHundredths, 100_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* The unit cost of a purchase of a quantity for a total value.
|
||||
*/
|
||||
public static function unitCostOf(int $quantityMilli, int $valueCents): int
|
||||
{
|
||||
return $quantityMilli === 0 ? 0 : self::divideRounded($valueCents * 100_000, $quantityMilli);
|
||||
}
|
||||
|
||||
/**
|
||||
* The average unit cost after a purchase: (old balance × old average +
|
||||
* purchase value) / new balance. When the stock before was empty or
|
||||
* negative, or nothing is left after, the purchase's own unit cost.
|
||||
*/
|
||||
public static function averageAfterPurchase(int $balanceMilli, int $averageHundredths, int $purchasedMilli, int $purchaseValueCents): int
|
||||
{
|
||||
$newBalance = $balanceMilli + $purchasedMilli;
|
||||
|
||||
if ($balanceMilli <= 0 || $newBalance <= 0) {
|
||||
return max(0, self::unitCostOf($purchasedMilli, $purchaseValueCents));
|
||||
}
|
||||
|
||||
$oldValueHundredthsMilli = $balanceMilli * $averageHundredths;
|
||||
|
||||
return max(0, self::divideRounded($oldValueHundredthsMilli + $purchaseValueCents * 100_000, $newBalance));
|
||||
}
|
||||
|
||||
private static function divideRounded(int $dividend, int $divisor): int
|
||||
{
|
||||
$sign = ($dividend < 0) !== ($divisor < 0) ? -1 : 1;
|
||||
$dividend = abs($dividend);
|
||||
$divisor = abs($divisor);
|
||||
|
||||
return $sign * intdiv($dividend + intdiv($divisor, 2), $divisor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
|
||||
/**
|
||||
* Name of a stock item or an item group, e.g. "Valokuvapaperi 10×15".
|
||||
*/
|
||||
final readonly class StockName
|
||||
{
|
||||
public const int MAX_LENGTH = 150;
|
||||
|
||||
public string $value;
|
||||
|
||||
/**
|
||||
* @throws InvalidStockName
|
||||
*/
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
|
||||
|
||||
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
|
||||
throw new InvalidStockName;
|
||||
}
|
||||
|
||||
$this->value = $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
|
||||
/**
|
||||
* A quantity of stock in thousandths of the item's unit (e.g. 2,5 m² =
|
||||
* 2500), so three decimals are kept exactly. Typed in as "2,5", "2.5" or
|
||||
* "1 200".
|
||||
*/
|
||||
final readonly class StockQuantity
|
||||
{
|
||||
public const int MAX_MILLI = 9_999_999_999;
|
||||
|
||||
private function __construct(public int $milli) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidStockQuantity
|
||||
*/
|
||||
public static function ofMilli(int $milli): self
|
||||
{
|
||||
if (abs($milli) > self::MAX_MILLI) {
|
||||
throw new InvalidStockQuantity;
|
||||
}
|
||||
|
||||
return new self($milli);
|
||||
}
|
||||
|
||||
/**
|
||||
* A quantity greater than zero, as typed in.
|
||||
*
|
||||
* @throws InvalidStockQuantity
|
||||
*/
|
||||
public static function parsePositive(string $value): self
|
||||
{
|
||||
$quantity = self::parse($value);
|
||||
|
||||
if ($quantity === null || $quantity->milli <= 0) {
|
||||
throw new InvalidStockQuantity;
|
||||
}
|
||||
|
||||
return $quantity;
|
||||
}
|
||||
|
||||
/**
|
||||
* A quantity of zero or more as typed in, or null for an empty value.
|
||||
*
|
||||
* @throws InvalidStockQuantity
|
||||
*/
|
||||
public static function parse(string $value): ?self
|
||||
{
|
||||
$value = preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? '';
|
||||
$value = str_replace(',', '.', $value);
|
||||
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) {
|
||||
throw new InvalidStockQuantity;
|
||||
}
|
||||
|
||||
return new self((int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0'));
|
||||
}
|
||||
|
||||
public function negated(): self
|
||||
{
|
||||
return new self(-$this->milli);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finnish format without trailing zeros: "2,5", "-1", "1 200".
|
||||
*/
|
||||
public static function format(int $milli): string
|
||||
{
|
||||
$whole = intdiv(abs($milli), 1000);
|
||||
$fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0');
|
||||
|
||||
return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value for an input field: "2,5" without thousands separators.
|
||||
*/
|
||||
public static function inputValue(int $milli): string
|
||||
{
|
||||
return str_replace("\u{00A0}", '', self::format($milli));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Inventory\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
|
||||
|
||||
/**
|
||||
* What stock was used for (spec 19.2): a job's task, a machine, a quick
|
||||
* sale order line or a machine's maintenance, each possibly with a reason.
|
||||
* Use without a target (e.g. a test run) needs a reason.
|
||||
*/
|
||||
final readonly class StockUseTarget
|
||||
{
|
||||
public ?string $reason;
|
||||
|
||||
/**
|
||||
* @throws StockReasonRequired
|
||||
*/
|
||||
public function __construct(
|
||||
public ?int $taskId = null,
|
||||
public ?int $jobId = null,
|
||||
public ?int $machineId = null,
|
||||
public ?int $orderLineId = null,
|
||||
public ?int $maintenanceRecordId = null,
|
||||
?string $reason = null,
|
||||
) {
|
||||
$reason = $reason === null ? null : trim($reason);
|
||||
$this->reason = $reason === '' || $reason === null ? null : mb_substr($reason, 0, 255);
|
||||
|
||||
if ($this->reason === null && $taskId === null && $machineId === null && $orderLineId === null && $maintenanceRecordId === null) {
|
||||
throw new StockReasonRequired;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws StockReasonRequired
|
||||
*/
|
||||
public static function reason(?string $reason): self
|
||||
{
|
||||
return new self(reason: $reason);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Files;
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockItemImages;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
|
||||
use App\Modules\Shared\Application\Contracts\ImageResizer;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Stock item images on the private local disk under stock-items/: an
|
||||
* upright JPEG without metadata and a thumbnail for touch-screen buttons.
|
||||
*/
|
||||
class StockItemImageFiles implements StockItemImages
|
||||
{
|
||||
public const string DISK = 'local';
|
||||
|
||||
public const int MAX_SIZE = 1280;
|
||||
|
||||
public const int THUMBNAIL_SIZE = 240;
|
||||
|
||||
public function __construct(private ImageResizer $resizer) {}
|
||||
|
||||
public function store(string $uploadedFilePath, int $itemId): array
|
||||
{
|
||||
$versions = $this->resizer->jpegVersions($uploadedFilePath, [self::MAX_SIZE, self::THUMBNAIL_SIZE]) ?? throw new InvalidStockImage;
|
||||
$name = 'stock-items/'.$itemId.'/'.Str::uuid()->toString();
|
||||
|
||||
Storage::disk(self::DISK)->put($name.'.jpg', $versions[0]['bytes']);
|
||||
Storage::disk(self::DISK)->put($name.'-thumb.jpg', $versions[1]['bytes']);
|
||||
|
||||
return ['path' => $name.'.jpg', 'thumbnailPath' => $name.'-thumb.jpg'];
|
||||
}
|
||||
|
||||
public function delete(array $paths): void
|
||||
{
|
||||
if ($paths !== []) {
|
||||
Storage::disk(self::DISK)->delete($paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Database\Factories\StockItemGroupFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Attributes\UseFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Inventory Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property int $sort_order
|
||||
* @property bool $is_active
|
||||
*/
|
||||
#[Table('stock_item_groups')]
|
||||
#[Fillable(['name', 'sort_order', 'is_active'])]
|
||||
#[UseFactory(StockItemGroupFactory::class)]
|
||||
class StockItemGroupModel extends Model
|
||||
{
|
||||
/** @use HasFactory<StockItemGroupFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return HasMany<StockItemModel, $this>
|
||||
*/
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(StockItemModel::class, 'stock_item_group_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'sort_order' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
use Database\Factories\StockItemFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Attributes\UseFactory;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Inventory Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $stock_item_group_id
|
||||
* @property string $name
|
||||
* @property StockUnit $unit
|
||||
* @property string|null $code
|
||||
* @property string|null $supplier
|
||||
* @property int|null $reorder_level_milli
|
||||
* @property int $average_cost_hundredths
|
||||
* @property string|null $image_path
|
||||
* @property string|null $thumbnail_path
|
||||
* @property bool $is_active
|
||||
* @property int|null $balance_milli Selected sum of the movements.
|
||||
*/
|
||||
#[Table('stock_items')]
|
||||
#[Fillable(['stock_item_group_id', 'name', 'unit', 'code', 'supplier', 'reorder_level_milli', 'average_cost_hundredths', 'image_path', 'thumbnail_path', 'is_active'])]
|
||||
#[UseFactory(StockItemFactory::class)]
|
||||
class StockItemModel extends Model
|
||||
{
|
||||
/** @use HasFactory<StockItemFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return BelongsTo<StockItemGroupModel, $this>
|
||||
*/
|
||||
public function group(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(StockItemGroupModel::class, 'stock_item_group_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'stock_item_group_id' => 'integer',
|
||||
'unit' => StockUnit::class,
|
||||
'reorder_level_milli' => 'integer',
|
||||
'average_cost_hundredths' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
'balance_milli' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Inventory Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $stock_item_id
|
||||
* @property StockMovementKind $kind
|
||||
* @property int $quantity_milli
|
||||
* @property int $unit_cost_hundredths
|
||||
* @property int $value_cents
|
||||
* @property Carbon $occurred_on
|
||||
* @property Carbon $recorded_at
|
||||
* @property int $user_id
|
||||
* @property int|null $task_id
|
||||
* @property int|null $customer_job_id
|
||||
* @property int|null $machine_id
|
||||
* @property int|null $quick_sale_order_line_id
|
||||
* @property int|null $maintenance_record_id
|
||||
* @property int|null $inventory_count_id
|
||||
* @property int|null $reverses_movement_id
|
||||
* @property string|null $reason
|
||||
* @property string|null $supplier
|
||||
* @property string|null $document_number
|
||||
*/
|
||||
#[Table('stock_movements')]
|
||||
#[Fillable([
|
||||
'stock_item_id', 'kind', 'quantity_milli', 'unit_cost_hundredths', 'value_cents', 'occurred_on', 'recorded_at', 'user_id',
|
||||
'task_id', 'customer_job_id', 'machine_id', 'quick_sale_order_line_id', 'maintenance_record_id', 'inventory_count_id',
|
||||
'reverses_movement_id', 'reason', 'supplier', 'document_number',
|
||||
])]
|
||||
class StockMovementModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return HasOne<StockMovementModel, $this>
|
||||
*/
|
||||
public function reversal(): HasOne
|
||||
{
|
||||
return $this->hasOne(StockMovementModel::class, 'reverses_movement_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'stock_item_id' => 'integer',
|
||||
'kind' => StockMovementKind::class,
|
||||
'quantity_milli' => 'integer',
|
||||
'unit_cost_hundredths' => 'integer',
|
||||
'value_cents' => 'integer',
|
||||
'occurred_on' => 'immutable_date',
|
||||
'recorded_at' => 'immutable_datetime',
|
||||
'user_id' => 'integer',
|
||||
'task_id' => 'integer',
|
||||
'customer_job_id' => 'integer',
|
||||
'machine_id' => 'integer',
|
||||
'quick_sale_order_line_id' => 'integer',
|
||||
'maintenance_record_id' => 'integer',
|
||||
'inventory_count_id' => 'integer',
|
||||
'reverses_movement_id' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockName;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
|
||||
|
||||
class EloquentStockItemGroupRepository implements StockItemGroupRepository
|
||||
{
|
||||
public function findById(int $id): ?StockItemGroup
|
||||
{
|
||||
$model = StockItemGroupModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function save(StockItemGroup $group): StockItemGroup
|
||||
{
|
||||
$model = $group->id() === null ? new StockItemGroupModel : StockItemGroupModel::query()->findOrFail($group->id());
|
||||
|
||||
$model->fill([
|
||||
'name' => $group->name()->value,
|
||||
'sort_order' => $group->sortOrder(),
|
||||
'is_active' => $group->isActive(),
|
||||
])->save();
|
||||
|
||||
return $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function isNameTaken(string $name, ?int $exceptId = null): bool
|
||||
{
|
||||
return StockItemGroupModel::query()
|
||||
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
|
||||
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function nextSortOrder(): int
|
||||
{
|
||||
return (int) StockItemGroupModel::query()->max('sort_order') + 1;
|
||||
}
|
||||
|
||||
public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup
|
||||
{
|
||||
$model = StockItemGroupModel::query()
|
||||
->where('sort_order', $up ? '<' : '>', $group->sortOrder())
|
||||
->orderBy('sort_order', $up ? 'desc' : 'asc')
|
||||
->first();
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
private function toEntity(StockItemGroupModel $model): StockItemGroup
|
||||
{
|
||||
return StockItemGroup::reconstitute($model->id, new StockName($model->name), $model->sort_order, $model->is_active);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
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\ValueObjects\StockName;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
|
||||
|
||||
class EloquentStockItemRepository implements StockItemRepository
|
||||
{
|
||||
public function findById(int $id): ?StockItem
|
||||
{
|
||||
$model = StockItemModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function lockById(int $id): ?StockItem
|
||||
{
|
||||
$model = StockItemModel::query()->lockForUpdate()->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function save(StockItem $item): StockItem
|
||||
{
|
||||
$model = $item->id() === null ? new StockItemModel : StockItemModel::query()->findOrFail($item->id());
|
||||
|
||||
$model->fill([
|
||||
'stock_item_group_id' => $item->groupId(),
|
||||
'name' => $item->name()->value,
|
||||
'unit' => $item->unit(),
|
||||
'code' => $item->code(),
|
||||
'supplier' => $item->supplier(),
|
||||
'reorder_level_milli' => $item->reorderLevelMilli(),
|
||||
'average_cost_hundredths' => $item->averageCostHundredths(),
|
||||
'image_path' => $item->imagePath(),
|
||||
'thumbnail_path' => $item->thumbnailPath(),
|
||||
'is_active' => $item->isActive(),
|
||||
])->save();
|
||||
|
||||
return $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function isNameTaken(string $name, ?int $exceptId = null): bool
|
||||
{
|
||||
return StockItemModel::query()
|
||||
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
|
||||
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
|
||||
->exists();
|
||||
}
|
||||
|
||||
private function toEntity(StockItemModel $model): StockItem
|
||||
{
|
||||
return StockItem::reconstitute(
|
||||
$model->id,
|
||||
$model->stock_item_group_id,
|
||||
new StockName($model->name),
|
||||
$model->unit,
|
||||
$model->code,
|
||||
$model->supplier,
|
||||
$model->reorder_level_milli,
|
||||
$model->average_cost_hundredths,
|
||||
$model->image_path,
|
||||
$model->thumbnail_path,
|
||||
$model->is_active,
|
||||
);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Domain\Entities\StockMovement;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentStockMovementRepository implements StockMovementRepository
|
||||
{
|
||||
public function add(StockMovement $movement): StockMovement
|
||||
{
|
||||
$target = $movement->target();
|
||||
|
||||
$model = StockMovementModel::query()->create([
|
||||
'stock_item_id' => $movement->itemId(),
|
||||
'kind' => $movement->kind(),
|
||||
'quantity_milli' => $movement->quantityMilli(),
|
||||
'unit_cost_hundredths' => $movement->unitCostHundredths(),
|
||||
'value_cents' => $movement->valueCents(),
|
||||
'occurred_on' => $movement->occurredOn()->format('Y-m-d'),
|
||||
'recorded_at' => $movement->recordedAt()->format('Y-m-d H:i:s'),
|
||||
'user_id' => $movement->userId(),
|
||||
'task_id' => $target?->taskId,
|
||||
'customer_job_id' => $target?->jobId,
|
||||
'machine_id' => $target?->machineId,
|
||||
'quick_sale_order_line_id' => $target?->orderLineId,
|
||||
'maintenance_record_id' => $target?->maintenanceRecordId,
|
||||
'inventory_count_id' => $movement->inventoryCountId(),
|
||||
'reverses_movement_id' => $movement->reversesMovementId(),
|
||||
'reason' => $movement->reason(),
|
||||
'supplier' => $movement->supplier(),
|
||||
'document_number' => $movement->documentNumber(),
|
||||
]);
|
||||
|
||||
return $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function findById(int $id): ?StockMovement
|
||||
{
|
||||
$model = StockMovementModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function isReversed(int $movementId): bool
|
||||
{
|
||||
return StockMovementModel::query()->where('reverses_movement_id', $movementId)->exists();
|
||||
}
|
||||
|
||||
public function balanceOf(int $itemId): int
|
||||
{
|
||||
return (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
|
||||
}
|
||||
|
||||
private function toEntity(StockMovementModel $model): StockMovement
|
||||
{
|
||||
$hasTarget = $model->task_id !== null || $model->machine_id !== null || $model->quick_sale_order_line_id !== null
|
||||
|| $model->maintenance_record_id !== null || ($model->reason !== null && $model->inventory_count_id === null);
|
||||
|
||||
return StockMovement::reconstitute(
|
||||
$model->id,
|
||||
$model->stock_item_id,
|
||||
$model->kind,
|
||||
$model->quantity_milli,
|
||||
$model->unit_cost_hundredths,
|
||||
$model->value_cents,
|
||||
DateTimeImmutable::createFromInterface($model->occurred_on),
|
||||
DateTimeImmutable::createFromInterface($model->recorded_at),
|
||||
$model->user_id,
|
||||
$hasTarget ? new StockUseTarget($model->task_id, $model->customer_job_id, $model->machine_id, $model->quick_sale_order_line_id, $model->maintenance_record_id, $model->reason) : null,
|
||||
$model->reason,
|
||||
$model->supplier,
|
||||
$model->document_number,
|
||||
$model->inventory_count_id,
|
||||
$model->reverses_movement_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
|
||||
use App\Modules\Inventory\Domain\Services\StockSearch;
|
||||
use App\Modules\Inventory\Domain\Services\StockValuation;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EloquentStockQueries implements StockQueries
|
||||
{
|
||||
public function __construct(private UserAccountQueries $users) {}
|
||||
|
||||
public function groups(bool $includeInactive = true): array
|
||||
{
|
||||
return StockItemGroupModel::query()
|
||||
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
|
||||
->withCount('items')
|
||||
->orderBy('sort_order')
|
||||
->get()
|
||||
->map(fn (StockItemGroupModel $model): StockGroupSummary => new StockGroupSummary($model->id, $model->name, $model->is_active, (int) $model->getAttribute('items_count')))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array
|
||||
{
|
||||
$search = trim((string) $search);
|
||||
|
||||
return $this->itemQuery()
|
||||
->when($groupId !== null, fn (Builder $query) => $query->where('stock_items.stock_item_group_id', $groupId))
|
||||
->when(! $includeInactive, fn (Builder $query) => $query->where('stock_items.is_active', true))
|
||||
->get()
|
||||
->filter(fn (StockItemModel $model): bool => $search === '' || StockSearch::matches($search, $model->name, $model->code))
|
||||
->map(fn (StockItemModel $model): StockItemSummary => $this->toSummary($model))
|
||||
->filter(fn (StockItemSummary $item): bool => ! $onlyReorder || $item->needsReorder())
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function findItem(int $id): ?StockItemSummary
|
||||
{
|
||||
$model = $this->itemQuery()->where('stock_items.id', $id)->first();
|
||||
|
||||
return $model === null ? null : $this->toSummary($model);
|
||||
}
|
||||
|
||||
public function itemsByIds(array $ids): array
|
||||
{
|
||||
if ($ids === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $this->itemQuery()
|
||||
->whereIn('stock_items.id', $ids)
|
||||
->get()
|
||||
->mapWithKeys(fn (StockItemModel $model): array => [$model->id => $this->toSummary($model)])
|
||||
->all();
|
||||
}
|
||||
|
||||
public function movementsOf(int $itemId, int $limit = 200): array
|
||||
{
|
||||
$models = StockMovementModel::query()
|
||||
->with('reversal:id,reverses_movement_id')
|
||||
->where('stock_item_id', $itemId)
|
||||
->orderByDesc('id')
|
||||
->limit($limit)
|
||||
->get();
|
||||
|
||||
$balance = (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
|
||||
|
||||
return $this->summaries($models, $balance);
|
||||
}
|
||||
|
||||
public function findMovement(int $id): ?StockMovementSummary
|
||||
{
|
||||
$model = StockMovementModel::query()->with('reversal:id,reverses_movement_id')->find($id);
|
||||
|
||||
if ($model === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$balance = (int) StockMovementModel::query()
|
||||
->where('stock_item_id', $model->stock_item_id)
|
||||
->where('id', '<=', $model->id)
|
||||
->sum('quantity_milli');
|
||||
|
||||
return $this->summaries(collect([$model]), $balance)[0];
|
||||
}
|
||||
|
||||
public function imagePathOf(int $itemId, bool $thumbnail): ?string
|
||||
{
|
||||
$model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']);
|
||||
|
||||
return $thumbnail ? $model?->thumbnail_path : $model?->image_path;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<StockItemModel>
|
||||
*/
|
||||
private function itemQuery(): Builder
|
||||
{
|
||||
return StockItemModel::query()
|
||||
->join('stock_item_groups', 'stock_item_groups.id', '=', 'stock_items.stock_item_group_id')
|
||||
->select('stock_items.*')
|
||||
->addSelect('stock_item_groups.name as group_name')
|
||||
->selectSub(
|
||||
StockMovementModel::query()->selectRaw('COALESCE(SUM(quantity_milli), 0)')->whereColumn('stock_movements.stock_item_id', 'stock_items.id'),
|
||||
'balance_milli',
|
||||
)
|
||||
->orderBy('stock_item_groups.sort_order')
|
||||
->orderBy('stock_items.name');
|
||||
}
|
||||
|
||||
private function toSummary(StockItemModel $model): StockItemSummary
|
||||
{
|
||||
$balance = (int) $model->getAttribute('balance_milli');
|
||||
|
||||
return new StockItemSummary(
|
||||
id: $model->id,
|
||||
groupId: $model->stock_item_group_id,
|
||||
groupName: (string) $model->getAttribute('group_name'),
|
||||
name: $model->name,
|
||||
unit: $model->unit,
|
||||
code: $model->code,
|
||||
supplier: $model->supplier,
|
||||
reorderLevelMilli: $model->reorder_level_milli,
|
||||
balanceMilli: $balance,
|
||||
averageCostHundredths: $model->average_cost_hundredths,
|
||||
valueCents: StockValuation::valueCents($balance, $model->average_cost_hundredths),
|
||||
hasImage: $model->thumbnail_path !== null,
|
||||
isActive: $model->is_active,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, StockMovementModel> $models Newest first.
|
||||
* @param int $balance The balance after the newest of them.
|
||||
* @return list<StockMovementSummary>
|
||||
*/
|
||||
private function summaries(Collection $models, int $balance): array
|
||||
{
|
||||
$names = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all());
|
||||
$summaries = [];
|
||||
|
||||
foreach ($models as $model) {
|
||||
$summaries[] = new StockMovementSummary(
|
||||
id: $model->id,
|
||||
itemId: $model->stock_item_id,
|
||||
kind: $model->kind,
|
||||
quantityMilli: $model->quantity_milli,
|
||||
balanceAfterMilli: $balance,
|
||||
valueCents: $model->value_cents,
|
||||
occurredOn: $model->occurred_on->format('Y-m-d'),
|
||||
recordedAt: Carbon::instance($model->recorded_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
|
||||
userId: $model->user_id,
|
||||
userName: $names[$model->user_id] ?? '',
|
||||
taskId: $model->task_id,
|
||||
jobId: $model->customer_job_id,
|
||||
machineId: $model->machine_id,
|
||||
orderLineId: $model->quick_sale_order_line_id,
|
||||
maintenanceRecordId: $model->maintenance_record_id,
|
||||
inventoryCountId: $model->inventory_count_id,
|
||||
reason: $model->reason,
|
||||
supplier: $model->supplier,
|
||||
documentNumber: $model->document_number,
|
||||
reversesMovementId: $model->reverses_movement_id,
|
||||
reversedByMovementId: $model->reversal?->id,
|
||||
);
|
||||
|
||||
$balance -= $model->quantity_milli;
|
||||
}
|
||||
|
||||
return $summaries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
|
||||
use App\Modules\Inventory\Application\Contracts\StockItemImages;
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
|
||||
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
|
||||
use App\Modules\Inventory\Infrastructure\Files\StockItemImageFiles;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemGroupRepository;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemRepository;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockMovementRepository;
|
||||
use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockQueries;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Livewire\Livewire;
|
||||
|
||||
/**
|
||||
* Wires the Inventory module (stock items, movements and stock counts,
|
||||
* spec 19.1–19.3) into Laravel: bindings, routes, the `inventory::`
|
||||
* Livewire namespace and the `inventory.*` abilities (spec 19.9).
|
||||
*/
|
||||
class InventoryServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
public array $bindings = [
|
||||
StockItemGroupRepository::class => EloquentStockItemGroupRepository::class,
|
||||
StockItemRepository::class => EloquentStockItemRepository::class,
|
||||
StockMovementRepository::class => EloquentStockMovementRepository::class,
|
||||
StockQueries::class => EloquentStockQueries::class,
|
||||
StockItemImages::class => StockItemImageFiles::class,
|
||||
];
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$presentationPath = dirname(__DIR__, 2).'/Presentation';
|
||||
|
||||
Livewire::addNamespace('inventory', viewPath: $presentationPath.'/Livewire');
|
||||
|
||||
if (! $this->app->routesAreCached()) {
|
||||
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
|
||||
}
|
||||
|
||||
$staff = fn (User $user): bool => $user->role !== Role::Subcontractor;
|
||||
$managers = fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true);
|
||||
|
||||
Gate::define('inventory.view', $staff);
|
||||
Gate::define('inventory.record-use', $staff);
|
||||
Gate::define('inventory.count', $staff);
|
||||
Gate::define('inventory.manage', $managers);
|
||||
Gate::define('inventory.manage-counts', $managers);
|
||||
Gate::define('inventory.reverse-any', $managers);
|
||||
Gate::define('inventory.see-value', $managers);
|
||||
|
||||
// The menu shows stock pages only when a service unit uses stock (spec 19).
|
||||
Gate::define('inventory.menu', fn (User $user): bool => $staff($user) && app(CatalogQueries::class)->stockServiceUnitIds() !== []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* A stock item's image or its thumbnail from the private disk, to those who
|
||||
* see the stock.
|
||||
*/
|
||||
class ShowStockItemImage
|
||||
{
|
||||
public function __invoke(int $item, string $size, StockQueries $stock): Response
|
||||
{
|
||||
Gate::authorize('inventory.view');
|
||||
|
||||
$path = $stock->imagePathOf($item, $size === 'thumbnail') ?? abort(404);
|
||||
$disk = Storage::disk('local');
|
||||
|
||||
abort_unless($disk->exists($path), 404);
|
||||
|
||||
return $disk->response($path, basename($path), ['Content-Type' => 'image/jpeg', 'Cache-Control' => 'private, max-age=86400']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Inventory\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Formatting shared by the stock pages and the components that show stock
|
||||
* elsewhere (task material, machine console). Values may be negative.
|
||||
*/
|
||||
trait FormatsStock
|
||||
{
|
||||
public function quantity(int $milli, StockUnit|string|null $unit = null): string
|
||||
{
|
||||
$unitKey = $unit instanceof StockUnit ? $unit->value : $unit;
|
||||
|
||||
return StockQuantity::format($milli).($unitKey === null ? '' : "\u{00A0}".__('inventory.units.'.$unitKey));
|
||||
}
|
||||
|
||||
public function money(int $cents): string
|
||||
{
|
||||
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
|
||||
}
|
||||
|
||||
/**
|
||||
* A unit cost in hundredths of a cent, e.g. "0,0123 €" or "12,50 €".
|
||||
*/
|
||||
public function unitCost(int $hundredths): string
|
||||
{
|
||||
$euros = number_format($hundredths / 10_000, 4, ',', "\u{00A0}");
|
||||
$euros = preg_replace('/(,\d\d)00$/', '$1', $euros) ?? $euros;
|
||||
$euros = preg_replace('/(,\d\d\d)0$/', '$1', $euros) ?? $euros;
|
||||
|
||||
return $euros."\u{00A0}€";
|
||||
}
|
||||
|
||||
/**
|
||||
* "24.11.2026" for "2026-11-24"; "24.11.2026 klo 14.05" for "2026-11-24 14:05".
|
||||
*/
|
||||
public function dateLabel(string $value): string
|
||||
{
|
||||
return strlen($value) > 10
|
||||
? CarbonImmutable::createFromFormat('Y-m-d H:i', $value)->format('j.n.Y \k\l\o H.i')
|
||||
: CarbonImmutable::createFromFormat('!Y-m-d', $value)->format('j.n.Y');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
||||
use App\Modules\Inventory\Application\UseCases\AddStockItemGroup;
|
||||
use App\Modules\Inventory\Application\UseCases\ChangeStockItemGroup;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* Stock item groups (nimikeryhmät, spec 19.1): adding, renaming, ordering
|
||||
* with Move up / Move down and taking out of use. Management only.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
public string $newName = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $editingId = null;
|
||||
|
||||
public string $editingName = '';
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<StockGroupSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function groups(): array
|
||||
{
|
||||
return app(StockQueries::class)->groups();
|
||||
}
|
||||
|
||||
public function add(AddStockItemGroup $addGroup): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
try {
|
||||
$addGroup->execute($this->newName);
|
||||
} catch (InvalidStockName) {
|
||||
$this->addError('newName', __('inventory.errors.name'));
|
||||
|
||||
return;
|
||||
} catch (StockNameTaken) {
|
||||
$this->addError('newName', __('inventory.errors.name_taken'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->message = __('inventory.groups.added', ['name' => trim($this->newName)]);
|
||||
$this->newName = '';
|
||||
unset($this->groups);
|
||||
$this->js("document.getElementById('new-group-name')?.focus()");
|
||||
}
|
||||
|
||||
public function startRename(int $groupId): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
|
||||
$this->editingId = $group->id;
|
||||
$this->editingName = $group->name;
|
||||
$this->resetErrorBag();
|
||||
$this->js("setTimeout(() => document.getElementById('rename-group')?.focus())");
|
||||
}
|
||||
|
||||
public function cancelRename(): void
|
||||
{
|
||||
$id = $this->editingId;
|
||||
$this->editingId = null;
|
||||
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
|
||||
}
|
||||
|
||||
public function rename(ChangeStockItemGroup $change): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
try {
|
||||
$change->rename((int) $this->editingId, $this->editingName);
|
||||
} catch (InvalidStockName) {
|
||||
$this->addError('editingName', __('inventory.errors.name'));
|
||||
|
||||
return;
|
||||
} catch (StockNameTaken) {
|
||||
$this->addError('editingName', __('inventory.errors.name_taken'));
|
||||
|
||||
return;
|
||||
} catch (StockItemGroupNotFound) {
|
||||
$this->message = __('inventory.errors.not_found');
|
||||
}
|
||||
|
||||
$id = $this->editingId;
|
||||
$this->message = __('inventory.groups.renamed', ['name' => trim($this->editingName)]);
|
||||
$this->editingId = null;
|
||||
unset($this->groups);
|
||||
$this->js("document.getElementById('rename-group-{$id}')?.focus()");
|
||||
}
|
||||
|
||||
public function move(int $groupId, string $direction, ChangeStockItemGroup $change): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
|
||||
$up = $direction === 'up';
|
||||
|
||||
try {
|
||||
$moved = $change->move($groupId, $up);
|
||||
} catch (StockItemGroupNotFound) {
|
||||
$this->message = __('inventory.errors.not_found');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->message = __('inventory.groups.'.($moved ? ($up ? 'moved_up' : 'moved_down') : ($up ? 'first' : 'last')), ['name' => $group->name]);
|
||||
unset($this->groups);
|
||||
}
|
||||
|
||||
public function toggleActive(int $groupId, ChangeStockItemGroup $change): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
$group = collect($this->groups)->firstWhere('id', $groupId) ?? abort(404);
|
||||
|
||||
try {
|
||||
$change->setActive($groupId, ! $group->isActive);
|
||||
} catch (StockItemGroupNotFound) {
|
||||
$this->message = __('inventory.errors.not_found');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->message = __($group->isActive ? 'inventory.groups.deactivated' : 'inventory.groups.activated', ['name' => $group->name]);
|
||||
unset($this->groups);
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('inventory.groups.title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-2xl font-semibold">{{ __('inventory.groups.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.groups.intro') }}</p>
|
||||
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
|
||||
</div>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
|
||||
|
||||
<form wire:submit="add" class="flex flex-wrap items-end gap-3" novalidate>
|
||||
<div class="min-w-0 flex-1">
|
||||
<x-input id="new-group-name" wire:model="newName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
|
||||
</div>
|
||||
<x-button submit icon="plus" :text="__('inventory.groups.add')" />
|
||||
</form>
|
||||
|
||||
@if ($this->groups === [])
|
||||
<p class="text-sm">{{ __('inventory.groups.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->groups as $group)
|
||||
<li wire:key="group-{{ $group->id }}" class="flex flex-wrap items-center gap-3 p-3">
|
||||
@if ($editingId === $group->id)
|
||||
<form wire:submit="rename" class="flex w-full flex-wrap items-end gap-2" novalidate>
|
||||
<div class="min-w-0 flex-1">
|
||||
<x-input id="rename-group" wire:model="editingName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
|
||||
</div>
|
||||
<x-button submit :text="__('inventory.groups.save')" />
|
||||
<x-button wire:click="cancelRename" subtle color="black" :text="__('inventory.groups.cancel')" />
|
||||
</form>
|
||||
@else
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="font-medium break-words">{{ $group->name }}</p>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">
|
||||
{{ trans_choice('inventory.groups.items', $group->itemCount, ['count' => $group->itemCount]) }}
|
||||
@unless ($group->isActive)
|
||||
· {{ __('inventory.status.inactive') }}
|
||||
@endunless
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
<x-button wire:click="move({{ $group->id }}, 'up')" subtle color="black" sm icon="arrow-up" :aria-label="__('inventory.groups.up_named', ['name' => $group->name])" />
|
||||
<x-button wire:click="move({{ $group->id }}, 'down')" subtle color="black" sm icon="arrow-down" :aria-label="__('inventory.groups.down_named', ['name' => $group->name])" />
|
||||
<x-button id="rename-group-{{ $group->id }}" wire:click="startRename({{ $group->id }})" subtle color="black" sm icon="pencil" :text="__('inventory.groups.rename')" :aria-label="__('inventory.groups.rename_named', ['name' => $group->name])" />
|
||||
<x-button
|
||||
wire:click="toggleActive({{ $group->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
:icon="$group->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'"
|
||||
:text="$group->isActive ? __('inventory.groups.deactivate') : __('inventory.groups.activate')"
|
||||
:aria-label="__($group->isActive ? 'inventory.groups.deactivate_named' : 'inventory.groups.activate_named', ['name' => $group->name])"
|
||||
/>
|
||||
</div>
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
||||
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Url;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* The stock list (spec 19.1): items with their balances, searched by name
|
||||
* or code and filtered by group and "only items to order". Management also
|
||||
* sees the average costs and the stock value.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsStock;
|
||||
|
||||
#[Url(as: 'haku', except: '')]
|
||||
public string $search = '';
|
||||
|
||||
#[Url(as: 'ryhma', except: '')]
|
||||
public string $group = '';
|
||||
|
||||
#[Url(as: 'tilattavat', except: false)]
|
||||
public bool $onlyReorder = false;
|
||||
|
||||
public bool $includeInactive = false;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('inventory.view');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<StockItemSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function items(): array
|
||||
{
|
||||
return app(StockQueries::class)->items(
|
||||
$this->search,
|
||||
$this->group === '' ? null : (int) $this->group,
|
||||
$this->onlyReorder,
|
||||
$this->includeInactive && Gate::allows('inventory.manage'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<StockGroupSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function groups(): array
|
||||
{
|
||||
return app(StockQueries::class)->groups(includeInactive: false);
|
||||
}
|
||||
|
||||
public function updated(): void
|
||||
{
|
||||
$this->authorize('inventory.view');
|
||||
unset($this->items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
$headers = [
|
||||
['index' => 'name', 'label' => __('inventory.columns.name'), 'sortable' => false],
|
||||
['index' => 'group', 'label' => __('inventory.columns.group'), 'sortable' => false],
|
||||
['index' => 'balance', 'label' => __('inventory.columns.balance'), 'sortable' => false, 'align' => 'right'],
|
||||
['index' => 'reorder', 'label' => __('inventory.columns.reorder_level'), 'sortable' => false, 'align' => 'right'],
|
||||
['index' => 'status', 'label' => __('inventory.columns.status'), 'sortable' => false],
|
||||
];
|
||||
|
||||
if (Gate::allows('inventory.see-value')) {
|
||||
$headers[] = ['index' => 'cost', 'label' => __('inventory.columns.average_cost'), 'sortable' => false, 'align' => 'right'];
|
||||
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('inventory.index.title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-2">
|
||||
<h1 class="text-2xl font-semibold">{{ __('inventory.index.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.index.intro') }}</p>
|
||||
@can('inventory.manage')
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<x-button :href="route('inventory.items.create')" wire:navigate icon="plus" :text="__('inventory.index.new_item')" />
|
||||
<x-button :href="route('inventory.groups')" wire:navigate subtle color="black" icon="folder" :text="__('inventory.index.groups')" />
|
||||
</div>
|
||||
@endcan
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<x-input id="stock-search" wire:model.live.debounce.300ms="search" type="search" icon="magnifying-glass" :label="__('inventory.index.search')" autocomplete="off" />
|
||||
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native id="stock-group" wire:model.live="group" :label="__('inventory.index.group')" :aria-label="__('inventory.index.group')">
|
||||
<option value="">{{ __('inventory.index.all_groups') }}</option>
|
||||
@foreach ($this->groups as $option)
|
||||
<option value="{{ $option->id }}">{{ $option->name }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
|
||||
<div class="flex flex-col justify-end gap-2">
|
||||
<x-checkbox id="only-reorder" wire:model.live="onlyReorder" :label="__('inventory.index.only_reorder')" />
|
||||
@can('inventory.manage')
|
||||
<x-checkbox id="include-inactive" wire:model.live="includeInactive" :label="__('inventory.index.include_inactive')" />
|
||||
@endcan
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm font-medium">
|
||||
{{ trans_choice('inventory.index.count', count($this->items), ['count' => count($this->items)]) }}
|
||||
</p>
|
||||
|
||||
@if ($this->items === [])
|
||||
<p class="text-sm">{{ __('inventory.index.none') }}</p>
|
||||
@else
|
||||
<x-table :headers="$this->headers()" :rows="$this->items">
|
||||
@interact('column_name', $item)
|
||||
<x-link :href="route('inventory.items.show', $item->id)" navigate class="whitespace-normal">{{ $item->name }}</x-link>
|
||||
@if ($item->code !== null)
|
||||
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $item->code }}</span>
|
||||
@endif
|
||||
@endinteract
|
||||
|
||||
@interact('column_group', $item)
|
||||
<span class="whitespace-normal">{{ $item->groupName }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_balance', $item)
|
||||
<span class="whitespace-nowrap">{{ $this->quantity($item->balanceMilli, $item->unit) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_reorder', $item)
|
||||
<span class="whitespace-nowrap">{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_status', $item)
|
||||
<x-inventory.stock-status :item="$item" />
|
||||
@endinteract
|
||||
|
||||
@interact('column_cost', $item)
|
||||
<span class="whitespace-nowrap">{{ $this->unitCost($item->averageCostHundredths) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_value', $item)
|
||||
<span class="whitespace-nowrap">{{ $this->money($item->valueCents) }}</span>
|
||||
@endinteract
|
||||
</x-table>
|
||||
|
||||
@can('inventory.see-value')
|
||||
<p class="text-right font-semibold">{{ __('inventory.index.total_value', ['value' => $this->money(array_sum(array_map(fn ($item) => $item->valueCents, $this->items)))]) }}</p>
|
||||
@endcan
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemData;
|
||||
use App\Modules\Inventory\Application\UseCases\AddStockItem;
|
||||
use App\Modules\Inventory\Application\UseCases\ChangeStockItemImage;
|
||||
use App\Modules\Inventory\Application\UseCases\UpdateStockItem;
|
||||
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
|
||||
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
/**
|
||||
* Add page (no {item}) and edit page (with {item}) of a stock item: group,
|
||||
* name, unit, code, supplier, reorder level and an optional image.
|
||||
* Management only.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
public const int MAX_KILOBYTES = 12288;
|
||||
|
||||
#[Locked]
|
||||
public ?int $itemId = null;
|
||||
|
||||
#[Locked]
|
||||
public bool $hasImage = false;
|
||||
|
||||
public string $groupId = '';
|
||||
|
||||
public string $name = '';
|
||||
|
||||
public string $unit = 'piece';
|
||||
|
||||
public string $code = '';
|
||||
|
||||
public string $supplier = '';
|
||||
|
||||
public string $reorderLevel = '';
|
||||
|
||||
/**
|
||||
* @var TemporaryUploadedFile|null
|
||||
*/
|
||||
public $image = null;
|
||||
|
||||
public bool $removeImage = false;
|
||||
|
||||
public function mount(StockQueries $stock, ?int $item = null): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
if ($item === null) {
|
||||
$this->groupId = (string) ($this->groups[0]->id ?? '');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$summary = $stock->findItem($item) ?? abort(404);
|
||||
|
||||
$this->itemId = $summary->id;
|
||||
$this->groupId = (string) $summary->groupId;
|
||||
$this->name = $summary->name;
|
||||
$this->unit = $summary->unit->value;
|
||||
$this->code = (string) $summary->code;
|
||||
$this->supplier = (string) $summary->supplier;
|
||||
$this->reorderLevel = $summary->reorderLevelMilli === null ? '' : StockQuantity::inputValue($summary->reorderLevelMilli);
|
||||
$this->hasImage = $summary->hasImage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups in use, and the item's own group even when out of use.
|
||||
*
|
||||
* @return list<StockGroupSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function groups(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
app(StockQueries::class)->groups(),
|
||||
fn (StockGroupSummary $group): bool => $group->isActive || (string) $group->id === $this->groupId,
|
||||
));
|
||||
}
|
||||
|
||||
public function save(AddStockItem $addItem, UpdateStockItem $updateItem, ChangeStockItemImage $changeImage): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
$this->resetErrorBag();
|
||||
|
||||
$this->validate(
|
||||
[
|
||||
'groupId' => ['required', 'integer'],
|
||||
'unit' => ['required', 'in:'.implode(',', array_column(StockUnit::cases(), 'value'))],
|
||||
'image' => ['nullable', 'file', 'image', 'mimes:jpg,jpeg,png,webp,gif', 'max:'.self::MAX_KILOBYTES],
|
||||
],
|
||||
[
|
||||
'groupId.required' => __('inventory.errors.group'),
|
||||
'groupId.integer' => __('inventory.errors.group'),
|
||||
'image.file' => __('inventory.errors.image'),
|
||||
'image.image' => __('inventory.errors.image'),
|
||||
'image.mimes' => __('inventory.errors.image'),
|
||||
'image.max' => __('inventory.errors.image_too_large', ['size' => self::MAX_KILOBYTES / 1024]),
|
||||
],
|
||||
);
|
||||
|
||||
$data = new StockItemData((int) $this->groupId, $this->name, $this->unit, $this->code, $this->supplier, $this->reorderLevel);
|
||||
|
||||
try {
|
||||
if ($this->itemId === null) {
|
||||
$this->itemId = $addItem->execute($data);
|
||||
$status = __('inventory.form.created', ['name' => trim($this->name)]);
|
||||
} else {
|
||||
$updateItem->execute($this->itemId, $data);
|
||||
$status = __('inventory.form.updated', ['name' => trim($this->name)]);
|
||||
}
|
||||
|
||||
if ($this->image instanceof TemporaryUploadedFile) {
|
||||
$changeImage->execute($this->itemId, (string) $this->image->getRealPath());
|
||||
} elseif ($this->removeImage) {
|
||||
$changeImage->execute($this->itemId, null);
|
||||
}
|
||||
} catch (InvalidStockName) {
|
||||
$this->addError('name', __('inventory.errors.name'));
|
||||
|
||||
return;
|
||||
} catch (StockNameTaken) {
|
||||
$this->addError('name', __('inventory.errors.name_taken'));
|
||||
|
||||
return;
|
||||
} catch (InvalidStockQuantity) {
|
||||
$this->addError('reorderLevel', __('inventory.errors.reorder_level'));
|
||||
|
||||
return;
|
||||
} catch (StockItemGroupNotFound) {
|
||||
$this->addError('groupId', __('inventory.errors.group'));
|
||||
|
||||
return;
|
||||
} catch (InvalidStockImage) {
|
||||
$this->addError('image', __('inventory.errors.image'));
|
||||
|
||||
return;
|
||||
} catch (StockItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
session()->flash('status', $status);
|
||||
$this->redirectRoute('inventory.items.show', $this->itemId, navigate: true);
|
||||
}
|
||||
|
||||
public function heading(): string
|
||||
{
|
||||
return __($this->itemId === null ? 'inventory.form.create_title' : 'inventory.form.edit_title');
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title($this->heading());
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
|
||||
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
|
||||
|
||||
@if ($this->groups === [])
|
||||
<p class="text-sm">{{ __('inventory.form.no_groups') }} <x-link :href="route('inventory.groups')" navigate>{{ __('inventory.index.groups') }}</x-link></p>
|
||||
@else
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native id="item-group" wire:model="groupId" :label="__('inventory.form.group')" :aria-label="__('inventory.form.group')">
|
||||
@foreach ($this->groups as $group)
|
||||
<option value="{{ $group->id }}">{{ $group->name }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
|
||||
<x-input id="item-name" wire:model="name" :label="__('inventory.form.name')" autocomplete="off" maxlength="150" required />
|
||||
|
||||
<x-select.native id="item-unit" wire:model="unit" :label="__('inventory.form.unit')" :aria-label="__('inventory.form.unit')">
|
||||
@foreach (StockUnit::cases() as $option)
|
||||
<option value="{{ $option->value }}">{{ __('inventory.units.'.$option->value) }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
|
||||
<x-input id="item-code" wire:model="code" :label="__('inventory.form.code')" :hint="__('inventory.form.code_hint')" autocomplete="off" maxlength="150" />
|
||||
|
||||
<x-input id="item-supplier" wire:model="supplier" :label="__('inventory.form.supplier')" autocomplete="off" maxlength="150" />
|
||||
|
||||
<x-input id="item-reorder" wire:model="reorderLevel" inputmode="decimal" :label="__('inventory.form.reorder_level')" :hint="__('inventory.form.reorder_level_hint')" autocomplete="off" />
|
||||
|
||||
<div class="space-y-2">
|
||||
<label for="item-image" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('inventory.form.image') }}</label>
|
||||
<p id="item-image-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
|
||||
@if ($hasImage && $itemId !== null)
|
||||
<img src="{{ route('inventory.items.image', [$itemId, 'thumbnail']) }}" alt="{{ __('inventory.form.current_image') }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
|
||||
<x-checkbox id="remove-image" wire:model="removeImage" :label="__('inventory.form.remove_image')" />
|
||||
@endif
|
||||
<input
|
||||
type="file"
|
||||
id="item-image"
|
||||
wire:model="image"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
aria-describedby="item-image-hint @error('image') item-image-error @enderror"
|
||||
@error('image') aria-invalid="true" @enderror
|
||||
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
|
||||
/>
|
||||
@error('image')
|
||||
<p id="item-image-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<x-button submit :text="__('inventory.form.save')" />
|
||||
<x-button :href="$itemId === null ? route('inventory.index') : route('inventory.items.show', $itemId)" wire:navigate subtle color="black" :text="__('inventory.form.cancel')" />
|
||||
</div>
|
||||
</form>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,522 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
||||
use App\Modules\Inventory\Application\DTOs\PurchaseData;
|
||||
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
|
||||
use App\Modules\Inventory\Application\DTOs\StockUseData;
|
||||
use App\Modules\Inventory\Application\UseCases\RecordStockPurchase;
|
||||
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
|
||||
use App\Modules\Inventory\Application\UseCases\RecordStockWriteOff;
|
||||
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
|
||||
use App\Modules\Inventory\Application\UseCases\SetStockItemActive;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
|
||||
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
|
||||
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
|
||||
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A stock item's page (spec 19.1–19.2): its details and balance, the
|
||||
* movement history with the balance after each, and the forms to record a
|
||||
* purchase or a write-off (management) and use without a target (everyone
|
||||
* using stock). Movements are corrected with reversals.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsStock;
|
||||
|
||||
public const int HISTORY_LIMIT = 200;
|
||||
|
||||
#[Locked]
|
||||
public int $itemId;
|
||||
|
||||
#[Locked]
|
||||
public string $message = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $reverseMovementId = null;
|
||||
|
||||
public string $purchaseDay = '';
|
||||
|
||||
public string $purchaseQuantity = '';
|
||||
|
||||
public string $purchaseTotal = '';
|
||||
|
||||
public string $purchaseUnitPrice = '';
|
||||
|
||||
public string $purchaseSupplier = '';
|
||||
|
||||
public string $purchaseDocument = '';
|
||||
|
||||
public string $writeOffQuantity = '';
|
||||
|
||||
public string $writeOffReason = '';
|
||||
|
||||
public string $useQuantity = '';
|
||||
|
||||
public string $useReason = '';
|
||||
|
||||
public function mount(StockQueries $stock, Clock $clock, int $item): void
|
||||
{
|
||||
$this->authorize('inventory.view');
|
||||
|
||||
$summary = $stock->findItem($item) ?? abort(404);
|
||||
$this->itemId = $summary->id;
|
||||
$this->purchaseDay = $clock->today()->format('Y-m-d');
|
||||
$this->purchaseSupplier = (string) $summary->supplier;
|
||||
$this->message = (string) session('status', '');
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function item(): StockItemSummary
|
||||
{
|
||||
return app(StockQueries::class)->findItem($this->itemId) ?? abort(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<StockMovementSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function movements(): array
|
||||
{
|
||||
return app(StockQueries::class)->movementsOf($this->itemId, self::HISTORY_LIMIT);
|
||||
}
|
||||
|
||||
public function recordPurchase(RecordStockPurchase $recordPurchase): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
$this->resetErrorBag();
|
||||
|
||||
if (trim($this->purchaseTotal) === '' && trim($this->purchaseUnitPrice) === '') {
|
||||
$this->addError('purchaseTotal', __('inventory.errors.price_required'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$recordPurchase->execute(new PurchaseData(
|
||||
$this->itemId,
|
||||
$this->purchaseDay,
|
||||
$this->purchaseQuantity,
|
||||
$this->purchaseTotal,
|
||||
$this->purchaseUnitPrice,
|
||||
$this->purchaseSupplier,
|
||||
$this->purchaseDocument,
|
||||
), (int) auth()->id());
|
||||
} catch (InvalidStockQuantity) {
|
||||
$this->addError('purchaseQuantity', __('inventory.errors.quantity'));
|
||||
|
||||
return;
|
||||
} catch (InvalidStockCost) {
|
||||
$this->addError(trim($this->purchaseTotal) !== '' ? 'purchaseTotal' : 'purchaseUnitPrice', __('inventory.errors.cost'));
|
||||
|
||||
return;
|
||||
} catch (InvalidStockDay) {
|
||||
$this->addError('purchaseDay', __('inventory.errors.day'));
|
||||
|
||||
return;
|
||||
} catch (StockItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->refreshItem();
|
||||
$this->message = __('inventory.purchase.saved', [
|
||||
'quantity' => $this->quantity((int) round((float) str_replace(',', '.', $this->purchaseQuantity) * 1000), $this->item->unit),
|
||||
'balance' => $this->quantity($this->item->balanceMilli, $this->item->unit),
|
||||
'cost' => $this->unitCost($this->item->averageCostHundredths),
|
||||
]);
|
||||
$this->reset('purchaseQuantity', 'purchaseTotal', 'purchaseUnitPrice', 'purchaseDocument');
|
||||
$this->js("document.getElementById('item-status')?.focus()");
|
||||
}
|
||||
|
||||
public function recordWriteOff(RecordStockWriteOff $recordWriteOff): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
$this->resetErrorBag();
|
||||
|
||||
try {
|
||||
$result = $recordWriteOff->execute(new StockUseData($this->itemId, $this->writeOffQuantity, reason: $this->writeOffReason), (int) auth()->id());
|
||||
} catch (InvalidStockQuantity) {
|
||||
$this->addError('writeOffQuantity', __('inventory.errors.quantity'));
|
||||
|
||||
return;
|
||||
} catch (StockReasonRequired) {
|
||||
$this->addError('writeOffReason', __('inventory.errors.reason'));
|
||||
|
||||
return;
|
||||
} catch (StockItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->refreshItem();
|
||||
$this->message = __('inventory.write_off.saved', [
|
||||
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
|
||||
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
|
||||
]);
|
||||
$this->reset('writeOffQuantity', 'writeOffReason');
|
||||
$this->js("document.getElementById('item-status')?.focus()");
|
||||
}
|
||||
|
||||
public function recordUse(RecordStockUse $recordUse): void
|
||||
{
|
||||
$this->authorize('inventory.record-use');
|
||||
$this->resetErrorBag();
|
||||
|
||||
try {
|
||||
$result = $recordUse->execute(new StockUseData($this->itemId, $this->useQuantity, reason: $this->useReason), (int) auth()->id());
|
||||
} catch (InvalidStockQuantity) {
|
||||
$this->addError('useQuantity', __('inventory.errors.quantity'));
|
||||
|
||||
return;
|
||||
} catch (StockReasonRequired) {
|
||||
$this->addError('useReason', __('inventory.errors.reason'));
|
||||
|
||||
return;
|
||||
} catch (StockItemInactive) {
|
||||
$this->addError('useQuantity', __('inventory.errors.inactive'));
|
||||
|
||||
return;
|
||||
} catch (StockItemNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->refreshItem();
|
||||
$this->message = __('inventory.use.saved', [
|
||||
'quantity' => $this->quantity($result->quantityMilli, $this->item->unit),
|
||||
'balance' => $this->quantity($result->balanceMilli, $this->item->unit),
|
||||
]);
|
||||
$this->reset('useQuantity', 'useReason');
|
||||
$this->js("document.getElementById('item-status')?.focus()");
|
||||
}
|
||||
|
||||
public function confirmReverse(int $movementId): void
|
||||
{
|
||||
$movement = $this->movement($movementId);
|
||||
abort_unless($this->mayReverse($movement), 403);
|
||||
|
||||
$this->reverseMovementId = $movementId;
|
||||
$this->js("document.getElementById('reverse-dialog').showModal()");
|
||||
}
|
||||
|
||||
public function reverse(ReverseStockMovement $reverseMovement): void
|
||||
{
|
||||
$movement = $this->movement((int) $this->reverseMovementId);
|
||||
abort_unless($this->mayReverse($movement), 403);
|
||||
|
||||
try {
|
||||
$reverseMovement->execute($movement->id, (int) auth()->id(), Gate::allows('inventory.reverse-any'));
|
||||
$this->refreshItem();
|
||||
$this->message = __('inventory.item.reversed', ['balance' => $this->quantity($this->item->balanceMilli, $this->item->unit)]);
|
||||
} catch (StockMovementNotFound) {
|
||||
$this->message = __('inventory.errors.not_found');
|
||||
} catch (StockMovementAlreadyReversed) {
|
||||
$this->message = __('inventory.errors.already_reversed');
|
||||
} catch (StockMovementNotReversible) {
|
||||
$this->message = __('inventory.errors.not_reversible');
|
||||
} catch (StockReversalNotAllowed) {
|
||||
$this->message = __('inventory.errors.reversal_not_allowed');
|
||||
}
|
||||
|
||||
$this->reverseMovementId = null;
|
||||
$this->refreshItem();
|
||||
$this->js("document.getElementById('reverse-dialog').close(); document.getElementById('item-status').focus()");
|
||||
}
|
||||
|
||||
public function toggleActive(SetStockItemActive $setActive): void
|
||||
{
|
||||
$this->authorize('inventory.manage');
|
||||
|
||||
$active = ! $this->item->isActive;
|
||||
$setActive->execute($this->itemId, $active);
|
||||
$this->refreshItem();
|
||||
$this->message = __($active ? 'inventory.item.activated' : 'inventory.item.deactivated');
|
||||
}
|
||||
|
||||
public function mayReverse(StockMovementSummary $movement): bool
|
||||
{
|
||||
if (! $movement->canBeReversed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Gate::allows('inventory.reverse-any')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Gate::allows('inventory.record-use')
|
||||
&& $movement->kind->value === 'consumption'
|
||||
&& $movement->userId === (int) auth()->id()
|
||||
&& $movement->occurredOn === app(Clock::class)->today()->format('Y-m-d');
|
||||
}
|
||||
|
||||
public function targetText(StockMovementSummary $movement): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
if ($movement->taskId !== null) {
|
||||
$parts[] = __('inventory.item.target_task', ['id' => $movement->taskId]);
|
||||
}
|
||||
if ($movement->machineId !== null) {
|
||||
$parts[] = __('inventory.item.target_machine', ['id' => $movement->machineId]);
|
||||
}
|
||||
if ($movement->orderLineId !== null) {
|
||||
$parts[] = __('inventory.item.target_order');
|
||||
}
|
||||
if ($movement->maintenanceRecordId !== null) {
|
||||
$parts[] = __('inventory.item.target_maintenance');
|
||||
}
|
||||
if ($movement->inventoryCountId !== null) {
|
||||
$parts[] = __('inventory.item.target_count', ['id' => $movement->inventoryCountId]);
|
||||
}
|
||||
if ($movement->supplier !== null) {
|
||||
$parts[] = $movement->supplier;
|
||||
}
|
||||
if ($movement->documentNumber !== null) {
|
||||
$parts[] = __('inventory.item.document', ['number' => $movement->documentNumber]);
|
||||
}
|
||||
if ($movement->reason !== null) {
|
||||
$parts[] = $movement->reason;
|
||||
}
|
||||
if ($movement->reversesMovementId !== null) {
|
||||
$parts[] = __('inventory.item.reverses', ['number' => $movement->reversesMovementId]);
|
||||
}
|
||||
|
||||
return $parts === [] ? '–' : implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
$headers = [
|
||||
['index' => 'time', 'label' => __('inventory.columns.time'), 'sortable' => false],
|
||||
['index' => 'kind', 'label' => __('inventory.columns.kind'), 'sortable' => false],
|
||||
['index' => 'quantity', 'label' => __('inventory.columns.quantity'), 'sortable' => false, 'align' => 'right'],
|
||||
['index' => 'balance', 'label' => __('inventory.columns.balance_after'), 'sortable' => false, 'align' => 'right'],
|
||||
['index' => 'user', 'label' => __('inventory.columns.user'), 'sortable' => false],
|
||||
['index' => 'target', 'label' => __('inventory.columns.target'), 'sortable' => false],
|
||||
];
|
||||
|
||||
if (Gate::allows('inventory.see-value')) {
|
||||
$headers[] = ['index' => 'value', 'label' => __('inventory.columns.value'), 'sortable' => false, 'align' => 'right'];
|
||||
}
|
||||
|
||||
$headers[] = ['index' => 'actions', 'label' => __('inventory.columns.actions'), 'sortable' => false];
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title($this->item->name);
|
||||
}
|
||||
|
||||
private function movement(int $movementId): StockMovementSummary
|
||||
{
|
||||
$movement = app(StockQueries::class)->findMovement($movementId);
|
||||
abort_if($movement === null || $movement->itemId !== $this->itemId, 404);
|
||||
|
||||
return $movement;
|
||||
}
|
||||
|
||||
private function refreshItem(): void
|
||||
{
|
||||
unset($this->item, $this->movements);
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
|
||||
@php($item = $this->item)
|
||||
|
||||
<div class="flex flex-wrap items-start gap-4">
|
||||
@if ($item->hasImage)
|
||||
<img src="{{ route('inventory.items.image', [$item->id, 'thumbnail']) }}" alt="{{ __('inventory.item.image_alt', ['name' => $item->name]) }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
|
||||
@endif
|
||||
<div class="min-w-0 flex-1 space-y-2">
|
||||
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
|
||||
<h1 class="text-2xl font-semibold break-words">{{ $item->name }}</h1>
|
||||
<x-inventory.stock-status :item="$item" />
|
||||
@can('inventory.manage')
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<x-button :href="route('inventory.items.edit', $item->id)" wire:navigate sm icon="pencil" :text="__('inventory.item.edit')" />
|
||||
<x-button wire:click="toggleActive" subtle color="black" sm :icon="$item->isActive ? 'archive-box-x-mark' : 'archive-box-arrow-down'" :text="$item->isActive ? __('inventory.item.deactivate') : __('inventory.item.activate')" />
|
||||
</div>
|
||||
@endcan
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p id="item-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
|
||||
|
||||
<section aria-labelledby="details-heading" class="space-y-3">
|
||||
<h2 id="details-heading" class="text-lg font-semibold">{{ __('inventory.item.details') }}</h2>
|
||||
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.item.balance') }}</dt>
|
||||
<dd class="text-lg font-semibold">{{ $this->quantity($item->balanceMilli, $item->unit) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.columns.group') }}</dt>
|
||||
<dd>{{ $item->groupName }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.columns.reorder_level') }}</dt>
|
||||
<dd>{{ $item->reorderLevelMilli === null ? '–' : $this->quantity($item->reorderLevelMilli, $item->unit) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.form.code') }}</dt>
|
||||
<dd>{{ $item->code ?? '–' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.form.supplier') }}</dt>
|
||||
<dd>{{ $item->supplier ?? '–' }}</dd>
|
||||
</div>
|
||||
@can('inventory.see-value')
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.columns.average_cost') }}</dt>
|
||||
<dd>{{ $this->unitCost($item->averageCostHundredths) }} / {{ __('inventory.units.'.$item->unit->value) }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="font-medium">{{ __('inventory.columns.value') }}</dt>
|
||||
<dd>{{ $this->money($item->valueCents) }}</dd>
|
||||
</div>
|
||||
@endcan
|
||||
</dl>
|
||||
@if ($item->isNegative())
|
||||
<p class="flex items-start gap-2 text-sm font-medium text-red-700 dark:text-red-400">
|
||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ __('inventory.use.negative_warning') }}
|
||||
</p>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
@php($unitLabel = __('inventory.units.'.$item->unit->value))
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
@can('inventory.manage')
|
||||
<section aria-labelledby="purchase-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="purchase-heading" class="text-lg font-semibold">{{ __('inventory.purchase.title') }}</h2>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.purchase.intro') }}</p>
|
||||
<form wire:submit="recordPurchase" class="space-y-4" novalidate>
|
||||
<x-input id="purchase-day" wire:model="purchaseDay" type="date" :label="__('inventory.purchase.day')" required />
|
||||
<x-input id="purchase-quantity" wire:model="purchaseQuantity" inputmode="decimal" :label="__('inventory.purchase.quantity', ['unit' => $unitLabel])" autocomplete="off" />
|
||||
<x-input id="purchase-total" wire:model="purchaseTotal" inputmode="decimal" :label="__('inventory.purchase.total_price')" autocomplete="off" />
|
||||
<x-input id="purchase-unit-price" wire:model="purchaseUnitPrice" inputmode="decimal" :label="__('inventory.purchase.unit_price', ['unit' => $unitLabel])" :hint="__('inventory.purchase.unit_price_hint')" autocomplete="off" />
|
||||
<x-input id="purchase-supplier" wire:model="purchaseSupplier" :label="__('inventory.purchase.supplier')" autocomplete="off" maxlength="255" />
|
||||
<x-input id="purchase-document" wire:model="purchaseDocument" :label="__('inventory.purchase.document_number')" autocomplete="off" maxlength="255" />
|
||||
<x-button submit icon="truck" :text="__('inventory.purchase.save')" />
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="write-off-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="write-off-heading" class="text-lg font-semibold">{{ __('inventory.write_off.title') }}</h2>
|
||||
<form wire:submit="recordWriteOff" class="space-y-4" novalidate>
|
||||
<x-input id="write-off-quantity" wire:model="writeOffQuantity" inputmode="decimal" :label="__('inventory.write_off.quantity', ['unit' => $unitLabel])" autocomplete="off" />
|
||||
<x-input id="write-off-reason" wire:model="writeOffReason" :label="__('inventory.write_off.reason')" :hint="__('inventory.write_off.reason_hint')" autocomplete="off" maxlength="255" />
|
||||
<x-button submit icon="trash" :text="__('inventory.write_off.save')" />
|
||||
</form>
|
||||
</section>
|
||||
@endcan
|
||||
|
||||
@if ($item->isActive)
|
||||
@can('inventory.record-use')
|
||||
<section aria-labelledby="use-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
|
||||
<h2 id="use-heading" class="text-lg font-semibold">{{ __('inventory.use.title') }}</h2>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.use.intro') }}</p>
|
||||
<form wire:submit="recordUse" class="space-y-4" novalidate>
|
||||
<x-input id="use-quantity" wire:model="useQuantity" inputmode="decimal" :label="__('inventory.use.quantity', ['unit' => $unitLabel])" autocomplete="off" />
|
||||
<x-input id="use-reason" wire:model="useReason" :label="__('inventory.use.reason')" autocomplete="off" maxlength="255" />
|
||||
<x-button submit icon="minus-circle" :text="__('inventory.use.save')" />
|
||||
</form>
|
||||
</section>
|
||||
@endcan
|
||||
@else
|
||||
<p class="text-sm">{{ __('inventory.item.inactive_note') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<section aria-labelledby="history-heading" class="space-y-3">
|
||||
<h2 id="history-heading" class="text-lg font-semibold">{{ __('inventory.item.history') }}</h2>
|
||||
|
||||
@if ($this->movements === [])
|
||||
<p class="text-sm">{{ __('inventory.item.history_none') }}</p>
|
||||
@else
|
||||
@if (count($this->movements) >= $this::HISTORY_LIMIT)
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}</p>
|
||||
@endif
|
||||
|
||||
<x-table :headers="$this->headers()" :rows="$this->movements">
|
||||
@interact('column_time', $movement)
|
||||
<span class="whitespace-nowrap">{{ $this->dateLabel($movement->recordedAt) }}</span>
|
||||
@if ($movement->occurredOn !== substr($movement->recordedAt, 0, 10))
|
||||
<span class="block text-xs">{{ $this->dateLabel($movement->occurredOn) }}</span>
|
||||
@endif
|
||||
@endinteract
|
||||
|
||||
@interact('column_kind', $movement)
|
||||
{{ __('inventory.kinds.'.$movement->kind->value) }}
|
||||
@if ($movement->reversedByMovementId !== null)
|
||||
<span class="block text-xs">{{ __('inventory.item.reversed_by', ['number' => $movement->reversedByMovementId]) }}</span>
|
||||
@endif
|
||||
@endinteract
|
||||
|
||||
@interact('column_quantity', $movement)
|
||||
<span class="whitespace-nowrap">{{ ($movement->quantityMilli > 0 ? '+' : '').$this->quantity($movement->quantityMilli) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_balance', $movement)
|
||||
<span class="whitespace-nowrap">{{ $this->quantity($movement->balanceAfterMilli) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_user', $movement)
|
||||
{{ $movement->userName }}
|
||||
@endinteract
|
||||
|
||||
@interact('column_target', $movement)
|
||||
<span class="whitespace-normal">{{ $this->targetText($movement) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_value', $movement)
|
||||
<span class="whitespace-nowrap">{{ $this->money($movement->valueCents) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_actions', $movement)
|
||||
@if ($this->mayReverse($movement))
|
||||
<x-button
|
||||
wire:click="confirmReverse({{ $movement->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
icon="arrow-uturn-left"
|
||||
:text="__('inventory.item.reverse')"
|
||||
:aria-label="__('inventory.item.reverse_named', ['kind' => __('inventory.kinds.'.$movement->kind->value), 'quantity' => $this->quantity($movement->quantityMilli), 'time' => $this->dateLabel($movement->recordedAt)])"
|
||||
/>
|
||||
@endif
|
||||
@endinteract
|
||||
</x-table>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<x-confirm-dialog id="reverse-dialog" :title="__('inventory.item.reverse_title')">
|
||||
@php($reverseMovement = $reverseMovementId === null ? null : collect($this->movements)->firstWhere('id', $reverseMovementId))
|
||||
@if ($reverseMovement !== null)
|
||||
<p>{{ __('inventory.item.reverse_text', ['kind' => __('inventory.kinds.'.$reverseMovement->kind->value), 'quantity' => $this->quantity($reverseMovement->quantityMilli, $item->unit)]) }}</p>
|
||||
@endif
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="reverse" color="red" :text="__('inventory.item.reverse_confirm')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:inventory.view'])
|
||||
->prefix('inventory')
|
||||
->name('inventory.')
|
||||
->group(function () {
|
||||
Route::livewire('/', 'inventory::index')->name('index');
|
||||
Route::get('/items/{item}/image/{size}', ShowStockItemImage::class)
|
||||
->whereNumber('item')
|
||||
->whereIn('size', ['full', 'thumbnail'])
|
||||
->name('items.image');
|
||||
|
||||
Route::middleware('can:inventory.manage')->group(function () {
|
||||
Route::livewire('/groups', 'inventory::groups')->name('groups');
|
||||
Route::livewire('/items/create', 'inventory::item-form')->name('items.create');
|
||||
Route::livewire('/items/{item}/edit', 'inventory::item-form')->whereNumber('item')->name('items.edit');
|
||||
});
|
||||
|
||||
Route::livewire('/items/{item}', 'inventory::item')->whereNumber('item')->name('items.show');
|
||||
});
|
||||
Reference in New Issue
Block a user