diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php index 8d4b61a..7e18a2b 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php @@ -249,4 +249,10 @@ new class extends Component + + @if ($productId !== null && $form->is_consumer_product) + @can('machines.manage') + + @endcan + @endif diff --git a/app/Modules/Machines/Application/Contracts/ProductionProcessQueries.php b/app/Modules/Machines/Application/Contracts/ProductionProcessQueries.php new file mode 100644 index 0000000..f4d5836 --- /dev/null +++ b/app/Modules/Machines/Application/Contracts/ProductionProcessQueries.php @@ -0,0 +1,25 @@ + In order; empty without a process. + */ + public function processOf(int $productId): array; + + /** + * @param list $productIds + * @return array> By product id; products without a process are left out. + */ + public function processesOf(array $productIds): array; +} diff --git a/app/Modules/Machines/Application/DTOs/ProductionStepData.php b/app/Modules/Machines/Application/DTOs/ProductionStepData.php new file mode 100644 index 0000000..9fbba10 --- /dev/null +++ b/app/Modules/Machines/Application/DTOs/ProductionStepData.php @@ -0,0 +1,23 @@ + $materials + */ + public function __construct( + public ?int $machineId, + public string $duration, + public int $workTypeId, + public array $materials = [], + ) {} +} diff --git a/app/Modules/Machines/Application/DTOs/ProductionStepSummary.php b/app/Modules/Machines/Application/DTOs/ProductionStepSummary.php new file mode 100644 index 0000000..12d06c1 --- /dev/null +++ b/app/Modules/Machines/Application/DTOs/ProductionStepSummary.php @@ -0,0 +1,26 @@ + $materials + */ + public function __construct( + public int $position, + public ?int $machineId, + public ?string $machineName, + public int $durationQuarters, + public int $workTypeId, + public string $workTypeName, + public array $materials, + ) {} +} diff --git a/app/Modules/Machines/Application/UseCases/MachineWorkList.php b/app/Modules/Machines/Application/UseCases/MachineWorkList.php index a36bd71..94500f1 100644 --- a/app/Modules/Machines/Application/UseCases/MachineWorkList.php +++ b/app/Modules/Machines/Application/UseCases/MachineWorkList.php @@ -153,6 +153,82 @@ final class MachineWorkList } } + /** + * Puts a step of a quick sale order line on the machine's list for the + * day (spec 19.7); customer waiting rows are listed first. + */ + public function enqueueOrderStep(int $orderLineId, int $stepPosition, int $machineId, DateTimeImmutable $day): void + { + $this->transactions->run(function () use ($orderLineId, $stepPosition, $machineId, $day): void { + $open = $this->queue->openEntryForOrderLine($orderLineId); + + if ($open !== null) { + $this->queue->delete($open); + } + + $this->queue->save(QueueEntry::forOrderLine($machineId, $orderLineId, $stepPosition, $day, 0)); + }); + } + + /** + * Closes an order line's open row as made. + */ + public function completeOrderLine(int $orderLineId, ?int $actorUserId): void + { + $this->transactions->run(function () use ($orderLineId, $actorUserId): void { + $entry = $this->queue->openEntryForOrderLine($orderLineId); + + if ($entry !== null) { + $entry->complete($actorUserId, $this->clock->now()); + $this->queue->save($entry); + } + }); + } + + /** + * Takes an order line's open row off its list (a cancelled order). + */ + public function removeOrderLine(int $orderLineId): void + { + $this->transactions->run(function () use ($orderLineId): void { + $entry = $this->queue->openEntryForOrderLine($orderLineId); + + if ($entry !== null) { + $this->queue->delete($entry); + } + }); + } + + /** + * Moves an order line's open row to another machine of the same type. + * + * @throws QueueEntryNotFound + * @throws MachineNotFound + * @throws MachineInactive + * @throws MachineNotForTask when the machine is of another type + */ + public function moveOrderLine(int $entryId, int $machineId): void + { + $this->transactions->run(function () use ($entryId, $machineId): void { + $entry = $this->queue->findById($entryId) ?? throw new QueueEntryNotFound; + + if (! $entry->isOrderLine()) { + throw new QueueEntryNotFound; + } + + $current = $this->machines->findById($entry->machineId()) ?? throw new MachineNotFound; + $target = $this->machines->findById($machineId) ?? throw new MachineNotFound; + $target->ensureActive(); + + if ($target->type() !== $current->type()) { + throw new MachineNotForTask; + } + + $entry->plan($machineId, $entry->plannedOn(), 0); + $this->queue->save($entry); + }); + } + /** * Closes the open row of a task that was marked done elsewhere. */ diff --git a/app/Modules/Machines/Application/UseCases/SaveProductionProcess.php b/app/Modules/Machines/Application/UseCases/SaveProductionProcess.php new file mode 100644 index 0000000..ac3e6f8 --- /dev/null +++ b/app/Modules/Machines/Application/UseCases/SaveProductionProcess.php @@ -0,0 +1,116 @@ + $steps + * + * @throws InvalidProductionStep with nothing saved + * @throws ProductionMachineNotAllowed + */ + public function execute(int $productId, array $steps): void + { + $product = $this->priceList->findProduct($productId) ?? throw new InvalidProductionStep; + $allowedUnits = $this->allowedUnits($product->workTypeId); + $parsed = []; + + foreach ($steps as $step) { + if ($this->catalog->findWorkType($step->workTypeId) === null) { + throw new InvalidProductionStep; + } + + if ($step->machineId !== null) { + $machine = $this->machines->findById($step->machineId); + + if ($machine === null || ! $machine->isActive() || ! $machine->servesAnyOf($allowedUnits)) { + throw new ProductionMachineNotAllowed; + } + } + + $parsed[] = new ProductionStep($step->machineId, $this->quarters($step->duration), $step->workTypeId, $this->materials($step->materials)); + } + + $this->transactions->run(fn () => $this->processes->replace($productId, $parsed)); + } + + /** + * @return list + */ + private function allowedUnits(?int $workTypeId): array + { + $stockUnits = $this->catalog->stockServiceUnitIds(); + $workType = $workTypeId === null ? null : $this->catalog->findWorkType($workTypeId); + $unit = $workType === null ? null : $this->catalog->findServiceUnit($workType->serviceUnitId); + + return $unit === null || $unit->isShared ? $stockUnits : array_values(array_intersect([$unit->id], $stockUnits)); + } + + /** + * @throws InvalidProductionStep + */ + private function quarters(string $duration): int + { + $duration = str_replace(',', '.', trim($duration)); + + if ($duration === '') { + return 0; + } + + if (! is_numeric($duration) || fmod((float) $duration * 4, 1.0) !== 0.0) { + throw new InvalidProductionStep; + } + + return (int) round((float) $duration * 4); + } + + /** + * @param list $materials + * @return list + * + * @throws InvalidProductionStep + */ + private function materials(array $materials): array + { + $parsed = []; + + foreach ($materials as $material) { + try { + $parsed[] = ['stockItemId' => $material['stockItemId'], 'quantityMilli' => Reading::parse($material['quantity']) ?? 0]; + } catch (InvalidReading) { + throw new InvalidProductionStep; + } + } + + return $parsed; + } +} diff --git a/app/Modules/Machines/Domain/Contracts/ProductionProcessRepository.php b/app/Modules/Machines/Domain/Contracts/ProductionProcessRepository.php new file mode 100644 index 0000000..a2e3790 --- /dev/null +++ b/app/Modules/Machines/Domain/Contracts/ProductionProcessRepository.php @@ -0,0 +1,17 @@ + $steps + */ + public function replace(int $productId, array $steps): void; +} diff --git a/app/Modules/Machines/Domain/Exceptions/InvalidProductionStep.php b/app/Modules/Machines/Domain/Exceptions/InvalidProductionStep.php new file mode 100644 index 0000000..3ee08cc --- /dev/null +++ b/app/Modules/Machines/Domain/Exceptions/InvalidProductionStep.php @@ -0,0 +1,15 @@ + $materials + * + * @throws InvalidProductionStep + */ + public function __construct( + public ?int $machineId, + public int $durationQuarters, + public int $workTypeId, + public array $materials = [], + ) { + if ($durationQuarters < 0 || $durationQuarters > self::MAX_QUARTERS || $workTypeId < 1) { + throw new InvalidProductionStep; + } + + foreach ($materials as $material) { + if ($material['stockItemId'] < 1 || $material['quantityMilli'] < 1) { + throw new InvalidProductionStep; + } + } + } +} diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentProductionProcesses.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentProductionProcesses.php new file mode 100644 index 0000000..42ca97b --- /dev/null +++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentProductionProcesses.php @@ -0,0 +1,97 @@ +where('product_id', $productId)->delete(); + $now = now(); + + foreach ($steps as $index => $step) { + $stepId = DB::table('production_steps')->insertGetId([ + 'product_id' => $productId, + 'sort_order' => $index + 1, + 'machine_id' => $step->machineId, + 'duration_quarters' => $step->durationQuarters, + 'work_type_id' => $step->workTypeId, + 'created_at' => $now, + 'updated_at' => $now, + ]); + + foreach ($step->materials as $material) { + DB::table('production_step_materials')->insert([ + 'production_step_id' => $stepId, + 'stock_item_id' => $material['stockItemId'], + 'quantity_milli' => $material['quantityMilli'], + 'created_at' => $now, + 'updated_at' => $now, + ]); + } + } + } + + public function processOf(int $productId): array + { + return $this->processesOf([$productId])[$productId] ?? []; + } + + public function processesOf(array $productIds): array + { + if ($productIds === []) { + return []; + } + + $steps = DB::table('production_steps')->whereIn('product_id', $productIds)->orderBy('product_id')->orderBy('sort_order')->get(); + + if ($steps->isEmpty()) { + return []; + } + + $materials = DB::table('production_step_materials')->whereIn('production_step_id', $steps->pluck('id'))->orderBy('id')->get()->groupBy('production_step_id'); + $items = $this->stock->itemsByIds($materials->flatten(1)->pluck('stock_item_id')->map(fn ($id): int => (int) $id)->unique()->values()->all()); + $machineNames = MachineModel::query()->whereIn('id', $steps->pluck('machine_id')->filter())->pluck('name', 'id'); + $processes = []; + + foreach ($steps->groupBy('product_id') as $productId => $productSteps) { + foreach ($productSteps->values() as $position => $step) { + $machineId = $step->machine_id === null ? null : (int) $step->machine_id; + + $processes[(int) $productId][] = new ProductionStepSummary( + position: $position, + machineId: $machineId, + machineName: $machineId === null ? null : (string) $machineNames->get($machineId), + durationQuarters: (int) $step->duration_quarters, + workTypeId: (int) $step->work_type_id, + workTypeName: (string) $this->catalog->findWorkType((int) $step->work_type_id)?->name, + materials: ($materials->get($step->id) ?? collect())->map(fn ($material): array => [ + 'stockItemId' => (int) $material->stock_item_id, + 'itemName' => $items[(int) $material->stock_item_id]->name ?? '', + 'unit' => $items[(int) $material->stock_item_id]->unit->value ?? 'piece', + 'quantityMilli' => (int) $material->quantity_milli, + ])->values()->all(), + ); + } + } + + return $processes; + } +} diff --git a/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php index 695dad5..fd57154 100644 --- a/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php +++ b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php @@ -9,9 +9,11 @@ use App\Modules\Machines\Application\Contracts\MachineQueries; use App\Modules\Machines\Application\Contracts\MachineTasks; use App\Modules\Machines\Application\Contracts\MaintenanceMaterials; use App\Modules\Machines\Application\Contracts\MaintenanceQueries; +use App\Modules\Machines\Application\Contracts\ProductionProcessQueries; use App\Modules\Machines\Application\UseCases\MachineWorkList; use App\Modules\Machines\Domain\Contracts\MachineRepository; use App\Modules\Machines\Domain\Contracts\MaintenanceRepository; +use App\Modules\Machines\Domain\Contracts\ProductionProcessRepository; use App\Modules\Machines\Domain\Contracts\QueueRepository; use App\Modules\Machines\Infrastructure\Adapters\JobsForMachines; use App\Modules\Machines\Infrastructure\Adapters\StockForMachines; @@ -19,6 +21,7 @@ use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMachine use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMachineRepository; use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMaintenanceQueries; use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentMaintenanceRepository; +use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentProductionProcesses; use App\Modules\Machines\Infrastructure\Persistence\Repositories\EloquentQueueRepository; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Event; @@ -44,6 +47,8 @@ class MachinesServiceProvider extends ServiceProvider MaintenanceRepository::class => EloquentMaintenanceRepository::class, MaintenanceQueries::class => EloquentMaintenanceQueries::class, MaintenanceMaterials::class => StockForMachines::class, + ProductionProcessQueries::class => EloquentProductionProcesses::class, + ProductionProcessRepository::class => EloquentProductionProcesses::class, ]; public function boot(): void diff --git a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php index 394ea08..1a6af6b 100644 --- a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php +++ b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php @@ -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 + */ + 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 + */ + #[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 + */ + #[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

{{ __('machines.console.next') }}

@endif @if ($row->isOrder()) -

{{ __('machines.show.order') }}

+ @php($line = $this->orderLines[$row->orderLineId] ?? null) +

+

+ @if ($line !== null) +

{{ __('sales.orders.pickup', ['number' => $line->pickupNumber]) }}

+

{{ $line->quantity }} × {{ $line->productName }}

+

+ {{ $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 +

+ @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))) +
+

{{ __('machines.console.order_materials') }}

+ @foreach ($line->currentMaterials as $material) + @php($item = $items[$material['stockItemId']] ?? null) +
+ +
+ +
+ +
+ @endforeach +

{{ __('sales.orders.complete_hint') }}

+ +
+ @else +
+ + @if ($this->sameTypeMachines !== []) +
+
+ + + @foreach ($this->sameTypeMachines as $other) + + @endforeach + +
+ +
+ @endif +
+ @endif + @endif + @endif @elseif ($task !== null)

{{ $task->title }}

{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->customerName }}

diff --git a/app/Modules/Machines/Presentation/Livewire/⚡production-process.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡production-process.blade.php new file mode 100644 index 0000000..53fcca9 --- /dev/null +++ b/app/Modules/Machines/Presentation/Livewire/⚡production-process.blade.php @@ -0,0 +1,280 @@ +}> + */ + 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 + */ + #[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 + */ + #[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 + */ + #[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'); + } +}; +?> + +
+ @if ($this->isAvailable()) +
+

{{ __('machines.process.title') }}

+

{{ __('machines.process.intro') }}

+ +

{{ $message }}

+ @error('steps') + + @enderror + +
    + @foreach ($steps as $index => $step) +
  1. +
    + {{ __('machines.process.step', ['number' => $index + 1]) }} + +
    + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->machines as $machine) + + @endforeach + + + + @foreach ($this->workTypes as $workType) + + @endforeach + +
    + +
    +

    {{ __('machines.process.materials') }}

    + @foreach ($step['materials'] as $materialIndex => $material) +
    +
    + + + @foreach ($this->stockItems as $stockItem) + + @endforeach + +
    +
    + +
    + +
    + @endforeach + +
    + +
    + + + +
    +
    +
  2. + @endforeach +
+ +
+ + +
+
+ @endif +
diff --git a/app/Modules/Sales/Application/Contracts/OrderMaterials.php b/app/Modules/Sales/Application/Contracts/OrderMaterials.php new file mode 100644 index 0000000..7c4741b --- /dev/null +++ b/app/Modules/Sales/Application/Contracts/OrderMaterials.php @@ -0,0 +1,20 @@ + $productIds + * @return array> By product id; products without a process are left out. + */ + public function stepsOf(array $productIds): array; +} diff --git a/app/Modules/Sales/Application/Contracts/ProductionQueue.php b/app/Modules/Sales/Application/Contracts/ProductionQueue.php new file mode 100644 index 0000000..f27c96c --- /dev/null +++ b/app/Modules/Sales/Application/Contracts/ProductionQueue.php @@ -0,0 +1,30 @@ + + */ + public function openOrders(): array; + + public function findOrder(int $id): ?OrderSummary; + + /** + * @param list $lineIds + * @return array By line id. + */ + public function lines(array $lineIds): array; + + /** + * How many orders are not yet paid (cancelled ones left out). + */ + public function unpaidCount(): int; +} diff --git a/app/Modules/Sales/Application/DTOs/OrderData.php b/app/Modules/Sales/Application/DTOs/OrderData.php new file mode 100644 index 0000000..b03e8f4 --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/OrderData.php @@ -0,0 +1,21 @@ + $quantities + */ + public function __construct( + public array $quantities, + public ?int $customerId = null, + public ?string $customerName = null, + ) {} +} diff --git a/app/Modules/Sales/Application/DTOs/OrderLineSummary.php b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php new file mode 100644 index 0000000..d08b498 --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php @@ -0,0 +1,42 @@ + $stepMachineIds + * @param list $currentMaterials + */ + public function __construct( + public int $id, + public int $orderId, + public int $pickupNumber, + public ?string $customerName, + public string $orderedAt, + public string $productName, + public int $quantity, + public int $totalCents, + public array $stepMachineIds, + public ?int $currentStep, + public array $currentMaterials, + public bool $isMade, + ) {} + + public function hasProduction(): bool + { + return $this->stepMachineIds !== []; + } + + public function currentMachineId(): ?int + { + return $this->currentStep === null ? null : $this->stepMachineIds[$this->currentStep]; + } +} diff --git a/app/Modules/Sales/Application/DTOs/OrderResult.php b/app/Modules/Sales/Application/DTOs/OrderResult.php new file mode 100644 index 0000000..487af8d --- /dev/null +++ b/app/Modules/Sales/Application/DTOs/OrderResult.php @@ -0,0 +1,18 @@ + $lines + */ + public function __construct( + public int $id, + public int $pickupNumber, + public string $orderedOn, + public string $orderedAt, + public string $sellerName, + public ?int $customerId, + public ?string $customerName, + public OrderStatus $status, + public ?int $saleId, + public int $totalCents, + public array $lines, + ) {} + + public function isPaid(): bool + { + return $this->saleId !== null; + } + + /** + * Whether making has not started on any line, so the order can still be + * cancelled without anything recorded. + */ + public function isOpen(): bool + { + return $this->status === OrderStatus::InProduction || $this->status === OrderStatus::Ready; + } +} diff --git a/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php new file mode 100644 index 0000000..92ee619 --- /dev/null +++ b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php @@ -0,0 +1,245 @@ +products->sellable() as $product) { + $sellable[$product->id] = $product; + } + + $steps = $this->processes->stepsOf(array_map('intval', array_keys($data->quantities))); + + if ($steps === []) { + throw new OrderHasNoProduction; + } + + if ($data->customerId !== null && $this->customers->findSummary($data->customerId) === null) { + throw new QuickSaleCustomerNotFound($data->customerId); + } + + $now = $this->clock->now(); + $today = $this->clock->today(); + $lines = []; + + foreach ($data->quantities as $productId => $quantity) { + $product = $sellable[$productId] ?? throw new ProductNotSellable($productId); + $lines[] = OrderLine::ordered( + QuickSaleLine::sold($product->id, $product->name, $quantity, $product->grossCents, $product->vatBasisPoints), + $steps[$productId] ?? [], + $now, + ); + } + + return $this->transactions->run(function () use ($sellerId, $data, $lines, $now, $today): OrderResult { + $order = QuickSaleOrder::place($today, $this->orders->nextPickupNumber($today), $now, $sellerId, $data->customerId, $data->customerName, $lines); + $order = $this->orders->save($order); + + foreach ($order->lines() as $line) { + $step = $line->currentStep(); + + if ($step !== null && $step->machineId !== null) { + $this->queue->enqueue((int) $line->id(), 0, $step->machineId, $today); + } + } + + $total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines())); + + return new OrderResult((int) $order->id(), $order->pickupNumber(), $total); + }); + } + + /** + * Completes a line's current step. $usedMilli gives the material used + * per stock item (by default quantity × the step's amount per piece); + * anything over the plan is written off as a reprint. + * + * @param array $usedMilli By stock item id. + * @return bool Whether the line is now made. + * + * @throws QuickSaleOrderNotFound + * @throws QuickSaleOrderClosed + * @throws OrderStepNotCurrent + */ + public function completeStep(int $lineId, int $stepPosition, int $actorUserId, array $usedMilli = []): bool + { + $today = $this->clock->today(); + + return $this->transactions->run(function () use ($lineId, $stepPosition, $actorUserId, $usedMilli, $today): bool { + $order = $this->orders->lockByLineId($lineId) ?? throw new QuickSaleOrderNotFound; + + if ($order->cancelledAt() !== null) { + throw new QuickSaleOrderClosed; + } + + $line = $order->lineById($lineId) ?? throw new QuickSaleOrderNotFound; + $step = $line->currentStep() ?? throw new OrderStepNotCurrent; + $quantity = $line->sale()->quantity; + + foreach ($step->materials as $material) { + $planned = $material['quantityMilli'] * $quantity; + $used = max(0, $usedMilli[$material['stockItemId']] ?? $planned); + + if (min($planned, $used) > 0) { + $this->materials->use($material['stockItemId'], min($planned, $used), $lineId, $step->machineId, $actorUserId); + } + + if ($used > $planned) { + $this->materials->writeOff($material['stockItemId'], $used - $planned, $lineId, $step->machineId, $actorUserId, 'reprint'); + } + } + + if ($step->durationQuarters > 0) { + $this->hours->bookForOrder($actorUserId, $today, $step->workTypeId, $step->durationQuarters * $quantity, $order->pickupNumber()); + } + + if ($step->machineId !== null) { + $this->queue->complete($lineId, $actorUserId); + } + + $next = $line->completeStep($stepPosition, $this->clock->now()); + + if ($next !== null && $next->machineId !== null) { + $this->queue->enqueue($lineId, (int) $line->currentStepPosition(), $next->machineId, $today); + } + + $this->orders->save($order); + + return $line->isMade(); + }); + } + + /** + * Takes the payment: an ordinary quick sale of the order's lines on + * today's cash day, its receipt emailed when an address is given. + * + * @throws QuickSaleOrderNotFound + * @throws QuickSaleOrderClosed + * @throws CashDayClosed + * @throws InvalidEmailAddress + */ + public function pay(int $orderId, int $actorUserId, string $paymentMethod, ?string $receiptEmail = null): SaleResult + { + $email = $receiptEmail === null || trim($receiptEmail) === '' ? null : new EmailAddress($receiptEmail); + $today = $this->clock->today(); + $now = $this->clock->now(); + + $result = $this->transactions->run(function () use ($orderId, $actorUserId, $paymentMethod, $email, $today, $now): SaleResult { + $order = $this->orders->lockById($orderId) ?? throw new QuickSaleOrderNotFound; + $this->cashDays->lockForDay($today)->ensureOpen(); + + $order->pay($now); + $sale = QuickSale::sell( + $actorUserId, + $order->customerId(), + PaymentMethod::from($paymentMethod), + array_map(fn (OrderLine $line): QuickSaleLine => $line->sale(), $order->lines()), + $now, + $today, + $email, + $orderId, + ); + $saleId = (int) $this->sales->add($sale)->id(); + $this->orders->save($order); + + return new SaleResult($saleId, $sale->totalCents(), 0, 0, $email?->value); + }); + + if ($result->receiptEmail !== null) { + $this->mailer->send($result->saleId); + } + + return $result; + } + + /** + * @throws QuickSaleOrderNotFound + * @throws QuickSaleOrderPaid + * @throws QuickSaleOrderClosed + */ + public function cancel(int $orderId, int $actorUserId): void + { + $this->transactions->run(function () use ($orderId, $actorUserId): void { + $order = $this->orders->lockById($orderId) ?? throw new QuickSaleOrderNotFound; + $order->cancel($actorUserId, $this->clock->now()); + + foreach ($order->lines() as $line) { + if ($line->isInProduction()) { + $this->queue->remove((int) $line->id()); + } + } + + $this->orders->save($order); + }); + } +} diff --git a/app/Modules/Sales/Domain/Contracts/QuickSaleOrderRepository.php b/app/Modules/Sales/Domain/Contracts/QuickSaleOrderRepository.php new file mode 100644 index 0000000..c6a33c7 --- /dev/null +++ b/app/Modules/Sales/Domain/Contracts/QuickSaleOrderRepository.php @@ -0,0 +1,32 @@ + $steps + */ + public function __construct( + private ?int $id, + private QuickSaleLine $sale, + private array $steps, + private ?int $currentStep, + private ?DateTimeImmutable $madeAt, + ) {} + + /** + * @param list $steps + */ + public static function ordered(QuickSaleLine $sale, array $steps, DateTimeImmutable $at): self + { + return new self(null, $sale, $steps, $steps === [] ? null : 0, $steps === [] ? $at : null); + } + + /** + * Completes the current step; the line moves to its next step or is made. + * + * @return OrderStep|null The next step, null when the line is made. + * + * @throws OrderStepNotCurrent + */ + public function completeStep(int $position, DateTimeImmutable $at): ?OrderStep + { + if ($this->currentStep !== $position) { + throw new OrderStepNotCurrent; + } + + $next = $position + 1; + + if (isset($this->steps[$next])) { + $this->currentStep = $next; + + return $this->steps[$next]; + } + + $this->currentStep = null; + $this->madeAt = $at; + + return null; + } + + public function currentStep(): ?OrderStep + { + return $this->currentStep === null ? null : $this->steps[$this->currentStep]; + } + + public function currentStepPosition(): ?int + { + return $this->currentStep; + } + + public function isMade(): bool + { + return $this->madeAt !== null; + } + + public function isInProduction(): bool + { + return $this->steps !== [] && $this->currentStep !== null; + } + + public function hasStarted(): bool + { + return $this->steps !== [] && ($this->currentStep === null || $this->currentStep > 0); + } + + public function id(): ?int + { + return $this->id; + } + + public function sale(): QuickSaleLine + { + return $this->sale; + } + + /** + * @return list + */ + public function steps(): array + { + return $this->steps; + } + + public function madeAt(): ?DateTimeImmutable + { + return $this->madeAt; + } +} diff --git a/app/Modules/Sales/Domain/Entities/QuickSale.php b/app/Modules/Sales/Domain/Entities/QuickSale.php index e407a70..d931811 100644 --- a/app/Modules/Sales/Domain/Entities/QuickSale.php +++ b/app/Modules/Sales/Domain/Entities/QuickSale.php @@ -32,6 +32,7 @@ final class QuickSale private array $lines, private ?int $creditsSaleId, private ?EmailAddress $receiptEmail = null, + private ?int $orderId = null, ) { if ($lines === []) { throw new QuickSaleEmpty; @@ -44,9 +45,9 @@ final class QuickSale * * @throws QuickSaleEmpty */ - public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, ?EmailAddress $receiptEmail = null): self + public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, ?EmailAddress $receiptEmail = null, ?int $orderId = null): self { - return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null, $receiptEmail); + return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null, $receiptEmail, $orderId); } /** @@ -74,9 +75,9 @@ final class QuickSale /** * @param list $lines */ - public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId, ?EmailAddress $receiptEmail = null): self + public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId, ?EmailAddress $receiptEmail = null, ?int $orderId = null): self { - return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId, $receiptEmail); + return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId, $receiptEmail, $orderId); } public function totalCents(): int @@ -136,4 +137,12 @@ final class QuickSale { return $this->receiptEmail; } + + /** + * The quick sale order this sale paid, if any. + */ + public function orderId(): ?int + { + return $this->orderId; + } } diff --git a/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php new file mode 100644 index 0000000..908153d --- /dev/null +++ b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php @@ -0,0 +1,192 @@ + $lines + */ + private function __construct( + private ?int $id, + private DateTimeImmutable $orderedOn, + private int $pickupNumber, + private DateTimeImmutable $orderedAt, + private int $userId, + private ?int $customerId, + private ?string $customerName, + private array $lines, + private ?DateTimeImmutable $paidAt, + private ?DateTimeImmutable $cancelledAt, + private ?int $cancelledBy, + ) { + if ($lines === []) { + throw new QuickSaleEmpty; + } + } + + /** + * @param list $lines + * + * @throws QuickSaleEmpty + */ + public static function place(DateTimeImmutable $orderedOn, int $pickupNumber, DateTimeImmutable $orderedAt, int $userId, ?int $customerId, ?string $customerName, array $lines): self + { + $customerName = $customerName === null ? null : mb_substr(trim($customerName), 0, 150); + + return new self(null, $orderedOn, $pickupNumber, $orderedAt, $userId, $customerId, $customerName === '' ? null : $customerName, $lines, null, null, null); + } + + /** + * @param list $lines + */ + public static function reconstitute(int $id, DateTimeImmutable $orderedOn, int $pickupNumber, DateTimeImmutable $orderedAt, int $userId, ?int $customerId, ?string $customerName, array $lines, ?DateTimeImmutable $paidAt, ?DateTimeImmutable $cancelledAt, ?int $cancelledBy): self + { + return new self($id, $orderedOn, $pickupNumber, $orderedAt, $userId, $customerId, $customerName, $lines, $paidAt, $cancelledAt, $cancelledBy); + } + + public function status(): OrderStatus + { + return match (true) { + $this->cancelledAt !== null => OrderStatus::Cancelled, + $this->isMade() && $this->paidAt !== null => OrderStatus::Completed, + $this->isMade() => OrderStatus::Ready, + default => OrderStatus::InProduction, + }; + } + + public function isMade(): bool + { + foreach ($this->lines as $line) { + if (! $line->isMade()) { + return false; + } + } + + return true; + } + + /** + * @throws QuickSaleOrderClosed + */ + public function ensureOpen(): void + { + if ($this->cancelledAt !== null || $this->status() === OrderStatus::Completed) { + throw new QuickSaleOrderClosed; + } + } + + /** + * @throws QuickSaleOrderClosed + */ + public function pay(DateTimeImmutable $at): void + { + if ($this->paidAt !== null || $this->cancelledAt !== null) { + throw new QuickSaleOrderClosed; + } + + $this->paidAt = $at; + } + + /** + * @throws QuickSaleOrderPaid + * @throws QuickSaleOrderClosed + */ + public function cancel(int $userId, DateTimeImmutable $at): void + { + if ($this->paidAt !== null) { + throw new QuickSaleOrderPaid; + } + + if ($this->cancelledAt !== null) { + throw new QuickSaleOrderClosed; + } + + $this->cancelledAt = $at; + $this->cancelledBy = $userId; + } + + public function lineById(int $lineId): ?OrderLine + { + foreach ($this->lines as $line) { + if ($line->id() === $lineId) { + return $line; + } + } + + return null; + } + + public function id(): ?int + { + return $this->id; + } + + public function orderedOn(): DateTimeImmutable + { + return $this->orderedOn; + } + + public function pickupNumber(): int + { + return $this->pickupNumber; + } + + public function orderedAt(): DateTimeImmutable + { + return $this->orderedAt; + } + + public function userId(): int + { + return $this->userId; + } + + public function customerId(): ?int + { + return $this->customerId; + } + + public function customerName(): ?string + { + return $this->customerName; + } + + /** + * @return list + */ + public function lines(): array + { + return $this->lines; + } + + public function paidAt(): ?DateTimeImmutable + { + return $this->paidAt; + } + + public function cancelledAt(): ?DateTimeImmutable + { + return $this->cancelledAt; + } + + public function cancelledBy(): ?int + { + return $this->cancelledBy; + } +} diff --git a/app/Modules/Sales/Domain/Enums/OrderStatus.php b/app/Modules/Sales/Domain/Enums/OrderStatus.php new file mode 100644 index 0000000..3a6fba7 --- /dev/null +++ b/app/Modules/Sales/Domain/Enums/OrderStatus.php @@ -0,0 +1,17 @@ + $materials + */ + public function __construct( + public ?int $machineId, + public int $durationQuarters, + public int $workTypeId, + public array $materials = [], + ) {} + + /** + * @return array{machineId: ?int, durationQuarters: int, workTypeId: int, materials: list} + */ + public function toArray(): array + { + return ['machineId' => $this->machineId, 'durationQuarters' => $this->durationQuarters, 'workTypeId' => $this->workTypeId, 'materials' => $this->materials]; + } + + /** + * @param array{machineId?: ?int, durationQuarters?: int, workTypeId?: int, materials?: list} $data + */ + public static function fromArray(array $data): self + { + return new self( + isset($data['machineId']) ? (int) $data['machineId'] : null, + (int) ($data['durationQuarters'] ?? 0), + (int) ($data['workTypeId'] ?? 0), + array_map(fn (array $material): array => ['stockItemId' => (int) $material['stockItemId'], 'quantityMilli' => (int) $material['quantityMilli']], $data['materials'] ?? []), + ); + } +} diff --git a/app/Modules/Sales/Infrastructure/Adapters/ProcessesFromMachines.php b/app/Modules/Sales/Infrastructure/Adapters/ProcessesFromMachines.php new file mode 100644 index 0000000..9e1f8d7 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Adapters/ProcessesFromMachines.php @@ -0,0 +1,29 @@ + array_map(fn (ProductionStepSummary $step): OrderStep => new OrderStep( + $step->machineId, + $step->durationQuarters, + $step->workTypeId, + array_map(fn (array $material): array => ['stockItemId' => $material['stockItemId'], 'quantityMilli' => $material['quantityMilli']], $step->materials), + ), $steps), + $this->processes->processesOf($productIds), + ); + } +} diff --git a/app/Modules/Sales/Infrastructure/Adapters/QueueOnMachines.php b/app/Modules/Sales/Infrastructure/Adapters/QueueOnMachines.php new file mode 100644 index 0000000..52cb3a9 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Adapters/QueueOnMachines.php @@ -0,0 +1,30 @@ +workList->enqueueOrderStep($orderLineId, $stepPosition, $machineId, $day); + } + + public function complete(int $orderLineId, int $userId): void + { + $this->workList->completeOrderLine($orderLineId, $userId); + } + + public function remove(int $orderLineId): void + { + $this->workList->removeOrderLine($orderLineId); + } +} diff --git a/app/Modules/Sales/Infrastructure/Adapters/StockForOrders.php b/app/Modules/Sales/Infrastructure/Adapters/StockForOrders.php new file mode 100644 index 0000000..ec144e2 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Adapters/StockForOrders.php @@ -0,0 +1,50 @@ +recordUse->execute(new StockUseData($stockItemId, StockQuantity::inputValue($quantityMilli), machineId: $machineId, orderLineId: $orderLineId), $userId); + } catch (DomainException) { + return false; + } + + return true; + } + + public function writeOff(int $stockItemId, int $quantityMilli, int $orderLineId, ?int $machineId, int $userId, string $reason): bool + { + try { + $this->recordWriteOff->execute(new StockUseData( + $stockItemId, + StockQuantity::inputValue($quantityMilli), + machineId: $machineId, + orderLineId: $orderLineId, + reason: __('sales.orders.reasons.'.$reason, [], 'fi'), + ), $userId); + } catch (DomainException) { + return false; + } + + return true; + } +} diff --git a/app/Modules/Sales/Infrastructure/HoursForQuickSales.php b/app/Modules/Sales/Infrastructure/HoursForQuickSales.php index c52f258..565936a 100644 --- a/app/Modules/Sales/Infrastructure/HoursForQuickSales.php +++ b/app/Modules/Sales/Infrastructure/HoursForQuickSales.php @@ -20,7 +20,17 @@ class HoursForQuickSales implements QuickSaleHours private AddTaskHours $addHours, ) {} + public function bookForOrder(int $userId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $pickupNumber): bool + { + return $this->bookWithNote($userId, $day, $workTypeId, $quarters, __('sales.orders.hours_note', ['number' => $pickupNumber])); + } + public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool + { + return $this->bookWithNote($sellerId, $day, $workTypeId, $quarters, __('sales.hours_note', ['number' => $saleId])); + } + + private function bookWithNote(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, string $note): bool { $year = (int) $day->format('Y'); @@ -31,7 +41,7 @@ class HoursForQuickSales implements QuickSaleHours $taskId, $day->format('Y-m-d'), number_format($quarters / 4, 2, ',', ''), - __('sales.hours_note', ['number' => $saleId]), + $note, ); } catch (DomainException) { // Approved or locked hours, or a day over 24 hours: the sale stands without them. diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php index 6bbc07e..8c8a32a 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php @@ -26,11 +26,12 @@ use Illuminate\Support\Carbon; * @property int $total_cents * @property int|null $credits_quick_sale_id * @property string|null $receipt_email + * @property int|null $quick_sale_order_id * @property Carbon|null $receipt_sent_at * @property Carbon|null $receipt_send_failed_at */ #[Table('quick_sales')] -#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id', 'receipt_email'])] +#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id', 'receipt_email', 'quick_sale_order_id'])] #[Hidden(['receipt_email'])] #[UseFactory(QuickSaleFactory::class)] class QuickSaleModel extends Model @@ -67,6 +68,7 @@ class QuickSaleModel extends Model 'total_cents' => 'integer', 'credits_quick_sale_id' => 'integer', 'receipt_email' => 'encrypted', + 'quick_sale_order_id' => 'integer', 'receipt_sent_at' => 'datetime', 'receipt_send_failed_at' => 'datetime', ]; diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderLineModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderLineModel.php new file mode 100644 index 0000000..b3c9367 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderLineModel.php @@ -0,0 +1,46 @@ +}> $production_steps + * @property int|null $current_step + * @property Carbon|null $made_at + * @property int $sort_order + */ +#[Table('quick_sale_order_lines')] +#[Fillable(['quick_sale_order_id', 'product_id', 'product_name', 'quantity', 'unit_price_cents', 'vat_basis_points', 'production_steps', 'current_step', 'made_at', 'sort_order'])] +class QuickSaleOrderLineModel extends Model +{ + /** + * @return array + */ + protected function casts(): array + { + return [ + 'quick_sale_order_id' => 'integer', + 'product_id' => 'integer', + 'quantity' => 'integer', + 'unit_price_cents' => 'integer', + 'vat_basis_points' => 'integer', + 'production_steps' => 'array', + 'current_step' => 'integer', + 'made_at' => 'immutable_datetime', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderModel.php new file mode 100644 index 0000000..1c90b0d --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderModel.php @@ -0,0 +1,64 @@ + + */ + public function lines(): HasMany + { + return $this->hasMany(QuickSaleOrderLineModel::class, 'quick_sale_order_id')->orderBy('sort_order'); + } + + /** + * @return HasOne + */ + public function sale(): HasOne + { + return $this->hasOne(QuickSaleModel::class, 'quick_sale_order_id')->whereNull('credits_quick_sale_id'); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'pickup_number' => 'integer', + 'ordered_at' => 'immutable_datetime', + 'user_id' => 'integer', + 'customer_id' => 'integer', + 'made_at' => 'immutable_datetime', + 'paid_at' => 'immutable_datetime', + 'cancelled_at' => 'immutable_datetime', + 'cancelled_by' => 'integer', + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderQueries.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderQueries.php new file mode 100644 index 0000000..4867b8c --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderQueries.php @@ -0,0 +1,125 @@ +summaries(QuickSaleOrderModel::query() + ->with(['lines', 'sale:id,quick_sale_order_id,credits_quick_sale_id']) + ->whereIn('status', [OrderStatus::InProduction->value, OrderStatus::Ready->value]) + ->orderBy('ordered_at') + ->orderBy('id') + ->get()); + } + + public function findOrder(int $id): ?OrderSummary + { + $model = QuickSaleOrderModel::query()->with(['lines', 'sale:id,quick_sale_order_id,credits_quick_sale_id'])->find($id); + + return $model === null ? null : $this->summaries(collect([$model]))[0]; + } + + public function lines(array $lineIds): array + { + if ($lineIds === []) { + return []; + } + + $lines = QuickSaleOrderLineModel::query()->whereIn('id', $lineIds)->get(); + $orders = QuickSaleOrderModel::query()->whereIn('id', $lines->pluck('quick_sale_order_id')->unique())->get()->keyBy('id'); + $result = []; + + foreach ($lines as $line) { + $order = $orders->get($line->quick_sale_order_id); + + if ($order !== null) { + $result[$line->id] = $this->lineSummary($line, $order, $this->customerName($order)); + } + } + + return $result; + } + + public function unpaidCount(): int + { + return QuickSaleOrderModel::query()->whereNull('paid_at')->whereNull('cancelled_at')->count(); + } + + /** + * @param Collection $models + * @return list + */ + private function summaries(Collection $models): array + { + $sellers = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); + $customerNames = $this->customers->namesByIds($models->pluck('customer_id')->filter()->unique()->values()->all()); + + return $models->map(function (QuickSaleOrderModel $model) use ($sellers, $customerNames): OrderSummary { + $customerName = $model->customer_name ?? ($model->customer_id === null ? null : ($customerNames[$model->customer_id] ?? null)); + $lines = $model->lines->map(fn (QuickSaleOrderLineModel $line): OrderLineSummary => $this->lineSummary($line, $model, $customerName))->values()->all(); + + return new OrderSummary( + id: $model->id, + pickupNumber: $model->pickup_number, + orderedOn: substr($model->ordered_on, 0, 10), + orderedAt: $this->localTime($model->ordered_at), + sellerName: $sellers[$model->user_id] ?? '', + customerId: $model->customer_id, + customerName: $customerName, + status: OrderStatus::from($model->status), + saleId: $model->sale?->id, + totalCents: array_sum(array_map(fn (OrderLineSummary $line): int => $line->totalCents, $lines)), + lines: $lines, + ); + })->values()->all(); + } + + private function lineSummary(QuickSaleOrderLineModel $line, QuickSaleOrderModel $order, ?string $customerName): OrderLineSummary + { + $steps = $line->production_steps; + $current = $line->current_step === null ? null : ($steps[$line->current_step] ?? null); + + return new OrderLineSummary( + id: $line->id, + orderId: $order->id, + pickupNumber: $order->pickup_number, + customerName: $customerName, + orderedAt: $this->localTime($order->ordered_at), + productName: $line->product_name, + quantity: $line->quantity, + totalCents: $line->quantity * $line->unit_price_cents, + stepMachineIds: array_map(fn (array $step): ?int => isset($step['machineId']) ? (int) $step['machineId'] : null, $steps), + currentStep: $line->current_step, + currentMaterials: array_map(fn (array $material): array => ['stockItemId' => (int) $material['stockItemId'], 'quantityMilli' => (int) $material['quantityMilli']], $current['materials'] ?? []), + isMade: $line->made_at !== null, + ); + } + + private function customerName(QuickSaleOrderModel $order): ?string + { + return $order->customer_name ?? ($order->customer_id === null ? null : ($this->customers->namesByIds([$order->customer_id])[$order->customer_id] ?? null)); + } + + private function localTime(\DateTimeInterface $moment): string + { + return Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'); + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php new file mode 100644 index 0000000..3bc7628 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php @@ -0,0 +1,99 @@ +lockForUpdate()->with('lines')->find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function lockByLineId(int $lineId): ?QuickSaleOrder + { + $orderId = QuickSaleOrderLineModel::query()->whereKey($lineId)->value('quick_sale_order_id'); + + return $orderId === null ? null : $this->lockById((int) $orderId); + } + + public function nextPickupNumber(DateTimeImmutable $day): int + { + $numbers = QuickSaleOrderModel::query()->where('ordered_on', $day->format('Y-m-d'))->lockForUpdate()->pluck('pickup_number'); + + return (int) $numbers->max() + 1; + } + + public function save(QuickSaleOrder $order): QuickSaleOrder + { + $model = $order->id() === null ? new QuickSaleOrderModel : QuickSaleOrderModel::query()->findOrFail($order->id()); + + $madeTimes = array_filter(array_map(fn (OrderLine $line): ?DateTimeImmutable => $line->madeAt(), $order->lines())); + $madeAt = $order->isMade() && $madeTimes !== [] ? max($madeTimes) : null; + + $model->fill([ + 'ordered_on' => $order->orderedOn()->format('Y-m-d'), + 'pickup_number' => $order->pickupNumber(), + 'ordered_at' => $order->orderedAt()->format('Y-m-d H:i:s'), + 'user_id' => $order->userId(), + 'customer_id' => $order->customerId(), + 'customer_name' => $order->customerName(), + 'status' => $order->status()->value, + 'made_at' => $madeAt?->format('Y-m-d H:i:s'), + 'paid_at' => $order->paidAt()?->format('Y-m-d H:i:s'), + 'cancelled_at' => $order->cancelledAt()?->format('Y-m-d H:i:s'), + 'cancelled_by' => $order->cancelledBy(), + ])->save(); + + foreach ($order->lines() as $index => $line) { + $lineModel = $line->id() === null ? new QuickSaleOrderLineModel(['quick_sale_order_id' => $model->id]) : QuickSaleOrderLineModel::query()->findOrFail($line->id()); + + $lineModel->fill([ + 'product_id' => $line->sale()->productId, + 'product_name' => $line->sale()->productName, + 'quantity' => $line->sale()->quantity, + 'unit_price_cents' => $line->sale()->unitPriceCents, + 'vat_basis_points' => $line->sale()->vatBasisPoints, + 'production_steps' => array_map(fn (OrderStep $step): array => $step->toArray(), $line->steps()), + 'current_step' => $line->currentStepPosition(), + 'made_at' => $line->madeAt()?->format('Y-m-d H:i:s'), + 'sort_order' => $index + 1, + ])->save(); + } + + return $this->lockById($model->id) ?? $order; + } + + private function toEntity(QuickSaleOrderModel $model): QuickSaleOrder + { + return QuickSaleOrder::reconstitute( + $model->id, + new DateTimeImmutable(substr($model->ordered_on, 0, 10)), + $model->pickup_number, + DateTimeImmutable::createFromInterface($model->ordered_at), + $model->user_id, + $model->customer_id, + $model->customer_name, + $model->lines->map(fn (QuickSaleOrderLineModel $line): OrderLine => new OrderLine( + $line->id, + new QuickSaleLine($line->product_id, $line->product_name, $line->quantity, $line->unit_price_cents, $line->vat_basis_points), + array_map(fn (array $step): OrderStep => OrderStep::fromArray($step), $line->production_steps), + $line->current_step, + $line->made_at === null ? null : DateTimeImmutable::createFromInterface($line->made_at), + ))->values()->all(), + $model->paid_at === null ? null : DateTimeImmutable::createFromInterface($model->paid_at), + $model->cancelled_at === null ? null : DateTimeImmutable::createFromInterface($model->cancelled_at), + $model->cancelled_by, + ); + } +} diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php index 572198d..28f7d1c 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php @@ -30,6 +30,7 @@ class EloquentQuickSaleRepository implements QuickSaleRepository 'total_cents' => $sale->totalCents(), 'credits_quick_sale_id' => $sale->creditsSaleId(), 'receipt_email' => $sale->receiptEmail()?->value, + 'quick_sale_order_id' => $sale->orderId(), ]); foreach ($sale->lines() as $index => $line) { @@ -101,6 +102,7 @@ class EloquentQuickSaleRepository implements QuickSaleRepository ))->values()->all(), $model->credits_quick_sale_id, $model->receipt_email === null ? null : new EmailAddress($model->receipt_email), + $model->quick_sale_order_id, ); } } diff --git a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php index fc6bab2..fc505b8 100644 --- a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php +++ b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php @@ -4,16 +4,26 @@ namespace App\Modules\Sales\Infrastructure\Providers; use App\Models\User; use App\Modules\Customers\Application\Contracts\CustomerReferences; +use App\Modules\Sales\Application\Contracts\OrderMaterials; +use App\Modules\Sales\Application\Contracts\ProductionProcesses; +use App\Modules\Sales\Application\Contracts\ProductionQueue; use App\Modules\Sales\Application\Contracts\QuickSaleHours; +use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries; use App\Modules\Sales\Application\Contracts\QuickSaleProducts; use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Sales\Application\Contracts\QuickSaleReportQueries; use App\Modules\Sales\Application\Contracts\ReceiptMailer; use App\Modules\Sales\Domain\Contracts\CashDayRepository; +use App\Modules\Sales\Domain\Contracts\QuickSaleOrderRepository; use App\Modules\Sales\Domain\Contracts\QuickSaleRepository; +use App\Modules\Sales\Infrastructure\Adapters\ProcessesFromMachines; +use App\Modules\Sales\Infrastructure\Adapters\QueueOnMachines; +use App\Modules\Sales\Infrastructure\Adapters\StockForOrders; use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales; use App\Modules\Sales\Infrastructure\HoursForQuickSales; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository; +use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleOrderQueries; +use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleOrderRepository; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleReportQueries; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository; @@ -42,6 +52,11 @@ class SalesServiceProvider extends ServiceProvider QuickSaleProducts::class => ProductsFromPriceList::class, QuickSaleHours::class => HoursForQuickSales::class, ReceiptMailer::class => QueuedReceiptMailer::class, + QuickSaleOrderRepository::class => EloquentQuickSaleOrderRepository::class, + QuickSaleOrderQueries::class => EloquentQuickSaleOrderQueries::class, + ProductionProcesses::class => ProcessesFromMachines::class, + ProductionQueue::class => QueueOnMachines::class, + OrderMaterials::class => StockForOrders::class, ]; public function register(): void diff --git a/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php index 8e9a55d..dd9dc67 100644 --- a/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php @@ -534,6 +534,10 @@ new class extends Component

{{ __('sales.cash_day.close_text') }}

+ @php($unpaidOrders = app(\App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries::class)->unpaidCount()) + @if ($unpaidOrders > 0) +

{{ trans_choice('sales.orders.unpaid', $unpaidOrders, ['count' => $unpaidOrders]) }}

+ @endif

{{ __('sales.cash_day.total') }}: {{ $this->money($cashDay->balance->totalCents()) }} ({{ __('sales.cash_day.cash') }} {{ $this->money($cashDay->balance->cashCents) }}, diff --git a/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php new file mode 100644 index 0000000..fd70473 --- /dev/null +++ b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php @@ -0,0 +1,427 @@ + + */ + 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 + */ + #[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 + */ + #[Computed] + public function orders(): array + { + return app(QuickSaleOrderQueries::class)->openOrders(); + } + + /** + * @return array + */ + #[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 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 + */ + 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 + */ + 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); + } +}; +?> + +

+
+

{{ __('sales.orders.title') }}

+ +
+ +
+

{{ $message }}

+ @if ($paidSaleId !== null) +

+ + +

+ @endif +
+ + @if ($this->orders === []) +

{{ __('sales.orders.none') }}

+ @else +
    + @foreach ($this->orders as $order) +
  • +
    +
    +

    {{ __('sales.orders.pickup', ['number' => $order->pickupNumber]) }}

    +

    + {{ $order->customerName ?? __('sales.anonymous') }} · {{ $this->dateLabel($order->orderedAt) }} · {{ $this->money($order->totalCents) }} +

    +
    +

    +

    +
    + +
      + @foreach ($order->lines as $line) +
    • +

      {{ $line->quantity }} × {{ $line->productName }} · {{ $this->lineState($line) }}

      + @if (! $line->isMade && $line->hasProduction()) + @if ($completingLineId === $line->id) +
      +

      {{ __('sales.orders.complete_title', ['product' => $line->productName]) }}

      + @php($items = $this->itemsOf($line)) + @foreach ($line->currentMaterials as $material) + @php($item = $items[$material['stockItemId']] ?? null) +
      + +
      + @endforeach +

      {{ __('sales.orders.complete_hint') }}

      +
      + + +
      +
      + @else +
      + + @if ($line->currentMachineId() !== null) + {{ __('sales.orders.open_console', ['machine' => $this->machineNames[$line->currentMachineId()] ?? '']) }} + @endif +
      + @endif + @endif +
    • + @endforeach +
    + + @unless ($order->isPaid()) + @if ($payingOrderId === $order->id) +
    +

    {{ __('sales.orders.pay_title', ['number' => $order->pickupNumber, 'total' => $this->money($order->totalCents)]) }}

    + + +
    + + +
    + + @else +
    + + +
    + @endif + @endunless +
  • + @endforeach +
+ @endif + + +

{{ __('sales.orders.cancel_text') }}

+ + + + +
+
diff --git a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php index 99a0ef1..b33f1b1 100644 --- a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php +++ b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php @@ -3,7 +3,11 @@ 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\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; @@ -65,6 +69,11 @@ new class extends Component #[Locked] public string $hoursMessage = ''; + #[Locked] + public ?int $savedPickupNumber = null; + + public string $orderCustomerName = ''; + public function mount(): void { $this->authorize('sales.use'); @@ -223,12 +232,36 @@ new class extends Component $this->js("document.getElementById('customer-search')?.focus()"); } - public function save(SellQuickSale $sellQuickSale): void + /** + * 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->sendOrder($orders); + + return; + } $this->validate([ 'paymentMethod' => ['required', Rule::enum(PaymentMethod::class)], @@ -293,6 +326,43 @@ new class extends Component 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']]); + + try { + $result = $orders->send((int) auth()->id(), new OrderData($this->quantities, $this->customerId, $this->orderCustomerName)); + } catch (QuickSaleEmpty|InvalidQuantity|OrderHasNoProduction) { + $this->addError('quantities', __('sales.errors.empty')); + + 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 = __('sales.orders.sent', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]); + + $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName'); + $this->forgetLines(); + $this->dispatch('quick-sale-orders-changed'); + + $this->js("document.getElementById('sale-saved')?.focus()"); + } + private function changed(int $productId): void { $this->forgetLines(); @@ -352,6 +422,9 @@ new class extends Component