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:
2026-11-24 12:33:46 +02:00
co-authored by Claude Opus 5.5
parent c149c56388
commit 6de5d9bef1
101 changed files with 4768 additions and 29 deletions
@@ -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',
];
}
}
@@ -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),
);
}
}
@@ -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');
}
}
@@ -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,
);
}
}