diff --git a/app/Modules/Sales/Application/DTOs/OrderLineSummary.php b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php
index d08b498..3d44142 100644
--- a/app/Modules/Sales/Application/DTOs/OrderLineSummary.php
+++ b/app/Modules/Sales/Application/DTOs/OrderLineSummary.php
@@ -28,6 +28,7 @@ final readonly class OrderLineSummary
public ?int $currentStep,
public array $currentMaterials,
public bool $isMade,
+ public int $productId = 0,
) {}
public function hasProduction(): bool
diff --git a/app/Modules/Sales/Application/DTOs/OrderSummary.php b/app/Modules/Sales/Application/DTOs/OrderSummary.php
index 3ace268..12762ef 100644
--- a/app/Modules/Sales/Application/DTOs/OrderSummary.php
+++ b/app/Modules/Sales/Application/DTOs/OrderSummary.php
@@ -27,6 +27,7 @@ final readonly class OrderSummary
public ?int $saleId,
public int $totalCents,
public array $lines,
+ public bool $canBeChanged = false,
) {}
public function isPaid(): bool
diff --git a/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php
index 92ee619..8a993a4 100644
--- a/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php
+++ b/app/Modules/Sales/Application/UseCases/QuickSaleOrders.php
@@ -29,6 +29,7 @@ use App\Modules\Sales\Domain\Exceptions\ProductNotSellable;
use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
+use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
@@ -72,6 +73,70 @@ final class QuickSaleOrders
* @throws OrderHasNoProduction
*/
public function send(int $sellerId, OrderData $data): OrderResult
+ {
+ $lines = $this->lines($data);
+ $now = $this->clock->now();
+ $today = $this->clock->today();
+
+ return $this->transactions->run(function () use ($sellerId, $data, $lines, $now, $today): OrderResult {
+ $order = QuickSaleOrder::place($today, $this->orders->nextPickupNumber($today), $now, $sellerId, $data->customerId, $data->customerName, $lines);
+ $order = $this->orders->save($order);
+ $this->enqueueFirstSteps($order);
+
+ return $this->result($order);
+ });
+ }
+
+ /**
+ * Changes an order's products and customer before making has started
+ * on any line (spec 19.7): the lines are replaced with the products'
+ * current prices and processes, and the work lists follow. The pickup
+ * number stays.
+ *
+ * @throws QuickSaleOrderNotFound
+ * @throws QuickSaleOrderClosed
+ * @throws QuickSaleOrderInProduction
+ * @throws ProductNotSellable
+ * @throws InvalidQuantity
+ * @throws QuickSaleEmpty
+ * @throws QuickSaleCustomerNotFound
+ * @throws OrderHasNoProduction
+ */
+ public function change(int $orderId, OrderData $data): OrderResult
+ {
+ $lines = $this->lines($data);
+
+ return $this->transactions->run(function () use ($orderId, $data, $lines): OrderResult {
+ $order = $this->orders->lockById($orderId) ?? throw new QuickSaleOrderNotFound;
+ $oldLines = $order->lines();
+
+ $order->change($data->customerId, $data->customerName, $lines);
+
+ foreach ($oldLines as $line) {
+ if ($line->isInProduction()) {
+ $this->queue->remove((int) $line->id());
+ }
+ }
+
+ $order = $this->orders->save($order);
+ $this->enqueueFirstSteps($order);
+
+ return $this->result($order);
+ });
+ }
+
+ /**
+ * New order lines of the products with their current prices and
+ * production processes.
+ *
+ * @return list
+ *
+ * @throws ProductNotSellable
+ * @throws InvalidQuantity
+ * @throws QuickSaleCustomerNotFound
+ * @throws OrderHasNoProduction
+ */
+ private function lines(OrderData $data): array
{
$sellable = [];
foreach ($this->products->sellable() as $product) {
@@ -89,7 +154,6 @@ final class QuickSaleOrders
}
$now = $this->clock->now();
- $today = $this->clock->today();
$lines = [];
foreach ($data->quantities as $productId => $quantity) {
@@ -101,22 +165,25 @@ final class QuickSaleOrders
);
}
- return $this->transactions->run(function () use ($sellerId, $data, $lines, $now, $today): OrderResult {
- $order = QuickSaleOrder::place($today, $this->orders->nextPickupNumber($today), $now, $sellerId, $data->customerId, $data->customerName, $lines);
- $order = $this->orders->save($order);
+ return $lines;
+ }
- foreach ($order->lines() as $line) {
- $step = $line->currentStep();
+ private function enqueueFirstSteps(QuickSaleOrder $order): void
+ {
+ foreach ($order->lines() as $line) {
+ $step = $line->currentStep();
- if ($step !== null && $step->machineId !== null) {
- $this->queue->enqueue((int) $line->id(), 0, $step->machineId, $today);
- }
+ if ($step !== null && $step->machineId !== null) {
+ $this->queue->enqueue((int) $line->id(), 0, $step->machineId, $order->orderedOn());
}
+ }
+ }
- $total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines()));
+ private function result(QuickSaleOrder $order): OrderResult
+ {
+ $total = array_sum(array_map(fn (OrderLine $line): int => $line->sale()->totalCents(), $order->lines()));
- return new OrderResult((int) $order->id(), $order->pickupNumber(), $total);
- });
+ return new OrderResult((int) $order->id(), $order->pickupNumber(), $total);
}
/**
diff --git a/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php
index 908153d..43a341d 100644
--- a/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php
+++ b/app/Modules/Sales/Domain/Entities/QuickSaleOrder.php
@@ -7,6 +7,7 @@ namespace App\Modules\Sales\Domain\Entities;
use App\Modules\Sales\Domain\Enums\OrderStatus;
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
+use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid;
use DateTimeImmutable;
@@ -121,6 +122,54 @@ final class QuickSaleOrder
$this->cancelledBy = $userId;
}
+ /**
+ * Whether no step has been completed on any line yet.
+ */
+ public function canBeChanged(): bool
+ {
+ if ($this->paidAt !== null || $this->cancelledAt !== null) {
+ return false;
+ }
+
+ foreach ($this->lines as $line) {
+ if ($line->hasStarted()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Replaces the products and the customer before making has started; the
+ * pickup number stays.
+ *
+ * @param list $lines
+ *
+ * @throws QuickSaleOrderClosed
+ * @throws QuickSaleOrderInProduction
+ * @throws QuickSaleEmpty
+ */
+ public function change(?int $customerId, ?string $customerName, array $lines): void
+ {
+ if ($this->paidAt !== null || $this->cancelledAt !== null) {
+ throw new QuickSaleOrderClosed;
+ }
+
+ if (! $this->canBeChanged()) {
+ throw new QuickSaleOrderInProduction;
+ }
+
+ if ($lines === []) {
+ throw new QuickSaleEmpty;
+ }
+
+ $customerName = $customerName === null ? null : mb_substr(trim($customerName), 0, 150);
+ $this->customerId = $customerId;
+ $this->customerName = $customerName === '' ? null : $customerName;
+ $this->lines = $lines;
+ }
+
public function lineById(int $lineId): ?OrderLine
{
foreach ($this->lines as $line) {
diff --git a/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php b/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php
new file mode 100644
index 0000000..e992dba
--- /dev/null
+++ b/app/Modules/Sales/Domain/Exceptions/QuickSaleOrderInProduction.php
@@ -0,0 +1,15 @@
+sale?->id,
totalCents: array_sum(array_map(fn (OrderLineSummary $line): int => $line->totalCents, $lines)),
lines: $lines,
+ canBeChanged: $model->paid_at === null && $model->cancelled_at === null && $model->lines->every(
+ fn (QuickSaleOrderLineModel $line): bool => $line->production_steps === [] || $line->current_step === 0,
+ ),
);
})->values()->all();
}
@@ -110,6 +113,7 @@ class EloquentQuickSaleOrderQueries implements QuickSaleOrderQueries
currentStep: $line->current_step,
currentMaterials: array_map(fn (array $material): array => ['stockItemId' => (int) $material['stockItemId'], 'quantityMilli' => (int) $material['quantityMilli']], $current['materials'] ?? []),
isMade: $line->made_at !== null,
+ productId: $line->product_id,
);
}
diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php
index 3bc7628..bbcd83d 100644
--- a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php
+++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleOrderRepository.php
@@ -55,6 +55,8 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository
'cancelled_by' => $order->cancelledBy(),
])->save();
+ $keptIds = [];
+
foreach ($order->lines() as $index => $line) {
$lineModel = $line->id() === null ? new QuickSaleOrderLineModel(['quick_sale_order_id' => $model->id]) : QuickSaleOrderLineModel::query()->findOrFail($line->id());
@@ -69,8 +71,12 @@ class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository
'made_at' => $line->madeAt()?->format('Y-m-d H:i:s'),
'sort_order' => $index + 1,
])->save();
+ $keptIds[] = $lineModel->id;
}
+ // Lines left out of a changed order are removed (nothing refers to them before making starts).
+ QuickSaleOrderLineModel::query()->where('quick_sale_order_id', $model->id)->whereNotIn('id', $keptIds)->delete();
+
return $this->lockById($model->id) ?? $order;
}
diff --git a/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php
index fd70473..fefd959 100644
--- a/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php
+++ b/app/Modules/Sales/Presentation/Livewire/⚡orders.blade.php
@@ -226,6 +226,13 @@ new class extends Component
$this->js("document.getElementById('orders-status')?.focus()");
}
+ public function edit(int $orderId): void
+ {
+ $this->authorize('sales.use');
+
+ $this->dispatch('edit-quick-sale-order', orderId: $this->order($orderId)->id);
+ }
+
public function confirmCancel(int $orderId): void
{
$this->authorize('sales.use');
@@ -408,6 +415,9 @@ new class extends Component
@else
+ @if ($order->canBeChanged)
+
+ @endif
@endif
diff --git a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php
index b33f1b1..cd66f12 100644
--- a/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php
+++ b/app/Modules/Sales/Presentation/Livewire/⚡sell.blade.php
@@ -4,6 +4,10 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
use App\Modules\Sales\Application\Contracts\ProductionProcesses;
+use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
+use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderClosed;
+use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderInProduction;
+use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderNotFound;
use App\Modules\Sales\Application\DTOs\OrderData;
use App\Modules\Sales\Application\DTOs\SaleData;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
@@ -22,6 +26,7 @@ use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
+use Livewire\Attributes\On;
use Livewire\Component;
/**
@@ -74,6 +79,57 @@ new class extends Component
public string $orderCustomerName = '';
+ /**
+ * The open order being changed on this form, if any (spec 19.7).
+ */
+ #[Locked]
+ public ?int $editingOrderId = null;
+
+ #[Locked]
+ public ?int $editingPickupNumber = null;
+
+ /**
+ * Loads an order whose making has not started into the form to change
+ * its products and customer.
+ */
+ #[On('edit-quick-sale-order')]
+ public function editOrder(int $orderId): void
+ {
+ $this->authorize('sales.use');
+
+ $order = app(QuickSaleOrderQueries::class)->findOrder($orderId) ?? abort(404);
+
+ if (! $order->canBeChanged) {
+ $this->addError('sale', __('sales.orders.errors.started'));
+
+ return;
+ }
+
+ $this->reset('quantities', 'cartMessage', 'savedMessage', 'hoursMessage', 'savedSaleId', 'savedPickupNumber');
+
+ foreach ($order->lines as $line) {
+ $this->quantities[$line->productId] = $line->quantity;
+ }
+
+ $this->editingOrderId = $order->id;
+ $this->editingPickupNumber = $order->pickupNumber;
+ $this->customerId = $order->customerId;
+ $this->customerName = $order->customerId === null ? '' : (string) $order->customerName;
+ $this->orderCustomerName = $order->customerId === null ? (string) $order->customerName : '';
+ $this->resetErrorBag();
+ $this->forgetLines();
+ $this->cartMessage = __('sales.orders.editing', ['number' => $order->pickupNumber]);
+ $this->js("document.getElementById('cart-heading')?.focus()");
+ }
+
+ public function stopEditing(): void
+ {
+ $this->reset('quantities', 'customerSearch', 'customerId', 'customerName', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
+ $this->forgetLines();
+ $this->cartMessage = __('sales.orders.editing_stopped');
+ $this->js("document.getElementById('cart-heading')?.focus()");
+ }
+
public function mount(): void
{
$this->authorize('sales.use');
@@ -257,7 +313,7 @@ new class extends Component
$this->savedSaleId = null;
$this->savedPickupNumber = null;
- if ($this->isOrder()) {
+ if ($this->isOrder() || $this->editingOrderId !== null) {
$this->sendOrder($orders);
return;
@@ -334,11 +390,24 @@ new class extends Component
{
$this->validate(['orderCustomerName' => ['nullable', 'string', 'max:150']]);
+ $data = new OrderData($this->quantities, $this->customerId, $this->orderCustomerName);
+
try {
- $result = $orders->send((int) auth()->id(), new OrderData($this->quantities, $this->customerId, $this->orderCustomerName));
- } catch (QuickSaleEmpty|InvalidQuantity|OrderHasNoProduction) {
+ $result = $this->editingOrderId === null
+ ? $orders->send((int) auth()->id(), $data)
+ : $orders->change($this->editingOrderId, $data);
+ } catch (QuickSaleEmpty|InvalidQuantity) {
$this->addError('quantities', __('sales.errors.empty'));
+ return;
+ } catch (OrderHasNoProduction) {
+ $this->addError('quantities', __($this->editingOrderId === null ? 'sales.errors.empty' : 'sales.orders.errors.no_production'));
+
+ return;
+ } catch (QuickSaleOrderInProduction|QuickSaleOrderClosed|QuickSaleOrderNotFound) {
+ $this->addError('sale', __('sales.orders.errors.started'));
+ $this->stopEditing();
+
return;
} catch (ProductNotSellable $exception) {
unset($this->quantities[$exception->id], $this->products);
@@ -354,9 +423,9 @@ new class extends Component
}
$this->savedPickupNumber = $result->pickupNumber;
- $this->savedMessage = __('sales.orders.sent', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]);
+ $this->savedMessage = __($this->editingOrderId === null ? 'sales.orders.sent' : 'sales.orders.changed', ['number' => $result->pickupNumber, 'total' => $this->money($result->totalCents)]);
- $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName');
+ $this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail', 'orderCustomerName', 'editingOrderId', 'editingPickupNumber');
$this->forgetLines();
$this->dispatch('quick-sale-orders-changed');
@@ -536,9 +605,16 @@ new class extends Component
- @php($isOrder = $this->isOrder())
+ @php($isOrder = $this->isOrder() || $editingOrderId !== null)
@endif
diff --git a/lang/en/sales.php b/lang/en/sales.php
index efffac9..9430c37 100644
--- a/lang/en/sales.php
+++ b/lang/en/sales.php
@@ -186,6 +186,14 @@ return [
'paid' => 'Order :number paid: :total, :method.',
'cancel' => 'Cancel order',
'cancel_named' => 'Cancel order :number',
+ 'change' => 'Change',
+ 'change_named' => 'Change order :number',
+ 'editing' => 'You are changing order :number. Its products and customer are in the cart.',
+ 'editing_notice' => 'You are changing order :number. The pickup number stays the same.',
+ 'stop_editing' => 'Discard change',
+ 'editing_stopped' => 'Order change discarded; the cart is empty.',
+ 'save_change' => 'Save order change',
+ 'changed' => 'Order :number changed, total :total.',
'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.',
@@ -197,6 +205,8 @@ return [
'errors' => [
'step' => 'The step could not be completed: the order has changed. Refresh the list.',
'closed' => 'The order is already paid or cancelled.',
+ 'started' => 'The order can no longer be changed: making has started or it is paid or cancelled.',
+ 'no_production' => 'An order needs at least one product that is made. Sell the other products as an ordinary sale.',
],
],
'errors' => [
diff --git a/lang/fi/sales.php b/lang/fi/sales.php
index c56ba84..588accc 100644
--- a/lang/fi/sales.php
+++ b/lang/fi/sales.php
@@ -186,6 +186,14 @@ return [
'paid' => 'Tilaus :number maksettu: :total, :method.',
'cancel' => 'Peru tilaus',
'cancel_named' => 'Peru tilaus :number',
+ 'change' => 'Muuta',
+ 'change_named' => 'Muuta tilausta :number',
+ 'editing' => 'Muutat tilausta :number. Tuotteet ja asiakas on tuotu ostoskoriin.',
+ 'editing_notice' => 'Muutat tilausta :number. Noutonumero pysyy samana.',
+ 'stop_editing' => 'Peru muutos',
+ 'editing_stopped' => 'Tilauksen muutos peruttu; ostoskori tyhjennetty.',
+ 'save_change' => 'Tallenna tilauksen muutos',
+ 'changed' => 'Tilaus :number muutettu, yhteensä :total.',
'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.',
@@ -197,6 +205,8 @@ return [
'errors' => [
'step' => 'Vaihetta ei voitu kuitata: tilauksen tila on muuttunut. Päivitä lista.',
'closed' => 'Tilaus on jo maksettu tai peruttu.',
+ 'started' => 'Tilausta ei voi enää muuttaa: valmistus on alkanut tai tilaus on maksettu tai peruttu.',
+ 'no_production' => 'Tilauksessa pitää olla vähintään yksi valmistettava tuote. Myy muut tuotteet tavallisena myyntinä.',
],
],
'errors' => [
diff --git a/tests/Browser/QuickSaleOrdersAccessibilityTest.php b/tests/Browser/QuickSaleOrdersAccessibilityTest.php
index 2997814..c4800f9 100644
--- a/tests/Browser/QuickSaleOrdersAccessibilityTest.php
+++ b/tests/Browser/QuickSaleOrdersAccessibilityTest.php
@@ -72,3 +72,45 @@ it('completes an order on the console and pays it on the quick sale page with th
->assertSee('Tilaus 1 maksettu')
->assertSee('Avaa kuitti');
});
+
+it('changes an order with the keyboard, moving focus to the cart', function () {
+ visit(route('sales.sell'))
+ ->keys('[aria-label="'.__('sales.orders.change_named', ['number' => 1]).'"]', 'Enter')
+ ->assertSee(__('sales.orders.editing_notice', ['number' => 1]))
+ ->assertScript('document.activeElement.id', 'cart-heading')
+ ->assertSee(__('sales.orders.save_change'))
+ ->assertNoAccessibilityIssues(level: 2)
+ ->keys('#stop-editing', 'Enter')
+ ->assertScript('document.activeElement.id', 'cart-heading')
+ ->assertDontSee(__('sales.orders.editing_notice', ['number' => 1]))
+ ->keys('[aria-label="'.__('sales.orders.change_named', ['number' => 1]).'"]', 'Enter')
+ ->keys('#order-customer-name', 'Control+a')
+ ->type('#order-customer-name', 'Liisa')
+ ->keys('#order-customer-name', 'Enter')
+ ->assertSee('Tilaus 1 muutettu')
+ ->assertSee('Liisa');
+});
+
+it('cancels an order in a dialog that takes and returns focus', function () {
+ $cancel = '[aria-label="'.__('sales.orders.cancel_named', ['number' => 1]).'"]';
+
+ visit(route('sales.sell'))
+ ->keys($cancel, 'Enter')
+ ->assertScript('document.getElementById("cancel-order-dialog").open', true)
+ ->assertScript('document.getElementById("cancel-order-dialog").contains(document.activeElement)', true)
+ ->assertNoAccessibilityIssues(level: 2)
+ ->keys('#cancel-order-dialog', 'Escape')
+ ->assertScript('document.getElementById("cancel-order-dialog").open', false)
+ ->assertScript('document.activeElement.getAttribute("aria-label")', __('sales.orders.cancel_named', ['number' => 1]))
+ ->keys($cancel, 'Enter')
+ ->click('#cancel-order-dialog button[wire\:click="cancel"]')
+ ->assertSee('Tilaus 1 peruttu.')
+ ->assertScript('document.activeElement.id', 'orders-status');
+});
+
+it('moves a production step with the keyboard, keeping focus', function () {
+ visit(route('catalog.products.edit', $this->sticker->id))
+ ->keys('[aria-label="'.__('catalog.workflows.move_up_named', ['number' => 2]).'"]', 'Enter')
+ ->assertScript('document.activeElement.getAttribute("aria-label")', __('catalog.workflows.move_up_named', ['number' => 1]))
+ ->assertNoAccessibilityIssues(level: 2);
+});
diff --git a/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php b/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
index f4cf8c8..2d3ccdd 100644
--- a/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
+++ b/tests/Feature/Modules/Sales/QuickSaleOrdersTest.php
@@ -165,3 +165,57 @@ it('sells products without a process at once as before', function () {
expect(QuickSaleModel::query()->count())->toBe(1)
->and(QuickSaleOrderModel::query()->count())->toBe(0);
});
+
+it('changes an order before making starts and keeps its pickup number', function () {
+ sendOrder($this);
+ $order = QuickSaleOrderModel::query()->sole();
+ $oldLineIds = QuickSaleOrderLineModel::query()->pluck('id')->all();
+
+ Livewire::test('sales::orders')
+ ->assertSee(__('sales.orders.change_named', ['number' => 1]))
+ ->call('edit', $order->id)
+ ->assertDispatched('edit-quick-sale-order', orderId: $order->id);
+
+ Livewire::test('sales::sell')
+ ->call('editOrder', $order->id)
+ ->assertSet('editingPickupNumber', 1)
+ ->assertSet('quantities', [$this->sticker->id => 2, $this->copy->id => 1])
+ ->assertSet('orderCustomerName', 'Matti')
+ ->assertSee(__('sales.orders.save_change'))
+ ->call('addProduct', $this->sticker->id)
+ ->set('orderCustomerName', 'Liisa')
+ ->call('save')
+ ->assertHasNoErrors()
+ ->assertSet('editingOrderId', null)
+ ->assertSet('savedMessage', fn (string $message) => str_starts_with($message, 'Tilaus 1 muutettu, yhteensä 31,00'));
+
+ $sticker = QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole();
+
+ expect(QuickSaleOrderModel::query()->sole()->only(['id', 'pickup_number', 'customer_name']))
+ ->toBe(['id' => $order->id, 'pickup_number' => 1, 'customer_name' => 'Liisa'])
+ ->and($sticker->quantity)->toBe(3)
+ ->and($sticker->id)->not->toBeIn($oldLineIds)
+ ->and(QuickSaleOrderLineModel::query()->count())->toBe(2)
+ ->and(MachineQueueEntryModel::query()->sole()->quick_sale_order_line_id)->toBe($sticker->id);
+});
+
+it('refuses to change an order once a step is completed', function () {
+ sendOrder($this);
+ $order = QuickSaleOrderModel::query()->sole();
+
+ $sell = Livewire::test('sales::sell')->call('editOrder', $order->id)->assertSet('editingOrderId', $order->id);
+
+ Livewire::test('machines::console', ['machine' => $this->printer->id])
+ ->call('startOrderComplete', MachineQueueEntryModel::query()->sole()->id)
+ ->call('completeOrder');
+
+ $sell->call('addProduct', $this->sticker->id)
+ ->call('save')
+ ->assertHasErrors('sale')
+ ->assertSet('editingOrderId', null);
+
+ expect(QuickSaleOrderLineModel::query()->where('product_name', 'Tarra')->sole()->quantity)->toBe(2);
+
+ Livewire::test('sales::orders')->assertDontSee(__('sales.orders.change_named', ['number' => 1]));
+ Livewire::test('sales::sell')->call('editOrder', $order->id)->assertHasErrors('sale')->assertSet('editingOrderId', null);
+});