Make quick sale products on machines as orders paid when ready

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 17:11:54 +02:00
co-authored by Claude Sonnet 5.5
parent 920fecdeb2
commit 38b8075a9c
58 changed files with 3435 additions and 26 deletions
@@ -249,4 +249,10 @@ new class extends Component
<x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
@if ($productId !== null && $form->is_consumer_product)
@can('machines.manage')
<livewire:machines::production-process :product-id="$productId" :wire:key="'process-'.$productId" />
@endcan
@endif
</div>
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Application\Contracts;
use App\Modules\Machines\Application\DTOs\ProductionStepSummary;
/**
* Production processes of quick sale products (spec 19.7). The Sales
* module reads them through this contract when an order is sent.
*/
interface ProductionProcessQueries
{
/**
* @return list<ProductionStepSummary> In order; empty without a process.
*/
public function processOf(int $productId): array;
/**
* @param list<int> $productIds
* @return array<int, list<ProductionStepSummary>> By product id; products without a process are left out.
*/
public function processesOf(array $productIds): array;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Application\DTOs;
/**
* A production step as entered: the machine (null: by hand), the duration
* per piece in hours as typed ("0,25"), the work type its hours go to, and
* materials per piece with quantities as typed.
*/
final readonly class ProductionStepData
{
/**
* @param list<array{stockItemId: int, quantity: string}> $materials
*/
public function __construct(
public ?int $machineId,
public string $duration,
public int $workTypeId,
public array $materials = [],
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Application\DTOs;
/**
* A step of a product's production process as stored. $position counts
* from 0. Materials are per piece, quantities in thousandths of the item's
* unit (the unit key in $unit).
*/
final readonly class ProductionStepSummary
{
/**
* @param list<array{stockItemId: int, itemName: string, unit: string, quantityMilli: int}> $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,
) {}
}
@@ -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.
*/
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Application\UseCases;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Machines\Application\DTOs\ProductionStepData;
use App\Modules\Machines\Domain\Contracts\MachineRepository;
use App\Modules\Machines\Domain\Contracts\ProductionProcessRepository;
use App\Modules\Machines\Domain\Exceptions\InvalidProductionStep;
use App\Modules\Machines\Domain\Exceptions\InvalidReading;
use App\Modules\Machines\Domain\Exceptions\ProductionMachineNotAllowed;
use App\Modules\Machines\Domain\ValueObjects\ProductionStep;
use App\Modules\Machines\Domain\ValueObjects\Reading;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Saves a consumer product's production process (management, spec 19.7).
* A step's machine must be in use and belong to the service unit of the
* product's work type (any unit using stock when the product has none).
* Orders already sent keep their own copy of the process.
*/
final class SaveProductionProcess
{
public function __construct(
private ProductionProcessRepository $processes,
private MachineRepository $machines,
private PriceListQueries $priceList,
private CatalogQueries $catalog,
private TransactionManager $transactions,
) {}
/**
* @param list<ProductionStepData> $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<int>
*/
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<array{stockItemId: int, quantity: string}> $materials
* @return list<array{stockItemId: int, quantityMilli: int}>
*
* @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;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Domain\Contracts;
use App\Modules\Machines\Domain\ValueObjects\ProductionStep;
interface ProductionProcessRepository
{
/**
* Replaces the product's production process; no steps removes it.
*
* @param list<ProductionStep> $steps
*/
public function replace(int $productId, array $steps): void;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidProductionStep extends DomainException
{
public function __construct()
{
parent::__construct('A production step needs a work type, a duration of 0-24 h in quarters and materials with positive quantities.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ProductionMachineNotAllowed extends DomainException
{
public function __construct()
{
parent::__construct('The machine of a production step must be in use and belong to the service unit of the work type of the product.');
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Machines\Domain\ValueObjects;
use App\Modules\Machines\Domain\Exceptions\InvalidProductionStep;
/**
* A step of a product's production process (spec 19.7): made on a machine
* or by hand ($machineId null, e.g. finishing or lamination), taking
* $durationQuarters per piece on $workTypeId, and using materials per
* piece (stock item ids with quantities in thousandths). A step by hand
* holds the auxiliary materials no machine needs.
*/
final readonly class ProductionStep
{
public const int MAX_QUARTERS = 96;
/**
* @param list<array{stockItemId: int, quantityMilli: int}> $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;
}
}
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Modules\Machines\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Machines\Application\Contracts\ProductionProcessQueries;
use App\Modules\Machines\Application\DTOs\ProductionStepSummary;
use App\Modules\Machines\Domain\Contracts\ProductionProcessRepository;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
use Illuminate\Support\Facades\DB;
/**
* Production steps and their materials, stored in production_steps and
* production_step_materials.
*/
class EloquentProductionProcesses implements ProductionProcessQueries, ProductionProcessRepository
{
public function __construct(
private CatalogQueries $catalog,
private StockQueries $stock,
) {}
public function replace(int $productId, array $steps): void
{
DB::table('production_steps')->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;
}
}
@@ -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
@@ -18,6 +18,9 @@ use App\Modules\Machines\Application\DTOs\QueueRow;
use App\Modules\Machines\Application\UseCases\MachineMaintenance;
use App\Modules\Machines\Application\UseCases\MachineWorkList;
use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\Users\Application\Contracts\Clock;
@@ -97,6 +100,18 @@ new #[Layout('layouts.console')] class extends Component
#[Locked]
public string $refreshMessage = '';
#[Locked]
public ?int $completingEntryId = null;
/**
* Material used per stock item while completing an order's step.
*
* @var array<int, string>
*/
public array $orderUsed = [];
public string $moveToMachineId = '';
public function mount(int $machine): void
{
$this->authorize('machines.use');
@@ -131,6 +146,109 @@ new #[Layout('layouts.console')] class extends Component
return app(MachineQueries::class)->rowsOn($this->machineId, $this->day(), $this->today);
}
/**
* The quick sale order lines on the list, by line id.
*
* @return array<int, OrderLineSummary>
*/
#[Computed]
public function orderLines(): array
{
$ids = array_values(array_filter(array_map(fn (QueueRow $row): ?int => $row->orderLineId, $this->rows)));
return app(QuickSaleOrderQueries::class)->lines($ids);
}
/**
* Machines of the same type to move an order's step to.
*
* @return list<MachineSummary>
*/
#[Computed]
public function sameTypeMachines(): array
{
return array_values(array_filter(
app(MachineQueries::class)->machines(),
fn (MachineSummary $machine): bool => $machine->type === $this->machine->type && $machine->id !== $this->machineId,
));
}
public function startOrderComplete(int $entryId): void
{
$this->authorize('sales.use');
$row = $this->row($entryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
$this->completingEntryId = $entryId;
$this->orderUsed = [];
foreach ($line->currentMaterials as $material) {
$this->orderUsed[$material['stockItemId']] = StockQuantity::inputValue($material['quantityMilli'] * $line->quantity);
}
$this->js("setTimeout(() => document.getElementById('order-complete-{$entryId}')?.focus())");
}
public function changeOrderUsed(int $itemId, int $step): void
{
$current = StockQuantity::parse($this->orderUsed[$itemId] ?? '0')?->milli ?? 0;
$this->orderUsed[$itemId] = StockQuantity::inputValue(max(0, $current + $step * 1000));
}
public function completeOrder(QuickSaleOrders $orders): void
{
$this->authorize('sales.use');
$row = $this->row((int) $this->completingEntryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
$used = [];
foreach ($this->orderUsed as $itemId => $value) {
try {
$used[(int) $itemId] = StockQuantity::parse($value)?->milli ?? 0;
} catch (DomainException) {
$this->addError('orderUsed.'.$itemId, __('inventory.errors.quantity'));
return;
}
}
try {
$orders->completeStep($line->id, (int) $row->stepPosition, (int) auth()->id(), $used);
} catch (DomainException) {
$this->message = __('sales.orders.errors.step');
$this->completingEntryId = null;
$this->reload();
return;
}
$this->message = __('machines.console.order_done', ['number' => $line->pickupNumber, 'product' => $line->productName]);
$this->completingEntryId = null;
$this->reload();
$this->js("document.getElementById('console-status')?.focus()");
}
public function moveOrder(int $entryId, MachineWorkList $workList): void
{
$this->authorize('machines.use');
$row = $this->row($entryId);
$line = $this->orderLines[$row->orderLineId] ?? abort(404);
try {
$workList->moveOrderLine($entryId, (int) $this->moveToMachineId);
} catch (DomainException) {
$this->addError('moveToMachineId', __('machines.errors.machine'));
return;
}
$this->message = __('machines.console.order_moved', ['number' => $line->pickupNumber, 'machine' => app(MachineQueries::class)->findMachine((int) $this->moveToMachineId)->name ?? '']);
$this->moveToMachineId = '';
$this->reload();
}
#[Computed]
public function selectedRow(): ?QueueRow
{
@@ -455,7 +573,7 @@ new #[Layout('layouts.console')] class extends Component
*/
private function reload(): int
{
unset($this->rows, $this->maintenance, $this->items, $this->selectedRow, $this->machine);
unset($this->rows, $this->maintenance, $this->items, $this->selectedRow, $this->machine, $this->orderLines);
$ids = array_map(fn (QueueRow $row): int => $row->entryId, $this->rows);
$new = count(array_diff($ids, $this->knownEntryIds));
@@ -544,7 +662,61 @@ new #[Layout('layouts.console')] class extends Component
<p class="text-base font-semibold">{{ __('machines.console.next') }}</p>
@endif
@if ($row->isOrder())
<p class="font-semibold">{{ __('machines.show.order') }}</p>
@php($line = $this->orderLines[$row->orderLineId] ?? null)
<p class="flex items-center gap-2 font-semibold">
<x-icon name="user" class="size-5" aria-hidden="true" />
{{ __('machines.show.order') }}
</p>
@if ($line !== null)
<p class="text-4xl font-bold">{{ __('sales.orders.pickup', ['number' => $line->pickupNumber]) }}</p>
<p class="text-xl font-semibold">{{ $line->quantity }} × {{ $line->productName }}</p>
<p class="text-base">
{{ $line->customerName ?? __('sales.anonymous') }} · {{ __('machines.console.ordered_at', ['time' => substr($line->orderedAt, 11)]) }}
@if (count($line->stepMachineIds) > 1)
· {{ __('machines.console.order_step', ['step' => (int) $row->stepPosition + 1, 'steps' => count($line->stepMachineIds)]) }}
@endif
</p>
@if (! $nextDay)
@if ($completingEntryId === $row->entryId)
@php($items = app(\App\Modules\Inventory\Application\Contracts\StockQueries::class)->itemsByIds(array_map(fn ($material) => $material['stockItemId'], $line->currentMaterials)))
<form wire:submit="completeOrder" class="space-y-3 rounded-lg border border-zinc-300 p-3 dark:border-zinc-600" novalidate>
<p id="order-complete-{{ $row->entryId }}" tabindex="-1" class="font-semibold focus:outline-none">{{ __('machines.console.order_materials') }}</p>
@foreach ($line->currentMaterials as $material)
@php($item = $items[$material['stockItemId']] ?? null)
<div wire:key="order-material-{{ $material['stockItemId'] }}" class="flex flex-wrap items-end gap-2">
<button type="button" wire:click="changeOrderUsed({{ $material['stockItemId'] }}, -1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.less_of', ['item' => $item->name ?? '']) }}">−</button>
<div class="w-40">
<x-input id="order-used-{{ $material['stockItemId'] }}" wire:model="orderUsed.{{ $material['stockItemId'] }}" inputmode="decimal" :label="($item->name ?? '').' ('.__('inventory.units.'.($item->unit->value ?? 'piece')).')'" autocomplete="off" />
</div>
<button type="button" wire:click="changeOrderUsed({{ $material['stockItemId'] }}, 1)" class="{{ $secondary }} text-2xl" aria-label="{{ __('machines.console.more_of', ['item' => $item->name ?? '']) }}">+</button>
</div>
@endforeach
<p class="text-base">{{ __('sales.orders.complete_hint') }}</p>
<button type="submit" class="{{ $primary }} w-full text-xl">{{ __('machines.console.confirm_order') }}</button>
</form>
@else
<div class="flex flex-wrap items-end gap-2">
<button type="button" wire:click="startOrderComplete({{ $row->entryId }})" class="{{ $primary }} text-xl" aria-label="{{ __('machines.console.order_finish_named', ['number' => $line->pickupNumber]) }}">
<x-icon name="check" class="size-6" aria-hidden="true" />
{{ __('machines.console.finish') }}
</button>
@if ($this->sameTypeMachines !== [])
<form wire:submit="moveOrder({{ $row->entryId }})" class="flex flex-wrap items-end gap-2">
<div class="min-w-40">
<x-select.native id="move-order-{{ $row->entryId }}" wire:model="moveToMachineId" :label="__('machines.console.move_to')" :aria-label="__('machines.console.move_to_named', ['number' => $line->pickupNumber])">
<option value="">{{ __('machines.task.choose_machine') }}</option>
@foreach ($this->sameTypeMachines as $other)
<option value="{{ $other->id }}">{{ $other->name }}</option>
@endforeach
</x-select.native>
</div>
<button type="submit" class="{{ $secondary }}">{{ __('machines.console.move') }}</button>
</form>
@endif
</div>
@endif
@endif
@endif
@elseif ($task !== null)
<p class="text-xl font-semibold break-words">{{ $task->title }}</p>
<p class="text-base">{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->customerName }}</p>
@@ -0,0 +1,280 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Machines\Application\Contracts\ProductionProcessQueries;
use App\Modules\Machines\Application\DTOs\MachineSummary;
use App\Modules\Machines\Application\DTOs\ProductionStepData;
use App\Modules\Machines\Application\UseCases\SaveProductionProcess;
use App\Modules\Machines\Domain\Exceptions\InvalidProductionStep;
use App\Modules\Machines\Domain\Exceptions\ProductionMachineNotAllowed;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A consumer product's production process on its edit page (management,
* spec 19.7): steps in order, each on a machine of the product's service
* unit or by hand, with a duration per piece, the work type its hours go
* to and materials per piece. A product with a process is sold as an order
* made before it is paid. Shown only when stock is used in a unit.
*/
new class extends Component
{
#[Locked]
public int $productId;
/**
* @var list<array{key: int, machine_id: string, duration: string, work_type_id: string, materials: list<array{key: int, stock_item_id: string, quantity: string}>}>
*/
public array $steps = [];
public int $nextKey = 1;
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('machines.manage');
foreach (app(ProductionProcessQueries::class)->processOf($this->productId) as $step) {
$this->steps[] = [
'key' => $this->nextKey++,
'machine_id' => (string) ($step->machineId ?? ''),
'duration' => rtrim(rtrim(number_format($step->durationQuarters / 4, 2, ',', ''), '0'), ','),
'work_type_id' => (string) $step->workTypeId,
'materials' => array_map(fn (array $material): array => [
'key' => $this->nextKey++,
'stock_item_id' => (string) $material['stockItemId'],
'quantity' => rtrim(rtrim(number_format($material['quantityMilli'] / 1000, 3, ',', ''), '0'), ','),
], $step->materials),
];
}
}
public function isAvailable(): bool
{
return app(CatalogQueries::class)->stockServiceUnitIds() !== [];
}
/**
* Machines of the product's work type's service unit (any unit using
* stock when the product has none or a shared one).
*
* @return list<MachineSummary>
*/
#[Computed]
public function machines(): array
{
$catalog = app(CatalogQueries::class);
$product = app(PriceListQueries::class)->findProduct($this->productId);
$workType = $product?->workTypeId === null ? null : $catalog->findWorkType($product->workTypeId);
$unit = $workType === null ? null : $catalog->findServiceUnit($workType->serviceUnitId);
$units = $unit === null || $unit->isShared ? $catalog->stockServiceUnitIds() : [$unit->id];
return app(MachineQueries::class)->machinesFor($units);
}
/**
* @return list<WorkTypeSummary>
*/
#[Computed]
public function workTypes(): array
{
$types = [];
foreach (app(CatalogQueries::class)->activeWorkTypesFor(app(CatalogQueries::class)->stockServiceUnitIds()) as $node) {
foreach ($node->workTypes as $workType) {
$types[] = $workType;
}
foreach ($node->services as $service) {
foreach ($service->workTypes as $workType) {
$types[] = $workType;
}
}
}
return $types;
}
/**
* @return list<StockItemSummary>
*/
#[Computed]
public function stockItems(): array
{
return app(StockQueries::class)->items();
}
public function addStep(): void
{
$this->authorize('machines.manage');
$product = app(PriceListQueries::class)->findProduct($this->productId);
$key = $this->nextKey++;
$this->steps[] = ['key' => $key, 'machine_id' => (string) ($this->machines[0]->id ?? ''), 'duration' => '0', 'work_type_id' => (string) ($product->workTypeId ?? ($this->workTypes[0]->id ?? '')), 'materials' => []];
$this->message = __('machines.process.step_added', ['number' => count($this->steps)]);
$this->js("document.getElementById('process-step-{$key}-machine')?.focus()");
}
public function removeStep(int $index): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index])) {
array_splice($this->steps, $index, 1);
$this->message = __('machines.process.step_removed', ['number' => $index + 1]);
$this->js("document.getElementById('process-add-step')?.focus()");
}
}
public function moveStep(int $index, string $direction): void
{
$this->authorize('machines.manage');
$target = $direction === 'up' ? $index - 1 : $index + 1;
if (! isset($this->steps[$index], $this->steps[$target])) {
return;
}
[$this->steps[$index], $this->steps[$target]] = [$this->steps[$target], $this->steps[$index]];
$this->message = __('machines.process.step_moved', ['from' => $index + 1, 'to' => $target + 1]);
$key = $this->steps[$target]['key'];
$this->js("document.getElementById('process-step-{$key}-{$direction}')?.focus()");
}
public function addMaterial(int $index): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index])) {
$key = $this->nextKey++;
$this->steps[$index]['materials'][] = ['key' => $key, 'stock_item_id' => '', 'quantity' => '1'];
$this->js("document.getElementById('process-material-{$key}-item')?.focus()");
}
}
public function removeMaterial(int $index, int $materialIndex): void
{
$this->authorize('machines.manage');
if (isset($this->steps[$index]['materials'][$materialIndex])) {
array_splice($this->steps[$index]['materials'], $materialIndex, 1);
$key = $this->steps[$index]['key'];
$this->js("document.getElementById('process-step-{$key}-add-material')?.focus()");
}
}
public function save(SaveProductionProcess $saveProcess): void
{
$this->authorize('machines.manage');
$this->resetErrorBag();
$data = [];
foreach ($this->steps as $step) {
$data[] = new ProductionStepData(
$step['machine_id'] === '' ? null : (int) $step['machine_id'],
$step['duration'],
(int) $step['work_type_id'],
array_values(array_map(
fn (array $material): array => ['stockItemId' => (int) $material['stock_item_id'], 'quantity' => $material['quantity']],
array_filter($step['materials'], fn (array $material): bool => $material['stock_item_id'] !== ''),
)),
);
}
try {
$saveProcess->execute($this->productId, $data);
} catch (InvalidProductionStep) {
$this->addError('steps', __('machines.process.errors.invalid'));
return;
} catch (ProductionMachineNotAllowed) {
$this->addError('steps', __('machines.process.errors.machine'));
return;
}
$this->message = $this->steps === [] ? __('machines.process.removed') : __('machines.process.saved');
}
};
?>
<div>
@if ($this->isAvailable())
<section aria-labelledby="process-heading" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="process-heading" class="text-xl font-semibold">{{ __('machines.process.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('machines.process.intro') }}</p>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
@error('steps')
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
<ol class="space-y-4">
@foreach ($steps as $index => $step)
<li wire:key="process-step-{{ $step['key'] }}-{{ $index }}">
<fieldset class="space-y-3 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
<legend class="px-1 font-medium">{{ __('machines.process.step', ['number' => $index + 1]) }}</legend>
<div class="grid gap-3 sm:grid-cols-3">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="process-step-{{ $step['key'] }}-machine" wire:model="steps.{{ $index }}.machine_id" :label="__('machines.process.machine')" :aria-label="__('machines.process.machine_of', ['number' => $index + 1])">
<option value="">{{ __('machines.process.by_hand') }}</option>
@foreach ($this->machines as $machine)
<option value="{{ $machine->id }}">{{ $machine->name }}</option>
@endforeach
</x-select.native>
<x-input id="process-step-{{ $step['key'] }}-duration" wire:model="steps.{{ $index }}.duration" inputmode="decimal" :label="__('machines.process.duration')" autocomplete="off" />
<x-select.native id="process-step-{{ $step['key'] }}-work-type" wire:model="steps.{{ $index }}.work_type_id" :label="__('machines.process.work_type')" :aria-label="__('machines.process.work_type_of', ['number' => $index + 1])">
@foreach ($this->workTypes as $workType)
<option value="{{ $workType->id }}">{{ $workType->name }}</option>
@endforeach
</x-select.native>
</div>
<div class="space-y-2">
<p class="text-sm font-semibold">{{ __('machines.process.materials') }}</p>
@foreach ($step['materials'] as $materialIndex => $material)
<div wire:key="process-material-{{ $material['key'] }}" class="flex flex-wrap items-end gap-2">
<div class="min-w-48 flex-1">
<x-select.native id="process-material-{{ $material['key'] }}-item" wire:model="steps.{{ $index }}.materials.{{ $materialIndex }}.stock_item_id" :label="__('machines.process.material')" :aria-label="__('machines.process.material_of', ['step' => $index + 1, 'number' => $materialIndex + 1])">
<option value="">{{ __('catalog.workflows.choose_material') }}</option>
@foreach ($this->stockItems as $stockItem)
<option value="{{ $stockItem->id }}">{{ $stockItem->name }} ({{ __('inventory.units.'.$stockItem->unit->value) }})</option>
@endforeach
</x-select.native>
</div>
<div class="w-28">
<x-input id="process-material-{{ $material['key'] }}-quantity" wire:model="steps.{{ $index }}.materials.{{ $materialIndex }}.quantity" inputmode="decimal" :label="__('machines.process.per_piece')" autocomplete="off" />
</div>
<x-button wire:click="removeMaterial({{ $index }}, {{ $materialIndex }})" subtle color="black" sm icon="trash" :aria-label="__('machines.process.remove_material', ['step' => $index + 1, 'number' => $materialIndex + 1])" />
</div>
@endforeach
<x-button id="process-step-{{ $step['key'] }}-add-material" wire:click="addMaterial({{ $index }})" subtle color="black" sm icon="plus" :text="__('catalog.workflows.add_material')" :aria-label="__('catalog.workflows.add_material_named', ['number' => $index + 1])" />
</div>
<div class="flex flex-wrap gap-2">
<x-button id="process-step-{{ $step['key'] }}-up" wire:click="moveStep({{ $index }}, 'up')" subtle color="black" sm icon="arrow-up" :aria-label="__('catalog.workflows.move_up_named', ['number' => $index + 1])" />
<x-button id="process-step-{{ $step['key'] }}-down" wire:click="moveStep({{ $index }}, 'down')" subtle color="black" sm icon="arrow-down" :aria-label="__('catalog.workflows.move_down_named', ['number' => $index + 1])" />
<x-button wire:click="removeStep({{ $index }})" subtle color="black" sm icon="trash" :text="__('catalog.workflows.remove_step')" :aria-label="__('catalog.workflows.remove_step_named', ['number' => $index + 1])" />
</div>
</fieldset>
</li>
@endforeach
</ol>
<div class="flex flex-wrap gap-2">
<x-button id="process-add-step" wire:click="addStep" subtle color="black" icon="plus" :text="__('machines.process.add_step')" />
<x-button wire:click="save" icon="check" :text="__('machines.process.save')" />
</div>
</section>
@endif
</div>
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
/**
* Records the stock used in making quick sale orders, through the
* Inventory module. Recording never stops production: a failure returns
* false.
*/
interface OrderMaterials
{
public function use(int $stockItemId, int $quantityMilli, int $orderLineId, ?int $machineId, int $userId): bool;
/**
* Records stock spoiled in production (e.g. a reprint) as a write-off.
*/
public function writeOff(int $stockItemId, int $quantityMilli, int $orderLineId, ?int $machineId, int $userId, string $reason): bool;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
use App\Modules\Sales\Domain\ValueObjects\OrderStep;
/**
* The production processes of consumer products (spec 19.7), read from the
* Machines module.
*/
interface ProductionProcesses
{
/**
* @param list<int> $productIds
* @return array<int, list<OrderStep>> By product id; products without a process are left out.
*/
public function stepsOf(array $productIds): array;
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
use DateTimeImmutable;
/**
* Puts the steps of quick sale order lines on machines' work lists and
* takes them off, through the Machines module.
*/
interface ProductionQueue
{
/**
* Puts the line's step on the machine's list for the day, with the
* customer waiting rows first.
*/
public function enqueue(int $orderLineId, int $stepPosition, int $machineId, DateTimeImmutable $day): void;
/**
* Closes the line's open row as made.
*/
public function complete(int $orderLineId, int $userId): void;
/**
* Takes the line's open row off its machine's list.
*/
public function remove(int $orderLineId): void;
}
@@ -19,4 +19,10 @@ interface QuickSaleHours
* day's hours are already approved or would pass 24 hours.
*/
public function book(int $sellerId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $saleId): bool;
/**
* Books the hours of a quick sale order's production step on the user
* who completed it, like book(); the note names the pickup number.
*/
public function bookForOrder(int $userId, DateTimeImmutable $day, int $workTypeId, int $quarters, int $pickupNumber): bool;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\DTOs\OrderSummary;
/**
* Reads quick sale orders. The Machines module reads order lines for the
* machine console through this contract.
*/
interface QuickSaleOrderQueries
{
/**
* Orders being made or waiting to be paid, and paid ones still being
* made, oldest first.
*
* @return list<OrderSummary>
*/
public function openOrders(): array;
public function findOrder(int $id): ?OrderSummary;
/**
* @param list<int> $lineIds
* @return array<int, OrderLineSummary> By line id.
*/
public function lines(array $lineIds): array;
/**
* How many orders are not yet paid (cancelled ones left out).
*/
public function unpaidCount(): int;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\DTOs;
/**
* A quick sale order as entered: quantities by product id, an optional
* customer and an optional name to call the customer by.
*/
final readonly class OrderData
{
/**
* @param array<int, int> $quantities
*/
public function __construct(
public array $quantities,
public ?int $customerId = null,
public ?string $customerName = null,
) {}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\DTOs;
/**
* A line of a quick sale order with its production: the steps (machine ids,
* null for a step by hand), the step now being made ($currentStep, from 0;
* null when made or with no process) and its materials per piece.
*/
final readonly class OrderLineSummary
{
/**
* @param list<?int> $stepMachineIds
* @param list<array{stockItemId: int, quantityMilli: int}> $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];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\DTOs;
/**
* A quick sale order sent to production: its id, the day's pickup number
* and the total with VAT.
*/
final readonly class OrderResult
{
public function __construct(
public int $orderId,
public int $pickupNumber,
public int $totalCents,
) {}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\DTOs;
use App\Modules\Sales\Domain\Enums\OrderStatus;
/**
* A quick sale order as listed. $orderedAt is "Y-m-d H:i" in the company's
* time zone; $saleId is the sale that paid it.
*/
final readonly class OrderSummary
{
/**
* @param list<OrderLineSummary> $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;
}
}
@@ -0,0 +1,245 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\UseCases;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
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\QuickSaleProducts;
use App\Modules\Sales\Application\Contracts\ReceiptMailer;
use App\Modules\Sales\Application\DTOs\OrderData;
use App\Modules\Sales\Application\DTOs\OrderResult;
use App\Modules\Sales\Application\DTOs\SaleResult;
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\Domain\Entities\OrderLine;
use App\Modules\Sales\Domain\Entities\QuickSale;
use App\Modules\Sales\Domain\Entities\QuickSaleOrder;
use App\Modules\Sales\Domain\Enums\PaymentMethod;
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
use App\Modules\Sales\Domain\Exceptions\InvalidQuantity;
use App\Modules\Sales\Domain\Exceptions\OrderHasNoProduction;
use App\Modules\Sales\Domain\Exceptions\OrderStepNotCurrent;
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\QuickSaleOrderNotFound;
use App\Modules\Sales\Domain\Exceptions\QuickSaleOrderPaid;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Quick sale orders of products made before they are paid (spec 19.7).
* Sending an order snapshots the prices and the products' production
* processes and puts each made line's first step on its machine's work
* list. Completing a step records its materials (anything over the plan
* as a reprint write-off) and hours on whoever completed it, and moves the
* line to its next step. Paying makes an ordinary quick sale on the day's
* cash day without hours (they were booked in production). An unpaid
* order can be cancelled; what was used stays recorded.
*/
final class QuickSaleOrders
{
public function __construct(
private QuickSaleOrderRepository $orders,
private QuickSaleRepository $sales,
private CashDayRepository $cashDays,
private QuickSaleProducts $products,
private ProductionProcesses $processes,
private ProductionQueue $queue,
private OrderMaterials $materials,
private QuickSaleHours $hours,
private ReceiptMailer $mailer,
private CustomerQueries $customers,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws ProductNotSellable
* @throws InvalidQuantity
* @throws QuickSaleEmpty
* @throws QuickSaleCustomerNotFound
* @throws OrderHasNoProduction
*/
public function send(int $sellerId, OrderData $data): OrderResult
{
$sellable = [];
foreach ($this->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<int, int> $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);
});
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Contracts;
use App\Modules\Sales\Domain\Entities\QuickSaleOrder;
use DateTimeImmutable;
interface QuickSaleOrderRepository
{
/**
* The order, locked until the end of the transaction.
*/
public function lockById(int $id): ?QuickSaleOrder;
/**
* The order a line belongs to, locked until the end of the transaction.
*/
public function lockByLineId(int $lineId): ?QuickSaleOrder;
/**
* The day's next pickup number, starting from 1 each day. The day's
* orders are locked so that two orders never get the same number.
*/
public function nextPickupNumber(DateTimeImmutable $day): int;
/**
* Inserts or updates the order and its lines; returns the stored order.
*/
public function save(QuickSaleOrder $order): QuickSaleOrder;
}
@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Entities;
use App\Modules\Sales\Domain\Exceptions\OrderStepNotCurrent;
use App\Modules\Sales\Domain\ValueObjects\OrderStep;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
use DateTimeImmutable;
/**
* A line of a quick sale order: a product with its price at ordering, and,
* for a product made before it is paid, its production steps and the step
* now being made. A line without steps is ready from the start.
*/
final class OrderLine
{
/**
* @param list<OrderStep> $steps
*/
public function __construct(
private ?int $id,
private QuickSaleLine $sale,
private array $steps,
private ?int $currentStep,
private ?DateTimeImmutable $madeAt,
) {}
/**
* @param list<OrderStep> $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<OrderStep>
*/
public function steps(): array
{
return $this->steps;
}
public function madeAt(): ?DateTimeImmutable
{
return $this->madeAt;
}
}
@@ -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<QuickSaleLine> $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;
}
}
@@ -0,0 +1,192 @@
<?php
declare(strict_types=1);
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\QuickSaleOrderPaid;
use DateTimeImmutable;
/**
* A quick sale order (tilaus, spec 19.7): products made on machines before
* the customer pays. It gets the day's running pickup number, is made step
* by step, and is paid as an ordinary quick sale, before or after it is
* ready. It ends when it is both paid and made; an unpaid order can be
* cancelled. It is not tied to a device or a seller.
*/
final class QuickSaleOrder
{
/**
* @param list<OrderLine> $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<OrderLine> $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<OrderLine> $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<OrderLine>
*/
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;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Enums;
/**
* Where a quick sale order is (spec 19.7): being made, made and waiting to
* be paid, made and paid (ended), or cancelled.
*/
enum OrderStatus: string
{
case InProduction = 'in_production';
case Ready = 'ready';
case Completed = 'completed';
case Cancelled = 'cancelled';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class OrderHasNoProduction extends DomainException
{
public function __construct()
{
parent::__construct('None of the products has a production process.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class OrderStepNotCurrent extends DomainException
{
public function __construct()
{
parent::__construct('The production step is not the current step of the line.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class QuickSaleOrderClosed extends DomainException
{
public function __construct()
{
parent::__construct('The quick sale order is already paid or cancelled.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class QuickSaleOrderNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The quick sale order was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class QuickSaleOrderPaid extends DomainException
{
public function __construct()
{
parent::__construct('A paid order cannot be cancelled; credit the sale instead.');
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain\ValueObjects;
/**
* A production step copied to an order line when the order is sent (spec
* 19.7): the machine (null: by hand), the duration and materials per
* piece and the work type the hours go to. Later changes to the product's
* process do not touch the copy.
*/
final readonly class OrderStep
{
/**
* @param list<array{stockItemId: int, quantityMilli: int}> $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<array{stockItemId: int, quantityMilli: int}>}
*/
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<array{stockItemId: int, quantityMilli: int}>} $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'] ?? []),
);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Modules\Sales\Infrastructure\Adapters;
use App\Modules\Machines\Application\Contracts\ProductionProcessQueries;
use App\Modules\Machines\Application\DTOs\ProductionStepSummary;
use App\Modules\Sales\Application\Contracts\ProductionProcesses;
use App\Modules\Sales\Domain\ValueObjects\OrderStep;
/**
* Production processes of products from the Machines module.
*/
class ProcessesFromMachines implements ProductionProcesses
{
public function __construct(private ProductionProcessQueries $processes) {}
public function stepsOf(array $productIds): array
{
return array_map(
fn (array $steps): array => 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),
);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Modules\Sales\Infrastructure\Adapters;
use App\Modules\Machines\Application\UseCases\MachineWorkList;
use App\Modules\Sales\Application\Contracts\ProductionQueue;
use DateTimeImmutable;
/**
* Order lines on machines' work lists through the Machines module.
*/
class QueueOnMachines implements ProductionQueue
{
public function __construct(private MachineWorkList $workList) {}
public function enqueue(int $orderLineId, int $stepPosition, int $machineId, DateTimeImmutable $day): void
{
$this->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);
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Modules\Sales\Infrastructure\Adapters;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\RecordStockWriteOff;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Sales\Application\Contracts\OrderMaterials;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Stock used in making quick sale orders, through the Inventory module.
* Reasons are stored in Finnish, like the rest of the business records.
*/
class StockForOrders implements OrderMaterials
{
public function __construct(
private RecordStockUse $recordUse,
private RecordStockWriteOff $recordWriteOff,
) {}
public function use(int $stockItemId, int $quantityMilli, int $orderLineId, ?int $machineId, int $userId): bool
{
try {
$this->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;
}
}
@@ -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.
@@ -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',
];
@@ -0,0 +1,46 @@
<?php
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* Persistence model, used only inside the Sales Infrastructure layer.
*
* @property int $id
* @property int $quick_sale_order_id
* @property int $product_id
* @property string $product_name
* @property int $quantity
* @property int $unit_price_cents
* @property int $vat_basis_points
* @property list<array{machineId?: ?int, durationQuarters?: int, workTypeId?: int, materials?: list<array{stockItemId: int, quantityMilli: int}>}> $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<string, string>
*/
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',
];
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
/**
* Persistence model, used only inside the Sales Infrastructure layer.
*
* @property int $id
* @property string $ordered_on Y-m-d
* @property int $pickup_number
* @property Carbon $ordered_at
* @property int $user_id
* @property int|null $customer_id
* @property string|null $customer_name
* @property string $status
* @property Carbon|null $made_at
* @property Carbon|null $paid_at
* @property Carbon|null $cancelled_at
* @property int|null $cancelled_by
*/
#[Table('quick_sale_orders')]
#[Fillable(['ordered_on', 'pickup_number', 'ordered_at', 'user_id', 'customer_id', 'customer_name', 'status', 'made_at', 'paid_at', 'cancelled_at', 'cancelled_by'])]
class QuickSaleOrderModel extends Model
{
/**
* @return HasMany<QuickSaleOrderLineModel, $this>
*/
public function lines(): HasMany
{
return $this->hasMany(QuickSaleOrderLineModel::class, 'quick_sale_order_id')->orderBy('sort_order');
}
/**
* @return HasOne<QuickSaleModel, $this>
*/
public function sale(): HasOne
{
return $this->hasOne(QuickSaleModel::class, 'quick_sale_order_id')->whereNull('credits_quick_sale_id');
}
/**
* @return array<string, string>
*/
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',
];
}
}
@@ -0,0 +1,125 @@
<?php
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\DTOs\OrderSummary;
use App\Modules\Sales\Domain\Enums\OrderStatus;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderLineModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class EloquentQuickSaleOrderQueries implements QuickSaleOrderQueries
{
public function __construct(
private UserAccountQueries $users,
private CustomerQueries $customers,
) {}
public function openOrders(): array
{
return $this->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<int, QuickSaleOrderModel> $models
* @return list<OrderSummary>
*/
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');
}
}
@@ -0,0 +1,99 @@
<?php
namespace App\Modules\Sales\Infrastructure\Persistence\Repositories;
use App\Modules\Sales\Domain\Contracts\QuickSaleOrderRepository;
use App\Modules\Sales\Domain\Entities\OrderLine;
use App\Modules\Sales\Domain\Entities\QuickSaleOrder;
use App\Modules\Sales\Domain\ValueObjects\OrderStep;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderLineModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderModel;
use DateTimeImmutable;
class EloquentQuickSaleOrderRepository implements QuickSaleOrderRepository
{
public function lockById(int $id): ?QuickSaleOrder
{
$model = QuickSaleOrderModel::query()->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,
);
}
}
@@ -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,
);
}
}
@@ -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
@@ -534,6 +534,10 @@ new class extends Component
<x-confirm-dialog id="close-dialog" :title="__('sales.cash_day.close_title')">
<p>{{ __('sales.cash_day.close_text') }}</p>
@php($unpaidOrders = app(\App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries::class)->unpaidCount())
@if ($unpaidOrders > 0)
<p class="mt-2">{{ trans_choice('sales.orders.unpaid', $unpaidOrders, ['count' => $unpaidOrders]) }}</p>
@endif
<p class="mt-2 font-medium">
{{ __('sales.cash_day.total') }}: {{ $this->money($cashDay->balance->totalCents()) }}
({{ __('sales.cash_day.cash') }} {{ $this->money($cashDay->balance->cashCents) }},
@@ -0,0 +1,427 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Machines\Application\Contracts\MachineQueries;
use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries;
use App\Modules\Sales\Application\DTOs\OrderLineSummary;
use App\Modules\Sales\Application\DTOs\OrderSummary;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use App\Modules\Sales\Domain\Enums\PaymentMethod;
use App\Modules\Sales\Domain\Exceptions\CashDayClosed;
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;
/**
* Open quick sale orders on the quick sale page (spec 19.7): pickup numbers
* with their state (being made, at which step and machine, or ready to be
* paid). A step can be completed here too (by hand, or a machine's step
* when working on one device), the order paid (an ordinary quick sale with
* a receipt) or cancelled while unpaid. The list refreshes itself and has
* a Refresh button; an order becoming ready is announced.
*/
new class extends Component
{
use FormatsSales;
#[Locked]
public ?int $completingLineId = null;
/**
* Used material per stock item while completing a step.
*
* @var array<int, string>
*/
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<int>
*/
#[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<OrderSummary>
*/
#[Computed]
public function orders(): array
{
return app(QuickSaleOrderQueries::class)->openOrders();
}
/**
* @return array<int, string>
*/
#[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<int, StockItemSummary>
*/
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<int>
*/
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);
}
};
?>
<section wire:poll.30s="refreshList" aria-labelledby="orders-heading" class="space-y-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 id="orders-heading" class="text-lg font-semibold">{{ __('sales.orders.title') }}</h2>
<x-button wire:click="refresh" subtle color="black" sm icon="arrow-path" :text="__('sales.orders.refresh')" />
</div>
<div id="orders-status" tabindex="-1" role="status" aria-live="polite" class="space-y-1 text-sm font-medium focus:outline-none">
<p>{{ $message }}</p>
@if ($paidSaleId !== null)
<p>
<a href="{{ route('sales.receipt', $paidSaleId) }}" target="_blank" rel="noopener" class="inline-flex items-center gap-1 underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
<x-icon name="document-text" class="size-5" aria-hidden="true" />
{{ __('sales.receipt.open', ['number' => $paidSaleId]) }}
</a>
</p>
@endif
</div>
@if ($this->orders === [])
<p class="text-sm">{{ __('sales.orders.none') }}</p>
@else
<ul class="space-y-3">
@foreach ($this->orders as $order)
<li wire:key="order-{{ $order->id }}" class="space-y-2 rounded-lg border border-zinc-300 bg-white p-3 dark:border-zinc-600 dark:bg-zinc-900">
<div class="flex flex-wrap items-start justify-between gap-2">
<div>
<h3 class="text-3xl font-bold">{{ __('sales.orders.pickup', ['number' => $order->pickupNumber]) }}</h3>
<p class="text-sm">
{{ $order->customerName ?? __('sales.anonymous') }} · {{ $this->dateLabel($order->orderedAt) }} · {{ $this->money($order->totalCents) }}
</p>
</div>
<p class="flex items-center gap-1 text-sm font-semibold">
<x-icon :name="$order->status->value === 'ready' ? 'check-circle' : 'cog-6-tooth'" class="size-5" aria-hidden="true" />
{{ __('sales.orders.statuses.'.$order->status->value) }}@if ($order->isPaid()), {{ __('sales.orders.is_paid') }}@endif
</p>
</div>
<ul class="space-y-2 text-sm">
@foreach ($order->lines as $line)
<li wire:key="order-line-{{ $line->id }}" class="space-y-1">
<p><span class="font-medium">{{ $line->quantity }} × {{ $line->productName }}</span> · {{ $this->lineState($line) }}</p>
@if (! $line->isMade && $line->hasProduction())
@if ($completingLineId === $line->id)
<form wire:submit="complete" class="space-y-2 rounded-md border border-zinc-300 p-2 dark:border-zinc-600" novalidate>
<p id="complete-line-{{ $line->id }}" tabindex="-1" class="font-medium focus:outline-none">{{ __('sales.orders.complete_title', ['product' => $line->productName]) }}</p>
@php($items = $this->itemsOf($line))
@foreach ($line->currentMaterials as $material)
@php($item = $items[$material['stockItemId']] ?? null)
<div class="w-48">
<x-input
id="used-{{ $line->id }}-{{ $material['stockItemId'] }}"
wire:model="used.{{ $material['stockItemId'] }}"
inputmode="decimal"
:label="($item->name ?? '').' ('.__('inventory.units.'.($item->unit->value ?? 'piece')).')'"
autocomplete="off"
/>
</div>
@endforeach
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('sales.orders.complete_hint') }}</p>
<div class="flex flex-wrap gap-2">
<x-button submit sm icon="check" :text="__('sales.orders.complete')" />
<x-button wire:click="$set('completingLineId', null)" subtle color="black" sm :text="__('layout.cancel')" />
</div>
</form>
@else
<div class="flex flex-wrap gap-2">
<x-button wire:click="startComplete({{ $line->id }})" subtle color="black" sm icon="check" :text="__('sales.orders.complete_step')" :aria-label="__('sales.orders.complete_step_named', ['number' => $order->pickupNumber, 'product' => $line->productName])" />
@if ($line->currentMachineId() !== null)
<x-link :href="route('machines.console', $line->currentMachineId())" class="text-sm">{{ __('sales.orders.open_console', ['machine' => $this->machineNames[$line->currentMachineId()] ?? '']) }}</x-link>
@endif
</div>
@endif
@endif
</li>
@endforeach
</ul>
@unless ($order->isPaid())
@if ($payingOrderId === $order->id)
<form wire:submit="pay" class="space-y-3 rounded-md border border-zinc-300 p-2 dark:border-zinc-600" novalidate>
<p id="pay-order-{{ $order->id }}" tabindex="-1" class="font-medium focus:outline-none">{{ __('sales.orders.pay_title', ['number' => $order->pickupNumber, 'total' => $this->money($order->totalCents)]) }}</p>
<x-radio.group
wire:model="paymentMethod"
:label="__('sales.sell.payment_method')"
:options="[
['label' => __('sales.payment_methods.cash'), 'value' => PaymentMethod::Cash->value],
['label' => __('sales.payment_methods.card'), 'value' => PaymentMethod::Card->value],
]"
/>
<x-input wire:model="receiptEmail" type="email" inputmode="email" autocomplete="off" :label="__('sales.sell.receipt_email')" />
<div class="flex flex-wrap gap-2">
<x-button submit icon="banknotes" :text="__('sales.orders.take_payment')" />
<x-button wire:click="$set('payingOrderId', null)" subtle color="black" :text="__('layout.cancel')" />
</div>
</form>
@else
<div class="flex flex-wrap gap-2">
<x-button wire:click="startPay({{ $order->id }})" sm icon="banknotes" :text="__('sales.orders.pay')" :aria-label="__('sales.orders.pay_named', ['number' => $order->pickupNumber])" />
<x-button wire:click="confirmCancel({{ $order->id }})" subtle color="black" sm icon="x-mark" :text="__('sales.orders.cancel')" :aria-label="__('sales.orders.cancel_named', ['number' => $order->pickupNumber])" />
</div>
@endif
@endunless
</li>
@endforeach
</ul>
@endif
<x-confirm-dialog id="cancel-order-dialog" :title="__('sales.orders.cancel_title')">
<p>{{ __('sales.orders.cancel_text') }}</p>
<x-slot:actions>
<x-button wire:click="cancel" color="red" :text="__('sales.orders.cancel')" />
</x-slot:actions>
</x-confirm-dialog>
</section>
@@ -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<int>
*/
#[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
<x-icon name="check-circle" class="size-5 shrink-0" aria-hidden="true" />
{{ $savedMessage }}
</p>
@if ($savedPickupNumber !== null)
<p class="text-4xl font-bold" aria-hidden="true">{{ $savedPickupNumber }}</p>
@endif
@if ($hoursMessage !== '')
<p>{{ $hoursMessage }}</p>
@endif
@@ -397,6 +470,12 @@ new class extends Component
>
<span class="font-medium break-words">{{ $product->name }}</span>
<span class="text-sm text-zinc-700 dark:text-zinc-300">{{ $this->money($product->grossCents) }} / {{ __('catalog.units.'.$product->unit) }}</span>
@if (in_array($product->id, $this->madeProductIds, true))
<span class="inline-flex items-center gap-1 text-xs">
<x-icon name="printer" class="size-4" aria-hidden="true" />
{{ __('sales.orders.made') }}
</span>
@endif
</button>
</li>
@endforeach
@@ -457,7 +536,16 @@ new class extends Component
</p>
</section>
@php($isOrder = $this->isOrder())
<form wire:submit="save" class="space-y-6" novalidate>
@if ($isOrder)
<p class="flex items-start gap-2 rounded-lg border border-zinc-400 p-3 text-sm dark:border-zinc-500">
<x-icon name="printer" class="size-5 shrink-0" aria-hidden="true" />
{{ __('sales.orders.order_note') }}
</p>
<x-input id="order-customer-name" wire:model="orderCustomerName" :label="__('sales.orders.customer_name')" :hint="__('sales.orders.customer_name_hint')" autocomplete="off" maxlength="150" />
@else
<x-radio.group
wire:model="paymentMethod"
:label="__('sales.sell.payment_method')"
@@ -466,6 +554,7 @@ new class extends Component
['label' => __('sales.payment_methods.card'), 'value' => PaymentMethod::Card->value],
]"
/>
@endif
<div class="space-y-2">
@if ($customerId !== null)
@@ -516,6 +605,7 @@ new class extends Component
@endif
</div>
@unless ($isOrder)
<x-input
wire:model="receiptEmail"
type="email"
@@ -524,8 +614,11 @@ new class extends Component
:label="__('sales.sell.receipt_email')"
:hint="__('sales.sell.receipt_email_hint')"
/>
@endunless
<x-button submit lg class="w-full" :text="__('sales.sell.save')" />
<x-button submit lg class="w-full" :text="$isOrder ? __('sales.orders.send') : __('sales.sell.save')" />
</form>
@endif
<livewire:sales::orders />
</div>
@@ -0,0 +1,105 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Making quick sale products (spec 19.7): a product's production process
* (steps on machines or by hand, with the hours and materials per piece),
* and quick sale orders made before they are paid. An order line keeps a
* snapshot of the process, so later changes do not touch sent orders.
*/
public function up(): void
{
Schema::create('production_steps', function (Blueprint $table) {
$table->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');
}
};
+39
View File
@@ -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.',
+52
View File
@@ -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. [email protected].',
'empty' => 'Enter a quantity for at least one product.',
+39
View File
@@ -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ä.',
+52
View File
@@ -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. [email protected].',
'empty' => 'Anna vähintään yhdelle tuotteelle määrä.',
@@ -0,0 +1,74 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Machines\Application\DTOs\ProductionStepData;
use App\Modules\Machines\Application\UseCases\SaveProductionProcess;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
use App\Modules\Sales\Application\DTOs\OrderData;
use App\Modules\Sales\Application\UseCases\QuickSaleOrders;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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');
});
+5
View File
@@ -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) {
@@ -36,6 +36,7 @@ class InMemoryQuickSaleRepository implements QuickSaleRepository
$sale->lines(),
$sale->creditsSaleId(),
$sale->receiptEmail(),
$sale->orderId(),
);
}
@@ -0,0 +1,167 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineQueueEntryModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderLineModel;
use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleOrderModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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);
});