Files
Toiminnanohjaus/app/Modules/Sales/Application/UseCases/CreditQuickSale.php
T

68 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\UseCases;
use App\Modules\Sales\Application\Contracts\ReceiptMailer;
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Sales\Domain\Entities\QuickSale;
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Credits a quick sale (hyvitys): records the sale's lines negated on
* today's cash day, so a sale of a closed day can be credited too. Hours
* stay as they are: the work was done, and a wrong amount is corrected in
* the weekly view. When the original's receipt went to an email address,
* the credit's receipt is emailed there too. Who may credit is checked by
* the caller.
*/
final class CreditQuickSale
{
public function __construct(
private QuickSaleRepository $sales,
private CashDayRepository $cashDays,
private ReceiptMailer $mailer,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The credit's id.
*
* @throws QuickSaleNotFound
* @throws QuickSaleAlreadyCredited
* @throws CreditCannotBeCredited
* @throws CashDayClosed
*/
public function execute(int $saleId, int $actorUserId): int
{
$today = $this->clock->today();
$credit = $this->transactions->run(function () use ($saleId, $actorUserId, $today): QuickSale {
$original = $this->sales->findById($saleId) ?? throw new QuickSaleNotFound($saleId);
$this->cashDays->lockForDay($today)->ensureOpen();
if ($this->sales->isCredited($saleId)) {
throw new QuickSaleAlreadyCredited;
}
$credit = QuickSale::creditFor($original, $actorUserId, $this->clock->now(), $today);
return $this->sales->add($credit);
});
if ($credit->receiptEmail() !== null) {
$this->mailer->send((int) $credit->id());
}
return (int) $credit->id();
}
}