Files
2026-11-26 17:11:54 +02:00

562 lines
24 KiB
PHP

<?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\Application\UseCases\ResendQuickSaleReceipt;
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\Shared\Domain\Exceptions\InvalidEmailAddress;
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. An emailed receipt's state is shown on its row, and a receipt
* can be emailed again, to a corrected address if need be.
*/
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 = '';
#[Locked]
public ?int $resendSaleId = null;
public string $resendEmail = '';
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 confirmResend(int $saleId): void
{
$sale = app(QuickSaleQueries::class)->findSale($saleId) ?? abort(404);
$this->authorize('sales.view-sale', $sale->sellerId);
$this->resendSaleId = $saleId;
$this->resendEmail = $sale->receiptEmail ?? '';
$this->resetErrorBag('resendEmail');
$this->js("document.getElementById('resend-dialog').showModal()");
}
public function resend(ResendQuickSaleReceipt $resendQuickSaleReceipt): void
{
$sale = app(QuickSaleQueries::class)->findSale((int) $this->resendSaleId) ?? abort(404);
$this->authorize('sales.view-sale', $sale->sellerId);
$this->validate(
['resendEmail' => ['required', 'string', 'email', 'max:255']],
attributes: ['resendEmail' => __('sales.sell.receipt_email')],
);
try {
$resendQuickSaleReceipt->execute($sale->id, $this->resendEmail);
} catch (InvalidEmailAddress) {
$this->addError('resendEmail', __('sales.errors.receipt_email'));
return;
}
$this->statusMessage = __('sales.receipt_mail.resent', ['number' => $sale->id, 'email' => mb_strtolower(trim($this->resendEmail))]);
$this->resendSaleId = null;
$this->resendEmail = '';
unset($this->sales);
$this->js("document.getElementById('resend-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->receiptStatus() !== null)
<span class="mr-2 inline-flex items-center gap-1 text-xs">
@if ($sale->receiptStatus() === 'failed')
<x-icon name="exclamation-triangle" class="size-4 text-red-700 dark:text-red-400" aria-hidden="true" />
@elseif ($sale->receiptStatus() === 'sent')
<x-icon name="envelope" class="size-4" aria-hidden="true" />
@else
<x-icon name="clock" class="size-4" aria-hidden="true" />
@endif
{{ __('sales.receipt_mail.status_'.$sale->receiptStatus()) }}
</span>
@endif
@can('sales.view-sale', $sale->sellerId)
<x-button
wire:click="confirmResend({{ $sale->id }})"
subtle
color="black"
sm
icon="envelope"
:text="__('sales.receipt_mail.send')"
:aria-label="__('sales.receipt_mail.send_named', ['number' => $sale->id])"
/>
@endcan
@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="resend-dialog" :title="__('sales.receipt_mail.send_title')">
@if ($resendSaleId !== null)
<p class="mb-3">{{ __('sales.receipt_mail.send_text', ['number' => $resendSaleId]) }}</p>
@endif
<x-input id="resend-email" wire:model="resendEmail" type="email" inputmode="email" autocomplete="off" :label="__('sales.sell.receipt_email')" />
<x-slot:actions>
<x-button wire:click="resend" icon="envelope" :text="__('sales.receipt_mail.send_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>
@php($unpaidOrders = app(\App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries::class)->unpaidCount())
@if ($unpaidOrders > 0)
<p class="mt-2">{{ trans_choice('sales.orders.unpaid', $unpaidOrders, ['count' => $unpaidOrders]) }}</p>
@endif
<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>