Files
petriandClaude Sonnet 5.5 701f05780f Change a quick sale order before making starts
An unpaid order whose lines have no completed step can be reopened in the
cart from the open orders list; saving replaces its lines with current
prices and processes, moves the machine work list rows and keeps the
pickup number. Keyboard browser tests cover changing and cancelling an
order and moving production steps.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:11:36 +02:00

701 lines
29 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\Contracts\ProductionProcesses;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound;
use App\Modules\Sales\Application\DTOs\OrderData;
use App\Modules\Sales\Application\DTOs\SaleData;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use App\Modules\Sales\Domain\Exceptions\OrderHasNoProduction;
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 App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
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, an optional
* customer and an optional address the PDF receipt is emailed to. 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, set and remove actions.
*
* @var array<int, int>
*/
#[Locked]
public array $quantities = [];
public string $paymentMethod = 'cash';
public string $customerSearch = '';
public string $receiptEmail = '';
#[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 = '';
#[Locked]
public ?int $savedPickupNumber = null;
public string $orderCustomerName = '';
/**
* The open order being changed on this form, if any (spec 19.7).
*/
#[Locked]
public ?int $editingOrderId = null;
#[Locked]
public ?int $editingPickupNumber = null;
/**
* Loads an order whose making has not started into the form to change
* its products and customer.
*/
#[On('edit-quick-sale-order')]
public function editOrder(int $orderId): void
{
$this->authorize('sales.use');
$order = app(QuickSaleOrderQueries::class)->findOrder($orderId) ?? abort(404);
if (! $order->canBeChanged) {
$this->addError('sale', __('sales.orders.errors.started'));
return;
}
$this->reset('quantities', 'cartMessage', 'savedMessage', 'hoursMessage', 'savedSaleId', 'savedPickupNumber');
foreach ($order->lines as $line) {
$this->quantities[$line->productId] = $line->quantity;
}
$this->editingOrderId = $order->id;
$this->editingPickupNumber = $order->pickupNumber;
$this->customerId = $order->customerId;
$this->customerName = $order->customerId === null ? '' : (string) $order->customerName;
$this->orderCustomerName = $order->customerId === null ? (string) $order->customerName : '';
$this->resetErrorBag();
$this->forgetLines();
$this->cartMessage = __('sales.orders.editing', ['number' => $order->pickupNumber]);
$this->js("document.getElementById('cart-heading')?.focus()");
}
public function stopEditing(): void
{
$this->reset('quantities', 'customerSearch', 'customerId', 'customerName', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
$this->forgetLines();
$this->cartMessage = __('sales.orders.editing_stopped');
$this->js("document.getElementById('cart-heading')?.focus()");
}
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);
}
/**
* Sets a line's quantity typed in its field: 0 removes the line, and an
* invalid value keeps the old quantity with an error.
*/
public function setQuantity(int $productId, string $value): void
{
$this->authorize('sales.use');
if (! isset($this->quantities[$productId])) {
return;
}
$value = trim($value);
if (preg_match('/^\d{1,3}$/', $value) !== 1) {
$this->addError('quantities', __('sales.errors.quantity'));
$this->showQuantity($productId, $this->quantities[$productId]);
return;
}
$quantity = (int) $value;
if ($quantity === 0) {
$this->removeProduct($productId);
return;
}
$this->quantities[$productId] = min(QuickSaleLine::MAX_QUANTITY, $quantity);
$this->changed($productId);
$this->showQuantity($productId, $this->quantities[$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 = '';
if (trim($this->receiptEmail) === '') {
$this->receiptEmail = $this->customerEmail($customer->id) ?? '';
}
$this->js("document.getElementById('change-customer')?.focus()");
}
}
public function clearCustomer(): void
{
$this->customerId = null;
$this->customerName = '';
$this->js("document.getElementById('customer-search')?.focus()");
}
/**
* Products with a production process: an order of any of them is made
* before it is paid (spec 19.7).
*
* @return list<int>
*/
#[Computed]
public function madeProductIds(): array
{
return array_keys(app(ProductionProcesses::class)->stepsOf(array_keys($this->products)));
}
public function isOrder(): bool
{
return array_intersect(array_keys($this->quantities), $this->madeProductIds) !== [];
}
public function save(SellQuickSale $sellQuickSale, QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$this->savedMessage = '';
$this->hoursMessage = '';
$this->savedSaleId = null;
$this->savedPickupNumber = null;
if ($this->isOrder() || $this->editingOrderId !== null) {
$this->sendOrder($orders);
return;
}
$this->validate([
'paymentMethod' => ['required', Rule::enum(PaymentMethod::class)],
'receiptEmail' => ['nullable', 'string', 'email', 'max:255'],
], attributes: ['receiptEmail' => __('sales.sell.receipt_email')]);
try {
$result = $sellQuickSale->execute((int) auth()->id(), new SaleData($this->quantities, $this->paymentMethod, $this->customerId, trim($this->receiptEmail) === '' ? null : $this->receiptEmail));
} 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;
} catch (InvalidEmailAddress) {
$this->addError('receiptEmail', __('sales.errors.receipt_email'));
return;
}
$this->savedSaleId = $result->saleId;
$this->savedMessage = __('sales.sell.saved', [
'number' => $result->saleId,
'total' => $this->money($result->totalCents),
'method' => __('sales.payment_methods.'.$this->paymentMethod),
]);
if ($result->receiptEmail !== null) {
$this->savedMessage .= ' '.__('sales.sell.receipt_queued', ['email' => $result->receiptEmail]);
}
$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', 'receiptEmail');
$this->forgetLines();
$this->js("document.getElementById('sale-saved')?.focus()");
}
public function render(): mixed
{
return $this->view()->title(__('sales.sell.title'));
}
/**
* Sends the sale to production as an order with the day's pickup number;
* it is paid on the open orders list once made (or in advance).
*/
private function sendOrder(QuickSaleOrders $orders): void
{
$this->validate(['orderCustomerName' => ['nullable', 'string', 'max:150']]);
$data = new OrderData($this->quantities, $this->customerId, $this->orderCustomerName);
try {
$result = $this->editingOrderId === null
? $orders->send((int) auth()->id(), $data)
: $orders->change($this->editingOrderId, $data);
} catch (QuickSaleEmpty|InvalidQuantity) {
$this->addError('quantities', __('sales.errors.empty'));
return;
} catch (OrderHasNoProduction) {
$this->addError('quantities', __($this->editingOrderId === null ? 'sales.errors.empty' : 'sales.orders.errors.no_production'));
return;
} catch (QuickSaleOrderInProduction|QuickSaleOrderClosed|QuickSaleOrderNotFound) {
$this->addError('sale', __('sales.orders.errors.started'));
$this->stopEditing();
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;
}
$this->savedPickupNumber = $result->pickupNumber;
$this->savedMessage = __($this->editingOrderId === null ? 'sales.orders.sent' : 'sales.orders.changed', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]);
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
$this->forgetLines();
$this->dispatch('quick-sale-orders-changed');
$this->js("document.getElementById('sale-saved')?.focus()");
}
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),
]);
}
/**
* Puts the saved quantity back in the field, which is not bound to a
* property and so keeps what was typed (e.g. "03" or an invalid value).
*/
private function showQuantity(int $productId, int $quantity): void
{
$this->js("const field = document.getElementById('quantity-{$productId}'); if (field) { field.value = '{$quantity}'; }");
}
/**
* The first email address among the customer's contacts, to prefill
* the receipt address.
*/
private function customerEmail(int $customerId): ?string
{
foreach (app(CustomerQueries::class)->contactsOf($customerId) as $contact) {
if ($contact->email !== null && $contact->email !== '') {
return $contact->email;
}
}
return null;
}
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 ($savedPickupNumber !== null)
<p class="text-4xl font-bold" aria-hidden="true">{{ $savedPickupNumber }}</p>
@endif
@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>
@if (in_array($product->id, $this->madeProductIds, true))
<span class="inline-flex items-center gap-1 text-xs">
<x-icon name="printer" class="size-4" aria-hidden="true" />
{{ __('sales.orders.made') }}
</span>
@endif
</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])" />
<label for="quantity-{{ $product->id }}" class="text-sm">{{ __('sales.sell.quantity') }}</label>
<input
id="quantity-{{ $product->id }}"
type="text"
inputmode="numeric"
pattern="[0-9]*"
maxlength="3"
autocomplete="off"
value="{{ $line['quantity'] }}"
wire:change="setQuantity({{ $product->id }}, $event.target.value)"
wire:keydown.enter.prevent="setQuantity({{ $product->id }}, $event.target.value)"
aria-label="{{ __('sales.sell.quantity_named', ['product' => $product->name]) }}"
class="h-9 w-14 rounded-md border border-zinc-500 bg-white px-2 text-center font-medium text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100"
/>
<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>
@php($isOrder = $this->isOrder() || $editingOrderId !== null)
<form wire:submit="save" class="space-y-6" novalidate>
@if ($editingOrderId !== null)
<div class="flex flex-wrap items-center gap-3 rounded-lg border border-zinc-400 p-3 text-sm dark:border-zinc-500">
<x-icon name="pencil" class="size-5 shrink-0" aria-hidden="true" />
<p class="grow">{{ __('sales.orders.editing_notice', ['number' => $editingPickupNumber]) }}</p>
<x-button id="stop-editing" wire:click="stopEditing" subtle color="black" sm :text="__('sales.orders.stop_editing')" />
</div>
@endif
@if ($isOrder)
<p class="flex items-start gap-2 rounded-lg border border-zinc-400 p-3 text-sm dark:border-zinc-500">
<x-icon name="printer" class="size-5 shrink-0" aria-hidden="true" />
{{ __('sales.orders.order_note') }}
</p>
<x-input id="order-customer-name" wire:model="orderCustomerName" :label="__('sales.orders.customer_name')" :hint="__('sales.orders.customer_name_hint')" autocomplete="off" maxlength="150" />
@else
<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],
]"
/>
@endif
<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>
@unless ($isOrder)
<x-input
wire:model="receiptEmail"
type="email"
inputmode="email"
autocomplete="off"
:label="__('sales.sell.receipt_email')"
:hint="__('sales.sell.receipt_email_hint')"
/>
@endunless
<x-button submit lg class="w-full" :text="$editingOrderId !== null ? __('sales.orders.save_change') : ($isOrder ? __('sales.orders.send') : __('sales.sell.save'))" />
</form>
@endif
<livewire:sales::orders />
</div>