Add quick sales with cash days, credits and PDF receipts
Quick sales (pikamyynti) of active consumer products at the counter, in a new Sales module: - Product buttons add one to the sale's list per press; quantities can be lowered, raised or removed. Payment by cash or card, optional customer. - Product durations are booked as the seller's hours on the yearly "Pikamyynnit" job (internal customer, not billed) through Jobs' ProvideQuickSaleTask and TimeTracking's AddTaskHours. The sale stands even when the hours cannot be booked, and the seller is told. - Sales are never deleted: a credit records the lines negated on today's cash day, once per sale, by the seller or management. - Closing a cash day stores its balance by payment method and VAT rate and stops sales on it; only management reopens a day. - A printable A5 PDF receipt (barryvdh/laravel-dompdf) with the company's details, business ID, VAT number, lines and VAT breakdown. Company details are kept in the settings and edited by the admin only on the new Yritystiedot page. BusinessId moves from Customers to Shared so both use the same check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Books the hours of a quick sale on the seller, on the year's quick sale
|
||||
* job. Implemented with the Jobs and TimeTracking modules.
|
||||
*/
|
||||
interface QuickSaleHours
|
||||
{
|
||||
/**
|
||||
* Adds the hours to the seller's day on the work type's task.
|
||||
*
|
||||
* @return bool False when the hours could not be booked, e.g. the
|
||||
* day's hours are already approved or would pass 24 hours.
|
||||
*/
|
||||
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
|
||||
/**
|
||||
* The products that can be sold at the counter: active consumer products
|
||||
* of the price list. Implemented with the Catalog module's queries.
|
||||
*/
|
||||
interface QuickSaleProducts
|
||||
{
|
||||
/**
|
||||
* @return list<SellableProduct> In price list order.
|
||||
*/
|
||||
public function sellable(): array;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\Contracts;
|
||||
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
|
||||
interface QuickSaleQueries
|
||||
{
|
||||
/**
|
||||
* The day's sales and credits, latest first; only the seller's when given.
|
||||
*
|
||||
* @param string $day Y-m-d
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
public function salesOn(string $day, ?int $sellerId = null): array;
|
||||
|
||||
public function findSale(int $id): ?QuickSaleSummary;
|
||||
|
||||
/**
|
||||
* @param string $day Y-m-d
|
||||
*/
|
||||
public function cashDay(string $day): CashDaySummary;
|
||||
|
||||
/**
|
||||
* Earlier days with sales that have not been closed, oldest first.
|
||||
*
|
||||
* @param string $day Y-m-d
|
||||
* @return list<string> Y-m-d
|
||||
*/
|
||||
public function unclosedDaysBefore(string $day): array;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
|
||||
/**
|
||||
* A cash day's state. The balance is the stored one of a closed day and
|
||||
* the balance that closing would form on an open day. Times are
|
||||
* "Y-m-d H:i" in the company's time zone.
|
||||
*/
|
||||
final readonly class CashDaySummary
|
||||
{
|
||||
public function __construct(
|
||||
public string $day,
|
||||
public bool $isClosed,
|
||||
public CashDayBalance $balance,
|
||||
public ?string $closedByName = null,
|
||||
public ?string $closedAt = null,
|
||||
public ?string $reopenedByName = null,
|
||||
public ?string $reopenedAt = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
final readonly class QuickSaleLineSummary
|
||||
{
|
||||
public function __construct(
|
||||
public string $productName,
|
||||
public int $quantity,
|
||||
public int $unitPriceCents,
|
||||
public int $totalCents,
|
||||
public int $vatBasisPoints = 0,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
|
||||
|
||||
/**
|
||||
* A quick sale as listed: amounts with VAT, negative on a credit.
|
||||
* $soldAt is "Y-m-d H:i" in the company's time zone. $creditsSaleId is set
|
||||
* on a credit, $creditedBySaleId on a sale that has been credited.
|
||||
*/
|
||||
final readonly class QuickSaleSummary
|
||||
{
|
||||
/**
|
||||
* @param list<QuickSaleLineSummary> $lines
|
||||
*/
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $soldAt,
|
||||
public int $sellerId,
|
||||
public string $sellerName,
|
||||
public ?string $customerName,
|
||||
public PaymentMethod $paymentMethod,
|
||||
public int $totalCents,
|
||||
public array $lines,
|
||||
public ?int $creditsSaleId,
|
||||
public ?int $creditedBySaleId,
|
||||
) {}
|
||||
|
||||
public function isCredit(): bool
|
||||
{
|
||||
return $this->creditsSaleId !== null;
|
||||
}
|
||||
|
||||
public function canBeCredited(): bool
|
||||
{
|
||||
return $this->creditsSaleId === null && $this->creditedBySaleId === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sale's VAT by rate, highest rate first, as on its receipt.
|
||||
*
|
||||
* @return list<VatTotal>
|
||||
*/
|
||||
public function vatTotals(): array
|
||||
{
|
||||
$grossByRate = [];
|
||||
|
||||
foreach ($this->lines as $line) {
|
||||
$grossByRate[$line->vatBasisPoints] = ($grossByRate[$line->vatBasisPoints] ?? 0) + $line->totalCents;
|
||||
}
|
||||
|
||||
krsort($grossByRate);
|
||||
|
||||
return array_map(
|
||||
fn (int $basisPoints, int $gross): VatTotal => VatTotal::ofGross($basisPoints, $gross),
|
||||
array_keys($grossByRate),
|
||||
array_values($grossByRate),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* Input for a quick sale: quantities by product id (zero or empty ones are
|
||||
* left out by the caller), the payment method key and an optional customer.
|
||||
*/
|
||||
final readonly class SaleData
|
||||
{
|
||||
/**
|
||||
* @param array<int, int> $quantities
|
||||
*/
|
||||
public function __construct(
|
||||
public array $quantities,
|
||||
public string $paymentMethod,
|
||||
public ?int $customerId = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A recorded quick sale: its id and total with VAT, and the hours booked
|
||||
* on the seller or left unbooked (in quarters of an hour).
|
||||
*/
|
||||
final readonly class SaleResult
|
||||
{
|
||||
public function __construct(
|
||||
public int $saleId,
|
||||
public int $totalCents,
|
||||
public int $bookedQuarters,
|
||||
public int $unbookedQuarters,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A consumer product as it is sold: its price with VAT and the hours its
|
||||
* sale books on the seller ($durationQuarters on $workTypeId). $unit is
|
||||
* the price list unit key, e.g. "piece".
|
||||
*/
|
||||
final readonly class SellableProduct
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
public string $unit,
|
||||
public int $grossCents,
|
||||
public int $vatBasisPoints,
|
||||
public int $durationQuarters,
|
||||
public ?int $workTypeId,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Closes a cash day (today or a forgotten earlier one) and stores the
|
||||
* balance of its quick sales.
|
||||
*/
|
||||
final class CloseCashDay
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleRepository $sales,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws CashDayInFuture
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function execute(DateTimeImmutable $day, int $actorUserId): void
|
||||
{
|
||||
if ($day->format('Y-m-d') > $this->clock->today()->format('Y-m-d')) {
|
||||
throw new CashDayInFuture;
|
||||
}
|
||||
|
||||
$this->transactions->run(function () use ($day, $actorUserId): void {
|
||||
$cashDay = $this->cashDays->lockForDay($day);
|
||||
$cashDay->close($this->sales->forDay($day), $actorUserId, $this->clock->now());
|
||||
$this->cashDays->save($cashDay);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
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. Who may credit is checked by the caller.
|
||||
*/
|
||||
final class CreditQuickSale
|
||||
{
|
||||
public function __construct(
|
||||
private QuickSaleRepository $sales,
|
||||
private CashDayRepository $cashDays,
|
||||
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();
|
||||
|
||||
return $this->transactions->run(function () use ($saleId, $actorUserId, $today): int {
|
||||
$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 (int) $this->sales->add($credit)->id();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Reopens a closed cash day (management only, checked by the caller). The
|
||||
* balance is formed again when the day is closed again.
|
||||
*/
|
||||
final class ReopenCashDay
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws CashDayNotClosed
|
||||
*/
|
||||
public function execute(DateTimeImmutable $day, int $actorUserId): void
|
||||
{
|
||||
$this->transactions->run(function () use ($day, $actorUserId): void {
|
||||
$cashDay = $this->cashDays->lockForDay($day);
|
||||
$cashDay->reopen($actorUserId, $this->clock->now());
|
||||
$this->cashDays->save($cashDay);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Application\UseCases;
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\DTOs\SaleResult;
|
||||
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\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
|
||||
/**
|
||||
* Records a quick sale on today's cash day with the products' current
|
||||
* prices, and books the products' durations as the seller's hours. The
|
||||
* customer has paid, so the sale is kept even when the hours cannot be
|
||||
* booked; the result tells how many were left out.
|
||||
*/
|
||||
final class SellQuickSale
|
||||
{
|
||||
public function __construct(
|
||||
private QuickSaleRepository $sales,
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleProducts $products,
|
||||
private QuickSaleHours $hours,
|
||||
private CustomerQueries $customers,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ProductNotSellable
|
||||
* @throws InvalidQuantity
|
||||
* @throws QuickSaleEmpty
|
||||
* @throws QuickSaleCustomerNotFound
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function execute(int $sellerId, SaleData $data): SaleResult
|
||||
{
|
||||
$sellable = [];
|
||||
foreach ($this->products->sellable() as $product) {
|
||||
$sellable[$product->id] = $product;
|
||||
}
|
||||
|
||||
$lines = [];
|
||||
$quartersByWorkType = [];
|
||||
|
||||
foreach ($data->quantities as $productId => $quantity) {
|
||||
$product = $sellable[$productId] ?? throw new ProductNotSellable($productId);
|
||||
$lines[] = QuickSaleLine::sold($product->id, $product->name, $quantity, $product->grossCents, $product->vatBasisPoints);
|
||||
|
||||
if ($product->durationQuarters > 0 && $product->workTypeId !== null) {
|
||||
$quartersByWorkType[$product->workTypeId] = ($quartersByWorkType[$product->workTypeId] ?? 0) + $product->durationQuarters * $quantity;
|
||||
}
|
||||
}
|
||||
|
||||
if ($data->customerId !== null && $this->customers->findSummary($data->customerId) === null) {
|
||||
throw new QuickSaleCustomerNotFound($data->customerId);
|
||||
}
|
||||
|
||||
$today = $this->clock->today();
|
||||
$sale = QuickSale::sell($sellerId, $data->customerId, PaymentMethod::from($data->paymentMethod), $lines, $this->clock->now(), $today);
|
||||
|
||||
return $this->transactions->run(function () use ($sale, $sellerId, $today, $quartersByWorkType): SaleResult {
|
||||
$this->cashDays->lockForDay($today)->ensureOpen();
|
||||
$saleId = (int) $this->sales->add($sale)->id();
|
||||
|
||||
$booked = 0;
|
||||
$unbooked = 0;
|
||||
|
||||
foreach ($quartersByWorkType as $workTypeId => $quarters) {
|
||||
if ($this->hours->book($sellerId, $today, $workTypeId, $quarters, $saleId)) {
|
||||
$booked += $quarters;
|
||||
} else {
|
||||
$unbooked += $quarters;
|
||||
}
|
||||
}
|
||||
|
||||
return new SaleResult($saleId, $sale->totalCents(), $booked, $unbooked);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Contracts;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface CashDayRepository
|
||||
{
|
||||
/**
|
||||
* The stored cash day, or an open one when the day has not been closed yet.
|
||||
*/
|
||||
public function forDay(DateTimeImmutable $day): CashDay;
|
||||
|
||||
/**
|
||||
* Stores the day's state and balance.
|
||||
*/
|
||||
public function save(CashDay $cashDay): CashDay;
|
||||
|
||||
/**
|
||||
* The day, stored if it was not, with its row locked until the
|
||||
* transaction ends, so a sale and the closing of the same day cannot
|
||||
* interleave.
|
||||
*/
|
||||
public function lockForDay(DateTimeImmutable $day): CashDay;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Contracts;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface QuickSaleRepository
|
||||
{
|
||||
public function findById(int $id): ?QuickSale;
|
||||
|
||||
/**
|
||||
* Inserts a new sale with its lines and returns the stored sale.
|
||||
*/
|
||||
public function add(QuickSale $sale): QuickSale;
|
||||
|
||||
public function isCredited(int $saleId): bool;
|
||||
|
||||
/**
|
||||
* The cash day's sales, credits included.
|
||||
*
|
||||
* @return list<QuickSale>
|
||||
*/
|
||||
public function forDay(DateTimeImmutable $day): array;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Entities;
|
||||
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A day of quick sales at the counter (kassapäivä). Closing it forms the
|
||||
* day's balance and stops further sales on it; management may reopen it,
|
||||
* which empties the balance until it is closed again.
|
||||
*/
|
||||
final class CashDay
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private DateTimeImmutable $day,
|
||||
private ?CashDayBalance $balance,
|
||||
private ?int $closedBy,
|
||||
private ?DateTimeImmutable $closedAt,
|
||||
private ?int $reopenedBy,
|
||||
private ?DateTimeImmutable $reopenedAt,
|
||||
) {}
|
||||
|
||||
public static function open(DateTimeImmutable $day): self
|
||||
{
|
||||
return new self(null, $day, null, null, null, null, null);
|
||||
}
|
||||
|
||||
public static function reconstitute(int $id, DateTimeImmutable $day, ?CashDayBalance $balance, ?int $closedBy, ?DateTimeImmutable $closedAt, ?int $reopenedBy, ?DateTimeImmutable $reopenedAt): self
|
||||
{
|
||||
return new self($id, $day, $balance, $closedBy, $closedAt, $reopenedBy, $reopenedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<QuickSale> $sales The day's sales, credits included.
|
||||
*
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function close(array $sales, int $closedBy, DateTimeImmutable $now): void
|
||||
{
|
||||
$this->ensureOpen();
|
||||
|
||||
$this->balance = CashDayBalance::of($sales);
|
||||
$this->closedBy = $closedBy;
|
||||
$this->closedAt = $now;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws CashDayNotClosed
|
||||
*/
|
||||
public function reopen(int $reopenedBy, DateTimeImmutable $now): void
|
||||
{
|
||||
if (! $this->isClosed()) {
|
||||
throw new CashDayNotClosed;
|
||||
}
|
||||
|
||||
$this->balance = null;
|
||||
$this->closedBy = null;
|
||||
$this->closedAt = null;
|
||||
$this->reopenedBy = $reopenedBy;
|
||||
$this->reopenedAt = $now;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws CashDayClosed
|
||||
*/
|
||||
public function ensureOpen(): void
|
||||
{
|
||||
if ($this->isClosed()) {
|
||||
throw new CashDayClosed;
|
||||
}
|
||||
}
|
||||
|
||||
public function isClosed(): bool
|
||||
{
|
||||
return $this->closedAt !== null;
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function day(): DateTimeImmutable
|
||||
{
|
||||
return $this->day;
|
||||
}
|
||||
|
||||
public function balance(): ?CashDayBalance
|
||||
{
|
||||
return $this->balance;
|
||||
}
|
||||
|
||||
public function closedBy(): ?int
|
||||
{
|
||||
return $this->closedBy;
|
||||
}
|
||||
|
||||
public function closedAt(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->closedAt;
|
||||
}
|
||||
|
||||
public function reopenedBy(): ?int
|
||||
{
|
||||
return $this->reopenedBy;
|
||||
}
|
||||
|
||||
public function reopenedAt(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->reopenedAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Entities;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A cash or card sale of consumer products at the counter (pikamyynti),
|
||||
* possibly to a named customer. A sale is never deleted: a mistake is
|
||||
* corrected with a credit, a sale of its own with the original's lines
|
||||
* negated, paid back the same way and booked on the day it is made.
|
||||
*/
|
||||
final class QuickSale
|
||||
{
|
||||
/**
|
||||
* @param list<QuickSaleLine> $lines
|
||||
*/
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private int $sellerId,
|
||||
private ?int $customerId,
|
||||
private PaymentMethod $paymentMethod,
|
||||
private DateTimeImmutable $soldAt,
|
||||
private DateTimeImmutable $soldOn,
|
||||
private array $lines,
|
||||
private ?int $creditsSaleId,
|
||||
) {
|
||||
if ($lines === []) {
|
||||
throw new QuickSaleEmpty;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<QuickSaleLine> $lines
|
||||
* @param DateTimeImmutable $soldOn The cash day, in the company's time zone.
|
||||
*
|
||||
* @throws QuickSaleEmpty
|
||||
*/
|
||||
public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn): self
|
||||
{
|
||||
return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws CreditCannotBeCredited
|
||||
*/
|
||||
public static function creditFor(self $original, int $actorUserId, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn): self
|
||||
{
|
||||
if ($original->isCredit()) {
|
||||
throw new CreditCannotBeCredited;
|
||||
}
|
||||
|
||||
return new self(
|
||||
null,
|
||||
$actorUserId,
|
||||
$original->customerId,
|
||||
$original->paymentMethod,
|
||||
$soldAt,
|
||||
$soldOn,
|
||||
array_map(fn (QuickSaleLine $line): QuickSaleLine => $line->negated(), $original->lines),
|
||||
$original->id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<QuickSaleLine> $lines
|
||||
*/
|
||||
public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId): self
|
||||
{
|
||||
return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId);
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (QuickSaleLine $line): int => $line->totalCents(), $this->lines));
|
||||
}
|
||||
|
||||
public function isCredit(): bool
|
||||
{
|
||||
return $this->creditsSaleId !== null;
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function sellerId(): int
|
||||
{
|
||||
return $this->sellerId;
|
||||
}
|
||||
|
||||
public function customerId(): ?int
|
||||
{
|
||||
return $this->customerId;
|
||||
}
|
||||
|
||||
public function paymentMethod(): PaymentMethod
|
||||
{
|
||||
return $this->paymentMethod;
|
||||
}
|
||||
|
||||
public function soldAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->soldAt;
|
||||
}
|
||||
|
||||
public function soldOn(): DateTimeImmutable
|
||||
{
|
||||
return $this->soldOn;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<QuickSaleLine>
|
||||
*/
|
||||
public function lines(): array
|
||||
{
|
||||
return $this->lines;
|
||||
}
|
||||
|
||||
public function creditsSaleId(): ?int
|
||||
{
|
||||
return $this->creditsSaleId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Enums;
|
||||
|
||||
/**
|
||||
* How a quick sale was paid at the counter.
|
||||
*/
|
||||
enum PaymentMethod: string
|
||||
{
|
||||
case Cash = 'cash';
|
||||
case Card = 'card';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayClosed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The cash day is closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayInFuture extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A cash day in the future cannot be closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CashDayNotClosed extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The cash day is not closed.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class CreditCannotBeCredited extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A credit cannot be credited.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidQuantity extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A quantity must be a whole number from 1 to 999.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class ProductNotSellable extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Product {$id} is not an active consumer product.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleAlreadyCredited extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The quick sale has already been credited.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleCustomerNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Customer {$id} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleEmpty extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('A quick sale needs at least one product.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class QuickSaleNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $id)
|
||||
{
|
||||
parent::__construct("Quick sale {$id} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
|
||||
/**
|
||||
* The balance of a cash day's quick sales: how many, how much by payment
|
||||
* method and by VAT rate (highest rate first). Credits are included as
|
||||
* negative amounts.
|
||||
*/
|
||||
final readonly class CashDayBalance
|
||||
{
|
||||
/**
|
||||
* @param list<VatTotal> $vatTotals
|
||||
*/
|
||||
public function __construct(
|
||||
public int $saleCount,
|
||||
public int $cashCents,
|
||||
public int $cardCents,
|
||||
public array $vatTotals,
|
||||
) {}
|
||||
|
||||
public static function empty(): self
|
||||
{
|
||||
return new self(0, 0, 0, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<QuickSale> $sales
|
||||
*/
|
||||
public static function of(array $sales): self
|
||||
{
|
||||
$cash = 0;
|
||||
$card = 0;
|
||||
$grossByRate = [];
|
||||
|
||||
foreach ($sales as $sale) {
|
||||
if ($sale->paymentMethod() === PaymentMethod::Cash) {
|
||||
$cash += $sale->totalCents();
|
||||
} else {
|
||||
$card += $sale->totalCents();
|
||||
}
|
||||
|
||||
foreach ($sale->lines() as $line) {
|
||||
$grossByRate[$line->vatBasisPoints] = ($grossByRate[$line->vatBasisPoints] ?? 0) + $line->totalCents();
|
||||
}
|
||||
}
|
||||
|
||||
krsort($grossByRate);
|
||||
|
||||
$vatTotals = [];
|
||||
foreach ($grossByRate as $basisPoints => $gross) {
|
||||
$vatTotals[] = VatTotal::ofGross($basisPoints, $gross);
|
||||
}
|
||||
|
||||
return new self(count($sales), $cash, $card, $vatTotals);
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->cashCents + $this->cardCents;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
|
||||
/**
|
||||
* One product on a quick sale. The name, price (with VAT) and VAT rate are
|
||||
* copied from the price list when sold, so later price changes do not
|
||||
* change the sale. A credit line has a negative quantity.
|
||||
*/
|
||||
final readonly class QuickSaleLine
|
||||
{
|
||||
public const int MAX_QUANTITY = 999;
|
||||
|
||||
public function __construct(
|
||||
public int $productId,
|
||||
public string $productName,
|
||||
public int $quantity,
|
||||
public int $unitPriceCents,
|
||||
public int $vatBasisPoints,
|
||||
) {
|
||||
if ($quantity === 0 || abs($quantity) > self::MAX_QUANTITY) {
|
||||
throw new InvalidQuantity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A sold line: the quantity must be positive.
|
||||
*
|
||||
* @throws InvalidQuantity
|
||||
*/
|
||||
public static function sold(int $productId, string $productName, int $quantity, int $unitPriceCents, int $vatBasisPoints): self
|
||||
{
|
||||
if ($quantity < 1) {
|
||||
throw new InvalidQuantity;
|
||||
}
|
||||
|
||||
return new self($productId, $productName, $quantity, $unitPriceCents, $vatBasisPoints);
|
||||
}
|
||||
|
||||
public function negated(): self
|
||||
{
|
||||
return new self($this->productId, $this->productName, -$this->quantity, $this->unitPriceCents, $this->vatBasisPoints);
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->quantity * $this->unitPriceCents;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Sales\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||
|
||||
/**
|
||||
* A cash day's sales of one VAT rate: with VAT, without VAT and the VAT.
|
||||
* The VAT is taken out of the day's total of the rate, not line by line,
|
||||
* as on a till report. Credits make amounts negative.
|
||||
*/
|
||||
final readonly class VatTotal
|
||||
{
|
||||
public function __construct(
|
||||
public int $vatBasisPoints,
|
||||
public int $grossCents,
|
||||
public int $netCents,
|
||||
public int $vatCents,
|
||||
) {}
|
||||
|
||||
public static function ofGross(int $vatBasisPoints, int $grossCents): self
|
||||
{
|
||||
$net = Money::fromCents(abs($grossCents))->removeVat(new VatPercentage($vatBasisPoints))->cents;
|
||||
$net = $grossCents < 0 ? -$net : $net;
|
||||
|
||||
return new self($vatBasisPoints, $grossCents, $net, $grossCents - $net);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure;
|
||||
|
||||
use App\Modules\Jobs\Application\UseCases\ProvideQuickSaleTask;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* Books quick sale hours with the Jobs module's yearly quick sale job and
|
||||
* the TimeTracking module's task booking, so they are the seller's usual
|
||||
* hours: in the weekly view, within 24 hours a day, approved as usual.
|
||||
*/
|
||||
class HoursForQuickSales implements QuickSaleHours
|
||||
{
|
||||
public function __construct(
|
||||
private ProvideQuickSaleTask $tasks,
|
||||
private AddTaskHours $addHours,
|
||||
) {}
|
||||
|
||||
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool
|
||||
{
|
||||
$year = (int) $day->format('Y');
|
||||
|
||||
try {
|
||||
$taskId = $this->tasks->execute($year, $workTypeId, $sellerId, __('sales.job_name', ['year' => $year]));
|
||||
$this->addHours->execute(
|
||||
$sellerId,
|
||||
$taskId,
|
||||
$day->format('Y-m-d'),
|
||||
number_format($quarters / 4, 2, ',', ''),
|
||||
__('sales.hours_note', ['number' => $saleId]),
|
||||
);
|
||||
} catch (DomainException) {
|
||||
// Approved or locked hours, or a day over 24 hours: the sale stands without them.
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property string $day Y-m-d
|
||||
* @property int|null $closed_by
|
||||
* @property Carbon|null $closed_at
|
||||
* @property int $sale_count
|
||||
* @property int $cash_cents
|
||||
* @property int $card_cents
|
||||
* @property int $total_cents
|
||||
* @property int|null $reopened_by
|
||||
* @property Carbon|null $reopened_at
|
||||
*/
|
||||
#[Table('cash_days')]
|
||||
#[Fillable(['day', 'closed_by', 'closed_at', 'sale_count', 'cash_cents', 'card_cents', 'total_cents', 'reopened_by', 'reopened_at'])]
|
||||
class CashDayModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return HasMany<CashDayVatTotalModel, $this>
|
||||
*/
|
||||
public function vatTotals(): HasMany
|
||||
{
|
||||
return $this->hasMany(CashDayVatTotalModel::class, 'cash_day_id')->orderByDesc('vat_basis_points');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'closed_by' => 'integer',
|
||||
'closed_at' => 'datetime',
|
||||
'sale_count' => 'integer',
|
||||
'cash_cents' => 'integer',
|
||||
'card_cents' => 'integer',
|
||||
'total_cents' => 'integer',
|
||||
'reopened_by' => 'integer',
|
||||
'reopened_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $cash_day_id
|
||||
* @property int $vat_basis_points
|
||||
* @property int $gross_cents
|
||||
* @property int $net_cents
|
||||
* @property int $vat_cents
|
||||
*/
|
||||
#[Table('cash_day_vat_totals')]
|
||||
#[Fillable(['cash_day_id', 'vat_basis_points', 'gross_cents', 'net_cents', 'vat_cents'])]
|
||||
class CashDayVatTotalModel extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'cash_day_id' => 'integer',
|
||||
'vat_basis_points' => 'integer',
|
||||
'gross_cents' => 'integer',
|
||||
'net_cents' => 'integer',
|
||||
'vat_cents' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $quick_sale_id
|
||||
* @property int $product_id
|
||||
* @property string $product_name
|
||||
* @property int $quantity
|
||||
* @property int $unit_price_cents
|
||||
* @property int $vat_basis_points
|
||||
* @property int $sort_order
|
||||
*/
|
||||
#[Table('quick_sale_lines')]
|
||||
#[Fillable(['quick_sale_id', 'product_id', 'product_name', 'quantity', 'unit_price_cents', 'vat_basis_points', 'sort_order'])]
|
||||
class QuickSaleLineModel extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'quick_sale_id' => 'integer',
|
||||
'product_id' => 'integer',
|
||||
'quantity' => 'integer',
|
||||
'unit_price_cents' => 'integer',
|
||||
'vat_basis_points' => 'integer',
|
||||
'sort_order' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use Database\Factories\QuickSaleFactory;
|
||||
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;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Sales Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $user_id
|
||||
* @property int|null $customer_id
|
||||
* @property PaymentMethod $payment_method
|
||||
* @property Carbon $sold_at
|
||||
* @property string $sold_on Y-m-d
|
||||
* @property int $total_cents
|
||||
* @property int|null $credits_quick_sale_id
|
||||
*/
|
||||
#[Table('quick_sales')]
|
||||
#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id'])]
|
||||
#[UseFactory(QuickSaleFactory::class)]
|
||||
class QuickSaleModel extends Model
|
||||
{
|
||||
/** @use HasFactory<QuickSaleFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return HasMany<QuickSaleLineModel, $this>
|
||||
*/
|
||||
public function lines(): HasMany
|
||||
{
|
||||
return $this->hasMany(QuickSaleLineModel::class, 'quick_sale_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<QuickSaleModel, $this>
|
||||
*/
|
||||
public function credit(): HasOne
|
||||
{
|
||||
return $this->hasOne(QuickSaleModel::class, 'credits_quick_sale_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'user_id' => 'integer',
|
||||
'customer_id' => 'integer',
|
||||
'payment_method' => PaymentMethod::class,
|
||||
'sold_at' => 'datetime',
|
||||
'total_cents' => 'integer',
|
||||
'credits_quick_sale_id' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Entities\CashDay;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use App\Modules\Sales\Domain\ValueObjects\VatTotal;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayVatTotalModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentCashDayRepository implements CashDayRepository
|
||||
{
|
||||
public function forDay(DateTimeImmutable $day): CashDay
|
||||
{
|
||||
$model = CashDayModel::query()->with('vatTotals')->where('day', $day->format('Y-m-d'))->first();
|
||||
|
||||
return $model === null ? CashDay::open($day) : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function lockForDay(DateTimeImmutable $day): CashDay
|
||||
{
|
||||
CashDayModel::query()->insertOrIgnore(['day' => $day->format('Y-m-d'), 'created_at' => now(), 'updated_at' => now()]);
|
||||
|
||||
$model = CashDayModel::query()->with('vatTotals')->where('day', $day->format('Y-m-d'))->lockForUpdate()->firstOrFail();
|
||||
|
||||
return $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function save(CashDay $cashDay): CashDay
|
||||
{
|
||||
$model = CashDayModel::query()->firstOrNew(['day' => $cashDay->day()->format('Y-m-d')]);
|
||||
$balance = $cashDay->balance() ?? CashDayBalance::empty();
|
||||
|
||||
$model->fill([
|
||||
'closed_by' => $cashDay->closedBy(),
|
||||
'closed_at' => $cashDay->closedAt()?->format('Y-m-d H:i:s'),
|
||||
'sale_count' => $balance->saleCount,
|
||||
'cash_cents' => $balance->cashCents,
|
||||
'card_cents' => $balance->cardCents,
|
||||
'total_cents' => $balance->totalCents(),
|
||||
'reopened_by' => $cashDay->reopenedBy(),
|
||||
'reopened_at' => $cashDay->reopenedAt()?->format('Y-m-d H:i:s'),
|
||||
])->save();
|
||||
|
||||
CashDayVatTotalModel::query()->where('cash_day_id', $model->id)->delete();
|
||||
|
||||
foreach ($balance->vatTotals as $total) {
|
||||
CashDayVatTotalModel::query()->create([
|
||||
'cash_day_id' => $model->id,
|
||||
'vat_basis_points' => $total->vatBasisPoints,
|
||||
'gross_cents' => $total->grossCents,
|
||||
'net_cents' => $total->netCents,
|
||||
'vat_cents' => $total->vatCents,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->toEntity($model->load('vatTotals'));
|
||||
}
|
||||
|
||||
private function toEntity(CashDayModel $model): CashDay
|
||||
{
|
||||
$balance = $model->closed_at === null ? null : new CashDayBalance(
|
||||
$model->sale_count,
|
||||
$model->cash_cents,
|
||||
$model->card_cents,
|
||||
$model->vatTotals->map(fn (CashDayVatTotalModel $total): VatTotal => new VatTotal(
|
||||
$total->vat_basis_points,
|
||||
$total->gross_cents,
|
||||
$total->net_cents,
|
||||
$total->vat_cents,
|
||||
))->values()->all(),
|
||||
);
|
||||
|
||||
return CashDay::reconstitute(
|
||||
$model->id,
|
||||
new DateTimeImmutable($model->day),
|
||||
$balance,
|
||||
$model->closed_by,
|
||||
$model->closed_at === null ? null : DateTimeImmutable::createFromInterface($model->closed_at),
|
||||
$model->reopened_by,
|
||||
$model->reopened_at === null ? null : DateTimeImmutable::createFromInterface($model->reopened_at),
|
||||
);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleLineSummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\ValueObjects\CashDayBalance;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\CashDayModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class EloquentQuickSaleQueries implements QuickSaleQueries
|
||||
{
|
||||
public function __construct(
|
||||
private CashDayRepository $cashDays,
|
||||
private QuickSaleRepository $sales,
|
||||
private UserAccountQueries $users,
|
||||
private CustomerQueries $customers,
|
||||
) {}
|
||||
|
||||
public function salesOn(string $day, ?int $sellerId = null): array
|
||||
{
|
||||
$models = QuickSaleModel::query()
|
||||
->with(['lines', 'credit'])
|
||||
->where('sold_on', $day)
|
||||
->when($sellerId !== null, fn ($query) => $query->where('user_id', $sellerId))
|
||||
->orderByDesc('sold_at')
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
return $this->summaries($models);
|
||||
}
|
||||
|
||||
public function findSale(int $id): ?QuickSaleSummary
|
||||
{
|
||||
$model = QuickSaleModel::query()->with(['lines', 'credit'])->find($id);
|
||||
|
||||
return $model === null ? null : $this->summaries(collect([$model]))[0];
|
||||
}
|
||||
|
||||
public function cashDay(string $day): CashDaySummary
|
||||
{
|
||||
$date = new DateTimeImmutable($day);
|
||||
$cashDay = $this->cashDays->forDay($date);
|
||||
$names = $this->users->namesByIds(array_values(array_filter([$cashDay->closedBy(), $cashDay->reopenedBy()])));
|
||||
|
||||
return new CashDaySummary(
|
||||
day: $day,
|
||||
isClosed: $cashDay->isClosed(),
|
||||
balance: $cashDay->balance() ?? CashDayBalance::of($this->sales->forDay($date)),
|
||||
closedByName: $cashDay->closedBy() === null ? null : ($names[$cashDay->closedBy()] ?? ''),
|
||||
closedAt: $this->localTime($cashDay->closedAt()),
|
||||
reopenedByName: $cashDay->reopenedBy() === null ? null : ($names[$cashDay->reopenedBy()] ?? ''),
|
||||
reopenedAt: $this->localTime($cashDay->reopenedAt()),
|
||||
);
|
||||
}
|
||||
|
||||
public function unclosedDaysBefore(string $day): array
|
||||
{
|
||||
$closed = CashDayModel::query()->whereNotNull('closed_at')->select('day');
|
||||
|
||||
return QuickSaleModel::query()
|
||||
->where('sold_on', '<', $day)
|
||||
->whereNotIn('sold_on', $closed)
|
||||
->distinct()
|
||||
->orderBy('sold_on')
|
||||
->pluck('sold_on')
|
||||
->map(fn ($value): string => substr((string) $value, 0, 10))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, QuickSaleModel> $models
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
private function summaries(Collection $models): array
|
||||
{
|
||||
$sellerNames = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all());
|
||||
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->filter()->unique()->values()->all());
|
||||
|
||||
return $models->map(fn (QuickSaleModel $model): QuickSaleSummary => new QuickSaleSummary(
|
||||
id: $model->id,
|
||||
soldAt: (string) $this->localTime($model->sold_at),
|
||||
sellerId: $model->user_id,
|
||||
sellerName: $sellerNames[$model->user_id] ?? '',
|
||||
customerName: $model->customer_id === null ? null : ($customerNames[$model->customer_id] ?? ''),
|
||||
paymentMethod: $model->payment_method,
|
||||
totalCents: $model->total_cents,
|
||||
lines: $model->lines->map(fn (QuickSaleLineModel $line): QuickSaleLineSummary => new QuickSaleLineSummary(
|
||||
$line->product_name,
|
||||
$line->quantity,
|
||||
$line->unit_price_cents,
|
||||
$line->quantity * $line->unit_price_cents,
|
||||
$line->vat_basis_points,
|
||||
))->values()->all(),
|
||||
creditsSaleId: $model->credits_quick_sale_id,
|
||||
creditedBySaleId: $model->credit?->id,
|
||||
))->values()->all();
|
||||
}
|
||||
|
||||
private function localTime(?DateTimeInterface $moment): ?string
|
||||
{
|
||||
return $moment === null ? null : Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i');
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Domain\Entities\QuickSale;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentQuickSaleRepository implements QuickSaleRepository
|
||||
{
|
||||
public function findById(int $id): ?QuickSale
|
||||
{
|
||||
$model = QuickSaleModel::query()->with('lines')->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function add(QuickSale $sale): QuickSale
|
||||
{
|
||||
$model = QuickSaleModel::query()->create([
|
||||
'user_id' => $sale->sellerId(),
|
||||
'customer_id' => $sale->customerId(),
|
||||
'payment_method' => $sale->paymentMethod(),
|
||||
'sold_at' => $sale->soldAt()->format('Y-m-d H:i:s'),
|
||||
'sold_on' => $sale->soldOn()->format('Y-m-d'),
|
||||
'total_cents' => $sale->totalCents(),
|
||||
'credits_quick_sale_id' => $sale->creditsSaleId(),
|
||||
]);
|
||||
|
||||
foreach ($sale->lines() as $index => $line) {
|
||||
QuickSaleLineModel::query()->create([
|
||||
'quick_sale_id' => $model->id,
|
||||
'product_id' => $line->productId,
|
||||
'product_name' => $line->productName,
|
||||
'quantity' => $line->quantity,
|
||||
'unit_price_cents' => $line->unitPriceCents,
|
||||
'vat_basis_points' => $line->vatBasisPoints,
|
||||
'sort_order' => $index + 1,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->toEntity($model->load('lines'));
|
||||
}
|
||||
|
||||
public function isCredited(int $saleId): bool
|
||||
{
|
||||
return QuickSaleModel::query()->where('credits_quick_sale_id', $saleId)->exists();
|
||||
}
|
||||
|
||||
public function forDay(DateTimeImmutable $day): array
|
||||
{
|
||||
return QuickSaleModel::query()
|
||||
->with('lines')
|
||||
->where('sold_on', $day->format('Y-m-d'))
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (QuickSaleModel $model): QuickSale => $this->toEntity($model))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
private function toEntity(QuickSaleModel $model): QuickSale
|
||||
{
|
||||
return QuickSale::reconstitute(
|
||||
$model->id,
|
||||
$model->user_id,
|
||||
$model->customer_id,
|
||||
$model->payment_method,
|
||||
DateTimeImmutable::createFromInterface($model->sold_at),
|
||||
new DateTimeImmutable($model->sold_on),
|
||||
$model->lines->map(fn (QuickSaleLineModel $line): QuickSaleLine => new QuickSaleLine(
|
||||
$line->product_id,
|
||||
$line->product_name,
|
||||
$line->quantity,
|
||||
$line->unit_price_cents,
|
||||
$line->vat_basis_points,
|
||||
))->values()->all(),
|
||||
$model->credits_quick_sale_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure;
|
||||
|
||||
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
|
||||
use App\Modules\Catalog\Application\DTOs\ProductSummary;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
|
||||
/**
|
||||
* Sellable products from the Catalog module's price list: its active
|
||||
* consumer products, whose prices are stored with VAT.
|
||||
*/
|
||||
class ProductsFromPriceList implements QuickSaleProducts
|
||||
{
|
||||
public function __construct(private PriceListQueries $priceList) {}
|
||||
|
||||
public function sellable(): array
|
||||
{
|
||||
return array_map(fn (ProductSummary $product): SellableProduct => new SellableProduct(
|
||||
$product->id,
|
||||
$product->name,
|
||||
$product->unit->value,
|
||||
$product->grossCents,
|
||||
$product->vatBasisPoints,
|
||||
$product->durationQuarters,
|
||||
$product->workTypeId,
|
||||
), $this->priceList->consumerProducts());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
|
||||
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
|
||||
use App\Modules\Sales\Infrastructure\HoursForQuickSales;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries;
|
||||
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository;
|
||||
use App\Modules\Sales\Infrastructure\ProductsFromPriceList;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Livewire\Livewire;
|
||||
|
||||
/**
|
||||
* Wires the Sales module (quick sales at the counter and cash days) into
|
||||
* Laravel: bindings, routes, the `sales::` Livewire namespace and the
|
||||
* `sales.*` abilities.
|
||||
*/
|
||||
class SalesServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
public array $bindings = [
|
||||
QuickSaleRepository::class => EloquentQuickSaleRepository::class,
|
||||
CashDayRepository::class => EloquentCashDayRepository::class,
|
||||
QuickSaleQueries::class => EloquentQuickSaleQueries::class,
|
||||
QuickSaleProducts::class => ProductsFromPriceList::class,
|
||||
QuickSaleHours::class => HoursForQuickSales::class,
|
||||
];
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$presentationPath = dirname(__DIR__, 2).'/Presentation';
|
||||
|
||||
Livewire::addNamespace('sales', viewPath: $presentationPath.'/Livewire');
|
||||
$this->loadViewsFrom($presentationPath.'/Views', 'sales-views');
|
||||
|
||||
if (! $this->app->routesAreCached()) {
|
||||
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
|
||||
}
|
||||
|
||||
// Everyone but subcontractors sells at the counter and closes the cash day (spec 2, 7).
|
||||
Gate::define('sales.use', fn (User $user): bool => $user->role !== Role::Subcontractor);
|
||||
|
||||
Gate::define('sales.view-all', fn (User $user): bool => $user->role->seesAllMoney());
|
||||
|
||||
Gate::define('sales.view-sale', fn (User $user, int $sellerId): bool => $user->role->seesAllMoney()
|
||||
|| ($user->role !== Role::Subcontractor && $user->id === $sellerId));
|
||||
|
||||
Gate::define('sales.credit', fn (User $user, int $sellerId): bool => $user->role->seesAllMoney()
|
||||
|| ($user->role !== Role::Subcontractor && $user->id === $sellerId));
|
||||
|
||||
Gate::define('sales.close-day', fn (User $user): bool => $user->role !== Role::Subcontractor);
|
||||
|
||||
Gate::define('sales.reopen-day', fn (User $user): bool => $user->role->seesAllMoney());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The printable PDF receipt of a quick sale or credit, opened in the
|
||||
* browser: the company's details, the lines, the total and the VAT by
|
||||
* rate. Sellers open their own sales' receipts, management anyone's.
|
||||
*/
|
||||
class ShowReceipt
|
||||
{
|
||||
public function __invoke(int $sale, QuickSaleQueries $sales, CompanyDetailsStore $company): Response
|
||||
{
|
||||
$summary = $sales->findSale($sale) ?? abort(404);
|
||||
Gate::authorize('sales.view-sale', $summary->sellerId);
|
||||
|
||||
return Pdf::loadView('sales-views::receipt', [
|
||||
'sale' => $summary,
|
||||
'company' => $company->get(),
|
||||
])
|
||||
->setPaper('a5')
|
||||
->setOption('isFontSubsettingEnabled', true)
|
||||
->stream(__('sales.receipt.file', ['number' => $summary->id]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Sales\Presentation\Livewire\Concerns;
|
||||
|
||||
use App\Modules\Shared\Domain\ValueObjects\Money;
|
||||
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Formatting shared by the quick sale pages. Amounts of credits are
|
||||
* negative, which Money does not hold, so the sign is added here.
|
||||
*/
|
||||
trait FormatsSales
|
||||
{
|
||||
public function money(int $cents): string
|
||||
{
|
||||
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
|
||||
}
|
||||
|
||||
public function vatRate(int $basisPoints): string
|
||||
{
|
||||
return (new VatPercentage($basisPoints))->format();
|
||||
}
|
||||
|
||||
public function hours(int $quarters): string
|
||||
{
|
||||
return rtrim(rtrim(number_format($quarters / 4, 2, ',', ''), '0'), ',');
|
||||
}
|
||||
|
||||
/**
|
||||
* "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,479 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
|
||||
use App\Modules\Sales\Application\DTOs\CashDaySummary;
|
||||
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
|
||||
use App\Modules\Sales\Application\UseCases\CloseCashDay;
|
||||
use App\Modules\Sales\Application\UseCases\CreditQuickSale;
|
||||
use App\Modules\Sales\Application\UseCases\ReopenCashDay;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayInFuture;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound;
|
||||
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Attributes\Url;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A day's quick sales and its cash day (kassapäivä). Sellers see their own
|
||||
* sales, management everyone's. Anyone selling may close the day, which
|
||||
* forms its balance; management may reopen it. Sales are credited, never
|
||||
* deleted.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsSales;
|
||||
|
||||
/**
|
||||
* The day shown (Y-m-d). Read from the URL on mount and then changed
|
||||
* only by showDay(), so the browser cannot set it.
|
||||
*/
|
||||
#[Locked]
|
||||
#[Url(as: 'paiva', except: '')]
|
||||
public string $day = '';
|
||||
|
||||
/**
|
||||
* Management's seller filter: a user id, or empty for everyone.
|
||||
*/
|
||||
public string $seller = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $creditSaleId = null;
|
||||
|
||||
#[Locked]
|
||||
public string $statusMessage = '';
|
||||
|
||||
public function mount(Clock $clock): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$this->day = $this->parseDay($this->day)?->format('Y-m-d') ?? $clock->today()->format('Y-m-d');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<QuickSaleSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function sales(): array
|
||||
{
|
||||
$sellerId = Gate::allows('sales.view-all')
|
||||
? ($this->seller === '' ? null : (int) $this->seller)
|
||||
: (int) auth()->id();
|
||||
|
||||
return app(QuickSaleQueries::class)->salesOn($this->day, $sellerId);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function cashDay(): CashDaySummary
|
||||
{
|
||||
return app(QuickSaleQueries::class)->cashDay($this->day);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
#[Computed]
|
||||
public function unclosedDays(): array
|
||||
{
|
||||
return app(QuickSaleQueries::class)->unclosedDaysBefore(app(Clock::class)->today()->format('Y-m-d'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
#[Computed]
|
||||
public function sellers(): array
|
||||
{
|
||||
return Gate::allows('sales.view-all') ? app(UserAccountQueries::class)->activeUserOptions() : [];
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function isFuture(): bool
|
||||
{
|
||||
return $this->day > app(Clock::class)->today()->format('Y-m-d');
|
||||
}
|
||||
|
||||
public function updatedSeller(): void
|
||||
{
|
||||
$this->authorize('sales.view-all');
|
||||
unset($this->sales);
|
||||
}
|
||||
|
||||
public function showDay(string $which, Clock $clock): void
|
||||
{
|
||||
$current = $this->parseDay($this->day) ?? CarbonImmutable::instance($clock->today());
|
||||
|
||||
$this->day = match ($which) {
|
||||
'previous' => $current->subDay()->format('Y-m-d'),
|
||||
'next' => $current->addDay()->format('Y-m-d'),
|
||||
default => $clock->today()->format('Y-m-d'),
|
||||
};
|
||||
|
||||
$this->statusMessage = '';
|
||||
unset($this->sales, $this->cashDay);
|
||||
}
|
||||
|
||||
public function confirmCredit(int $saleId): void
|
||||
{
|
||||
$sale = app(QuickSaleQueries::class)->findSale($saleId) ?? abort(404);
|
||||
$this->authorize('sales.credit', $sale->sellerId);
|
||||
|
||||
$this->creditSaleId = $saleId;
|
||||
$this->js("document.getElementById('credit-dialog').showModal()");
|
||||
}
|
||||
|
||||
public function credit(CreditQuickSale $creditQuickSale, Clock $clock): void
|
||||
{
|
||||
$sale = app(QuickSaleQueries::class)->findSale((int) $this->creditSaleId) ?? abort(404);
|
||||
$this->authorize('sales.credit', $sale->sellerId);
|
||||
|
||||
try {
|
||||
$creditId = $creditQuickSale->execute($sale->id, (int) auth()->id());
|
||||
$this->statusMessage = __('sales.credited', ['number' => $sale->id, 'credit' => $creditId]);
|
||||
$this->day = $clock->today()->format('Y-m-d');
|
||||
} catch (QuickSaleNotFound) {
|
||||
$this->statusMessage = __('sales.errors.not_found');
|
||||
} catch (QuickSaleAlreadyCredited) {
|
||||
$this->statusMessage = __('sales.errors.already_credited');
|
||||
} catch (CreditCannotBeCredited) {
|
||||
$this->statusMessage = __('sales.errors.credit_of_credit');
|
||||
} catch (CashDayClosed) {
|
||||
$this->statusMessage = __('sales.errors.day_closed');
|
||||
}
|
||||
|
||||
$this->creditSaleId = null;
|
||||
unset($this->sales, $this->cashDay);
|
||||
$this->js("document.getElementById('credit-dialog').close(); document.getElementById('sales-status').focus()");
|
||||
}
|
||||
|
||||
public function confirmClose(): void
|
||||
{
|
||||
$this->authorize('sales.close-day');
|
||||
$this->js("document.getElementById('close-dialog').showModal()");
|
||||
}
|
||||
|
||||
public function closeDay(CloseCashDay $closeCashDay): void
|
||||
{
|
||||
$this->authorize('sales.close-day');
|
||||
|
||||
try {
|
||||
$closeCashDay->execute(new DateTimeImmutable($this->day), (int) auth()->id());
|
||||
$this->statusMessage = __('sales.cash_day.closed_message', ['day' => $this->dateLabel($this->day)]);
|
||||
} catch (CashDayClosed) {
|
||||
$this->statusMessage = __('sales.errors.day_closed');
|
||||
} catch (CashDayInFuture) {
|
||||
$this->statusMessage = __('sales.errors.future');
|
||||
}
|
||||
|
||||
unset($this->cashDay, $this->unclosedDays);
|
||||
$this->js("document.getElementById('close-dialog').close(); document.getElementById('sales-status').focus()");
|
||||
}
|
||||
|
||||
public function confirmReopen(): void
|
||||
{
|
||||
$this->authorize('sales.reopen-day');
|
||||
$this->js("document.getElementById('reopen-dialog').showModal()");
|
||||
}
|
||||
|
||||
public function reopenDay(ReopenCashDay $reopenCashDay): void
|
||||
{
|
||||
$this->authorize('sales.reopen-day');
|
||||
|
||||
try {
|
||||
$reopenCashDay->execute(new DateTimeImmutable($this->day), (int) auth()->id());
|
||||
$this->statusMessage = __('sales.cash_day.reopened_message', ['day' => $this->dateLabel($this->day)]);
|
||||
} catch (CashDayNotClosed) {
|
||||
$this->statusMessage = __('sales.errors.not_closed');
|
||||
}
|
||||
|
||||
unset($this->cashDay, $this->unclosedDays);
|
||||
$this->js("document.getElementById('reopen-dialog').close(); document.getElementById('sales-status').focus()");
|
||||
}
|
||||
|
||||
public function linesText(QuickSaleSummary $sale): string
|
||||
{
|
||||
return implode(', ', array_map(fn ($line): string => __('sales.line', [
|
||||
'quantity' => $line->quantity,
|
||||
'product' => $line->productName,
|
||||
'price' => $this->money($line->unitPriceCents),
|
||||
]), $sale->lines));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
|
||||
*/
|
||||
public function headers(): array
|
||||
{
|
||||
return [
|
||||
['index' => 'time', 'label' => __('sales.columns.time'), 'sortable' => false],
|
||||
['index' => 'number', 'label' => __('sales.columns.number'), 'sortable' => false],
|
||||
['index' => 'seller', 'label' => __('sales.columns.seller'), 'sortable' => false],
|
||||
['index' => 'customer', 'label' => __('sales.columns.customer'), 'sortable' => false],
|
||||
['index' => 'products', 'label' => __('sales.columns.products'), 'sortable' => false],
|
||||
['index' => 'method', 'label' => __('sales.columns.payment_method'), 'sortable' => false],
|
||||
['index' => 'total', 'label' => __('sales.columns.total'), 'sortable' => false, 'align' => 'right'],
|
||||
['index' => 'actions', 'label' => __('sales.columns.actions'), 'sortable' => false],
|
||||
];
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('sales.index.title'));
|
||||
}
|
||||
|
||||
private function parseDay(string $day): ?CarbonImmutable
|
||||
{
|
||||
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $day) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $day);
|
||||
|
||||
return $date !== null && $date->format('Y-m-d') === $day ? $date : null;
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<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">{{ __('sales.index.title') }}</h1>
|
||||
<p>
|
||||
<x-button :href="route('sales.sell')" wire:navigate icon="plus" :text="__('sales.index.new_sale')" />
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<nav aria-label="{{ __('sales.index.day_navigation') }}" class="flex flex-wrap items-center gap-2">
|
||||
<x-button wire:click="showDay('previous')" subtle color="black" sm icon="chevron-left" :text="__('sales.index.previous')" />
|
||||
<x-button wire:click="showDay('today')" subtle color="black" sm :text="__('sales.index.today')" />
|
||||
<x-button wire:click="showDay('next')" subtle color="black" sm icon="chevron-right" position="right" :text="__('sales.index.next')" />
|
||||
</nav>
|
||||
|
||||
<p id="sales-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $statusMessage }}</p>
|
||||
|
||||
@if ($this->unclosedDays !== [])
|
||||
<div class="rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
|
||||
<p class="flex items-start gap-2">
|
||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ __('sales.index.unclosed') }}
|
||||
</p>
|
||||
<ul class="mt-2 flex flex-wrap gap-x-4 gap-y-1">
|
||||
@foreach ($this->unclosedDays as $unclosed)
|
||||
<li><x-link :href="route('sales.index', ['paiva' => $unclosed])" navigate>{{ $this->dateLabel($unclosed) }}</x-link></li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<h2 class="text-xl font-semibold" aria-live="polite">{{ $this->dateLabel($day) }}</h2>
|
||||
|
||||
<section aria-labelledby="cash-day-heading" class="space-y-3">
|
||||
<h3 id="cash-day-heading" class="text-lg font-semibold">{{ __('sales.cash_day.title') }}</h3>
|
||||
|
||||
@php($cashDay = $this->cashDay)
|
||||
|
||||
@if ($cashDay->isClosed)
|
||||
<p class="flex items-center gap-2 text-sm">
|
||||
<x-icon name="lock-closed" class="size-5" aria-hidden="true" />
|
||||
{{ __('sales.cash_day.closed', ['at' => $this->dateLabel((string) $cashDay->closedAt), 'name' => $cashDay->closedByName]) }}
|
||||
</p>
|
||||
@else
|
||||
<p class="text-sm">{{ __('sales.cash_day.open') }}</p>
|
||||
@endif
|
||||
|
||||
@if ($cashDay->reopenedAt !== null)
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.cash_day.reopened', ['at' => $this->dateLabel($cashDay->reopenedAt), 'name' => $cashDay->reopenedByName]) }}</p>
|
||||
@endif
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<table class="w-full text-sm">
|
||||
<caption class="mb-2 text-left font-semibold">{{ $cashDay->isClosed ? __('sales.cash_day.balance') : __('sales.cash_day.preview') }}</caption>
|
||||
<thead class="sr-only">
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.cash_day.item') }}</th>
|
||||
<th scope="col">{{ __('sales.cash_day.amount') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.sale_count') }}</th>
|
||||
<td class="py-1 text-right">{{ $cashDay->balance->saleCount }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.cash') }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($cashDay->balance->cashCents) }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ __('sales.cash_day.card') }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($cashDay->balance->cardCents) }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row" class="py-1 text-left font-semibold">{{ __('sales.cash_day.total') }}</th>
|
||||
<td class="py-1 text-right font-semibold whitespace-nowrap">{{ $this->money($cashDay->balance->totalCents()) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@if ($cashDay->balance->vatTotals !== [])
|
||||
<table class="w-full text-sm">
|
||||
<caption class="mb-2 text-left font-semibold">{{ __('sales.cash_day.vat_breakdown') }}</caption>
|
||||
<thead>
|
||||
<tr class="text-left">
|
||||
<th scope="col" class="py-1">{{ __('sales.cash_day.vat_rate') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.gross') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.net') }}</th>
|
||||
<th scope="col" class="py-1 text-right">{{ __('sales.cash_day.vat') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
@foreach ($cashDay->balance->vatTotals as $vatTotal)
|
||||
<tr wire:key="vat-{{ $vatTotal->vatBasisPoints }}">
|
||||
<th scope="row" class="py-1 text-left font-normal">{{ $this->vatRate($vatTotal->vatBasisPoints) }}</th>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->grossCents) }}</td>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->netCents) }}</td>
|
||||
<td class="py-1 text-right whitespace-nowrap">{{ $this->money($vatTotal->vatCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
@if (! $cashDay->isClosed && ! $this->isFuture)
|
||||
@can('sales.close-day')
|
||||
<x-button wire:click="confirmClose" icon="lock-closed" :text="__('sales.cash_day.close')" />
|
||||
@endcan
|
||||
@elseif ($cashDay->isClosed)
|
||||
@can('sales.reopen-day')
|
||||
<x-button wire:click="confirmReopen" subtle color="black" icon="lock-open" :text="__('sales.cash_day.reopen')" />
|
||||
@endcan
|
||||
@endif
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="sales-heading" class="space-y-3">
|
||||
<h3 id="sales-heading" class="text-lg font-semibold">{{ __('sales.index.sales') }}</h3>
|
||||
|
||||
@can('sales.view-all')
|
||||
<div class="max-w-xs">
|
||||
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
|
||||
<x-select.native wire:model.live="seller" :label="__('sales.index.seller')" :aria-label="__('sales.index.seller')">
|
||||
<option value="">{{ __('sales.index.all_sellers') }}</option>
|
||||
@foreach ($this->sellers as $option)
|
||||
<option value="{{ $option->id }}">{{ $option->name }}</option>
|
||||
@endforeach
|
||||
</x-select.native>
|
||||
</div>
|
||||
@else
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.index.own_only') }}</p>
|
||||
@endcan
|
||||
|
||||
@if ($this->sales === [])
|
||||
<p class="text-sm">{{ __('sales.index.none') }}</p>
|
||||
@else
|
||||
<x-table :headers="$this->headers()" :rows="$this->sales">
|
||||
@interact('column_time', $sale)
|
||||
<span class="whitespace-nowrap">{{ substr($sale->soldAt, 11) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_number', $sale)
|
||||
<span class="whitespace-nowrap">#{{ $sale->id }}</span>
|
||||
@if ($sale->isCredit())
|
||||
<span class="block text-xs">{{ __('sales.credit_of', ['number' => $sale->creditsSaleId]) }}</span>
|
||||
@elseif ($sale->creditedBySaleId !== null)
|
||||
<span class="block text-xs">{{ __('sales.credited_by', ['number' => $sale->creditedBySaleId]) }}</span>
|
||||
@endif
|
||||
@endinteract
|
||||
|
||||
@interact('column_seller', $sale)
|
||||
{{ $sale->sellerName }}
|
||||
@endinteract
|
||||
|
||||
@interact('column_customer', $sale)
|
||||
<span class="whitespace-normal">{{ $sale->customerName ?? __('sales.anonymous') }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_products', $sale)
|
||||
<span class="block whitespace-normal">{{ $this->linesText($sale) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_method', $sale)
|
||||
{{ __('sales.payment_methods.'.$sale->paymentMethod->value) }}
|
||||
@endinteract
|
||||
|
||||
@interact('column_total', $sale)
|
||||
<span class="whitespace-nowrap">{{ $this->money($sale->totalCents) }}</span>
|
||||
@endinteract
|
||||
|
||||
@interact('column_actions', $sale)
|
||||
<a
|
||||
href="{{ route('sales.receipt', $sale->id) }}"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="mr-2 inline-flex items-center gap-1 text-sm font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700"
|
||||
aria-label="{{ __('sales.receipt.open_named', ['number' => $sale->id]) }}"
|
||||
>
|
||||
<x-icon name="document-text" class="size-4" aria-hidden="true" />
|
||||
{{ __('sales.receipt_link') }}
|
||||
</a>
|
||||
@if ($sale->canBeCredited())
|
||||
@can('sales.credit', $sale->sellerId)
|
||||
<x-button
|
||||
wire:click="confirmCredit({{ $sale->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
icon="arrow-uturn-left"
|
||||
:text="__('sales.credit')"
|
||||
:aria-label="__('sales.credit_named', ['number' => $sale->id])"
|
||||
/>
|
||||
@endcan
|
||||
@endif
|
||||
@endinteract
|
||||
</x-table>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<x-confirm-dialog id="credit-dialog" :title="__('sales.credit_title')">
|
||||
@php($creditSale = $creditSaleId === null ? null : collect($this->sales)->firstWhere('id', $creditSaleId))
|
||||
@if ($creditSale !== null)
|
||||
<p>{{ __('sales.credit_text', ['number' => $creditSale->id, 'total' => $this->money($creditSale->totalCents), 'method' => __('sales.payment_methods.'.$creditSale->paymentMethod->value)]) }}</p>
|
||||
@endif
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="credit" color="red" :text="__('sales.credit_confirm')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
|
||||
<x-confirm-dialog id="close-dialog" :title="__('sales.cash_day.close_title')">
|
||||
<p>{{ __('sales.cash_day.close_text') }}</p>
|
||||
<p class="mt-2 font-medium">
|
||||
{{ __('sales.cash_day.total') }}: {{ $this->money($cashDay->balance->totalCents()) }}
|
||||
({{ __('sales.cash_day.cash') }} {{ $this->money($cashDay->balance->cashCents) }},
|
||||
{{ __('sales.cash_day.card') }} {{ $this->money($cashDay->balance->cardCents) }})
|
||||
</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="closeDay" :text="__('sales.cash_day.close')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
|
||||
@can('sales.reopen-day')
|
||||
<x-confirm-dialog id="reopen-dialog" :title="__('sales.cash_day.reopen_title')">
|
||||
<p>{{ __('sales.cash_day.reopen_text') }}</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button wire:click="reopenDay" :text="__('sales.cash_day.reopen')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
@endcan
|
||||
</div>
|
||||
@@ -0,0 +1,432 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Application\DTOs\CustomerSummary;
|
||||
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
|
||||
use App\Modules\Sales\Application\DTOs\SaleData;
|
||||
use App\Modules\Sales\Application\DTOs\SellableProduct;
|
||||
use App\Modules\Sales\Application\UseCases\SellQuickSale;
|
||||
use App\Modules\Sales\Domain\Enums\PaymentMethod;
|
||||
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
|
||||
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
|
||||
use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
|
||||
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
|
||||
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
|
||||
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* A quick sale at the counter (pikamyynti), made for phones: each press of
|
||||
* a product button adds one to the sale's list, where quantities can be
|
||||
* lowered, raised or removed; then the payment method and an optional
|
||||
* customer. After saving, the form empties for the next customer and the
|
||||
* result is announced with a link to the PDF receipt. Prices are consumer
|
||||
* prices with VAT, which everyone may see.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use FormatsSales;
|
||||
|
||||
/**
|
||||
* Quantities on the sale by product id, in the order added. Changed only
|
||||
* by the add, decrease and remove actions.
|
||||
*
|
||||
* @var array<int, int>
|
||||
*/
|
||||
#[Locked]
|
||||
public array $quantities = [];
|
||||
|
||||
public string $paymentMethod = 'cash';
|
||||
|
||||
public string $customerSearch = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $customerId = null;
|
||||
|
||||
#[Locked]
|
||||
public string $customerName = '';
|
||||
|
||||
#[Locked]
|
||||
public string $cartMessage = '';
|
||||
|
||||
#[Locked]
|
||||
public ?int $savedSaleId = null;
|
||||
|
||||
#[Locked]
|
||||
public string $savedMessage = '';
|
||||
|
||||
#[Locked]
|
||||
public string $hoursMessage = '';
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, SellableProduct> By product id, in price list order.
|
||||
*/
|
||||
#[Computed]
|
||||
public function products(): array
|
||||
{
|
||||
$products = [];
|
||||
|
||||
foreach (app(QuickSaleProducts::class)->sellable() as $product) {
|
||||
$products[$product->id] = $product;
|
||||
}
|
||||
|
||||
return $products;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sale's lines with their products, in the order added.
|
||||
*
|
||||
* @return list<array{product: SellableProduct, quantity: int}>
|
||||
*/
|
||||
#[Computed]
|
||||
public function lines(): array
|
||||
{
|
||||
$lines = [];
|
||||
|
||||
foreach ($this->quantities as $productId => $quantity) {
|
||||
if (isset($this->products[$productId])) {
|
||||
$lines[] = ['product' => $this->products[$productId], 'quantity' => $quantity];
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function totalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (array $line): int => $line['quantity'] * $line['product']->grossCents, $this->lines));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<CustomerSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function customerResults(): array
|
||||
{
|
||||
$term = trim($this->customerSearch);
|
||||
|
||||
return mb_strlen($term) < 2 ? [] : app(CustomerQueries::class)->search($term, 8);
|
||||
}
|
||||
|
||||
public function addProduct(int $productId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
if (! isset($this->products[$productId])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->quantities[$productId] = min(QuickSaleLine::MAX_QUANTITY, ($this->quantities[$productId] ?? 0) + 1);
|
||||
$this->changed($productId);
|
||||
}
|
||||
|
||||
public function decreaseProduct(int $productId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
if (! isset($this->quantities[$productId])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->quantities[$productId] <= 1) {
|
||||
$this->removeProduct($productId);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->quantities[$productId]--;
|
||||
$this->changed($productId);
|
||||
}
|
||||
|
||||
public function removeProduct(int $productId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$name = $this->products[$productId]->name ?? '';
|
||||
unset($this->quantities[$productId]);
|
||||
$this->forgetLines();
|
||||
|
||||
$this->cartMessage = __('sales.sell.removed', ['product' => $name, 'total' => $this->money($this->totalCents)]);
|
||||
$this->js("document.getElementById('cart-heading')?.focus()");
|
||||
}
|
||||
|
||||
public function selectCustomer(int $customerId): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
|
||||
$customer = app(CustomerQueries::class)->findSummary($customerId);
|
||||
|
||||
if ($customer !== null) {
|
||||
$this->customerId = $customer->id;
|
||||
$this->customerName = $customer->name;
|
||||
$this->customerSearch = '';
|
||||
$this->js("document.getElementById('change-customer')?.focus()");
|
||||
}
|
||||
}
|
||||
|
||||
public function clearCustomer(): void
|
||||
{
|
||||
$this->customerId = null;
|
||||
$this->customerName = '';
|
||||
$this->js("document.getElementById('customer-search')?.focus()");
|
||||
}
|
||||
|
||||
public function save(SellQuickSale $sellQuickSale): void
|
||||
{
|
||||
$this->authorize('sales.use');
|
||||
$this->savedMessage = '';
|
||||
$this->hoursMessage = '';
|
||||
$this->savedSaleId = null;
|
||||
|
||||
$this->validate(['paymentMethod' => ['required', Rule::enum(PaymentMethod::class)]]);
|
||||
|
||||
try {
|
||||
$result = $sellQuickSale->execute((int) auth()->id(), new SaleData($this->quantities, $this->paymentMethod, $this->customerId));
|
||||
} catch (QuickSaleEmpty) {
|
||||
$this->addError('quantities', __('sales.errors.empty'));
|
||||
|
||||
return;
|
||||
} catch (InvalidQuantity) {
|
||||
$this->addError('quantities', __('sales.errors.quantity'));
|
||||
|
||||
return;
|
||||
} catch (ProductNotSellable $exception) {
|
||||
unset($this->quantities[$exception->id], $this->products);
|
||||
$this->forgetLines();
|
||||
$this->addError('quantities', __('sales.errors.product'));
|
||||
|
||||
return;
|
||||
} catch (QuickSaleCustomerNotFound) {
|
||||
$this->addError('customerSearch', __('sales.errors.customer'));
|
||||
$this->clearCustomer();
|
||||
|
||||
return;
|
||||
} catch (CashDayClosed) {
|
||||
$this->addError('sale', __('sales.errors.day_closed'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->savedSaleId = $result->saleId;
|
||||
$this->savedMessage = __('sales.sell.saved', [
|
||||
'number' => $result->saleId,
|
||||
'total' => $this->money($result->totalCents),
|
||||
'method' => __('sales.payment_methods.'.$this->paymentMethod),
|
||||
]);
|
||||
|
||||
$this->hoursMessage = trim(
|
||||
($result->bookedQuarters > 0 ? __('sales.sell.hours_booked', ['hours' => $this->hours($result->bookedQuarters)]) : '')
|
||||
.' '.($result->unbookedQuarters > 0 ? __('sales.sell.hours_not_booked', ['hours' => $this->hours($result->unbookedQuarters)]) : ''),
|
||||
);
|
||||
|
||||
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage');
|
||||
$this->forgetLines();
|
||||
|
||||
$this->js("document.getElementById('sale-saved')?.focus()");
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('sales.sell.title'));
|
||||
}
|
||||
|
||||
private function changed(int $productId): void
|
||||
{
|
||||
$this->forgetLines();
|
||||
$this->resetErrorBag('quantities');
|
||||
|
||||
$this->cartMessage = __('sales.sell.changed', [
|
||||
'product' => $this->products[$productId]->name,
|
||||
'quantity' => $this->quantities[$productId],
|
||||
'total' => $this->money($this->totalCents),
|
||||
]);
|
||||
}
|
||||
|
||||
private function forgetLines(): void
|
||||
{
|
||||
unset($this->lines, $this->totalCents);
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-lg space-y-6 p-4 sm:p-6">
|
||||
<div class="space-y-1">
|
||||
<h1 class="text-2xl font-semibold">{{ __('sales.sell.title') }}</h1>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.intro') }}</p>
|
||||
<p class="text-sm">
|
||||
<x-link :href="route('sales.index')" navigate>{{ __('sales.sell.to_list') }}</x-link>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div id="sale-saved" tabindex="-1" role="status" aria-live="polite" class="focus:outline-none">
|
||||
@if ($savedMessage !== '')
|
||||
<div class="space-y-2 rounded-lg border border-green-700 bg-green-50 p-4 text-sm text-green-900 dark:border-green-500 dark:bg-green-950 dark:text-green-100">
|
||||
<p class="flex items-start gap-2 font-medium">
|
||||
<x-icon name="check-circle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ $savedMessage }}
|
||||
</p>
|
||||
@if ($hoursMessage !== '')
|
||||
<p>{{ $hoursMessage }}</p>
|
||||
@endif
|
||||
@if ($savedSaleId !== null)
|
||||
<p>
|
||||
<a
|
||||
href="{{ route('sales.receipt', $savedSaleId) }}"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="inline-flex items-center gap-1 font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700"
|
||||
>
|
||||
<x-icon name="document-text" class="size-5" aria-hidden="true" />
|
||||
{{ __('sales.receipt.open', ['number' => $savedSaleId]) }}
|
||||
</a>
|
||||
</p>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
@error('sale')
|
||||
<p role="alert" class="flex items-start gap-2 rounded-lg border border-red-700 p-4 text-sm text-red-700 dark:border-red-400 dark:text-red-400">
|
||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||
{{ $message }}
|
||||
</p>
|
||||
@enderror
|
||||
|
||||
@if ($this->products === [])
|
||||
<p class="text-sm">{{ __('sales.sell.no_products') }}</p>
|
||||
@else
|
||||
<section aria-labelledby="products-heading" class="space-y-3">
|
||||
<h2 id="products-heading" class="text-lg font-semibold">{{ __('sales.sell.products') }}</h2>
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.products_help') }}</p>
|
||||
|
||||
<ul class="grid grid-cols-2 gap-2">
|
||||
@foreach ($this->products as $product)
|
||||
<li wire:key="product-{{ $product->id }}">
|
||||
<button
|
||||
type="button"
|
||||
wire:click="addProduct({{ $product->id }})"
|
||||
class="flex h-full min-h-16 w-full flex-col items-start justify-center rounded-lg border border-zinc-400 bg-white px-3 py-2 text-left hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800 dark:hover:bg-zinc-700"
|
||||
aria-label="{{ __('sales.sell.add_named', ['product' => $product->name, 'price' => $this->money($product->grossCents), 'unit' => __('catalog.units.'.$product->unit)]) }}"
|
||||
>
|
||||
<span class="font-medium break-words">{{ $product->name }}</span>
|
||||
<span class="text-sm text-zinc-700 dark:text-zinc-300">{{ $this->money($product->grossCents) }} / {{ __('catalog.units.'.$product->unit) }}</span>
|
||||
</button>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section aria-labelledby="cart-heading" class="space-y-3">
|
||||
<h2 id="cart-heading" tabindex="-1" class="text-lg font-semibold focus:outline-none">{{ __('sales.sell.cart') }}</h2>
|
||||
|
||||
<p role="status" aria-live="polite" class="sr-only">{{ $cartMessage }}</p>
|
||||
|
||||
@error('quantities')
|
||||
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
|
||||
@if ($this->lines === [])
|
||||
<p class="text-sm">{{ __('sales.sell.cart_empty') }}</p>
|
||||
@else
|
||||
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||
@foreach ($this->lines as $line)
|
||||
@php($product = $line['product'])
|
||||
<li wire:key="line-{{ $product->id }}" class="flex flex-wrap items-center gap-x-3 gap-y-2 py-2">
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="font-medium break-words">{{ $product->name }}</p>
|
||||
<p class="text-sm text-zinc-700 dark:text-zinc-300">
|
||||
{{ __('sales.sell.line', ['quantity' => $line['quantity'], 'price' => $this->money($product->grossCents), 'total' => $this->money($line['quantity'] * $product->grossCents)]) }}
|
||||
</p>
|
||||
@if ($product->durationQuarters > 0 && $product->workTypeId !== null)
|
||||
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('sales.sell.line_hours', ['hours' => $this->hours($product->durationQuarters * $line['quantity'])]) }}</p>
|
||||
@endif
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<x-button wire:click="decreaseProduct({{ $product->id }})" subtle color="black" sm icon="minus" :aria-label="__('sales.sell.decrease_named', ['product' => $product->name])" />
|
||||
<span class="min-w-8 text-center font-medium" aria-hidden="true">{{ $line['quantity'] }}</span>
|
||||
<x-button wire:click="addProduct({{ $product->id }})" subtle color="black" sm icon="plus" :aria-label="__('sales.sell.increase_named', ['product' => $product->name])" />
|
||||
<x-button wire:click="removeProduct({{ $product->id }})" subtle color="black" sm icon="trash" :aria-label="__('sales.sell.remove_named', ['product' => $product->name])" />
|
||||
</div>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
|
||||
<p class="text-lg font-semibold">
|
||||
{{ __('sales.sell.total', ['total' => $this->money($this->totalCents)]) }}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
<x-radio.group
|
||||
wire:model="paymentMethod"
|
||||
:label="__('sales.sell.payment_method')"
|
||||
:options="[
|
||||
['label' => __('sales.payment_methods.cash'), 'value' => PaymentMethod::Cash->value],
|
||||
['label' => __('sales.payment_methods.card'), 'value' => PaymentMethod::Card->value],
|
||||
]"
|
||||
/>
|
||||
|
||||
<div class="space-y-2">
|
||||
@if ($customerId !== null)
|
||||
<p class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ __('sales.sell.customer') }}</p>
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<span class="font-medium break-words">{{ $customerName }}</span>
|
||||
<x-button
|
||||
id="change-customer"
|
||||
wire:click="clearCustomer"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
:text="__('sales.sell.change_customer')"
|
||||
:aria-label="__('sales.sell.change_customer').': '.$customerName"
|
||||
/>
|
||||
</div>
|
||||
@else
|
||||
<x-input
|
||||
id="customer-search"
|
||||
wire:model.live.debounce.300ms="customerSearch"
|
||||
type="search"
|
||||
icon="magnifying-glass"
|
||||
:label="__('sales.sell.customer')"
|
||||
:hint="__('sales.sell.customer_search_description')"
|
||||
autocomplete="off"
|
||||
/>
|
||||
|
||||
@if (mb_strlen(trim($customerSearch)) >= 2)
|
||||
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
|
||||
{{ trans_choice('sales.sell.customer_results', count($this->customerResults), ['count' => count($this->customerResults)]) }}
|
||||
</p>
|
||||
|
||||
<ul class="space-y-1">
|
||||
@foreach ($this->customerResults as $customer)
|
||||
<li wire:key="customer-result-{{ $customer->id }}">
|
||||
<button
|
||||
type="button"
|
||||
wire:click="selectCustomer({{ $customer->id }})"
|
||||
class="w-full rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
|
||||
aria-label="{{ __('sales.sell.choose_customer', ['name' => $customer->name]) }}"
|
||||
>
|
||||
<span class="font-medium">{{ $customer->name }}</span>
|
||||
</button>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<x-button submit lg class="w-full" :text="__('sales.sell.save')" />
|
||||
</form>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Sales\Presentation\Http\Controllers\ShowReceipt;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:sales.use'])
|
||||
->prefix('sales')
|
||||
->name('sales.')
|
||||
->group(function () {
|
||||
Route::livewire('/', 'sales::index')->name('index');
|
||||
Route::livewire('/new', 'sales::sell')->name('sell');
|
||||
Route::get('/{sale}/receipt', ShowReceipt::class)->whereNumber('sale')->name('receipt');
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
{{--
|
||||
PDF receipt of a quick sale, rendered by dompdf (no Tailwind or
|
||||
JavaScript; DejaVu Sans has the € sign and Finnish letters). Amounts of
|
||||
a credit are negative.
|
||||
--}}
|
||||
@use('App\Modules\Shared\Domain\ValueObjects\Money')
|
||||
@use('App\Modules\Shared\Domain\ValueObjects\VatPercentage')
|
||||
@use('Carbon\CarbonImmutable')
|
||||
@php
|
||||
$money = fn (int $cents): string => ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
|
||||
$title = $sale->isCredit() ? __('sales.receipt.credit_title') : __('sales.receipt.title');
|
||||
@endphp
|
||||
<!DOCTYPE html>
|
||||
<html lang="fi">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>{{ $title }} {{ $sale->id }}</title>
|
||||
<style>
|
||||
@page { margin: 14mm 12mm; }
|
||||
body { font-family: "DejaVu Sans", sans-serif; font-size: 9.5pt; color: #000; }
|
||||
h1 { font-size: 14pt; margin: 0 0 2mm; }
|
||||
h2 { font-size: 10.5pt; margin: 5mm 0 1.5mm; }
|
||||
p { margin: 0 0 1mm; }
|
||||
.company { margin-bottom: 5mm; }
|
||||
.company .name { font-size: 12pt; font-weight: bold; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { padding: 1.2mm 1mm; vertical-align: top; }
|
||||
thead th { border-bottom: 0.6pt solid #000; text-align: left; }
|
||||
.num { text-align: right; white-space: nowrap; }
|
||||
.meta th { text-align: left; font-weight: normal; width: 35%; }
|
||||
.total td, .total th { border-top: 0.6pt solid #000; font-weight: bold; font-size: 11pt; }
|
||||
.footer { margin-top: 8mm; text-align: center; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="company">
|
||||
@if ($company !== null)
|
||||
<p class="name">{{ $company->name }}</p>
|
||||
@if ($company->address !== null)
|
||||
<p>{!! nl2br(e($company->address)) !!}</p>
|
||||
@endif
|
||||
@if ($company->phone !== null)
|
||||
<p>{{ $company->phone }}</p>
|
||||
@endif
|
||||
@if ($company->email !== null)
|
||||
<p>{{ $company->email }}</p>
|
||||
@endif
|
||||
<p>{{ __('sales.receipt.business_id') }}: {{ $company->businessId }} {{ __('sales.receipt.vat_number') }}: {{ $company->vatNumber() }}</p>
|
||||
@else
|
||||
<p>{{ __('sales.receipt.company_missing') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<h1>{{ $title }}</h1>
|
||||
|
||||
<table class="meta">
|
||||
<tr><th scope="row">{{ __('sales.receipt.number') }}</th><td>{{ $sale->id }}</td></tr>
|
||||
<tr><th scope="row">{{ __('sales.receipt.date') }}</th><td>{{ CarbonImmutable::createFromFormat('Y-m-d H:i', $sale->soldAt)->format('j.n.Y H.i') }}</td></tr>
|
||||
<tr><th scope="row">{{ __('sales.receipt.seller') }}</th><td>{{ $sale->sellerName }}</td></tr>
|
||||
@if ($sale->customerName !== null)
|
||||
<tr><th scope="row">{{ __('sales.receipt.customer') }}</th><td>{{ $sale->customerName }}</td></tr>
|
||||
@endif
|
||||
<tr><th scope="row">{{ __('sales.receipt.payment_method') }}</th><td>{{ __('sales.payment_methods.'.$sale->paymentMethod->value) }}</td></tr>
|
||||
@if ($sale->isCredit())
|
||||
<tr><th scope="row"></th><td>{{ __('sales.receipt.credits', ['number' => $sale->creditsSaleId]) }}</td></tr>
|
||||
@endif
|
||||
</table>
|
||||
|
||||
<table style="margin-top: 5mm;">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.receipt.product') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.quantity') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.unit_price') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.vat_rate') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.line_total') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($sale->lines as $line)
|
||||
<tr>
|
||||
<td>{{ $line->productName }}</td>
|
||||
<td class="num">{{ $line->quantity }}</td>
|
||||
<td class="num">{{ $money($line->unitPriceCents) }}</td>
|
||||
<td class="num">{{ (new VatPercentage($line->vatBasisPoints))->format() }}</td>
|
||||
<td class="num">{{ $money($line->totalCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
<tr class="total">
|
||||
<th scope="row" colspan="4" style="text-align: left;">{{ __('sales.receipt.total') }}</th>
|
||||
<td class="num">{{ $money($sale->totalCents) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<h2>{{ __('sales.receipt.vat_heading') }}</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ __('sales.receipt.vat_rate') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.net') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.vat') }}</th>
|
||||
<th scope="col" class="num">{{ __('sales.receipt.gross') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($sale->vatTotals() as $vatTotal)
|
||||
<tr>
|
||||
<td>{{ (new VatPercentage($vatTotal->vatBasisPoints))->format() }}</td>
|
||||
<td class="num">{{ $money($vatTotal->netCents) }}</td>
|
||||
<td class="num">{{ $money($vatTotal->vatCents) }}</td>
|
||||
<td class="num">{{ $money($vatTotal->grossCents) }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p class="footer">{{ __('sales.receipt.thanks') }}</p>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user