diff --git a/app/Modules/Sales/Application/DTOs/OrderLineSummary.php b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php index d08b498..3d44142 100644 --- a/app/Modules/Sales/Application/DTOs/OrderLineSummary.php +++ b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php @@ -28,6 +28,7 @@ final readonly class OrderLineSummary public ?int $currentStep, public array $currentMaterials, public bool $isMade, + public int $productId = 0, ) {} public function hasProduction(): bool diff --git a/app/Modules/Sales/Application/DTOs/OrderSummary.php b/app/Modules/Sales/Application/DTOs/OrderSummary.php index 3ace268..12762ef 100644 --- a/app/Modules/Sales/Application/DTOs/OrderSummary.php +++ b/app/Modules/Sales/Application/DTOs/OrderSummary.php @@ -27,6 +27,7 @@ final readonly class OrderSummary public ?int $saleId, public int $totalCents, public array $lines, + public bool $canBeChanged = false, ) {} public function isPaid(): bool diff --git a/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php index 92ee619..8a993a4 100644 --- a/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php +++ b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php @@ -29,6 +29,7 @@ use App\Modules\Sales\Domain\Exceptions\ProductNotSellable; use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound; use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty; use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed; +use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction; use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound; use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid; use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine; @@ -72,6 +73,70 @@ final class QuickSaleOrders * @throws OrderHasNoProduction */ public function send(int $sellerId, OrderData $data): OrderResult + { + $lines = $this->lines($data); + $now = $this->clock->now(); + $today = $this->clock->today(); + + 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); + $this->enqueueFirstSteps($order); + + return $this->result($order); + }); + } + + /** + * Changes an order's products and customer before making has started + * on any line (spec 19.7): the lines are replaced with the products' + * current prices and processes, and the work lists follow. The pickup + * number stays. + * + * @throws QuickSaleOrderNotFound + * @throws QuickSaleOrderClosed + * @throws QuickSaleOrderInProduction + * @throws ProductNotSellable + * @throws InvalidQuantity + * @throws QuickSaleEmpty + * @throws QuickSaleCustomerNotFound + * @throws OrderHasNoProduction + */ + public function change(int $orderId, OrderData $data): OrderResult + { + $lines = $this->lines($data); + + return $this->transactions->run(function () use ($orderId, $data, $lines): OrderResult { + $order = $this->orders->lockById($orderId) ?? throw new QuickSaleOrderNotFound; + $oldLines = $order->lines(); + + $order->change($data->customerId, $data->customerName, $lines); + + foreach ($oldLines as $line) { + if ($line->isInProduction()) { + $this->queue->remove((int) $line->id()); + } + } + + $order = $this->orders->save($order); + $this->enqueueFirstSteps($order); + + return $this->result($order); + }); + } + + /** + * New order lines of the products with their current prices and + * production processes. + * + * @return list + * + * @throws ProductNotSellable + * @throws InvalidQuantity + * @throws QuickSaleCustomerNotFound + * @throws OrderHasNoProduction + */ + private function lines(OrderData $data): array { $sellable = []; foreach ($this->products->sellable() as $product) { @@ -89,7 +154,6 @@ final class QuickSaleOrders } $now = $this->clock->now(); - $today = $this->clock->today(); $lines = []; foreach ($data->quantities as $productId => $quantity) { @@ -101,22 +165,25 @@ final class QuickSaleOrders ); } - 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); + return $lines; + } - foreach ($order->lines() as $line) { - $step = $line->currentStep(); + private function enqueueFirstSteps(QuickSaleOrder $order): void + { + foreach ($order->lines() as $line) { + $step = $line->currentStep(); - if ($step !== null && $step->machineId !== null) { - $this->queue->enqueue((int) $line->id(), 0, $step->machineId, $today); - } + if ($step !== null && $step->machineId !== null) { + $this->queue->enqueue((int) $line->id(), 0, $step->machineId, $order->orderedOn()); } + } + } - $total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines())); + private function result(QuickSaleOrder $order): OrderResult + { + $total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines())); - return new OrderResult((int) $order->id(), $order->pickupNumber(), $total); - }); + return new OrderResult((int) $order->id(), $order->pickupNumber(), $total); } /** diff --git a/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php index 908153d..43a341d 100644 --- a/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php +++ b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php @@ -7,6 +7,7 @@ namespace App\Modules\Sales\Domain\Entities; use App\Modules\Sales\Domain\Enums\OrderStatus; use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty; use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed; +use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction; use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid; use DateTimeImmutable; @@ -121,6 +122,54 @@ final class QuickSaleOrder $this->cancelledBy = $userId; } + /** + * Whether no step has been completed on any line yet. + */ + public function canBeChanged(): bool + { + if ($this->paidAt !== null || $this->cancelledAt !== null) { + return false; + } + + foreach ($this->lines as $line) { + if ($line->hasStarted()) { + return false; + } + } + + return true; + } + + /** + * Replaces the products and the customer before making has started; the + * pickup number stays. + * + * @param list $lines + * + * @throws QuickSaleOrderClosed + * @throws QuickSaleOrderInProduction + * @throws QuickSaleEmpty + */ + public function change(?int $customerId, ?string $customerName, array $lines): void + { + if ($this->paidAt !== null || $this->cancelledAt !== null) { + throw new QuickSaleOrderClosed; + } + + if (! $this->canBeChanged()) { + throw new QuickSaleOrderInProduction; + } + + if ($lines === []) { + throw new QuickSaleEmpty; + } + + $customerName = $customerName === null ? null : mb_substr(trim($customerName), 0, 150); + $this->customerId = $customerId; + $this->customerName = $customerName === '' ? null : $customerName; + $this->lines = $lines; + } + public function lineById(int $lineId): ?OrderLine { foreach ($this->lines as $line) { diff --git a/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php b/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php new file mode 100644 index 0000000..e992dba --- /dev/null +++ b/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php @@ -0,0 +1,15 @@ +sale?->id, totalCents: array_sum(array_map(fn (OrderLineSummary $line): int => $line->totalCents, $lines)), lines: $lines, + canBeChanged: $model->paid_at === null && $model->cancelled_at === null && $model->lines->every( + fn (QuickSaleOrderLineModel $line): bool => $line->production_steps === [] || $line->current_step === 0, + ), ); })->values()->all(); } @@ -110,6 +113,7 @@ class EloquentQuickSaleOrderQueries implements QuickSaleOrderQueries 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, + productId: $line->product_id, ); } diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php index 3bc7628..bbcd83d 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php @@ -55,6 +55,8 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository 'cancelled_by' => $order->cancelledBy(), ])->save(); + $keptIds = []; + foreach ($order->lines() as $index => $line) { $lineModel = $line->id() === null ? new QuickSaleOrderLineModel(['quick_sale_order_id' => $model->id]) : QuickSaleOrderLineModel::query()->findOrFail($line->id()); @@ -69,8 +71,12 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository 'made_at' => $line->madeAt()?->format('Y-m-d H:i:s'), 'sort_order' => $index + 1, ])->save(); + $keptIds[] = $lineModel->id; } + // Lines left out of a changed order are removed (nothing refers to them before making starts). + QuickSaleOrderLineModel::query()->where('quick_sale_order_id', $model->id)->whereNotIn('id', $keptIds)->delete(); + return $this->lockById($model->id) ?? $order; } diff --git a/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php index fd70473..fefd959 100644 --- a/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php +++ b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php @@ -226,6 +226,13 @@ new class extends Component $this->js("document.getElementById('orders-status')?.focus()"); } + public function edit(int $orderId): void + { + $this->authorize('sales.use'); + + $this->dispatch('edit-quick-sale-order', orderId: $this->order($orderId)->id); + } + public function confirmCancel(int $orderId): void { $this->authorize('sales.use'); @@ -408,6 +415,9 @@ new class extends Component @else
+ @if ($order->canBeChanged) + + @endif
@endif diff --git a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php index b33f1b1..cd66f12 100644 --- a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php +++ b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php @@ -4,6 +4,10 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Customers\Application\DTOs\CustomerSummary; use App\Modules\Sales\Application\Contracts\QuickSaleProducts; use App\Modules\Sales\Application\Contracts\ProductionProcesses; +use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries; +use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed; +use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction; +use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound; use App\Modules\Sales\Application\DTOs\OrderData; use App\Modules\Sales\Application\DTOs\SaleData; use App\Modules\Sales\Application\UseCases\QuickSaleOrders; @@ -22,6 +26,7 @@ use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress; use Illuminate\Validation\Rule; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; +use Livewire\Attributes\On; use Livewire\Component; /** @@ -74,6 +79,57 @@ new class extends Component public string $orderCustomerName = ''; + /** + * The open order being changed on this form, if any (spec 19.7). + */ + #[Locked] + public ?int $editingOrderId = null; + + #[Locked] + public ?int $editingPickupNumber = null; + + /** + * Loads an order whose making has not started into the form to change + * its products and customer. + */ + #[On('edit-quick-sale-order')] + public function editOrder(int $orderId): void + { + $this->authorize('sales.use'); + + $order = app(QuickSaleOrderQueries::class)->findOrder($orderId) ?? abort(404); + + if (! $order->canBeChanged) { + $this->addError('sale', __('sales.orders.errors.started')); + + return; + } + + $this->reset('quantities', 'cartMessage', 'savedMessage', 'hoursMessage', 'savedSaleId', 'savedPickupNumber'); + + foreach ($order->lines as $line) { + $this->quantities[$line->productId] = $line->quantity; + } + + $this->editingOrderId = $order->id; + $this->editingPickupNumber = $order->pickupNumber; + $this->customerId = $order->customerId; + $this->customerName = $order->customerId === null ? '' : (string) $order->customerName; + $this->orderCustomerName = $order->customerId === null ? (string) $order->customerName : ''; + $this->resetErrorBag(); + $this->forgetLines(); + $this->cartMessage = __('sales.orders.editing', ['number' => $order->pickupNumber]); + $this->js("document.getElementById('cart-heading')?.focus()"); + } + + public function stopEditing(): void + { + $this->reset('quantities', 'customerSearch', 'customerId', 'customerName', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber'); + $this->forgetLines(); + $this->cartMessage = __('sales.orders.editing_stopped'); + $this->js("document.getElementById('cart-heading')?.focus()"); + } + public function mount(): void { $this->authorize('sales.use'); @@ -257,7 +313,7 @@ new class extends Component $this->savedSaleId = null; $this->savedPickupNumber = null; - if ($this->isOrder()) { + if ($this->isOrder() || $this->editingOrderId !== null) { $this->sendOrder($orders); return; @@ -334,11 +390,24 @@ new class extends Component { $this->validate(['orderCustomerName' => ['nullable', 'string', 'max:150']]); + $data = new OrderData($this->quantities, $this->customerId, $this->orderCustomerName); + try { - $result = $orders->send((int) auth()->id(), new OrderData($this->quantities, $this->customerId, $this->orderCustomerName)); - } catch (QuickSaleEmpty|InvalidQuantity|OrderHasNoProduction) { + $result = $this->editingOrderId === null + ? $orders->send((int) auth()->id(), $data) + : $orders->change($this->editingOrderId, $data); + } catch (QuickSaleEmpty|InvalidQuantity) { $this->addError('quantities', __('sales.errors.empty')); + return; + } catch (OrderHasNoProduction) { + $this->addError('quantities', __($this->editingOrderId === null ? 'sales.errors.empty' : 'sales.orders.errors.no_production')); + + return; + } catch (QuickSaleOrderInProduction|QuickSaleOrderClosed|QuickSaleOrderNotFound) { + $this->addError('sale', __('sales.orders.errors.started')); + $this->stopEditing(); + return; } catch (ProductNotSellable $exception) { unset($this->quantities[$exception->id], $this->products); @@ -354,9 +423,9 @@ new class extends Component } $this->savedPickupNumber = $result->pickupNumber; - $this->savedMessage = __('sales.orders.sent', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]); + $this->savedMessage = __($this->editingOrderId === null ? 'sales.orders.sent' : 'sales.orders.changed', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]); - $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName'); + $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber'); $this->forgetLines(); $this->dispatch('quick-sale-orders-changed'); @@ -536,9 +605,16 @@ new class extends Component

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