Files
Toiminnanohjaus/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php
T
petriandClaude Opus 5.5 f4b58f6b1d Darken the dark canvas, add customer colours, the ongoing status and the board model
- Dark theme page background is #5a5e60; text on it is lifted to zinc-200 /
  primary-100 and TallStackUI's dark labels, hints and checkbox labels are
  lightened so everything stays at 4.5:1.
- Shared HexColor picks white or black text by the higher WCAG contrast; a
  native-dialog colour picker and a large work dialog component.
- Customers get a header colour (customers.header_color), set on the
  customer page.
- New job status Jatkuvat / Kausi (ongoing): open, never late, billed
  monthly like running jobs.
- Kanban model: board columns and views, urgent threshold, per-user board
  preferences (density, column colours and sort), card positions, tasks of
  continuing jobs pinned to the board, MoveBoardCard and board queries with
  logged hours from TimeTracking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 06:11:49 +02:00

438 lines
19 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\DTOs\OrderSummary;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use App\Modules\Sales\Domain\Enums\PaymentMethod;
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;
/**
* Open quick sale orders on the quick sale page (spec 19.7): pickup numbers
* with their state (being made, at which step and machine, or ready to be
* paid). A step can be completed here too (by hand, or a machine's step
* when working on one device), the order paid (an ordinary quick sale with
* a receipt) or cancelled while unpaid. The list refreshes itself and has
* a Refresh button; an order becoming ready is announced.
*/
new class extends Component
{
use FormatsSales;
#[Locked]
public ?int $completingLineId = null;
/**
* Used material per stock item while completing a step.
*
* @var array<int, string>
*/
public array $used = [];
#[Locked]
public ?int $payingOrderId = null;
public string $paymentMethod = 'cash';
public string $receiptEmail = '';
#[Locked]
public ?int $cancelOrderId = null;
/**
* Orders already seen as ready, to announce newly ready ones.
*
* @var list<int>
*/
#[Locked]
public array $knownReady = [];
#[Locked]
public string $message = '';
#[Locked]
public ?int $paidSaleId = null;
public function mount(): void
{
$this->authorize('sales.use');
$this->knownReady = $this->readyIds();
}
/**
* @return list<OrderSummary>
*/
#[Computed]
public function orders(): array
{
return app(QuickSaleOrderQueries::class)->openOrders();
}
/**
* @return array<int, string>
*/
#[Computed]
public function machineNames(): array
{
$names = [];
foreach (app(MachineQueries::class)->machines(includeInactive: true) as $machine) {
$names[$machine->id] = $machine->name;
}
return $names;
}
#[On('quick-sale-orders-changed')]
public function reloadOrders(): void
{
unset($this->orders);
$this->knownReady = array_values(array_unique([...$this->knownReady, ...$this->readyIds()]));
}
public function refreshList(): void
{
$this->authorize('sales.use');
unset($this->orders);
$ready = $this->readyIds();
$new = array_diff($ready, $this->knownReady);
if ($new !== []) {
$numbers = array_map(fn (OrderSummary $order): int => $order->pickupNumber, array_filter($this->orders, fn (OrderSummary $order): bool => in_array($order->id, $new, true)));
$this->message = trans_choice('sales.orders.became_ready', count($numbers), ['numbers' => implode(', ', $numbers)]);
}
$this->knownReady = array_values(array_unique([...$this->knownReady, ...$ready]));
}
public function refresh(Clock $clock): void
{
$this->refreshList();
if ($this->message === '') {
$this->message = __('sales.orders.refreshed', ['time' => $clock->now()->setTimezone(new DateTimeZone((string) config('app.business_timezone')))->format('H.i')]);
}
}
public function startComplete(int $lineId): void
{
$this->authorize('sales.use');
$line = $this->line($lineId);
$this->completingLineId = $lineId;
$this->used = [];
foreach ($line->currentMaterials as $material) {
$this->used[$material['stockItemId']] = StockQuantity::inputValue($material['quantityMilli'] * $line->quantity);
}
$this->js("setTimeout(() => document.getElementById('complete-line-{$lineId}')?.focus())");
}
public function complete(QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$line = $this->line((int) $this->completingLineId);
$usedMilli = [];
foreach ($this->used as $itemId => $value) {
try {
$usedMilli[(int) $itemId] = StockQuantity::parse($value)?->milli ?? 0;
} catch (DomainException) {
$this->addError('used.'.$itemId, __('inventory.errors.quantity'));
return;
}
}
try {
$made = $orders->completeStep($line->id, (int) $line->currentStep, (int) auth()->id(), $usedMilli);
} catch (DomainException) {
$this->message = __('sales.orders.errors.step');
$this->completingLineId = null;
unset($this->orders);
return;
}
$this->message = $made
? __('sales.orders.line_made', ['number' => $line->pickupNumber, 'product' => $line->productName])
: __('sales.orders.step_done', ['number' => $line->pickupNumber, 'product' => $line->productName]);
$this->completingLineId = null;
$this->reloadOrders();
$this->js("document.getElementById('orders-status')?.focus()");
}
public function startPay(int $orderId): void
{
$this->authorize('sales.use');
$order = $this->order($orderId);
$this->payingOrderId = $order->id;
$this->paymentMethod = 'cash';
$this->receiptEmail = '';
$this->resetErrorBag();
$this->js("setTimeout(() => document.getElementById('pay-order-{$orderId}')?.focus())");
}
public function pay(QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$order = $this->order((int) $this->payingOrderId);
$this->validate([
'paymentMethod' => ['required', Rule::enum(PaymentMethod::class)],
'receiptEmail' => ['nullable', 'string', 'email', 'max:255'],
], attributes: ['receiptEmail' => __('sales.sell.receipt_email')]);
try {
$result = $orders->pay($order->id, (int) auth()->id(), $this->paymentMethod, $this->receiptEmail);
} catch (InvalidEmailAddress) {
$this->addError('receiptEmail', __('sales.errors.receipt_email'));
return;
} catch (CashDayClosed) {
$this->addError('paymentMethod', __('sales.errors.day_closed'));
return;
} catch (DomainException) {
$this->message = __('sales.orders.errors.closed');
$this->payingOrderId = null;
unset($this->orders);
return;
}
$this->paidSaleId = $result->saleId;
$this->message = __('sales.orders.paid', ['number' => $order->pickupNumber, 'total' => $this->money($result->totalCents), 'method' => __('sales.payment_methods.'.$this->paymentMethod)])
.($result->receiptEmail === null ? '' : ' '.__('sales.sell.receipt_queued', ['email' => $result->receiptEmail]));
$this->payingOrderId = null;
unset($this->orders);
$this->js("document.getElementById('orders-status')?.focus()");
}
public function edit(int $orderId): void
{
$this->authorize('sales.use');
$this->dispatch('edit-quick-sale-order', orderId: $this->order($orderId)->id);
}
public function confirmCancel(int $orderId): void
{
$this->authorize('sales.use');
$this->cancelOrderId = $this->order($orderId)->id;
$this->js("document.getElementById('cancel-order-dialog').showModal()");
}
public function cancel(QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$order = $this->order((int) $this->cancelOrderId);
try {
$orders->cancel($order->id, (int) auth()->id());
$this->message = __('sales.orders.cancelled', ['number' => $order->pickupNumber]);
} catch (DomainException) {
$this->message = __('sales.orders.errors.closed');
}
$this->cancelOrderId = null;
unset($this->orders);
$this->js("document.getElementById('cancel-order-dialog').close(); document.getElementById('orders-status').focus()");
}
/**
* @return array<int, StockItemSummary>
*/
public function itemsOf(OrderLineSummary $line): array
{
return app(StockQueries::class)->itemsByIds(array_map(fn (array $material): int => $material['stockItemId'], $line->currentMaterials));
}
public function lineState(OrderLineSummary $line): string
{
if ($line->isMade) {
return __('sales.orders.line_ready');
}
if (! $line->hasProduction()) {
return __('sales.orders.line_no_production');
}
$machineId = $line->currentMachineId();
return __('sales.orders.line_step', [
'step' => (int) $line->currentStep + 1,
'steps' => count($line->stepMachineIds),
'where' => $machineId === null ? __('sales.orders.by_hand') : ($this->machineNames[$machineId] ?? ''),
]);
}
/**
* @return list<int>
*/
private function readyIds(): array
{
return array_values(array_map(
fn (OrderSummary $order): int => $order->id,
array_filter($this->orders, fn (OrderSummary $order): bool => $order->status->value === 'ready'),
));
}
private function order(int $orderId): OrderSummary
{
return collect($this->orders)->firstWhere('id', $orderId) ?? abort(404);
}
private function line(int $lineId): OrderLineSummary
{
foreach ($this->orders as $order) {
foreach ($order->lines as $line) {
if ($line->id === $lineId) {
return $line;
}
}
}
abort(404);
}
};
?>
<section wire:poll.30s="refreshList" aria-labelledby="orders-heading" class="space-y-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="orders-heading" class="text-lg font-semibold">{{ __('sales.orders.title') }}</h2>
<x-button wire:click="refresh" subtle color="black" sm icon="arrow-path" :text="__('sales.orders.refresh')" />
</div>
<div id="orders-status" tabindex="-1" role="status" aria-live="polite" class="space-y-1 text-sm font-medium focus:outline-none">
<p>{{ $message }}</p>
@if ($paidSaleId !== null)
<p>
<a href="{{ route('sales.receipt', $paidSaleId) }}" target="_blank" rel="noopener" class="inline-flex items-center gap-1 underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="document-text" class="size-5" aria-hidden="true" />
{{ __('sales.receipt.open', ['number' => $paidSaleId]) }}
</a>
</p>
@endif
</div>
@if ($this->orders === [])
<x-empty-state icon="shopping-cart">{{ __('sales.orders.none') }}</x-empty-state>
@else
<ul class="space-y-3">
@foreach ($this->orders as $order)
<li wire:key="order-{{ $order->id }}" class="space-y-2 rounded-lg border border-zinc-300 bg-white p-3 dark:border-zinc-600 dark:bg-zinc-900">
<div class="flex flex-wrap items-start justify-between gap-2">
<div>
<h3 class="text-3xl font-bold">{{ __('sales.orders.pickup', ['number' => $order->pickupNumber]) }}</h3>
<p class="text-sm">
{{ $order->customerName ?? __('sales.anonymous') }} · {{ $this->dateLabel($order->orderedAt) }} · {{ $this->money($order->totalCents) }}
</p>
</div>
<p class="flex items-center gap-1 text-sm font-semibold">
<x-icon :name="$order->status->value === 'ready' ? 'check-circle' : 'cog-6-tooth'" class="size-5" aria-hidden="true" />
{{ __('sales.orders.statuses.'.$order->status->value) }}@if ($order->isPaid()), {{ __('sales.orders.is_paid') }}@endif
</p>
</div>
<ul class="space-y-2 text-sm">
@foreach ($order->lines as $line)
<li wire:key="order-line-{{ $line->id }}" class="space-y-1">
<p><span class="font-medium">{{ $line->quantity }} × {{ $line->productName }}</span> · {{ $this->lineState($line) }}</p>
@if (! $line->isMade && $line->hasProduction())
@if ($completingLineId === $line->id)
<form wire:submit="complete" class="space-y-2 rounded-md border border-zinc-300 p-2 dark:border-zinc-600" novalidate>
<p id="complete-line-{{ $line->id }}" tabindex="-1" class="font-medium focus:outline-none">{{ __('sales.orders.complete_title', ['product' => $line->productName]) }}</p>
@php($items = $this->itemsOf($line))
@foreach ($line->currentMaterials as $material)
@php($item = $items[$material['stockItemId']] ?? null)
<div class="w-48">
<x-input
id="used-{{ $line->id }}-{{ $material['stockItemId'] }}"
wire:model="used.{{ $material['stockItemId'] }}"
inputmode="decimal"
:label="($item->name ?? '').' ('.__('inventory.units.'.($item->unit->value ?? 'piece')).')'"
autocomplete="off"
/>
</div>
@endforeach
<p class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('sales.orders.complete_hint') }}</p>
<div class="flex flex-wrap gap-2">
<x-button submit sm icon="check" :text="__('sales.orders.complete')" />
<x-button wire:click="$set('completingLineId', null)" subtle color="black" sm :text="__('layout.cancel')" />
</div>
</form>
@else
<div class="flex flex-wrap gap-2">
<x-button wire:click="startComplete({{ $line->id }})" subtle color="black" sm icon="check" :text="__('sales.orders.complete_step')" :aria-label="__('sales.orders.complete_step_named', ['number' => $order->pickupNumber, 'product' => $line->productName])" />
@if ($line->currentMachineId() !== null)
<x-link :href="route('console.handoff', ['to' => route('machines.console', $line->currentMachineId())])" blank class="text-sm">{{ __('sales.orders.open_console', ['machine' => $this->machineNames[$line->currentMachineId()] ?? '']) }}<span class="sr-only"> ({{ __('layout.opens_in_new_window') }})</span></x-link>
@endif
</div>
@endif
@endif
</li>
@endforeach
</ul>
@unless ($order->isPaid())
@if ($payingOrderId === $order->id)
<form wire:submit="pay" class="space-y-3 rounded-md border border-zinc-300 p-2 dark:border-zinc-600" novalidate>
<p id="pay-order-{{ $order->id }}" tabindex="-1" class="font-medium focus:outline-none">{{ __('sales.orders.pay_title', ['number' => $order->pickupNumber, 'total' => $this->money($order->totalCents)]) }}</p>
<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],
]"
/>
<x-input wire:model="receiptEmail" type="email" inputmode="email" autocomplete="off" :label="__('sales.sell.receipt_email')" />
<div class="flex flex-wrap gap-2">
<x-button submit icon="banknotes" :text="__('sales.orders.take_payment')" />
<x-button wire:click="$set('payingOrderId', null)" subtle color="black" :text="__('layout.cancel')" />
</div>
</form>
@else
<div class="flex flex-wrap gap-2">
<x-button wire:click="startPay({{ $order->id }})" sm icon="banknotes" :text="__('sales.orders.pay')" :aria-label="__('sales.orders.pay_named', ['number' => $order->pickupNumber])" />
@if ($order->canBeChanged)
<x-button wire:click="edit({{ $order->id }})" subtle color="black" sm icon="pencil" :text="__('sales.orders.change')" :aria-label="__('sales.orders.change_named', ['number' => $order->pickupNumber])" />
@endif
<x-button wire:click="confirmCancel({{ $order->id }})" subtle color="black" sm icon="x-mark" :text="__('sales.orders.cancel')" :aria-label="__('sales.orders.cancel_named', ['number' => $order->pickupNumber])" />
</div>
@endif
@endunless
</li>
@endforeach
</ul>
@endif
<x-confirm-dialog id="cancel-order-dialog" :title="__('sales.orders.cancel_title')">
<p>{{ __('sales.orders.cancel_text') }}</p>
<x-slot:actions>
<x-button wire:click="cancel" color="red" :text="__('sales.orders.cancel')" />
</x-slot:actions>
</x-confirm-dialog>
</section>