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,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>