diff --git a/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php b/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php
index 3a976b1..59d5270 100644
--- a/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php
+++ b/app/Modules/Jobs/Application/UseCases/ChangeTaskStatus.php
@@ -6,14 +6,21 @@ namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
+use App\Modules\Jobs\Domain\Events\TaskCompleted;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
+use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
+/**
+ * Changes a task's status. A task newly marked done is published as
+ * completed, so that e.g. a machine's work list closes its row.
+ */
final class ChangeTaskStatus
{
public function __construct(
private TaskRepository $tasks,
private TransactionManager $transactions,
+ private EventDispatcher $events,
) {}
/**
@@ -23,8 +30,14 @@ final class ChangeTaskStatus
{
$this->transactions->run(function () use ($jobId, $taskId, $status): void {
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
+ $wasDone = $task->status() === TaskStatus::Done;
+
$task->changeStatus($status);
$this->tasks->save($task);
+
+ if (! $wasDone && $status === TaskStatus::Done) {
+ $this->events->dispatch(new TaskCompleted($taskId, $jobId));
+ }
});
}
}
diff --git a/app/Modules/Jobs/Application/UseCases/UpdateTask.php b/app/Modules/Jobs/Application/UseCases/UpdateTask.php
index 2e827d8..e748454 100644
--- a/app/Modules/Jobs/Application/UseCases/UpdateTask.php
+++ b/app/Modules/Jobs/Application/UseCases/UpdateTask.php
@@ -12,6 +12,7 @@ use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Events\PeopleAddedToTask;
+use App\Modules\Jobs\Domain\Events\TaskCompleted;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
@@ -49,6 +50,7 @@ final class UpdateTask
$before = self::planningInput($task);
$peopleBefore = PeopleAddedToTask::peopleOf($task);
+ $wasDone = $task->status() === TaskStatus::Done;
$task->changeDetails(
$data->workTypeId,
@@ -75,6 +77,10 @@ final class UpdateTask
if ($added !== null) {
$this->events->dispatch($added);
}
+
+ if (! $wasDone && $task->status() === TaskStatus::Done) {
+ $this->events->dispatch(new TaskCompleted($taskId, $jobId));
+ }
});
}
diff --git a/app/Modules/Jobs/Domain/Events/TaskCompleted.php b/app/Modules/Jobs/Domain/Events/TaskCompleted.php
new file mode 100644
index 0000000..139a11a
--- /dev/null
+++ b/app/Modules/Jobs/Domain/Events/TaskCompleted.php
@@ -0,0 +1,17 @@
+id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
+
@if ($canChangeStatus)
diff --git a/app/Modules/Machines/Application/Contracts/MachineQueries.php b/app/Modules/Machines/Application/Contracts/MachineQueries.php
new file mode 100644
index 0000000..20f2c92
--- /dev/null
+++ b/app/Modules/Machines/Application/Contracts/MachineQueries.php
@@ -0,0 +1,48 @@
+ By name.
+ */
+ public function machines(bool $includeInactive = false): array;
+
+ public function findMachine(int $id): ?MachineSummary;
+
+ /**
+ * Active machines serving any of the service units.
+ *
+ * @param list $serviceUnitIds
+ * @return list
+ */
+ public function machinesFor(array $serviceUnitIds): array;
+
+ /**
+ * The task's open row on a machine's work list, without task details.
+ */
+ public function rowForTask(int $taskId): ?QueueRow;
+
+ /**
+ * A machine's work list for the day: quick sale orders first, then on
+ * today's list the late rows of earlier days, then the day's rows in
+ * order. Rows on days after today are listed for viewing only.
+ *
+ * @return list
+ */
+ public function rowsOn(int $machineId, string $day, string $today): array;
+
+ /**
+ * The machine's planned rows and estimated hours on the days.
+ *
+ * @return list
+ */
+ public function load(int $machineId, string $from, int $days): array;
+}
diff --git a/app/Modules/Machines/Application/Contracts/MachineTasks.php b/app/Modules/Machines/Application/Contracts/MachineTasks.php
new file mode 100644
index 0000000..260250e
--- /dev/null
+++ b/app/Modules/Machines/Application/Contracts/MachineTasks.php
@@ -0,0 +1,27 @@
+ $taskIds
+ * @return array By task id.
+ */
+ public function infos(array $taskIds): array;
+
+ /**
+ * Changes a task's status ("in_progress", "in_review" or "done").
+ */
+ public function changeStatus(int $taskId, string $status): void;
+}
diff --git a/app/Modules/Machines/Application/DTOs/CounterSummary.php b/app/Modules/Machines/Application/DTOs/CounterSummary.php
new file mode 100644
index 0000000..15d3e6a
--- /dev/null
+++ b/app/Modules/Machines/Application/DTOs/CounterSummary.php
@@ -0,0 +1,22 @@
+ $serviceUnitIds
+ * @param list $counters
+ */
+ public function __construct(
+ public string $name,
+ public string $type,
+ public ?string $description,
+ public array $serviceUnitIds,
+ public ?int $responsibleUserId,
+ public array $counters = [],
+ ) {}
+}
diff --git a/app/Modules/Machines/Application/DTOs/MachineSummary.php b/app/Modules/Machines/Application/DTOs/MachineSummary.php
new file mode 100644
index 0000000..adfc308
--- /dev/null
+++ b/app/Modules/Machines/Application/DTOs/MachineSummary.php
@@ -0,0 +1,28 @@
+ $serviceUnitIds
+ * @param list $serviceUnitNames
+ * @param list $counters
+ */
+ public function __construct(
+ public int $id,
+ public string $name,
+ public MachineType $type,
+ public ?string $description,
+ public array $serviceUnitIds,
+ public array $serviceUnitNames,
+ public ?int $responsibleUserId,
+ public ?string $responsibleName,
+ public array $counters,
+ public bool $isActive,
+ ) {}
+}
diff --git a/app/Modules/Machines/Application/DTOs/MachineTaskInfo.php b/app/Modules/Machines/Application/DTOs/MachineTaskInfo.php
new file mode 100644
index 0000000..ef20618
--- /dev/null
+++ b/app/Modules/Machines/Application/DTOs/MachineTaskInfo.php
@@ -0,0 +1,49 @@
+ $allowedServiceUnitIds
+ */
+ public function __construct(
+ public int $taskId,
+ public int $jobId,
+ public string $jobNumber,
+ public string $jobName,
+ public string $customerName,
+ public string $title,
+ public ?string $description,
+ public ?string $instructions,
+ public string $status,
+ public string $priority,
+ public int $priorityRank,
+ public ?string $dueOn,
+ public ?string $plannedFrom,
+ public ?string $plannedTo,
+ public ?string $estimatedHours,
+ public array $allowedServiceUnitIds,
+ public bool $isDone,
+ ) {}
+
+ /**
+ * Whether making the task on the day is outside its schedule or after
+ * its due date (spec 19.4: shown as a note, not prevented).
+ */
+ public function isOutsidePlan(string $day): bool
+ {
+ return ($this->plannedFrom !== null && $day < $this->plannedFrom)
+ || ($this->plannedTo !== null && $day > $this->plannedTo)
+ || ($this->dueOn !== null && $day > $this->dueOn);
+ }
+}
diff --git a/app/Modules/Machines/Application/DTOs/QueueRow.php b/app/Modules/Machines/Application/DTOs/QueueRow.php
new file mode 100644
index 0000000..b9a0d59
--- /dev/null
+++ b/app/Modules/Machines/Application/DTOs/QueueRow.php
@@ -0,0 +1,30 @@
+orderLineId !== null;
+ }
+}
diff --git a/app/Modules/Machines/Application/UseCases/MachineWorkList.php b/app/Modules/Machines/Application/UseCases/MachineWorkList.php
new file mode 100644
index 0000000..a36bd71
--- /dev/null
+++ b/app/Modules/Machines/Application/UseCases/MachineWorkList.php
@@ -0,0 +1,243 @@
+tasks->info($taskId) ?? throw new MachineTaskNotFound;
+
+ if ($task->isDone) {
+ throw new MachineTaskNotFound;
+ }
+
+ $today = $this->clock->today()->format('Y-m-d');
+ $plannedOn = $this->day($day ?? ($task->plannedFrom !== null && $task->plannedFrom > $today ? $task->plannedFrom : $today));
+
+ $this->transactions->run(function () use ($task, $taskId, $machineId, $plannedOn): void {
+ $machine = $this->machines->findById($machineId) ?? throw new MachineNotFound;
+ $machine->ensureActive();
+
+ if (! $machine->servesAnyOf($task->allowedServiceUnitIds)) {
+ throw new MachineNotForTask;
+ }
+
+ $entry = $this->queue->openEntryForTask($taskId);
+
+ if ($entry !== null) {
+ $this->takeOut($entry);
+ }
+
+ $rows = array_values(array_filter(
+ $this->dayRows($machineId, $plannedOn),
+ fn (array $row): bool => $entry === null || $row['entry']->id() !== $entry->id(),
+ ));
+ $index = QueueOrder::insertionIndex(array_map(fn (array $row): array => $row['order'], $rows), $task->priorityRank, $task->dueOn);
+
+ $entry ??= QueueEntry::forTask($machineId, $taskId, $plannedOn, 0);
+ $entry->plan($machineId, $plannedOn, 0);
+
+ $entries = array_map(fn (array $row): QueueEntry => $row['entry'], $rows);
+ array_splice($entries, $index, 0, [$entry]);
+ $this->renumber($entries);
+ });
+ }
+
+ /**
+ * Takes the task off its machine's list.
+ */
+ public function removeTask(int $taskId): void
+ {
+ $this->transactions->run(function () use ($taskId): void {
+ $entry = $this->queue->openEntryForTask($taskId);
+
+ if ($entry !== null) {
+ $this->takeOut($entry);
+ $this->queue->delete($entry);
+ }
+ });
+ }
+
+ /**
+ * Moves a row one place up or down among its day's rows.
+ *
+ * @return bool False when it already was first (up) or last.
+ *
+ * @throws QueueEntryNotFound
+ * @throws QueueEntryCompleted
+ */
+ public function move(int $entryId, bool $up): bool
+ {
+ return $this->transactions->run(function () use ($entryId, $up): bool {
+ $entry = $this->queue->findById($entryId) ?? throw new QueueEntryNotFound;
+ $entry->ensureOpen();
+
+ $entries = $this->queue->openEntriesOn($entry->machineId(), $entry->plannedOn());
+ $index = $this->indexOf($entries, $entryId);
+ $target = $up ? $index - 1 : $index + 1;
+
+ if (! isset($entries[$target])) {
+ return false;
+ }
+
+ [$entries[$index], $entries[$target]] = [$entries[$target], $entries[$index]];
+ $this->renumber($entries);
+
+ return true;
+ });
+ }
+
+ /**
+ * Finishes a task's row from the machine: the row leaves the list and
+ * the task is marked done.
+ *
+ * @throws QueueEntryNotFound
+ * @throws QueueEntryCompleted
+ */
+ public function finish(int $entryId, int $actorUserId): void
+ {
+ $taskId = $this->transactions->run(function () use ($entryId, $actorUserId): ?int {
+ $entry = $this->queue->findById($entryId) ?? throw new QueueEntryNotFound;
+ $entry->complete($actorUserId, $this->clock->now());
+ $this->queue->save($entry);
+
+ return $entry->taskId();
+ });
+
+ if ($taskId !== null) {
+ $this->tasks->changeStatus($taskId, 'done');
+ }
+ }
+
+ /**
+ * Closes the open row of a task that was marked done elsewhere.
+ */
+ public function closeTask(int $taskId): void
+ {
+ $this->transactions->run(function () use ($taskId): void {
+ $entry = $this->queue->openEntryForTask($taskId);
+
+ if ($entry !== null) {
+ $entry->complete(null, $this->clock->now());
+ $this->queue->save($entry);
+ }
+ });
+ }
+
+ /**
+ * Removes the entry from its day's order and closes the gap.
+ */
+ private function takeOut(QueueEntry $entry): void
+ {
+ $remaining = array_values(array_filter(
+ $this->queue->openEntriesOn($entry->machineId(), $entry->plannedOn()),
+ fn (QueueEntry $other): bool => $other->id() !== $entry->id(),
+ ));
+
+ $this->renumber($remaining);
+ }
+
+ /**
+ * The day's open rows with what ordering needs.
+ *
+ * @return list
+ */
+ private function dayRows(int $machineId, DateTimeImmutable $day): array
+ {
+ $entries = $this->queue->openEntriesOn($machineId, $day);
+ $taskIds = array_values(array_filter(array_map(fn (QueueEntry $entry): ?int => $entry->taskId(), $entries)));
+ $infos = $this->tasks->infos($taskIds);
+
+ return array_map(function (QueueEntry $entry) use ($infos): array {
+ $info = $entry->taskId() === null ? null : ($infos[$entry->taskId()] ?? null);
+
+ return [
+ 'entry' => $entry,
+ 'order' => ['isOrder' => $entry->isOrderLine(), 'rank' => $info->priorityRank ?? 0, 'dueOn' => $info?->dueOn],
+ ];
+ }, $entries);
+ }
+
+ /**
+ * @param list $entries
+ */
+ private function renumber(array $entries): void
+ {
+ foreach ($entries as $index => $entry) {
+ $entry->moveTo($index + 1);
+ $this->queue->save($entry);
+ }
+ }
+
+ /**
+ * @param list $entries
+ */
+ private function indexOf(array $entries, int $entryId): int
+ {
+ foreach ($entries as $index => $entry) {
+ if ($entry->id() === $entryId) {
+ return $index;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * @throws InvalidPlannedDay
+ */
+ private function day(string $value): DateTimeImmutable
+ {
+ $day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
+
+ if ($day === false || $day->format('Y-m-d') !== $value) {
+ throw new InvalidPlannedDay;
+ }
+
+ return $day;
+ }
+}
diff --git a/app/Modules/Machines/Application/UseCases/SaveMachine.php b/app/Modules/Machines/Application/UseCases/SaveMachine.php
new file mode 100644
index 0000000..a6c7a57
--- /dev/null
+++ b/app/Modules/Machines/Application/UseCases/SaveMachine.php
@@ -0,0 +1,124 @@
+parse($data);
+ $unitIds = $this->allowedUnits($data->serviceUnitIds, []);
+
+ return $this->transactions->run(function () use ($data, $name, $type, $counters, $unitIds): int {
+ if ($this->machines->isNameTaken($name->value)) {
+ throw new MachineNameTaken;
+ }
+
+ $machine = Machine::create($name, $type, $data->description, $unitIds, $data->responsibleUserId, $counters);
+
+ return (int) $this->machines->save($machine)->id();
+ });
+ }
+
+ /**
+ * @throws MachineNotFound
+ * @throws InvalidMachineName
+ * @throws InvalidCounter
+ * @throws MachineNameTaken
+ * @throws MachineNeedsServiceUnit
+ */
+ public function update(int $machineId, MachineData $data): void
+ {
+ [$name, $type, $counters] = $this->parse($data);
+
+ $this->transactions->run(function () use ($machineId, $data, $name, $type, $counters): void {
+ $machine = $this->machines->findById($machineId) ?? throw new MachineNotFound;
+
+ if ($this->machines->isNameTaken($name->value, $machineId)) {
+ throw new MachineNameTaken;
+ }
+
+ $machine->change($name, $type, $data->description, $this->allowedUnits($data->serviceUnitIds, $machine->serviceUnitIds()), $data->responsibleUserId, $counters);
+ $this->machines->save($machine);
+ });
+ }
+
+ /**
+ * @throws MachineNotFound
+ */
+ public function setActive(int $machineId, bool $active): void
+ {
+ $this->transactions->run(function () use ($machineId, $active): void {
+ $machine = $this->machines->findById($machineId) ?? throw new MachineNotFound;
+ $active ? $machine->activate() : $machine->deactivate();
+ $this->machines->save($machine);
+ });
+ }
+
+ /**
+ * @return array{0: MachineName, 1: MachineType, 2: list}
+ *
+ * @throws InvalidMachineName
+ * @throws InvalidCounter
+ */
+ private function parse(MachineData $data): array
+ {
+ $counters = [];
+
+ foreach ($data->counters as $counter) {
+ $unit = CounterUnit::tryFrom($counter['unit']) ?? throw new InvalidCounter;
+ $counters[] = new MachineCounter($counter['id'], $counter['name'], $unit);
+ }
+
+ return [new MachineName($data->name), MachineType::tryFrom($data->type) ?? MachineType::Other, $counters];
+ }
+
+ /**
+ * @param list $requested
+ * @param list $current
+ * @return list
+ */
+ private function allowedUnits(array $requested, array $current): array
+ {
+ $stockUnitIds = $this->catalog->stockServiceUnitIds();
+
+ return array_values(array_filter(
+ array_unique($requested),
+ fn (int $id): bool => in_array($id, $stockUnitIds, true) || in_array($id, $current, true),
+ ));
+ }
+}
diff --git a/app/Modules/Machines/Domain/Contracts/MachineRepository.php b/app/Modules/Machines/Domain/Contracts/MachineRepository.php
new file mode 100644
index 0000000..c3cca0d
--- /dev/null
+++ b/app/Modules/Machines/Domain/Contracts/MachineRepository.php
@@ -0,0 +1,20 @@
+
+ */
+ public function openEntriesOn(int $machineId, DateTimeImmutable $day): array;
+
+ public function save(QueueEntry $entry): QueueEntry;
+
+ public function delete(QueueEntry $entry): void;
+}
diff --git a/app/Modules/Machines/Domain/Entities/Machine.php b/app/Modules/Machines/Domain/Entities/Machine.php
new file mode 100644
index 0000000..9ed8967
--- /dev/null
+++ b/app/Modules/Machines/Domain/Entities/Machine.php
@@ -0,0 +1,162 @@
+ $serviceUnitIds
+ * @param list $counters
+ */
+ private function __construct(
+ private ?int $id,
+ private MachineName $name,
+ private MachineType $type,
+ private ?string $description,
+ private array $serviceUnitIds,
+ private ?int $responsibleUserId,
+ private array $counters,
+ private bool $active,
+ ) {
+ if ($serviceUnitIds === []) {
+ throw new MachineNeedsServiceUnit;
+ }
+ }
+
+ /**
+ * @param list $serviceUnitIds
+ * @param list $counters
+ *
+ * @throws MachineNeedsServiceUnit
+ */
+ public static function create(MachineName $name, MachineType $type, ?string $description, array $serviceUnitIds, ?int $responsibleUserId, array $counters): self
+ {
+ return new self(null, $name, $type, self::text($description), array_values(array_unique($serviceUnitIds)), $responsibleUserId, $counters, true);
+ }
+
+ /**
+ * @param list $serviceUnitIds
+ * @param list $counters
+ */
+ public static function reconstitute(int $id, MachineName $name, MachineType $type, ?string $description, array $serviceUnitIds, ?int $responsibleUserId, array $counters, bool $active): self
+ {
+ return new self($id, $name, $type, $description, $serviceUnitIds, $responsibleUserId, $counters, $active);
+ }
+
+ /**
+ * @param list $serviceUnitIds
+ * @param list $counters
+ *
+ * @throws MachineNeedsServiceUnit
+ */
+ public function change(MachineName $name, MachineType $type, ?string $description, array $serviceUnitIds, ?int $responsibleUserId, array $counters): void
+ {
+ if ($serviceUnitIds === []) {
+ throw new MachineNeedsServiceUnit;
+ }
+
+ $this->name = $name;
+ $this->type = $type;
+ $this->description = self::text($description);
+ $this->serviceUnitIds = array_values(array_unique($serviceUnitIds));
+ $this->responsibleUserId = $responsibleUserId;
+ $this->counters = $counters;
+ }
+
+ /**
+ * Whether the machine serves any of the service units.
+ *
+ * @param list $serviceUnitIds
+ */
+ public function servesAnyOf(array $serviceUnitIds): bool
+ {
+ return array_intersect($this->serviceUnitIds, $serviceUnitIds) !== [];
+ }
+
+ /**
+ * @throws MachineInactive
+ */
+ public function ensureActive(): void
+ {
+ if (! $this->active) {
+ throw new MachineInactive;
+ }
+ }
+
+ public function activate(): void
+ {
+ $this->active = true;
+ }
+
+ public function deactivate(): void
+ {
+ $this->active = false;
+ }
+
+ public function id(): ?int
+ {
+ return $this->id;
+ }
+
+ public function name(): MachineName
+ {
+ return $this->name;
+ }
+
+ public function type(): MachineType
+ {
+ return $this->type;
+ }
+
+ public function description(): ?string
+ {
+ return $this->description;
+ }
+
+ /**
+ * @return list
+ */
+ public function serviceUnitIds(): array
+ {
+ return $this->serviceUnitIds;
+ }
+
+ public function responsibleUserId(): ?int
+ {
+ return $this->responsibleUserId;
+ }
+
+ /**
+ * @return list
+ */
+ public function counters(): array
+ {
+ return $this->counters;
+ }
+
+ public function isActive(): bool
+ {
+ return $this->active;
+ }
+
+ private static function text(?string $value): ?string
+ {
+ $value = $value === null ? '' : trim($value);
+
+ return $value === '' ? null : mb_substr($value, 0, 5000);
+ }
+}
diff --git a/app/Modules/Machines/Domain/Entities/QueueEntry.php b/app/Modules/Machines/Domain/Entities/QueueEntry.php
new file mode 100644
index 0000000..f08ed55
--- /dev/null
+++ b/app/Modules/Machines/Domain/Entities/QueueEntry.php
@@ -0,0 +1,132 @@
+ensureOpen();
+ $this->machineId = $machineId;
+ $this->plannedOn = $plannedOn;
+ $this->position = $position;
+ }
+
+ public function moveTo(int $position): void
+ {
+ $this->position = $position;
+ }
+
+ /**
+ * @param int|null $userId Null when the task was marked done elsewhere.
+ *
+ * @throws QueueEntryCompleted
+ */
+ public function complete(?int $userId, DateTimeImmutable $at): void
+ {
+ $this->ensureOpen();
+ $this->completedBy = $userId;
+ $this->completedAt = $at;
+ }
+
+ /**
+ * @throws QueueEntryCompleted
+ */
+ public function ensureOpen(): void
+ {
+ if ($this->completedAt !== null) {
+ throw new QueueEntryCompleted;
+ }
+ }
+
+ public function isOrderLine(): bool
+ {
+ return $this->orderLineId !== null;
+ }
+
+ public function id(): ?int
+ {
+ return $this->id;
+ }
+
+ public function machineId(): int
+ {
+ return $this->machineId;
+ }
+
+ public function plannedOn(): DateTimeImmutable
+ {
+ return $this->plannedOn;
+ }
+
+ public function position(): int
+ {
+ return $this->position;
+ }
+
+ public function taskId(): ?int
+ {
+ return $this->taskId;
+ }
+
+ public function orderLineId(): ?int
+ {
+ return $this->orderLineId;
+ }
+
+ public function stepPosition(): ?int
+ {
+ return $this->stepPosition;
+ }
+
+ public function completedAt(): ?DateTimeImmutable
+ {
+ return $this->completedAt;
+ }
+
+ public function completedBy(): ?int
+ {
+ return $this->completedBy;
+ }
+}
diff --git a/app/Modules/Machines/Domain/Enums/CounterUnit.php b/app/Modules/Machines/Domain/Enums/CounterUnit.php
new file mode 100644
index 0000000..af8d607
--- /dev/null
+++ b/app/Modules/Machines/Domain/Enums/CounterUnit.php
@@ -0,0 +1,19 @@
+
+ */
+ public function suggestedCounters(): array
+ {
+ return match ($this) {
+ self::Printer => [
+ ['name' => 'prints', 'unit' => CounterUnit::Piece],
+ ['name' => 'printed_area', 'unit' => CounterUnit::SquareMetre],
+ ],
+ self::Cutter => [
+ ['name' => 'cut_length', 'unit' => CounterUnit::Metre],
+ ],
+ self::Other => [],
+ };
+ }
+}
diff --git a/app/Modules/Machines/Domain/Exceptions/InvalidCounter.php b/app/Modules/Machines/Domain/Exceptions/InvalidCounter.php
new file mode 100644
index 0000000..4a4d3ca
--- /dev/null
+++ b/app/Modules/Machines/Domain/Exceptions/InvalidCounter.php
@@ -0,0 +1,15 @@
+ $rows The day's open rows in order.
+ * @return int The index to insert the new task at.
+ */
+ public static function insertionIndex(array $rows, int $rank, ?string $dueOn): int
+ {
+ foreach ($rows as $index => $row) {
+ if ($row['isOrder']) {
+ continue;
+ }
+
+ if (self::before($rank, $dueOn, $row['rank'], $row['dueOn'])) {
+ return $index;
+ }
+ }
+
+ return count($rows);
+ }
+
+ private static function before(int $rank, ?string $dueOn, int $otherRank, ?string $otherDueOn): bool
+ {
+ if ($rank !== $otherRank) {
+ return $rank > $otherRank;
+ }
+
+ if ($dueOn === null) {
+ return false;
+ }
+
+ return $otherDueOn === null || $dueOn < $otherDueOn;
+ }
+}
diff --git a/app/Modules/Machines/Domain/ValueObjects/MachineCounter.php b/app/Modules/Machines/Domain/ValueObjects/MachineCounter.php
new file mode 100644
index 0000000..134dc62
--- /dev/null
+++ b/app/Modules/Machines/Domain/ValueObjects/MachineCounter.php
@@ -0,0 +1,36 @@
+ self::MAX_LENGTH) {
+ throw new InvalidCounter;
+ }
+
+ $this->name = $name;
+ }
+}
diff --git a/app/Modules/Machines/Domain/ValueObjects/MachineName.php b/app/Modules/Machines/Domain/ValueObjects/MachineName.php
new file mode 100644
index 0000000..503b6e5
--- /dev/null
+++ b/app/Modules/Machines/Domain/ValueObjects/MachineName.php
@@ -0,0 +1,31 @@
+ self::MAX_LENGTH) {
+ throw new InvalidMachineName;
+ }
+
+ $this->value = $value;
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Adapters/JobsForMachines.php b/app/Modules/Machines/Infrastructure/Adapters/JobsForMachines.php
new file mode 100644
index 0000000..37a046c
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Adapters/JobsForMachines.php
@@ -0,0 +1,123 @@
+ */
+ private array $jobCache = [];
+
+ public function __construct(
+ private TaskQueries $tasks,
+ private CustomerJobQueries $jobs,
+ private CatalogQueries $catalog,
+ private ChangeTaskStatus $changeTaskStatus,
+ ) {}
+
+ public function info(int $taskId): ?MachineTaskInfo
+ {
+ return $this->infos([$taskId])[$taskId] ?? null;
+ }
+
+ public function infos(array $taskIds): array
+ {
+ if ($taskIds === []) {
+ return [];
+ }
+
+ $stockUnitIds = $this->catalog->stockServiceUnitIds();
+ $infos = [];
+
+ foreach ($this->tasks->bookableTasks($taskIds) as $bookable) {
+ $task = $this->tasks->findTask($bookable->jobId, $bookable->taskId);
+ $job = $this->job($bookable->jobId);
+
+ if ($task === null || $job === null) {
+ continue;
+ }
+
+ $infos[$task->id] = new MachineTaskInfo(
+ taskId: $task->id,
+ jobId: $job->id,
+ jobNumber: $job->number,
+ jobName: $job->name,
+ customerName: $job->customer->name,
+ title: $task->title,
+ description: $task->description,
+ instructions: $job->instructions,
+ status: $task->status->value,
+ priority: $job->priority->value,
+ priorityRank: self::rank($job->priority),
+ dueOn: $task->dueOn ?? $job->dueOn,
+ plannedFrom: $task->plannedFrom,
+ plannedTo: $task->plannedTo,
+ estimatedHours: $task->estimatedHours,
+ allowedServiceUnitIds: $this->allowedUnits($bookable->workTypeId, $job, $stockUnitIds),
+ isDone: $task->status === TaskStatus::Done,
+ );
+ }
+
+ return $infos;
+ }
+
+ public function changeStatus(int $taskId, string $status): void
+ {
+ $task = $this->tasks->bookableTask($taskId);
+
+ if ($task !== null) {
+ $this->changeTaskStatus->execute($task->jobId, $taskId, TaskStatus::from($status));
+ }
+ }
+
+ /**
+ * @param list $stockUnitIds
+ * @return list
+ */
+ private function allowedUnits(int $workTypeId, CustomerJobDetails $job, array $stockUnitIds): array
+ {
+ $workType = $this->catalog->findWorkType($workTypeId);
+ $unit = $workType === null ? null : $this->catalog->findServiceUnit($workType->serviceUnitId);
+
+ if ($unit === null) {
+ return [];
+ }
+
+ $unitIds = $unit->isShared ? array_map(fn ($jobUnit): int => $jobUnit->id, $job->serviceUnits) : [$unit->id];
+
+ return array_values(array_intersect($unitIds, $stockUnitIds));
+ }
+
+ private function job(int $jobId): ?CustomerJobDetails
+ {
+ if (! array_key_exists($jobId, $this->jobCache)) {
+ $this->jobCache[$jobId] = $this->jobs->findDetails($jobId);
+ }
+
+ return $this->jobCache[$jobId];
+ }
+
+ private static function rank(Priority $priority): int
+ {
+ return match ($priority) {
+ Priority::Immediate => 4,
+ Priority::Urgent => 3,
+ Priority::First => 2,
+ Priority::Normal => 1,
+ Priority::Waiting => 0,
+ };
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterModel.php
new file mode 100644
index 0000000..62b8bd8
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterModel.php
@@ -0,0 +1,43 @@
+
+ */
+ public function latestReading(): HasOne
+ {
+ return $this->hasOne(MachineCounterReadingModel::class, 'machine_counter_id')->latestOfMany('read_at');
+ }
+
+ /**
+ * @return array
+ */
+ protected function casts(): array
+ {
+ return [
+ 'machine_id' => 'integer',
+ 'unit' => CounterUnit::class,
+ 'sort_order' => 'integer',
+ ];
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterReadingModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterReadingModel.php
new file mode 100644
index 0000000..d581919
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineCounterReadingModel.php
@@ -0,0 +1,35 @@
+
+ */
+ protected function casts(): array
+ {
+ return [
+ 'machine_counter_id' => 'integer',
+ 'reading_milli' => 'integer',
+ 'user_id' => 'integer',
+ 'read_at' => 'immutable_datetime',
+ ];
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineModel.php
new file mode 100644
index 0000000..0d7eeb6
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineModel.php
@@ -0,0 +1,51 @@
+ */
+ use HasFactory;
+
+ /**
+ * @return HasMany
+ */
+ public function counters(): HasMany
+ {
+ return $this->hasMany(MachineCounterModel::class, 'machine_id')->orderBy('sort_order');
+ }
+
+ /**
+ * @return array
+ */
+ protected function casts(): array
+ {
+ return [
+ 'type' => MachineType::class,
+ 'responsible_user_id' => 'integer',
+ 'is_active' => 'boolean',
+ ];
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineQueueEntryModel.php b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineQueueEntryModel.php
new file mode 100644
index 0000000..b9061a6
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Eloquent/MachineQueueEntryModel.php
@@ -0,0 +1,42 @@
+
+ */
+ protected function casts(): array
+ {
+ return [
+ 'machine_id' => 'integer',
+ 'position' => 'integer',
+ 'task_id' => 'integer',
+ 'quick_sale_order_line_id' => 'integer',
+ 'production_step_position' => 'integer',
+ 'completed_at' => 'immutable_datetime',
+ 'completed_by' => 'integer',
+ ];
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineQueries.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineQueries.php
new file mode 100644
index 0000000..475cba1
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineQueries.php
@@ -0,0 +1,176 @@
+summaries(MachineModel::query()
+ ->with('counters.latestReading')
+ ->when(! $includeInactive, fn ($query) => $query->where('is_active', true))
+ ->orderBy('name')
+ ->get());
+ }
+
+ public function findMachine(int $id): ?MachineSummary
+ {
+ $model = MachineModel::query()->with('counters.latestReading')->find($id);
+
+ return $model === null ? null : $this->summaries(collect([$model]))[0];
+ }
+
+ public function machinesFor(array $serviceUnitIds): array
+ {
+ if ($serviceUnitIds === []) {
+ return [];
+ }
+
+ return $this->summaries(MachineModel::query()
+ ->with('counters.latestReading')
+ ->where('is_active', true)
+ ->whereIn('id', DB::table('machine_service_units')->select('machine_id')->whereIn('service_unit_id', $serviceUnitIds))
+ ->orderBy('name')
+ ->get());
+ }
+
+ public function rowForTask(int $taskId): ?QueueRow
+ {
+ $model = MachineQueueEntryModel::query()->where('task_id', $taskId)->whereNull('completed_at')->first();
+
+ return $model === null ? null : $this->toRow($model, null, false);
+ }
+
+ public function rowsOn(int $machineId, string $day, string $today): array
+ {
+ $models = MachineQueueEntryModel::query()
+ ->where('machine_id', $machineId)
+ ->whereNull('completed_at')
+ ->when(
+ $day === $today,
+ fn ($query) => $query->where('planned_on', '<=', $day),
+ fn ($query) => $query->where('planned_on', $day),
+ )
+ ->get();
+
+ $infos = $this->tasks->infos($models->pluck('task_id')->filter()->unique()->values()->all());
+
+ return $models
+ ->sortBy(fn (MachineQueueEntryModel $model): string => sprintf(
+ '%d-%d-%s-%05d-%010d',
+ $model->quick_sale_order_line_id === null ? 1 : 0,
+ substr($model->planned_on, 0, 10) < $day ? 0 : 1,
+ substr($model->planned_on, 0, 10),
+ $model->position,
+ $model->id,
+ ))
+ ->map(fn (MachineQueueEntryModel $model): QueueRow => $this->toRow(
+ $model,
+ $model->task_id === null ? null : ($infos[$model->task_id] ?? null),
+ substr($model->planned_on, 0, 10) < $day,
+ ))
+ ->values()
+ ->all();
+ }
+
+ public function load(int $machineId, string $from, int $days): array
+ {
+ $to = CarbonImmutable::parse($from)->addDays($days - 1)->format('Y-m-d');
+ $models = MachineQueueEntryModel::query()
+ ->where('machine_id', $machineId)
+ ->whereNull('completed_at')
+ ->whereBetween('planned_on', [$from, $to])
+ ->get();
+ $infos = $this->tasks->infos($models->pluck('task_id')->filter()->unique()->values()->all());
+ $loads = [];
+
+ for ($i = 0; $i < $days; $i++) {
+ $day = CarbonImmutable::parse($from)->addDays($i)->format('Y-m-d');
+ $rows = $models->filter(fn (MachineQueueEntryModel $model): bool => substr($model->planned_on, 0, 10) === $day);
+ $quarters = $rows->sum(function (MachineQueueEntryModel $model) use ($infos): int {
+ $hours = $model->task_id === null ? null : ($infos[$model->task_id]->estimatedHours ?? null);
+
+ return $hours === null ? 0 : (int) round((float) $hours * 4);
+ });
+
+ $loads[] = new DayLoad($day, $rows->count(), $quarters);
+ }
+
+ return $loads;
+ }
+
+ private function toRow(MachineQueueEntryModel $model, mixed $task, bool $isLate): QueueRow
+ {
+ return new QueueRow(
+ entryId: $model->id,
+ machineId: $model->machine_id,
+ plannedOn: substr($model->planned_on, 0, 10),
+ position: $model->position,
+ isLate: $isLate,
+ taskId: $model->task_id,
+ orderLineId: $model->quick_sale_order_line_id,
+ stepPosition: $model->production_step_position,
+ task: $task,
+ );
+ }
+
+ /**
+ * @param Collection $models
+ * @return list
+ */
+ private function summaries(Collection $models): array
+ {
+ $unitIdsByMachine = DB::table('machine_service_units')
+ ->whereIn('machine_id', $models->pluck('id'))
+ ->get()
+ ->groupBy('machine_id')
+ ->map(fn ($rows) => $rows->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->values()->all());
+ $unitNames = $this->catalog->serviceUnitNames($unitIdsByMachine->flatten()->unique()->values()->all());
+ $userNames = $this->users->namesByIds($models->pluck('responsible_user_id')->filter()->unique()->values()->all());
+
+ return $models->map(function (MachineModel $model) use ($unitIdsByMachine, $unitNames, $userNames): MachineSummary {
+ $unitIds = $unitIdsByMachine->get($model->id, []);
+
+ return new MachineSummary(
+ id: $model->id,
+ name: $model->name,
+ type: $model->type,
+ description: $model->description,
+ serviceUnitIds: $unitIds,
+ serviceUnitNames: array_values(array_intersect_key($unitNames, array_flip($unitIds))),
+ responsibleUserId: $model->responsible_user_id,
+ responsibleName: $model->responsible_user_id === null ? null : ($userNames[$model->responsible_user_id] ?? ''),
+ counters: $model->counters->map(fn (MachineCounterModel $counter): CounterSummary => new CounterSummary(
+ $counter->id,
+ $counter->name,
+ $counter->unit,
+ $counter->latestReading?->reading_milli,
+ $counter->latestReading === null ? null : Carbon::instance($counter->latestReading->read_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
+ ))->values()->all(),
+ isActive: $model->is_active,
+ );
+ })->values()->all();
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineRepository.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineRepository.php
new file mode 100644
index 0000000..e621019
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMachineRepository.php
@@ -0,0 +1,77 @@
+with('counters')->find($id);
+
+ return $model === null ? null : $this->toEntity($model);
+ }
+
+ public function save(Machine $machine): Machine
+ {
+ $model = $machine->id() === null ? new MachineModel : MachineModel::query()->findOrFail($machine->id());
+
+ $model->fill([
+ 'name' => $machine->name()->value,
+ 'type' => $machine->type(),
+ 'description' => $machine->description(),
+ 'responsible_user_id' => $machine->responsibleUserId(),
+ 'is_active' => $machine->isActive(),
+ ])->save();
+
+ DB::table('machine_service_units')->where('machine_id', $model->id)->delete();
+ DB::table('machine_service_units')->insert(array_map(
+ fn (int $unitId): array => ['machine_id' => $model->id, 'service_unit_id' => $unitId],
+ $machine->serviceUnitIds(),
+ ));
+
+ $keptIds = [];
+
+ foreach ($machine->counters() as $index => $counter) {
+ $counterModel = $counter->id === null
+ ? new MachineCounterModel(['machine_id' => $model->id])
+ : MachineCounterModel::query()->where('machine_id', $model->id)->findOrFail($counter->id);
+
+ $counterModel->fill(['name' => $counter->name, 'unit' => $counter->unit, 'sort_order' => $index + 1])->save();
+ $keptIds[] = $counterModel->id;
+ }
+
+ MachineCounterModel::query()->where('machine_id', $model->id)->whereNotIn('id', $keptIds)->delete();
+
+ return $this->toEntity($model->load('counters'));
+ }
+
+ public function isNameTaken(string $name, ?int $exceptId = null): bool
+ {
+ return MachineModel::query()
+ ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
+ ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
+ ->exists();
+ }
+
+ private function toEntity(MachineModel $model): Machine
+ {
+ return Machine::reconstitute(
+ $model->id,
+ new MachineName($model->name),
+ $model->type,
+ $model->description,
+ DB::table('machine_service_units')->where('machine_id', $model->id)->orderBy('service_unit_id')->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->values()->all(),
+ $model->responsible_user_id,
+ $model->counters->map(fn (MachineCounterModel $counter): MachineCounter => new MachineCounter($counter->id, $counter->name, $counter->unit))->values()->all(),
+ $model->is_active,
+ );
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentQueueRepository.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentQueueRepository.php
new file mode 100644
index 0000000..22dc204
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentQueueRepository.php
@@ -0,0 +1,86 @@
+find($id);
+
+ return $model === null ? null : $this->toEntity($model);
+ }
+
+ public function openEntryForTask(int $taskId): ?QueueEntry
+ {
+ $model = MachineQueueEntryModel::query()->where('task_id', $taskId)->whereNull('completed_at')->first();
+
+ return $model === null ? null : $this->toEntity($model);
+ }
+
+ public function openEntryForOrderLine(int $orderLineId): ?QueueEntry
+ {
+ $model = MachineQueueEntryModel::query()->where('quick_sale_order_line_id', $orderLineId)->whereNull('completed_at')->first();
+
+ return $model === null ? null : $this->toEntity($model);
+ }
+
+ public function openEntriesOn(int $machineId, DateTimeImmutable $day): array
+ {
+ return MachineQueueEntryModel::query()
+ ->where('machine_id', $machineId)
+ ->where('planned_on', $day->format('Y-m-d'))
+ ->whereNull('completed_at')
+ ->orderBy('position')
+ ->orderBy('id')
+ ->get()
+ ->map(fn (MachineQueueEntryModel $model): QueueEntry => $this->toEntity($model))
+ ->values()
+ ->all();
+ }
+
+ public function save(QueueEntry $entry): QueueEntry
+ {
+ $model = $entry->id() === null ? new MachineQueueEntryModel : MachineQueueEntryModel::query()->findOrFail($entry->id());
+
+ $model->fill([
+ 'machine_id' => $entry->machineId(),
+ 'planned_on' => $entry->plannedOn()->format('Y-m-d'),
+ 'position' => $entry->position(),
+ 'task_id' => $entry->taskId(),
+ 'quick_sale_order_line_id' => $entry->orderLineId(),
+ 'production_step_position' => $entry->stepPosition(),
+ 'completed_at' => $entry->completedAt()?->format('Y-m-d H:i:s'),
+ 'completed_by' => $entry->completedBy(),
+ ])->save();
+
+ return $this->toEntity($model);
+ }
+
+ public function delete(QueueEntry $entry): void
+ {
+ if ($entry->id() !== null) {
+ MachineQueueEntryModel::query()->whereKey($entry->id())->delete();
+ }
+ }
+
+ private function toEntity(MachineQueueEntryModel $model): QueueEntry
+ {
+ return QueueEntry::reconstitute(
+ $model->id,
+ $model->machine_id,
+ new DateTimeImmutable(substr($model->planned_on, 0, 10)),
+ $model->position,
+ $model->task_id,
+ $model->quick_sale_order_line_id,
+ $model->production_step_position,
+ $model->completed_at === null ? null : DateTimeImmutable::createFromInterface($model->completed_at),
+ $model->completed_by,
+ );
+ }
+}
diff --git a/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php
new file mode 100644
index 0000000..69ad43a
--- /dev/null
+++ b/app/Modules/Machines/Infrastructure/Providers/MachinesServiceProvider.php
@@ -0,0 +1,60 @@
+
+ */
+ public array $bindings = [
+ MachineRepository::class => EloquentMachineRepository::class,
+ QueueRepository::class => EloquentQueueRepository::class,
+ MachineQueries::class => EloquentMachineQueries::class,
+ MachineTasks::class => JobsForMachines::class,
+ ];
+
+ public function boot(): void
+ {
+ $presentationPath = dirname(__DIR__, 2).'/Presentation';
+
+ Livewire::addNamespace('machines', viewPath: $presentationPath.'/Livewire');
+
+ if (! $this->app->routesAreCached()) {
+ $this->loadRoutesFrom($presentationPath.'/Routes/web.php');
+ }
+
+ // A task marked done elsewhere leaves its machine's work list.
+ Event::listen(TaskCompleted::class, fn (TaskCompleted $event) => app(MachineWorkList::class)->closeTask($event->taskId));
+
+ $staff = fn (User $user): bool => $user->role !== Role::Subcontractor;
+
+ // Moving tasks to machines, the console and maintenance records: everyone but subcontractors (spec 19.9).
+ Gate::define('machines.use', $staff);
+ Gate::define('machines.manage', fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true));
+ Gate::define('machines.menu', fn (User $user): bool => $staff($user) && app(CatalogQueries::class)->stockServiceUnitIds() !== []);
+ }
+}
diff --git a/app/Modules/Machines/Presentation/Livewire/Concerns/FormatsMachines.php b/app/Modules/Machines/Presentation/Livewire/Concerns/FormatsMachines.php
new file mode 100644
index 0000000..803a03b
--- /dev/null
+++ b/app/Modules/Machines/Presentation/Livewire/Concerns/FormatsMachines.php
@@ -0,0 +1,47 @@
+ 10
+ ? CarbonImmutable::createFromFormat('Y-m-d H:i', $value)->format('j.n.Y \k\l\o H.i')
+ : CarbonImmutable::createFromFormat('!Y-m-d', $value)->format('j.n.Y');
+ }
+
+ /**
+ * "ti 24.11." for "2026-11-24".
+ */
+ public function shortDay(string $value): string
+ {
+ $date = CarbonImmutable::createFromFormat('!Y-m-d', $value)->locale(app()->getLocale());
+
+ return $date->isoFormat('dd').' '.$date->format('j.n.');
+ }
+
+ public function quarters(int $quarters): string
+ {
+ return rtrim(rtrim(number_format($quarters / 4, 2, ',', ''), '0'), ',');
+ }
+
+ /**
+ * A counter reading in thousandths, e.g. "20 000" or "12,5".
+ */
+ public function reading(int $milli): string
+ {
+ $whole = intdiv(abs($milli), 1000);
+ $fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0');
+
+ return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction);
+ }
+}
diff --git a/app/Modules/Machines/Presentation/Livewire/⚡form.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡form.blade.php
new file mode 100644
index 0000000..4d34b78
--- /dev/null
+++ b/app/Modules/Machines/Presentation/Livewire/⚡form.blade.php
@@ -0,0 +1,323 @@
+
+ */
+ #[Locked]
+ public array $storedUnitIds = [];
+
+ #[Locked]
+ public bool $isActive = true;
+
+ public string $name = '';
+
+ public string $type = 'printer';
+
+ public string $description = '';
+
+ /**
+ * @var list
+ */
+ public array $serviceUnitIds = [];
+
+ public string $responsibleUserId = '';
+
+ /**
+ * @var list
+ */
+ public array $counters = [];
+
+ public int $nextKey = 1;
+
+ #[Locked]
+ public string $message = '';
+
+ public function mount(MachineQueries $machines, ?int $machine = null): void
+ {
+ $this->authorize('machines.manage');
+
+ if ($machine === null) {
+ $stockUnits = app(CatalogQueries::class)->stockServiceUnitIds();
+ $this->serviceUnitIds = count($stockUnits) === 1 ? [(string) $stockUnits[0]] : [];
+ $this->suggestCounters(announce: false);
+
+ return;
+ }
+
+ $summary = $machines->findMachine($machine) ?? abort(404);
+
+ $this->machineId = $summary->id;
+ $this->isActive = $summary->isActive;
+ $this->name = $summary->name;
+ $this->type = $summary->type->value;
+ $this->description = (string) $summary->description;
+ $this->serviceUnitIds = array_map('strval', $summary->serviceUnitIds);
+ $this->storedUnitIds = $summary->serviceUnitIds;
+ $this->responsibleUserId = (string) ($summary->responsibleUserId ?? '');
+
+ foreach ($summary->counters as $counter) {
+ $this->counters[] = ['key' => $this->nextKey++, 'id' => $counter->id, 'name' => $counter->name, 'unit' => $counter->unit->value];
+ }
+ }
+
+ /**
+ * @return list
+ */
+ #[Computed]
+ public function unitOptions(): array
+ {
+ $ids = array_values(array_unique(array_merge(app(CatalogQueries::class)->stockServiceUnitIds(), $this->storedUnitIds)));
+ $options = [];
+
+ foreach (app(CatalogQueries::class)->serviceUnitNames($ids) as $id => $name) {
+ $options[] = ['value' => $id, 'label' => $name];
+ }
+
+ return $options;
+ }
+
+ /**
+ * @return list
+ */
+ #[Computed]
+ public function users(): array
+ {
+ return app(UserAccountQueries::class)->activeUserOptions();
+ }
+
+ public function addCounter(): void
+ {
+ $this->authorize('machines.manage');
+
+ $key = $this->nextKey++;
+ $this->counters[] = ['key' => $key, 'id' => null, 'name' => '', 'unit' => CounterUnit::Piece->value];
+ $this->message = __('machines.form.counter_added', ['number' => count($this->counters)]);
+ $this->js("document.getElementById('counter-{$key}-name')?.focus()");
+ }
+
+ public function removeCounter(int $index): void
+ {
+ $this->authorize('machines.manage');
+
+ if (! isset($this->counters[$index])) {
+ return;
+ }
+
+ array_splice($this->counters, $index, 1);
+ $this->resetErrorBag();
+ $this->message = __('machines.form.counter_removed', ['number' => $index + 1]);
+ $this->js("document.getElementById('add-counter')?.focus()");
+ }
+
+ /**
+ * Adds the usual counters of the machine type that are not there yet.
+ */
+ public function suggestCounters(bool $announce = true): void
+ {
+ $this->authorize('machines.manage');
+
+ $added = 0;
+ $names = array_map(fn (array $counter): string => mb_strtolower($counter['name']), $this->counters);
+
+ foreach ((MachineType::tryFrom($this->type) ?? MachineType::Other)->suggestedCounters() as $suggestion) {
+ $name = __('machines.counter_names.'.$suggestion['name']);
+
+ if (! in_array(mb_strtolower($name), $names, true)) {
+ $this->counters[] = ['key' => $this->nextKey++, 'id' => null, 'name' => $name, 'unit' => $suggestion['unit']->value];
+ $added++;
+ }
+ }
+
+ if ($announce) {
+ $this->message = trans_choice('machines.form.counters_suggested', $added, ['count' => $added]);
+ }
+ }
+
+ public function save(SaveMachine $saveMachine): void
+ {
+ $this->authorize('machines.manage');
+ $this->resetErrorBag();
+
+ $this->validate([
+ 'type' => ['required', 'in:'.implode(',', array_column(MachineType::cases(), 'value'))],
+ 'description' => ['nullable', 'string', 'max:5000'],
+ 'serviceUnitIds' => ['array'],
+ 'serviceUnitIds.*' => ['integer'],
+ 'responsibleUserId' => ['nullable', 'integer'],
+ 'counters.*.unit' => ['required', 'in:'.implode(',', array_column(CounterUnit::cases(), 'value'))],
+ ]);
+
+ $data = new MachineData(
+ $this->name,
+ $this->type,
+ $this->description,
+ array_map('intval', $this->serviceUnitIds),
+ $this->responsibleUserId === '' ? null : (int) $this->responsibleUserId,
+ array_map(fn (array $counter): array => ['id' => $counter['id'], 'name' => $counter['name'], 'unit' => $counter['unit']], $this->counters),
+ );
+
+ try {
+ if ($this->machineId === null) {
+ $this->machineId = $saveMachine->add($data);
+ $status = __('machines.form.created', ['name' => trim($this->name)]);
+ } else {
+ $saveMachine->update($this->machineId, $data);
+ $status = __('machines.form.updated', ['name' => trim($this->name)]);
+ }
+ } catch (InvalidMachineName) {
+ $this->addError('name', __('machines.errors.name'));
+
+ return;
+ } catch (MachineNameTaken) {
+ $this->addError('name', __('machines.errors.name_taken'));
+
+ return;
+ } catch (MachineNeedsServiceUnit) {
+ $this->addError('serviceUnitIds', __('machines.errors.service_units'));
+
+ return;
+ } catch (InvalidCounter) {
+ $this->addError('counters', __('machines.errors.counter'));
+
+ return;
+ } catch (MachineNotFound) {
+ abort(404);
+ }
+
+ session()->flash('status', $status);
+ $this->redirectRoute('machines.show', $this->machineId, navigate: true);
+ }
+
+ public function toggleActive(SaveMachine $saveMachine): void
+ {
+ $this->authorize('machines.manage');
+
+ if ($this->machineId === null) {
+ return;
+ }
+
+ $saveMachine->setActive($this->machineId, ! $this->isActive);
+ $this->isActive = ! $this->isActive;
+ $this->message = __($this->isActive ? 'machines.form.activated' : 'machines.form.deactivated');
+ }
+
+ public function heading(): string
+ {
+ return __($this->machineId === null ? 'machines.form.create_title' : 'machines.form.edit_title');
+ }
+
+ public function render(): mixed
+ {
+ return $this->view()->title($this->heading());
+ }
+};
+?>
+
+
+
{{ $this->heading() }}
+
+
{{ $message }}
+
+
+
diff --git a/app/Modules/Machines/Presentation/Livewire/⚡index.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡index.blade.php
new file mode 100644
index 0000000..ea87091
--- /dev/null
+++ b/app/Modules/Machines/Presentation/Livewire/⚡index.blade.php
@@ -0,0 +1,138 @@
+authorize('machines.use');
+ }
+
+ /**
+ * @return array Service units that use stock or have machines.
+ */
+ #[Computed]
+ public function units(): array
+ {
+ $ids = array_unique(array_merge(
+ app(CatalogQueries::class)->stockServiceUnitIds(),
+ ...array_map(fn (MachineSummary $machine): array => $machine->serviceUnitIds, $this->machines),
+ ));
+
+ return app(CatalogQueries::class)->serviceUnitNames(array_values($ids));
+ }
+
+ /**
+ * @return list
+ */
+ #[Computed]
+ public function machines(): array
+ {
+ return app(MachineQueries::class)->machines($this->includeInactive && Gate::allows('machines.manage'));
+ }
+
+ /**
+ * Machines by unit name; a shared machine is under each of its units.
+ *
+ * @return array>
+ */
+ public function grouped(): array
+ {
+ $groups = [];
+
+ foreach ($this->units as $unitId => $unitName) {
+ if ($this->unit !== '' && (int) $this->unit !== $unitId) {
+ continue;
+ }
+
+ $machines = array_values(array_filter($this->machines, fn (MachineSummary $machine): bool => in_array($unitId, $machine->serviceUnitIds, true)));
+
+ if ($machines !== []) {
+ $groups[$unitName] = $machines;
+ }
+ }
+
+ return $groups;
+ }
+
+ public function updated(): void
+ {
+ $this->authorize('machines.use');
+ unset($this->machines, $this->units);
+ }
+
+ public function render(): mixed
+ {
+ return $this->view()->title(__('machines.index.title'));
+ }
+};
+?>
+
+
+
+
{{ __('machines.index.title') }}
+
{{ __('machines.index.intro') }}
+ @can('machines.manage')
+
+ @endcan
+
+
+
+
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
+
+
+ @foreach ($this->units as $unitId => $unitName)
+
+ @endforeach
+
+
+ @can('machines.manage')
+
+ @endcan
+
+
+ @forelse ($this->grouped() as $unitName => $machines)
+
+