*/ #[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 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 */ #[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 */ #[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 */ #[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); } }; ?>
{{ __('sales.sell.title') }}

{{ __('sales.sell.intro') }}

{{ __('sales.sell.to_list') }}

@if ($savedMessage !== '')

@if ($savedPickupNumber !== null) @endif @if ($hoursMessage !== '')

{{ $hoursMessage }}

@endif @if ($savedSaleId !== null)

@endif
@endif
@error('sale') @enderror @if ($this->products === []) {{ __('sales.sell.no_products') }} @else

{{ __('sales.sell.products') }}

{{ __('sales.sell.products_help') }}

    @foreach ($this->products as $product)
  • @endforeach

{{ __('sales.sell.cart') }}

{{ $cartMessage }}

@error('quantities') @enderror @if ($this->lines === [])

{{ __('sales.sell.cart_empty') }}

@else
    @foreach ($this->lines as $line) @php($product = $line['product'])
  • {{ $product->name }}

    {{ __('sales.sell.line', ['quantity' => $line['quantity'], 'price' => $this->money($product->grossCents), 'total' => $this->money($line['quantity'] * $product->grossCents)]) }}

    @if ($product->durationQuarters > 0 && $product->workTypeId !== null)

    {{ __('sales.sell.line_hours', ['hours' => $this->hours($product->durationQuarters * $line['quantity'])]) }}

    @endif
  • @endforeach
@endif

{{ __('sales.sell.total', ['total' => $this->money($this->totalCents)]) }}

@php($isOrder = $this->isOrder() || $editingOrderId !== null)
@if ($editingOrderId !== null)
@endif @if ($isOrder)

@else @endif
@if ($customerId !== null)

{{ __('sales.sell.customer') }}

{{ $customerName }}
@else @if (mb_strlen(trim($customerSearch)) >= 2)

{{ trans_choice('sales.sell.customer_results', count($this->customerResults), ['count' => count($this->customerResults)]) }}

    @foreach ($this->customerResults as $customer)
  • @endforeach
@endif @endif
@unless ($isOrder) @endunless @endif