Make quick sale products on machines as orders paid when ready

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 17:11:54 +02:00
co-authored by Claude Sonnet 5.5
parent 920fecdeb2
commit 38b8075a9c
58 changed files with 3435 additions and 26 deletions
@@ -18,6 +18,9 @@ use App\Modules\Machines\Application\DTOs\QueueRow;
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
use App\Modules\Machines\Application\UseCases\MachineWorkList;
use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\Users\Application\Contracts\Clock;
@@ -97,6 +100,18 @@ new #[Layout('layouts.console')] class extends Component
#[Locked]
public string $refreshMessage = '';
#[Locked]
public ?int $completingEntryId = null;
/**
* Material used per stock item while completing an order's step.
*
* @var array<int, string>
*/
public array $orderUsed = [];
public string $moveToMachineId = '';
public function mount(int $machine): void
{
$this->authorize('machines.use');
@@ -131,6 +146,109 @@ new #[Layout('layouts.console')] class extends Component
return app(MachineQueries::class)->rowsOn($this->machineId, $this->day(), $this->today);
}
/**
* The quick sale order lines on the list, by line id.
*
* @return array<int, OrderLineSummary>
*/
#[Computed]
public function orderLines(): array
{
$ids = array_values(array_filter(array_map(fn (QueueRow $row): ?int => $row->orderLineId, $this->rows)));
return app(QuickSaleOrderQueries::class)->lines($ids);
}
/**
* Machines of the same type to move an order's step to.
*
* @return list<MachineSummary>
*/
#[Computed]
public function sameTypeMachines(): array
{
return array_values(array_filter(
app(MachineQueries::class)->machines(),
fn (MachineSummary $machine): bool => $machine->type === $this->machine->type && $machine->id !== $this->machineId,
));
}
public function startOrderComplete(int $entryId): void
{
$this->authorize('sales.use');
$row = $this->row($entryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
$this->completingEntryId = $entryId;
$this->orderUsed = [];
foreach ($line->currentMaterials as $material) {
$this->orderUsed[$material['stockItemId']] = StockQuantity::inputValue($material['quantityMilli'] * $line->quantity);
}
$this->js("setTimeout(() => document.getElementById('order-complete-{$entryId}')?.focus())");
}
public function changeOrderUsed(int $itemId, int $step): void
{
$current = StockQuantity::parse($this->orderUsed[$itemId] ?? '0')?->milli ?? 0;
$this->orderUsed[$itemId] = StockQuantity::inputValue(max(0, $current + $step * 1000));
}
public function completeOrder(QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$row = $this->row((int) $this->completingEntryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
$used = [];
foreach ($this->orderUsed as $itemId => $value) {
try {
$used[(int) $itemId] = StockQuantity::parse($value)?->milli ?? 0;
} catch (DomainException) {
$this->addError('orderUsed.'.$itemId, __('inventory.errors.quantity'));
return;
}
}
try {
$orders->completeStep($line->id, (int) $row->stepPosition, (int) auth()->id(), $used);
} catch (DomainException) {
$this->message = __('sales.orders.errors.step');
$this->completingEntryId = null;
$this->reload();
return;
}
$this->message = __('machines.console.order_done', ['number' => $line->pickupNumber, 'product' => $line->productName]);
$this->completingEntryId = null;
$this->reload();
$this->js("document.getElementById('console-status')?.focus()");
}
public function moveOrder(int $entryId, MachineWorkList $workList): void
{
$this->authorize('machines.use');
$row = $this->row($entryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
try {
$workList->moveOrderLine($entryId, (int) $this->moveToMachineId);
} catch (DomainException) {
$this->addError('moveToMachineId', __('machines.errors.machine'));
return;
}
$this->message = __('machines.console.order_moved', ['number' => $line->pickupNumber, 'machine' => app(MachineQueries::class)->findMachine((int) $this->moveToMachineId)->name ?? '']);
$this->moveToMachineId = '';
$this->reload();
}
#[Computed]
public function selectedRow(): ?QueueRow
{
@@ -455,7 +573,7 @@ new #[Layout('layouts.console')] class extends Component
*/
private function reload(): int
{
unset($this->rows, $this->maintenance, $this->items, $this->selectedRow, $this->machine);
unset($this->rows, $this->maintenance, $this->items, $this->selectedRow, $this->machine, $this->orderLines);
$ids = array_map(fn (QueueRow $row): int => $row->entryId, $this->rows);
$new = count(array_diff($ids, $this->knownEntryIds));
@@ -544,7 +662,61 @@ new #[Layout('layouts.console')] class extends Component
<p class="text-base font-semibold">{{ __('machines.console.next') }}</p>
@endif
@if ($row->isOrder())
<p class="font-semibold">{{ __('machines.show.order') }}</p>
@php($line = $this->orderLines[$row->orderLineId] ?? null)
<p class="flex items-center gap-2 font-semibold">
<x-icon name="user" class="size-5" aria-hidden="true" />
{{ __('machines.show.order') }}
</p>
@if ($line !== null)
<p class="text-4xl font-bold">{{ __('sales.orders.pickup', ['number' => $line->pickupNumber]) }}</p>
<p class="text-xl font-semibold">{{ $line->quantity }} × {{ $line->productName }}</p>
<p class="text-base">
{{ $line->customerName ?? __('sales.anonymous') }} · {{ __('machines.console.ordered_at', ['time' => substr($line->orderedAt, 11)]) }}
@if (count($line->stepMachineIds) > 1)
· {{ __('machines.console.order_step', ['step' => (int) $row->stepPosition + 1, 'steps' => count($line->stepMachineIds)]) }}
@endif
</p>
@if (! $nextDay)
@if ($completingEntryId === $row->entryId)
@php($items = app(\App\Modules\Inventory\Application\Contracts\StockQueries::class)->itemsByIds(array_map(fn ($material) => $material['stockItemId'], $line->currentMaterials)))
<form wire:submit="completeOrder" class="space-y-3 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600" novalidate>
<p id="order-complete-{{ $row->entryId }}" tabindex="-1" class="font-semibold focus:outline-none">{{ __('machines.console.order_materials') }}</p>
@foreach ($line->currentMaterials as $material)
@php($item = $items[$material['stockItemId']] ?? null)
<div wire:key="order-material-{{ $material['stockItemId'] }}" class="flex flex-wrap items-end gap-2">
<button type="button" wire:click="changeOrderUsed({{ $material['stockItemId'] }}, -1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.less_of', ['item' => $item->name ?? '']) }}">−</button>
<div class="w-40">
<x-input id="order-used-{{ $material['stockItemId'] }}" wire:model="orderUsed.{{ $material['stockItemId'] }}" inputmode="decimal" :label="($item->name ?? '').' ('.__('inventory.units.'.($item->unit->value ?? 'piece')).')'" autocomplete="off" />
</div>
<button type="button" wire:click="changeOrderUsed({{ $material['stockItemId'] }}, 1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.more_of', ['item' => $item->name ?? '']) }}">+</button>
</div>
@endforeach
<p class="text-base">{{ __('sales.orders.complete_hint') }}</p>
<button type="submit" class="{{ $primary }} w-full text-xl">{{ __('machines.console.confirm_order') }}</button>
</form>
@else
<div class="flex flex-wrap items-end gap-2">
<button type="button" wire:click="startOrderComplete({{ $row->entryId }})" class="{{ $primary }} text-xl" aria-label="{{ __('machines.console.order_finish_named', ['number' => $line->pickupNumber]) }}">
<x-icon name="check" class="size-6" aria-hidden="true" />
{{ __('machines.console.finish') }}
</button>
@if ($this->sameTypeMachines !== [])
<form wire:submit="moveOrder({{ $row->entryId }})" class="flex flex-wrap items-end gap-2">
<div class="min-w-40">
<x-select.native id="move-order-{{ $row->entryId }}" wire:model="moveToMachineId" :label="__('machines.console.move_to')" :aria-label="__('machines.console.move_to_named', ['number' => $line->pickupNumber])">
<option value="">{{ __('machines.task.choose_machine') }}</option>
@foreach ($this->sameTypeMachines as $other)
<option value="{{ $other->id }}">{{ $other->name }}</option>
@endforeach
</x-select.native>
</div>
<button type="submit" class="{{ $secondary }}">{{ __('machines.console.move') }}</button>
</form>
@endif
</div>
@endif
@endif
@endif
@elseif ($task !== null)
<p class="text-xl font-semibold break-words">{{ $task->title }}</p>
<p class="text-base">{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->customerName }}</p>
@@ -0,0 +1,280 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Machines\Application\Contracts\ProductionProcessQueries;
use App\Modules\Machines\Application\DTOs\MachineSummary;
use App\Modules\Machines\Application\DTOs\ProductionStepData;
use App\Modules\Machines\Application\UseCases\SaveProductionProcess;
use App\Modules\Machines\Domain\Exceptions\InvalidProductionStep;
use App\Modules\Machines\Domain\Exceptions\ProductionMachineNotAllowed;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A consumer product's production process on its edit page (management,
* spec 19.7): steps in order, each on a machine of the product's service
* unit or by hand, with a duration per piece, the work type its hours go
* to and materials per piece. A product with a process is sold as an order
* made before it is paid. Shown only when stock is used in a unit.
*/
new class extends Component
{
#[Locked]
public int $productId;
/**
* @var list<array{key: int, machine_id: string, duration: string, work_type_id: string, materials: list<array{key: int, stock_item_id: string, quantity: string}>}>
*/
public array $steps = [];
public int $nextKey = 1;
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('machines.manage');
foreach (app(ProductionProcessQueries::class)->processOf($this->productId) as $step) {
$this->steps[] = [
'key' => $this->nextKey++,
'machine_id' => (string) ($step->machineId ?? ''),
'duration' => rtrim(rtrim(number_format($step->durationQuarters / 4, 2, ',', ''), '0'), ','),
'work_type_id' => (string) $step->workTypeId,
'materials' => array_map(fn (array $material): array => [
'key' => $this->nextKey++,
'stock_item_id' => (string) $material['stockItemId'],
'quantity' => rtrim(rtrim(number_format($material['quantityMilli'] / 1000, 3, ',', ''), '0'), ','),
], $step->materials),
];
}
}
public function isAvailable(): bool
{
return app(CatalogQueries::class)->stockServiceUnitIds() !== [];
}
/**
* Machines of the product's work type's service unit (any unit using
* stock when the product has none or a shared one).
*
* @return list<MachineSummary>
*/
#[Computed]
public function machines(): array
{
$catalog = app(CatalogQueries::class);
$product = app(PriceListQueries::class)->findProduct($this->productId);
$workType = $product?->workTypeId === null ? null : $catalog->findWorkType($product->workTypeId);
$unit = $workType === null ? null : $catalog->findServiceUnit($workType->serviceUnitId);
$units = $unit === null || $unit->isShared ? $catalog->stockServiceUnitIds() : [$unit->id];
return app(MachineQueries::class)->machinesFor($units);
}
/**
* @return list<WorkTypeSummary>
*/
#[Computed]
public function workTypes(): array
{
$types = [];
foreach (app(CatalogQueries::class)->activeWorkTypesFor(app(CatalogQueries::class)->stockServiceUnitIds()) as $node) {
foreach ($node->workTypes as $workType) {
$types[] = $workType;
}
foreach ($node->services as $service) {
foreach ($service->workTypes as $workType) {
$types[] = $workType;
}
}
}
return $types;
}
/**
* @return list<StockItemSummary>
*/
#[Computed]
public function stockItems(): array
{
return app(StockQueries::class)->items();
}
public function addStep(): void
{
$this->authorize('machines.manage');
$product = app(PriceListQueries::class)->findProduct($this->productId);
$key = $this->nextKey++;
$this->steps[] = ['key' => $key, 'machine_id' => (string) ($this->machines[0]->id ?? ''), 'duration' => '0', 'work_type_id' => (string) ($product->workTypeId ?? ($this->workTypes[0]->id ?? '')), 'materials' => []];
$this->message = __('machines.process.step_added', ['number' => count($this->steps)]);
$this->js("document.getElementById('process-step-{$key}-machine')?.focus()");
}
public function removeStep(int $index): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index])) {
array_splice($this->steps, $index, 1);
$this->message = __('machines.process.step_removed', ['number' => $index + 1]);
$this->js("document.getElementById('process-add-step')?.focus()");
}
}
public function moveStep(int $index, string $direction): void
{
$this->authorize('machines.manage');
$target = $direction === 'up' ? $index - 1 : $index + 1;
if (! isset($this->steps[$index], $this->steps[$target])) {
return;
}
[$this->steps[$index], $this->steps[$target]] = [$this->steps[$target], $this->steps[$index]];
$this->message = __('machines.process.step_moved', ['from' => $index + 1, 'to' => $target + 1]);
$key = $this->steps[$target]['key'];
$this->js("document.getElementById('process-step-{$key}-{$direction}')?.focus()");
}
public function addMaterial(int $index): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index])) {
$key = $this->nextKey++;
$this->steps[$index]['materials'][] = ['key' => $key, 'stock_item_id' => '', 'quantity' => '1'];
$this->js("document.getElementById('process-material-{$key}-item')?.focus()");
}
}
public function removeMaterial(int $index, int $materialIndex): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index]['materials'][$materialIndex])) {
array_splice($this->steps[$index]['materials'], $materialIndex, 1);
$key = $this->steps[$index]['key'];
$this->js("document.getElementById('process-step-{$key}-add-material')?.focus()");
}
}
public function save(SaveProductionProcess $saveProcess): void
{
$this->authorize('machines.manage');
$this->resetErrorBag();
$data = [];
foreach ($this->steps as $step) {
$data[] = new ProductionStepData(
$step['machine_id'] === '' ? null : (int) $step['machine_id'],
$step['duration'],
(int) $step['work_type_id'],
array_values(array_map(
fn (array $material): array => ['stockItemId' => (int) $material['stock_item_id'], 'quantity' => $material['quantity']],
array_filter($step['materials'], fn (array $material): bool => $material['stock_item_id'] !== ''),
)),
);
}
try {
$saveProcess->execute($this->productId, $data);
} catch (InvalidProductionStep) {
$this->addError('steps', __('machines.process.errors.invalid'));
return;
} catch (ProductionMachineNotAllowed) {
$this->addError('steps', __('machines.process.errors.machine'));
return;
}
$this->message = $this->steps === [] ? __('machines.process.removed') : __('machines.process.saved');
}
};
?>
<div>
@if ($this->isAvailable())
<section aria-labelledby="process-heading" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="process-heading" class="text-xl font-semibold">{{ __('machines.process.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('machines.process.intro') }}</p>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
@error('steps')
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
<ol class="space-y-4">
@foreach ($steps as $index => $step)
<li wire:key="process-step-{{ $step['key'] }}-{{ $index }}">
<fieldset class="space-y-3 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
<legend class="px-1 font-medium">{{ __('machines.process.step', ['number' => $index + 1]) }}</legend>
<div class="grid gap-3 sm:grid-cols-3">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="process-step-{{ $step['key'] }}-machine" wire:model="steps.{{ $index }}.machine_id" :label="__('machines.process.machine')" :aria-label="__('machines.process.machine_of', ['number' => $index + 1])">
<option value="">{{ __('machines.process.by_hand') }}</option>
@foreach ($this->machines as $machine)
<option value="{{ $machine->id }}">{{ $machine->name }}</option>
@endforeach
</x-select.native>
<x-input id="process-step-{{ $step['key'] }}-duration" wire:model="steps.{{ $index }}.duration" inputmode="decimal" :label="__('machines.process.duration')" autocomplete="off" />
<x-select.native id="process-step-{{ $step['key'] }}-work-type" wire:model="steps.{{ $index }}.work_type_id" :label="__('machines.process.work_type')" :aria-label="__('machines.process.work_type_of', ['number' => $index + 1])">
@foreach ($this->workTypes as $workType)
<option value="{{ $workType->id }}">{{ $workType->name }}</option>
@endforeach
</x-select.native>
</div>
<div class="space-y-2">
<p class="text-sm font-semibold">{{ __('machines.process.materials') }}</p>
@foreach ($step['materials'] as $materialIndex => $material)
<div wire:key="process-material-{{ $material['key'] }}" class="flex flex-wrap items-end gap-2">
<div class="min-w-48 flex-1">
<x-select.native id="process-material-{{ $material['key'] }}-item" wire:model="steps.{{ $index }}.materials.{{ $materialIndex }}.stock_item_id" :label="__('machines.process.material')" :aria-label="__('machines.process.material_of', ['step' => $index + 1, 'number' => $materialIndex + 1])">
<option value="">{{ __('catalog.workflows.choose_material') }}</option>
@foreach ($this->stockItems as $stockItem)
<option value="{{ $stockItem->id }}">{{ $stockItem->name }} ({{ __('inventory.units.'.$stockItem->unit->value) }})</option>
@endforeach
</x-select.native>
</div>
<div class="w-28">
<x-input id="process-material-{{ $material['key'] }}-quantity" wire:model="steps.{{ $index }}.materials.{{ $materialIndex }}.quantity" inputmode="decimal" :label="__('machines.process.per_piece')" autocomplete="off" />
</div>
<x-button wire:click="removeMaterial({{ $index }}, {{ $materialIndex }})" subtle color="black" sm icon="trash" :aria-label="__('machines.process.remove_material', ['step' => $index + 1, 'number' => $materialIndex + 1])" />
</div>
@endforeach
<x-button id="process-step-{{ $step['key'] }}-add-material" wire:click="addMaterial({{ $index }})" subtle color="black" sm icon="plus" :text="__('catalog.workflows.add_material')" :aria-label="__('catalog.workflows.add_material_named', ['number' => $index + 1])" />
</div>
<div class="flex flex-wrap gap-2">
<x-button id="process-step-{{ $step['key'] }}-up" wire:click="moveStep({{ $index }}, 'up')" subtle color="black" sm icon="arrow-up" :aria-label="__('catalog.workflows.move_up_named', ['number' => $index + 1])" />
<x-button id="process-step-{{ $step['key'] }}-down" wire:click="moveStep({{ $index }}, 'down')" subtle color="black" sm icon="arrow-down" :aria-label="__('catalog.workflows.move_down_named', ['number' => $index + 1])" />
<x-button wire:click="removeStep({{ $index }})" subtle color="black" sm icon="trash" :text="__('catalog.workflows.remove_step')" :aria-label="__('catalog.workflows.remove_step_named', ['number' => $index + 1])" />
</div>
</fieldset>
</li>
@endforeach
</ol>
<div class="flex flex-wrap gap-2">
<x-button id="process-add-step" wire:click="addStep" subtle color="black" icon="plus" :text="__('machines.process.add_step')" />
<x-button wire:click="save" icon="check" :text="__('machines.process.save')" />
</div>
</section>
@endif
</div>