Files
Toiminnanohjaus/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php
T
petriandClaude Opus 5.5 6de5d9bef1 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]>
2026-11-24 12:33:46 +02:00

433 lines
18 KiB
PHP

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