Files
2026-11-26 16:18:59 +02:00

71 lines
2.7 KiB
PHP

<?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();
});
}
}