From 38b8075a9c2050baeebaaed550ca519e56613276 Mon Sep 17 00:00:00 2001
From: Petri Saarinen
Date: Thu, 26 Nov 2026 17:11:54 +0200
Subject: [PATCH] Make quick sale products on machines as orders paid when
ready
Co-Authored-By: Claude Sonnet 5.5
---
.../Livewire/⚡product-form.blade.php | 6 +
.../Contracts/ProductionProcessQueries.php | 25 +
.../Application/DTOs/ProductionStepData.php | 23 +
.../DTOs/ProductionStepSummary.php | 26 ++
.../Application/UseCases/MachineWorkList.php | 76 ++++
.../UseCases/SaveProductionProcess.php | 116 +++++
.../Contracts/ProductionProcessRepository.php | 17 +
.../Exceptions/InvalidProductionStep.php | 15 +
.../ProductionMachineNotAllowed.php | 15 +
.../Domain/ValueObjects/ProductionStep.php | 41 ++
.../EloquentProductionProcesses.php | 97 ++++
.../Providers/MachinesServiceProvider.php | 5 +
.../Presentation/Livewire/⚡console.blade.php | 176 +++++++-
.../Livewire/⚡production-process.blade.php | 280 ++++++++++++
.../Application/Contracts/OrderMaterials.php | 20 +
.../Contracts/ProductionProcesses.php | 20 +
.../Application/Contracts/ProductionQueue.php | 30 ++
.../Application/Contracts/QuickSaleHours.php | 6 +
.../Contracts/QuickSaleOrderQueries.php | 36 ++
.../Sales/Application/DTOs/OrderData.php | 21 +
.../Application/DTOs/OrderLineSummary.php | 42 ++
.../Sales/Application/DTOs/OrderResult.php | 18 +
.../Sales/Application/DTOs/OrderSummary.php | 45 ++
.../Application/UseCases/QuickSaleOrders.php | 245 ++++++++++
.../Contracts/QuickSaleOrderRepository.php | 32 ++
.../Sales/Domain/Entities/OrderLine.php | 112 +++++
.../Sales/Domain/Entities/QuickSale.php | 17 +-
.../Sales/Domain/Entities/QuickSaleOrder.php | 192 ++++++++
.../Sales/Domain/Enums/OrderStatus.php | 17 +
.../Exceptions/OrderHasNoProduction.php | 15 +
.../Domain/Exceptions/OrderStepNotCurrent.php | 15 +
.../Exceptions/QuickSaleOrderClosed.php | 15 +
.../Exceptions/QuickSaleOrderNotFound.php | 15 +
.../Domain/Exceptions/QuickSaleOrderPaid.php | 15 +
.../Sales/Domain/ValueObjects/OrderStep.php | 45 ++
.../Adapters/ProcessesFromMachines.php | 29 ++
.../Adapters/QueueOnMachines.php | 30 ++
.../Adapters/StockForOrders.php | 50 ++
.../Infrastructure/HoursForQuickSales.php | 12 +-
.../Persistence/Eloquent/QuickSaleModel.php | 4 +-
.../Eloquent/QuickSaleOrderLineModel.php | 46 ++
.../Eloquent/QuickSaleOrderModel.php | 64 +++
.../EloquentQuickSaleOrderQueries.php | 125 +++++
.../EloquentQuickSaleOrderRepository.php | 99 ++++
.../EloquentQuickSaleRepository.php | 2 +
.../Providers/SalesServiceProvider.php | 15 +
.../Presentation/Livewire/⚡index.blade.php | 4 +
.../Presentation/Livewire/⚡orders.blade.php | 427 ++++++++++++++++++
.../Presentation/Livewire/⚡sell.blade.php | 129 +++++-
...826_create_production_and_order_tables.php | 105 +++++
lang/en/machines.php | 39 ++
lang/en/sales.php | 52 +++
lang/fi/machines.php | 39 ++
lang/fi/sales.php | 52 +++
.../QuickSaleOrdersAccessibilityTest.php | 74 +++
tests/Fakes/FakeQuickSaleHours.php | 5 +
tests/Fakes/InMemoryQuickSaleRepository.php | 1 +
.../Modules/Sales/QuickSaleOrdersTest.php | 167 +++++++
58 files changed, 3435 insertions(+), 26 deletions(-)
create mode 100644 app/Modules/Machines/Application/Contracts/ProductionProcessQueries.php
create mode 100644 app/Modules/Machines/Application/DTOs/ProductionStepData.php
create mode 100644 app/Modules/Machines/Application/DTOs/ProductionStepSummary.php
create mode 100644 app/Modules/Machines/Application/UseCases/SaveProductionProcess.php
create mode 100644 app/Modules/Machines/Domain/Contracts/ProductionProcessRepository.php
create mode 100644 app/Modules/Machines/Domain/Exceptions/InvalidProductionStep.php
create mode 100644 app/Modules/Machines/Domain/Exceptions/ProductionMachineNotAllowed.php
create mode 100644 app/Modules/Machines/Domain/ValueObjects/ProductionStep.php
create mode 100644 app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentProductionProcesses.php
create mode 100644 app/Modules/Machines/Presentation/Livewire/⚡production-process.blade.php
create mode 100644 app/Modules/Sales/Application/Contracts/OrderMaterials.php
create mode 100644 app/Modules/Sales/Application/Contracts/ProductionProcesses.php
create mode 100644 app/Modules/Sales/Application/Contracts/ProductionQueue.php
create mode 100644 app/Modules/Sales/Application/Contracts/QuickSaleOrderQueries.php
create mode 100644 app/Modules/Sales/Application/DTOs/OrderData.php
create mode 100644 app/Modules/Sales/Application/DTOs/OrderLineSummary.php
create mode 100644 app/Modules/Sales/Application/DTOs/OrderResult.php
create mode 100644 app/Modules/Sales/Application/DTOs/OrderSummary.php
create mode 100644 app/Modules/Sales/Application/UseCases/QuickSaleOrders.php
create mode 100644 app/Modules/Sales/Domain/Contracts/QuickSaleOrderRepository.php
create mode 100644 app/Modules/Sales/Domain/Entities/OrderLine.php
create mode 100644 app/Modules/Sales/Domain/Entities/QuickSaleOrder.php
create mode 100644 app/Modules/Sales/Domain/Enums/OrderStatus.php
create mode 100644 app/Modules/Sales/Domain/Exceptions/OrderHasNoProduction.php
create mode 100644 app/Modules/Sales/Domain/Exceptions/OrderStepNotCurrent.php
create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleOrderClosed.php
create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleOrderNotFound.php
create mode 100644 app/Modules/Sales/Domain/Exceptions/QuickSaleOrderPaid.php
create mode 100644 app/Modules/Sales/Domain/ValueObjects/OrderStep.php
create mode 100644 app/Modules/Sales/Infrastructure/Adapters/ProcessesFromMachines.php
create mode 100644 app/Modules/Sales/Infrastructure/Adapters/QueueOnMachines.php
create mode 100644 app/Modules/Sales/Infrastructure/Adapters/StockForOrders.php
create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderLineModel.php
create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleOrderModel.php
create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderQueries.php
create mode 100644 app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php
create mode 100644 app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php
create mode 100644 database/migrations/2026_11_26_145826_create_production_and_order_tables.php
create mode 100644 tests/Browser/QuickSaleOrdersAccessibilityTest.php
create mode 100644 tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
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)
+
+
+ {{ __('machines.show.order') }}
+
+ @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)))
+
+ @else
+
+
+ @if ($this->sameTypeMachines !== [])
+
+ @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')
+ {{ $message }}
+ @enderror
+
+
+ @foreach ($steps as $index => $step)
+ -
+
+
+ @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)
+
+
+
+ {{ __('sales.receipt.open', ['number' => $paidSaleId]) }}
+
+
+ @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) }}
+
+
+
+
+ {{ __('sales.orders.statuses.'.$order->status->value) }}@if ($order->isPaid()), {{ __('sales.orders.is_paid') }}@endif
+
+
+
+
+ @foreach ($order->lines as $line)
+ -
+
{{ $line->quantity }} × {{ $line->productName }} · {{ $this->lineState($line) }}
+ @if (! $line->isMade && $line->hasProduction())
+ @if ($completingLineId === $line->id)
+
+ @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)
+
+ @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
{{ $savedMessage }}
+ @if ($savedPickupNumber !== null)
+ {{ $savedPickupNumber }}
+ @endif
@if ($hoursMessage !== '')
{{ $hoursMessage }}
@endif
@@ -397,6 +470,12 @@ new class extends Component
>
{{ $product->name }}
{{ $this->money($product->grossCents) }} / {{ __('catalog.units.'.$product->unit) }}
+ @if (in_array($product->id, $this->madeProductIds, true))
+
+
+ {{ __('sales.orders.made') }}
+
+ @endif
@endforeach
@@ -457,15 +536,25 @@ new class extends Component
+ @php($isOrder = $this->isOrder())
+
@endif
+
+
diff --git a/database/migrations/2026_11_26_145826_create_production_and_order_tables.php b/database/migrations/2026_11_26_145826_create_production_and_order_tables.php
new file mode 100644
index 0000000..b79ffb7
--- /dev/null
+++ b/database/migrations/2026_11_26_145826_create_production_and_order_tables.php
@@ -0,0 +1,105 @@
+id();
+ $table->foreignId('product_id')->constrained()->cascadeOnDelete();
+ $table->unsignedSmallInteger('sort_order');
+ $table->foreignId('machine_id')->nullable()->constrained()->restrictOnDelete();
+ $table->unsignedSmallInteger('duration_quarters')->default(0);
+ $table->foreignId('work_type_id')->constrained()->restrictOnDelete();
+ $table->timestamps();
+ });
+
+ Schema::create('production_step_materials', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('production_step_id')->constrained()->cascadeOnDelete();
+ $table->foreignId('stock_item_id')->constrained()->restrictOnDelete();
+ $table->bigInteger('quantity_milli');
+ $table->timestamps();
+ });
+
+ Schema::create('quick_sale_orders', function (Blueprint $table) {
+ $table->id();
+ $table->date('ordered_on');
+ $table->unsignedInteger('pickup_number');
+ $table->timestamp('ordered_at');
+ $table->foreignId('user_id')->constrained()->restrictOnDelete();
+ $table->foreignId('customer_id')->nullable()->constrained()->restrictOnDelete();
+ $table->string('customer_name', 150)->nullable();
+ $table->string('status', 20);
+ $table->timestamp('made_at')->nullable();
+ $table->timestamp('paid_at')->nullable();
+ $table->timestamp('cancelled_at')->nullable();
+ $table->foreignId('cancelled_by')->nullable()->constrained('users')->restrictOnDelete();
+ $table->timestamps();
+
+ $table->unique(['ordered_on', 'pickup_number']);
+ $table->index('status');
+ });
+
+ Schema::create('quick_sale_order_lines', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('quick_sale_order_id')->constrained()->cascadeOnDelete();
+ $table->foreignId('product_id')->constrained()->restrictOnDelete();
+ $table->string('product_name');
+ $table->unsignedInteger('quantity');
+ $table->unsignedInteger('unit_price_cents');
+ $table->unsignedSmallInteger('vat_basis_points');
+ $table->json('production_steps');
+ $table->unsignedSmallInteger('current_step')->nullable();
+ $table->timestamp('made_at')->nullable();
+ $table->unsignedSmallInteger('sort_order');
+ $table->timestamps();
+ });
+
+ Schema::table('quick_sales', function (Blueprint $table) {
+ $column = $table->foreignId('quick_sale_order_id')->nullable()->after('credits_quick_sale_id');
+
+ // SQLite (tests) could not drop the column again with a foreign key on it.
+ if (Schema::getConnection()->getDriverName() !== 'sqlite') {
+ $column->constrained()->restrictOnDelete();
+ }
+ });
+
+ Schema::table('machine_queue_entries', function (Blueprint $table) {
+ $table->foreign('quick_sale_order_line_id', 'machine_queue_order_line_foreign')->references('id')->on('quick_sale_order_lines')->cascadeOnDelete();
+ });
+
+ Schema::table('stock_movements', function (Blueprint $table) {
+ $table->foreign('quick_sale_order_line_id', 'stock_movements_order_line_foreign')->references('id')->on('quick_sale_order_lines')->restrictOnDelete();
+ });
+ }
+
+ public function down(): void
+ {
+ // SQLite (tests) cannot drop a foreign key; there the tables are dropped by the earlier migrations' rollback.
+ if (Schema::getConnection()->getDriverName() !== 'sqlite') {
+ Schema::table('stock_movements', fn (Blueprint $table) => $table->dropForeign('stock_movements_order_line_foreign'));
+ Schema::table('machine_queue_entries', fn (Blueprint $table) => $table->dropForeign('machine_queue_order_line_foreign'));
+ Schema::table('quick_sales', fn (Blueprint $table) => $table->dropForeign(['quick_sale_order_id']));
+ }
+
+ Schema::table('quick_sales', function (Blueprint $table) {
+ $table->dropColumn('quick_sale_order_id');
+ });
+
+ Schema::dropIfExists('quick_sale_order_lines');
+ Schema::dropIfExists('quick_sale_orders');
+ Schema::dropIfExists('production_step_materials');
+ Schema::dropIfExists('production_steps');
+ }
+};
diff --git a/lang/en/machines.php b/lang/en/machines.php
index 0a0e467..93ca7c1 100644
--- a/lang/en/machines.php
+++ b/lang/en/machines.php
@@ -222,6 +222,18 @@ return [
],
],
'console' => [
+ 'ordered_at' => 'ordered at :time',
+ 'order_step' => 'step :step/:steps',
+ 'order_materials' => 'Materials of the step: check the quantities and confirm.',
+ 'less_of' => 'Less: :item',
+ 'more_of' => 'More: :item',
+ 'confirm_order' => 'Confirm as done',
+ 'order_finish_named' => 'Done: order :number',
+ 'order_done' => ':product of order :number completed.',
+ 'move_to' => 'Move to machine',
+ 'move_to_named' => 'Move order :number to machine',
+ 'move' => 'Move',
+ 'order_moved' => 'Order :number moved to :machine.',
'title' => 'Machine console: :name',
'user' => 'User: :name',
'refresh' => 'Refresh',
@@ -264,6 +276,33 @@ return [
'counters_and_maintenance' => 'Counters and maintenance',
'latest' => 'Latest reading :reading',
],
+ 'process' => [
+ 'title' => 'Production process',
+ 'intro' => 'A product with a production process is sold as an order: the order goes on the work list of the first step\'s machine, and the product is paid when it is ready. A step by hand (e.g. finishing) holds the auxiliary materials no machine needs. Changes do not touch orders already sent.',
+ 'step' => 'Step :number',
+ 'machine' => 'Machine',
+ 'machine_of' => 'Machine of step :number',
+ 'by_hand' => 'No machine (by hand)',
+ 'duration' => 'Duration per piece (h)',
+ 'work_type' => 'Work type',
+ 'work_type_of' => 'Work type of step :number',
+ 'materials' => 'Materials per piece',
+ 'material' => 'Item',
+ 'material_of' => 'Material :number of step :step',
+ 'per_piece' => 'Quantity / pc',
+ 'remove_material' => 'Remove material :number of step :step',
+ 'add_step' => 'Add step',
+ 'save' => 'Save production process',
+ 'saved' => 'Production process saved.',
+ 'removed' => 'Production process removed: the product is paid at once.',
+ 'step_added' => 'Step :number added.',
+ 'step_removed' => 'Step :number removed.',
+ 'step_moved' => 'Step :from moved to :to.',
+ 'errors' => [
+ 'invalid' => 'Check the steps: a duration of 0–24 h in steps of 0.25 h, a work type and material quantities greater than zero.',
+ 'machine' => 'A step\'s machine must be in use and in the service unit of the product\'s work type.',
+ ],
+ ],
'errors' => [
'name' => 'Enter a name (1–150 characters).',
'name_taken' => 'The name is already in use.',
diff --git a/lang/en/sales.php b/lang/en/sales.php
index db72e35..efffac9 100644
--- a/lang/en/sales.php
+++ b/lang/en/sales.php
@@ -147,6 +147,58 @@ return [
'reopen_text' => 'The balance is removed, and it is formed again when the day is closed.',
'reopened_message' => 'Cash day :day reopened.',
],
+ 'orders' => [
+ 'title' => 'Open orders',
+ 'refresh' => 'Refresh',
+ 'refreshed' => 'Refreshed at :time.',
+ 'none' => 'No open orders.',
+ 'made' => 'Made before payment',
+ 'order_note' => 'The sale has products that are made first: it is sent to production as an order, and the order is paid when it is ready (or in advance).',
+ 'customer_name' => 'Customer name',
+ 'customer_name_hint' => 'An optional name to call the customer by when the order is ready.',
+ 'send' => 'Send to production',
+ 'sent' => 'Order sent to production. Pickup number :number, total :total.',
+ 'pickup' => 'No. :number',
+ 'statuses' => [
+ 'in_production' => 'Being made',
+ 'ready' => 'Ready, to be paid',
+ 'completed' => 'Ready and paid',
+ 'cancelled' => 'Cancelled',
+ ],
+ 'is_paid' => 'paid',
+ 'line_ready' => 'ready',
+ 'line_no_production' => 'not made',
+ 'line_step' => 'step :step/:steps: :where',
+ 'by_hand' => 'by hand, completed on this page',
+ 'complete_step' => 'Complete step',
+ 'complete_step_named' => 'Complete step: order :number, :product',
+ 'complete_title' => 'Step done: :product',
+ 'complete_hint' => 'The materials are prefilled. A quantity over the plan is recorded as a write-off (reprint). The step\'s hours are recorded on you.',
+ 'complete' => 'Mark done',
+ 'open_console' => 'Open the machine console of :machine',
+ 'step_done' => 'Step of :product in order :number completed; the next step is on a work list.',
+ 'line_made' => ':product of order :number is ready.',
+ 'became_ready' => '{1} Order :numbers is ready.|[2,*] Orders :numbers are ready.',
+ 'pay' => 'Take payment',
+ 'pay_named' => 'Take payment: order :number',
+ 'pay_title' => 'Payment of order :number, total :total',
+ 'take_payment' => 'Record payment',
+ 'paid' => 'Order :number paid: :total, :method.',
+ 'cancel' => 'Cancel order',
+ 'cancel_named' => 'Cancel order :number',
+ 'cancel_title' => 'Cancel the order?',
+ 'cancel_text' => 'The order leaves the machines\' work lists and no sale is made. Material and hours already recorded stay.',
+ 'cancelled' => 'Order :number cancelled.',
+ 'unpaid' => '{1} 1 order is unpaid; it stays open for the next day.|[2,*] :count orders are unpaid; they stay open for the next day.',
+ 'hours_note' => 'Quick sale order :number',
+ 'reasons' => [
+ 'reprint' => 'reprint',
+ ],
+ 'errors' => [
+ 'step' => 'The step could not be completed: the order has changed. Refresh the list.',
+ 'closed' => 'The order is already paid or cancelled.',
+ ],
+ ],
'errors' => [
'receipt_email' => 'Enter a valid email address, e.g. name@example.com.',
'empty' => 'Enter a quantity for at least one product.',
diff --git a/lang/fi/machines.php b/lang/fi/machines.php
index ce5b054..498e298 100644
--- a/lang/fi/machines.php
+++ b/lang/fi/machines.php
@@ -222,6 +222,18 @@ return [
],
],
'console' => [
+ 'ordered_at' => 'tilattu klo :time',
+ 'order_step' => 'vaihe :step/:steps',
+ 'order_materials' => 'Vaiheen materiaalit: tarkista määrät ja vahvista.',
+ 'less_of' => 'Vähemmän: :item',
+ 'more_of' => 'Enemmän: :item',
+ 'confirm_order' => 'Vahvista valmiiksi',
+ 'order_finish_named' => 'Valmis: tilaus :number',
+ 'order_done' => 'Tilauksen :number tuote :product kuitattu.',
+ 'move_to' => 'Siirrä koneelle',
+ 'move_to_named' => 'Siirrä tilaus :number koneelle',
+ 'move' => 'Siirrä',
+ 'order_moved' => 'Tilaus :number siirretty koneelle :machine.',
'title' => 'Konekäyttöliittymä: :name',
'user' => 'Käyttäjä: :name',
'refresh' => 'Päivitä',
@@ -264,6 +276,33 @@ return [
'counters_and_maintenance' => 'Laskurit ja huollot',
'latest' => 'Viimeisin lukema :reading',
],
+ 'process' => [
+ 'title' => 'Valmistusprosessi',
+ 'intro' => 'Tuote, jolla on valmistusprosessi, myydään tilauksena: tilaus menee ensimmäisen vaiheen koneen työlistalle, ja tuote maksetaan, kun se on valmis. Koneettomassa vaiheessa (esim. viimeistely) kirjataan apumateriaalit, joita koneella ei tarvita. Muutos ei koske jo lähetettyjä tilauksia.',
+ 'step' => 'Vaihe :number',
+ 'machine' => 'Kone',
+ 'machine_of' => 'Vaiheen :number kone',
+ 'by_hand' => 'Ei konetta (käsin)',
+ 'duration' => 'Kesto kappaleelta (h)',
+ 'work_type' => 'Työtehtävä',
+ 'work_type_of' => 'Vaiheen :number työtehtävä',
+ 'materials' => 'Materiaalit kappaletta kohden',
+ 'material' => 'Nimike',
+ 'material_of' => 'Vaiheen :step materiaali :number',
+ 'per_piece' => 'Määrä / kpl',
+ 'remove_material' => 'Poista vaiheen :step materiaali :number',
+ 'add_step' => 'Lisää vaihe',
+ 'save' => 'Tallenna valmistusprosessi',
+ 'saved' => 'Valmistusprosessi tallennettu.',
+ 'removed' => 'Valmistusprosessi poistettu: tuote myydään heti maksettavana.',
+ 'step_added' => 'Vaihe :number lisätty.',
+ 'step_removed' => 'Vaihe :number poistettu.',
+ 'step_moved' => 'Vaihe :from siirretty kohtaan :to.',
+ 'errors' => [
+ 'invalid' => 'Tarkista vaiheet: kesto 0–24 h 0,25 h tarkkuudella, työtehtävä ja materiaalien määrät nollaa suurempina.',
+ 'machine' => 'Vaiheen koneen on oltava käytössä ja tuotteen työtehtävän palveluyksikössä.',
+ ],
+ ],
'errors' => [
'name' => 'Anna nimi (1–150 merkkiä).',
'name_taken' => 'Nimi on jo käytössä.',
diff --git a/lang/fi/sales.php b/lang/fi/sales.php
index 3a607cf..c56ba84 100644
--- a/lang/fi/sales.php
+++ b/lang/fi/sales.php
@@ -147,6 +147,58 @@ return [
'reopen_text' => 'Saldo poistetaan, ja se muodostetaan uudelleen, kun päivä päätetään.',
'reopened_message' => 'Kassapäivä :day avattu uudelleen.',
],
+ 'orders' => [
+ 'title' => 'Avoimet tilaukset',
+ 'refresh' => 'Päivitä',
+ 'refreshed' => 'Päivitetty klo :time.',
+ 'none' => 'Ei avoimia tilauksia.',
+ 'made' => 'Valmistetaan ennen maksua',
+ 'order_note' => 'Myynnissä on valmistettavia tuotteita: se lähetetään valmistukseen tilauksena, ja tilaus maksetaan, kun se on valmis (tai etukäteen).',
+ 'customer_name' => 'Asiakkaan nimi',
+ 'customer_name_hint' => 'Vapaaehtoinen nimi, jolla asiakas kutsutaan noutamaan tilaus.',
+ 'send' => 'Lähetä valmistukseen',
+ 'sent' => 'Tilaus lähetetty valmistukseen. Noutonumero :number, yhteensä :total.',
+ 'pickup' => 'Nro :number',
+ 'statuses' => [
+ 'in_production' => 'Valmistuksessa',
+ 'ready' => 'Valmis, maksettavana',
+ 'completed' => 'Valmis ja maksettu',
+ 'cancelled' => 'Peruttu',
+ ],
+ 'is_paid' => 'maksettu',
+ 'line_ready' => 'valmis',
+ 'line_no_production' => 'ei valmistusta',
+ 'line_step' => 'vaihe :step/:steps: :where',
+ 'by_hand' => 'käsin, kuitataan tältä sivulta',
+ 'complete_step' => 'Kuittaa vaihe',
+ 'complete_step_named' => 'Kuittaa vaihe: tilaus :number, :product',
+ 'complete_title' => 'Vaihe valmis: :product',
+ 'complete_hint' => 'Materiaalit on esitäytetty. Suunniteltua suurempi määrä kirjataan hävikiksi (uusintatuloste). Vaiheen tunnit kirjataan sinulle.',
+ 'complete' => 'Kuittaa valmiiksi',
+ 'open_console' => 'Avaa koneen :machine konekäyttöliittymä',
+ 'step_done' => 'Tilauksen :number tuotteen :product vaihe kuitattu; seuraava vaihe on työlistalla.',
+ 'line_made' => 'Tilauksen :number tuote :product on valmis.',
+ 'became_ready' => '{1} Tilaus :numbers on valmis.|[2,*] Tilaukset :numbers ovat valmiita.',
+ 'pay' => 'Ota maksu',
+ 'pay_named' => 'Ota maksu: tilaus :number',
+ 'pay_title' => 'Tilauksen :number maksu, yhteensä :total',
+ 'take_payment' => 'Kirjaa maksu',
+ 'paid' => 'Tilaus :number maksettu: :total, :method.',
+ 'cancel' => 'Peru tilaus',
+ 'cancel_named' => 'Peru tilaus :number',
+ 'cancel_title' => 'Perutaanko tilaus?',
+ 'cancel_text' => 'Tilaus poistuu koneiden työlistoilta, eikä myyntiä synny. Jo kirjattu materiaali ja tunnit jäävät.',
+ 'cancelled' => 'Tilaus :number peruttu.',
+ 'unpaid' => '{1} 1 tilaus on maksamatta; se jää avoimeksi seuraavalle päivälle.|[2,*] :count tilausta on maksamatta; ne jäävät avoimiksi seuraavalle päivälle.',
+ 'hours_note' => 'Pikamyyntitilaus :number',
+ 'reasons' => [
+ 'reprint' => 'uusintatuloste',
+ ],
+ 'errors' => [
+ 'step' => 'Vaihetta ei voitu kuitata: tilauksen tila on muuttunut. Päivitä lista.',
+ 'closed' => 'Tilaus on jo maksettu tai peruttu.',
+ ],
+ ],
'errors' => [
'receipt_email' => 'Anna kelvollinen sähköpostiosoite, esim. nimi@esimerkki.fi.',
'empty' => 'Anna vähintään yhdelle tuotteelle määrä.',
diff --git a/tests/Browser/QuickSaleOrdersAccessibilityTest.php b/tests/Browser/QuickSaleOrdersAccessibilityTest.php
new file mode 100644
index 0000000..2997814
--- /dev/null
+++ b/tests/Browser/QuickSaleOrdersAccessibilityTest.php
@@ -0,0 +1,74 @@
+user = User::factory()->management()->create(['name' => 'Johtaja']);
+ $this->actingAs($this->user);
+
+ $print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole();
+ $print->update(['uses_stock' => true]);
+ $printing = WorkTypeModel::query()->where('name', 'painotyö')->sole();
+ $this->printer = MachineModel::factory()->inUnits([$print->id])->create(['name' => 'Tarratulostin']);
+ $this->sticker = ProductModel::factory()->consumer()->create(['name' => 'Tarra', 'price_cents' => 1000, 'work_type_id' => $printing->id]);
+ $vinyl = StockItemModel::factory()->create(['name' => 'Tarramateriaali', 'unit' => 'square_metre']);
+
+ app(SaveProductionProcess::class)->execute($this->sticker->id, [
+ new ProductionStepData($this->printer->id, '0,25', $printing->id, [['stockItemId' => $vinyl->id, 'quantity' => '0,5']]),
+ new ProductionStepData(null, '0', $printing->id),
+ ]);
+ app(QuickSaleOrders::class)->send($this->user->id, new OrderData([$this->sticker->id => 2], customerName: 'Matti'));
+});
+
+it('has no accessibility issues on the pages of quick sale orders', function (string $page, string $device, string $colorScheme) {
+ $url = match ($page) {
+ 'sell' => route('sales.sell'),
+ 'product' => route('catalog.products.edit', $this->sticker->id),
+ 'console' => route('machines.console', $this->printer->id),
+ };
+
+ $visit = visit($url);
+ $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
+ $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
+
+ $visit->assertSee($page === 'product' ? __('machines.process.title') : 'Nro 1')
+ ->assertNoJavaScriptErrors()
+ ->assertNoAccessibilityIssues(level: 2);
+})->with(['sell', 'product', 'console'])->with([
+ 'desktop, light' => ['desktop', 'light'],
+ 'desktop, dark' => ['desktop', 'dark'],
+ 'mobile, light' => ['mobile', 'light'],
+ 'mobile, dark' => ['mobile', 'dark'],
+]);
+
+it('completes an order on the console and pays it on the quick sale page with the keyboard', function () {
+ visit(route('machines.console', $this->printer->id))
+ ->click('[aria-label="'.__('machines.console.order_finish_named', ['number' => 1]).'"]')
+ ->assertSee(__('machines.console.order_materials'))
+ ->assertNoAccessibilityIssues(level: 2)
+ ->click(__('machines.console.confirm_order'))
+ ->assertSee('Tilauksen 1 tuote Tarra kuitattu.');
+
+ visit(route('sales.sell'))
+ ->assertSee('vaihe 2/2')
+ ->click('[aria-label="'.__('sales.orders.complete_step_named', ['number' => 1, 'product' => 'Tarra']).'"]')
+ ->click(__('sales.orders.complete'))
+ ->assertSee('Tilauksen 1 tuote Tarra on valmis.')
+ ->click('[aria-label="'.__('sales.orders.pay_named', ['number' => 1]).'"]')
+ ->assertNoAccessibilityIssues(level: 2)
+ ->click(__('sales.orders.take_payment'))
+ ->assertSee('Tilaus 1 maksettu')
+ ->assertSee('Avaa kuitti');
+});
diff --git a/tests/Fakes/FakeQuickSaleHours.php b/tests/Fakes/FakeQuickSaleHours.php
index 57e3a3b..0276ad0 100644
--- a/tests/Fakes/FakeQuickSaleHours.php
+++ b/tests/Fakes/FakeQuickSaleHours.php
@@ -12,6 +12,11 @@ class FakeQuickSaleHours implements QuickSaleHours
public bool $fails = false;
+ public function bookForOrder(int $userId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $pickupNumber): bool
+ {
+ return $this->book($userId, $day, $workTypeId, $quarters, 0);
+ }
+
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool
{
if ($this->fails) {
diff --git a/tests/Fakes/InMemoryQuickSaleRepository.php b/tests/Fakes/InMemoryQuickSaleRepository.php
index 87f4b3f..4c19ac1 100644
--- a/tests/Fakes/InMemoryQuickSaleRepository.php
+++ b/tests/Fakes/InMemoryQuickSaleRepository.php
@@ -36,6 +36,7 @@ class InMemoryQuickSaleRepository implements QuickSaleRepository
$sale->lines(),
$sale->creditsSaleId(),
$sale->receiptEmail(),
+ $sale->orderId(),
);
}
diff --git a/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php b/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
new file mode 100644
index 0000000..f4cf8c8
--- /dev/null
+++ b/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
@@ -0,0 +1,167 @@
+travelTo(now()->setTimezone(config('app.business_timezone'))->setTime(10, 0));
+ $this->manager = User::factory()->management()->create(['name' => 'Maija Johto']);
+ $this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
+
+ $print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole();
+ $print->update(['uses_stock' => true]);
+ $this->printing = WorkTypeModel::query()->where('name', 'painotyö')->sole();
+ $this->printer = MachineModel::factory()->inUnits([$print->id])->create(['name' => 'Tarratulostin']);
+
+ $this->sticker = ProductModel::factory()->consumer()->create(['name' => 'Tarra', 'price_cents' => 1000, 'work_type_id' => $this->printing->id]);
+ $this->copy = ProductModel::factory()->consumer()->create(['name' => 'Tuloste', 'price_cents' => 100]);
+ $this->vinyl = StockItemModel::factory()->create(['name' => 'Tarramateriaali', 'unit' => 'square_metre']);
+ $this->transfer = StockItemModel::factory()->create(['name' => 'Siirtotarrapaperi', 'unit' => 'sheet']);
+
+ $this->actingAs($this->manager);
+ Livewire::test('machines::production-process', ['productId' => $this->sticker->id])
+ ->call('addStep')
+ ->set('steps.0.machine_id', (string) $this->printer->id)
+ ->set('steps.0.duration', '0,25')
+ ->call('addMaterial', 0)
+ ->set('steps.0.materials.0.stock_item_id', (string) $this->vinyl->id)
+ ->set('steps.0.materials.0.quantity', '0,5')
+ ->call('addStep')
+ ->set('steps.1.machine_id', '')
+ ->set('steps.1.duration', '0')
+ ->call('addMaterial', 1)
+ ->set('steps.1.materials.0.stock_item_id', (string) $this->transfer->id)
+ ->set('steps.1.materials.0.quantity', '1')
+ ->call('save')
+ ->assertHasNoErrors()
+ ->assertSet('message', __('machines.process.saved'));
+
+ $this->actingAs($this->employee);
+});
+
+function sendOrder(object $test): mixed
+{
+ return Livewire::test('sales::sell')
+ ->call('addProduct', $test->sticker->id)
+ ->call('addProduct', $test->sticker->id)
+ ->call('addProduct', $test->copy->id)
+ ->assertSee(__('sales.orders.send'))
+ ->assertDontSee(__('sales.sell.payment_method'))
+ ->set('orderCustomerName', 'Matti')
+ ->call('save');
+}
+
+it('sends a sale with made products to production with the day\'s pickup number', function () {
+ sendOrder($this)
+ ->assertHasNoErrors()
+ ->assertSet('savedPickupNumber', 1)
+ ->assertSet('savedMessage', fn (string $message) => str_contains($message, 'Noutonumero 1'));
+
+ $order = QuickSaleOrderModel::query()->sole();
+ $line = QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole();
+
+ expect($order->customer_name)->toBe('Matti')
+ ->and($order->status)->toBe('in_production')
+ ->and(QuickSaleModel::query()->count())->toBe(0)
+ ->and(MachineQueueEntryModel::query()->sole()->only(['machine_id', 'quick_sale_order_line_id', 'production_step_position']))
+ ->toBe(['machine_id' => $this->printer->id, 'quick_sale_order_line_id' => $line->id, 'production_step_position' => 0]);
+
+ sendOrder($this)->assertSet('savedPickupNumber', 2);
+
+ Livewire::test('sales::orders')->assertSee('Nro 1')->assertSee('Matti')->assertSee('Valmistuksessa');
+});
+
+it('makes an order step by step, records materials and hours, and takes the payment', function () {
+ sendOrder($this);
+ $order = QuickSaleOrderModel::query()->sole();
+ $entry = MachineQueueEntryModel::query()->sole();
+
+ Livewire::test('machines::console', ['machine' => $this->printer->id])
+ ->assertSee('Nro 1')
+ ->assertSee('2 × Tarra')
+ ->call('startOrderComplete', $entry->id)
+ ->assertSet('orderUsed.'.$this->vinyl->id, '1')
+ ->call('changeOrderUsed', $this->vinyl->id, 1)
+ ->call('completeOrder')
+ ->assertHasNoErrors()
+ ->assertDontSee('2 × Tarra');
+
+ $movements = StockMovementModel::query()->where('stock_item_id', $this->vinyl->id)->orderBy('id')->get();
+
+ expect($movements->map->only(['kind', 'quantity_milli', 'machine_id'])->map(fn ($row) => [$row['kind']->value, $row['quantity_milli'], $row['machine_id']])->all())
+ ->toBe([['consumption', -1_000, $this->printer->id], ['write_off', -1_000, $this->printer->id]])
+ ->and($movements->last()->reason)->toBe('uusintatuloste')
+ ->and((float) TimeEntryModel::query()->sole()->hours)->toBe(0.5)
+ ->and(MachineQueueEntryModel::query()->whereNull('completed_at')->count())->toBe(0);
+
+ $line = QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole();
+
+ Livewire::test('sales::orders')
+ ->assertSee('vaihe 2/2')
+ ->call('startComplete', $line->id)
+ ->assertSet('used.'.$this->transfer->id, '2')
+ ->call('complete')
+ ->assertSet('message', 'Tilauksen 1 tuote Tarra on valmis.')
+ ->assertSee('Valmis, maksettavana')
+ ->call('startPay', $order->id)
+ ->set('paymentMethod', 'card')
+ ->call('pay')
+ ->assertHasNoErrors()
+ ->assertSet('message', fn (string $message) => str_starts_with($message, 'Tilaus 1 maksettu: 21,00'))
+ ->assertDontSee('Nro 1');
+
+ $sale = QuickSaleModel::query()->sole();
+
+ expect($sale->quick_sale_order_id)->toBe($order->id)
+ ->and($sale->total_cents)->toBe(2_100)
+ ->and($order->fresh()->status)->toBe('completed')
+ ->and(TimeEntryModel::query()->count())->toBe(1);
+});
+
+it('lets an order be paid in advance and cancelled only while unpaid', function () {
+ sendOrder($this);
+ sendOrder($this);
+ [$first, $second] = QuickSaleOrderModel::query()->orderBy('id')->get()->all();
+
+ Livewire::test('sales::orders')
+ ->call('startPay', $first->id)
+ ->call('pay')
+ ->assertSee('maksettu')
+ ->call('confirmCancel', $second->id)
+ ->call('cancel')
+ ->assertSet('message', 'Tilaus 2 peruttu.');
+
+ expect($first->fresh()->status)->toBe('in_production')
+ ->and($first->fresh()->paid_at)->not->toBeNull()
+ ->and($second->fresh()->status)->toBe('cancelled')
+ ->and(MachineQueueEntryModel::query()->whereNull('completed_at')->count())->toBe(1);
+
+ Livewire::test('sales::index')->call('confirmClose')->assertDontSee('tilaus on maksamatta');
+ sendOrder($this);
+ Livewire::test('sales::index')->assertSee('1 tilaus on maksamatta');
+});
+
+it('sells products without a process at once as before', function () {
+ Livewire::test('sales::sell')
+ ->call('addProduct', $this->copy->id)
+ ->assertSee(__('sales.sell.save'))
+ ->call('save')
+ ->assertHasNoErrors();
+
+ expect(QuickSaleModel::query()->count())->toBe(1)
+ ->and(QuickSaleOrderModel::query()->count())->toBe(0);
+});