Record used material on tasks and suggest workflow steps' default materials

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:28:16 +02:00
co-authored by Claude Sonnet 5.5
parent 30132deb0e
commit bca1eed166
41 changed files with 1521 additions and 19 deletions
@@ -5,27 +5,45 @@ declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A step of a workflow template as entered. A null work type means the template's own.
* A step of a workflow template as entered. A null work type means the
* template's own. Materials are the step's default materials: a stock item
* id and the quantity as typed ("2,5").
*/
final readonly class WorkflowStepData
{
/**
* @param list<array{stockItemId: int, quantity: string}> $materials
*/
public function __construct(
public string $title,
public ?string $description = null,
public ?int $workTypeId = null,
public array $materials = [],
) {}
/**
* @param array{title?: string, description?: string|null, work_type_id?: int|string|null} $input
* Rows without an item are left out.
*
* @param array{title?: string, description?: string|null, work_type_id?: int|string|null, materials?: list<array{stock_item_id?: int|string|null, quantity?: string|null}>} $input
*/
public static function fromArray(array $input): self
{
$workTypeId = $input['work_type_id'] ?? null;
$materials = [];
foreach ($input['materials'] ?? [] as $material) {
$itemId = $material['stock_item_id'] ?? null;
if ($itemId !== null && $itemId !== '') {
$materials[] = ['stockItemId' => (int) $itemId, 'quantity' => (string) ($material['quantity'] ?? '')];
}
}
return new self(
(string) ($input['title'] ?? ''),
$input['description'] ?? null,
$workTypeId === null || $workTypeId === '' ? null : (int) $workTypeId,
$materials,
);
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A default material of a workflow step: a stock item and its quantity in
* thousandths of the item's unit.
*/
final readonly class WorkflowStepMaterialSummary
{
public function __construct(
public int $stockItemId,
public int $quantityMilli,
) {}
}
@@ -6,15 +6,20 @@ namespace App\Modules\Catalog\Application\DTOs;
/**
* A step of a workflow template. $workTypeId is the step's own work type
* (null: the template's), $effectiveWorkTypeId the one its task gets.
* (null: the template's), $effectiveWorkTypeId the one its task gets, and
* $materials the default materials suggested on the task.
*/
final readonly class WorkflowStepSummary
{
/**
* @param list<WorkflowStepMaterialSummary> $materials
*/
public function __construct(
public string $title,
public ?string $description,
public ?int $workTypeId,
public int $effectiveWorkTypeId,
public string $workTypeName,
public array $materials = [],
) {}
}
@@ -8,9 +8,11 @@ use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepMaterial;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
/**
@@ -28,6 +30,7 @@ final class WorkflowStepBuilder
* @return list<WorkflowStep>
*
* @throws InvalidWorkflowStepTitle with the index of the step
* @throws InvalidWorkflowStepMaterial with the indexes of the step and the material
*/
public function build(array $input): array
{
@@ -40,7 +43,17 @@ final class WorkflowStepBuilder
throw new InvalidWorkflowStepTitle($index);
}
$steps[] = new WorkflowStep($title, $step->description, $step->workTypeId);
$materials = [];
foreach ($step->materials as $materialIndex => $material) {
try {
$materials[] = WorkflowStepMaterial::parse($material['stockItemId'], $material['quantity']);
} catch (InvalidWorkflowStepMaterial) {
throw new InvalidWorkflowStepMaterial($index, $materialIndex);
}
}
$steps[] = new WorkflowStep($title, $step->description, $step->workTypeId, $materials);
}
return $steps;
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A step's default material has no item or no valid quantity. $stepIndex
* and $materialIndex count from 0 when known.
*/
final class InvalidWorkflowStepMaterial extends DomainException
{
public function __construct(public readonly ?int $stepIndex = null, public readonly ?int $materialIndex = null)
{
parent::__construct('A default material needs an item and a quantity greater than zero.');
}
}
@@ -7,16 +7,20 @@ namespace App\Modules\Catalog\Domain\ValueObjects;
/**
* One step of a workflow template. A task is made of it: the title, the
* description and the work type, which is the template's own when
* $workTypeId is null.
* $workTypeId is null, and the default materials suggested on the task.
*/
final readonly class WorkflowStep
{
public ?string $description;
/**
* @param list<WorkflowStepMaterial> $materials
*/
public function __construct(
public WorkflowStepTitle $title,
?string $description = null,
public ?int $workTypeId = null,
public array $materials = [],
) {
$description = $description === null ? '' : trim($description);
$this->description = $description === '' ? null : $description;
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
/**
* A default material of a workflow step (spec 19.4): a stock item and its
* quantity in thousandths of the item's unit, suggested on the step's task.
*/
final readonly class WorkflowStepMaterial
{
public const int MAX_MILLI = 9_999_999_999;
public function __construct(
public int $stockItemId,
public int $quantityMilli,
) {
if ($stockItemId < 1 || $quantityMilli < 1 || $quantityMilli > self::MAX_MILLI) {
throw new InvalidWorkflowStepMaterial;
}
}
/**
* A quantity typed as "2,5" or "2.5", with at most three decimals.
*
* @throws InvalidWorkflowStepMaterial
*/
public static function parse(int $stockItemId, string $quantity): self
{
$quantity = str_replace(',', '.', preg_replace('/[\s\x{00A0}]+/u', '', $quantity) ?? '');
if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $quantity, $matches) !== 1) {
throw new InvalidWorkflowStepMaterial;
}
return new self($stockItemId, (int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0'));
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property int $workflow_template_step_id
* @property int $stock_item_id
* @property int $quantity_milli
* @property int $sort_order
*/
#[Table('workflow_template_step_materials')]
#[Fillable(['workflow_template_step_id', 'stock_item_id', 'quantity_milli', 'sort_order'])]
class WorkflowTemplateStepMaterialModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'workflow_template_step_id' => 'integer',
'stock_item_id' => 'integer',
'quantity_milli' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -5,6 +5,7 @@ namespace App\Modules\Catalog\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;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
@@ -20,6 +21,14 @@ use Illuminate\Database\Eloquent\Model;
#[Fillable(['workflow_template_id', 'work_type_id', 'title', 'description', 'sort_order'])]
class WorkflowTemplateStepModel extends Model
{
/**
* @return HasMany<WorkflowTemplateStepMaterialModel, $this>
*/
public function materials(): HasMany
{
return $this->hasMany(WorkflowTemplateStepMaterialModel::class, 'workflow_template_step_id')->orderBy('sort_order');
}
/**
* @return array<string, string>
*/
@@ -3,10 +3,12 @@
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowStepMaterialSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowStepSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepMaterialModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Builder;
@@ -93,6 +95,7 @@ class EloquentWorkflowTemplateQueries implements WorkflowTemplateQueries
}
$steps = WorkflowTemplateStepModel::query()
->with('materials')
->whereIn('workflow_template_id', $models->pluck('id'))
->orderBy('sort_order')
->get()
@@ -119,6 +122,10 @@ class EloquentWorkflowTemplateQueries implements WorkflowTemplateQueries
$step->work_type_id,
$step->work_type_id ?? $model->work_type_id,
$step->work_type_id === null ? $workTypeName : (string) $workTypeNames->get($step->work_type_id),
$step->materials
->map(fn (WorkflowTemplateStepMaterialModel $material): WorkflowStepMaterialSummary => new WorkflowStepMaterialSummary($material->stock_item_id, $material->quantity_milli))
->values()
->all(),
))
->values()
->all(),
@@ -6,15 +6,17 @@ use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Entities\WorkflowTemplate;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepMaterial;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepMaterialModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
{
public function findById(int $id): ?WorkflowTemplate
{
$model = WorkflowTemplateModel::query()->with('steps')->find($id);
$model = WorkflowTemplateModel::query()->with('steps.materials')->find($id);
return $model === null ? null : $this->toEntity($model);
}
@@ -33,16 +35,25 @@ class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
WorkflowTemplateStepModel::query()->where('workflow_template_id', $model->id)->delete();
foreach ($template->steps() as $index => $step) {
WorkflowTemplateStepModel::query()->create([
$stepModel = WorkflowTemplateStepModel::query()->create([
'workflow_template_id' => $model->id,
'work_type_id' => $step->workTypeId,
'title' => $step->title->value,
'description' => $step->description,
'sort_order' => $index + 1,
]);
foreach ($step->materials as $materialIndex => $material) {
WorkflowTemplateStepMaterialModel::query()->create([
'workflow_template_step_id' => $stepModel->id,
'stock_item_id' => $material->stockItemId,
'quantity_milli' => $material->quantityMilli,
'sort_order' => $materialIndex + 1,
]);
}
}
return $this->toEntity($model->load('steps'));
return $this->toEntity($model->load('steps.materials'));
}
public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool
@@ -66,6 +77,10 @@ class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
new WorkflowStepTitle($step->title),
$step->description,
$step->work_type_id,
$step->materials
->map(fn (WorkflowTemplateStepMaterialModel $material): WorkflowStepMaterial => new WorkflowStepMaterial($material->stock_item_id, $material->quantity_milli))
->values()
->all(),
))
->values()
->all(),
@@ -6,6 +6,7 @@ use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepMaterial;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken;
@@ -24,16 +25,34 @@ class WorkflowTemplateForm extends Form
public string $work_type_id = '';
/**
* @var list<array{key: int, title: string, work_type_id: string, description: string}>
* @var list<array{key: int, title: string, work_type_id: string, description: string, materials: list<array{key: int, stock_item_id: string, quantity: string}>}>
*/
public array $steps = [];
public int $nextKey = 1;
public function addStep(string $title = '', string $workTypeId = '', string $description = ''): int
/**
* @param list<array{stock_item_id: string, quantity: string}> $materials
*/
public function addStep(string $title = '', string $workTypeId = '', string $description = '', array $materials = []): int
{
$key = $this->nextKey++;
$this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description];
$this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description, 'materials' => []];
foreach ($materials as $material) {
$this->addMaterial(count($this->steps) - 1, $material['stock_item_id'], $material['quantity']);
}
return $key;
}
/**
* Adds a default material row to a step and returns its key.
*/
public function addMaterial(int $stepIndex, string $stockItemId = '', string $quantity = '1'): int
{
$key = $this->nextKey++;
$this->steps[$stepIndex]['materials'][] = ['key' => $key, 'stock_item_id' => $stockItemId, 'quantity' => $quantity];
return $key;
}
@@ -60,6 +79,7 @@ class WorkflowTemplateForm extends Form
$exception instanceof CatalogItemNotFound => ['work_type_id', 'catalog.errors.work_type_unavailable'],
$exception instanceof WorkflowTemplateNeedsSteps => ['steps', 'catalog.workflows.errors.steps_required'],
$exception instanceof InvalidWorkflowStepTitle => ['steps.'.($exception->stepIndex ?? 0).'.title', 'catalog.workflows.errors.invalid_step_title'],
$exception instanceof InvalidWorkflowStepMaterial => ['steps.'.($exception->stepIndex ?? 0).'.materials.'.($exception->materialIndex ?? 0).'.quantity', 'catalog.workflows.errors.invalid_material'],
$exception instanceof WorkflowStepWorkTypeNotAllowed => ['steps.'.$exception->stepIndex.'.work_type_id', 'catalog.workflows.errors.step_work_type_not_allowed'],
default => throw $exception,
};
@@ -79,6 +99,9 @@ class WorkflowTemplateForm extends Form
'steps.*.title' => ['required', 'string', 'max:255'],
'steps.*.work_type_id' => ['nullable', 'integer'],
'steps.*.description' => ['nullable', 'string', 'max:5000'],
'steps.*.materials' => ['array'],
'steps.*.materials.*.stock_item_id' => ['nullable', 'integer'],
'steps.*.materials.*.quantity' => ['nullable', 'string', 'max:20'],
];
}
@@ -98,6 +121,8 @@ class WorkflowTemplateForm extends Form
'steps.*.title.max' => __('catalog.workflows.errors.invalid_step_title'),
'steps.*.work_type_id.integer' => __('catalog.workflows.errors.step_work_type_not_allowed'),
'steps.*.description.max' => __('catalog.workflows.errors.description_too_long'),
'steps.*.materials.*.stock_item_id.integer' => __('catalog.workflows.errors.invalid_material'),
'steps.*.materials.*.quantity.max' => __('catalog.workflows.errors.invalid_material'),
];
}
}
@@ -7,6 +7,8 @@ use App\Modules\Catalog\Application\UseCases\AddWorkflowTemplate;
use App\Modules\Catalog\Application\UseCases\UpdateWorkflowTemplate;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\WorkflowTemplateForm;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
@@ -15,7 +17,8 @@ use Livewire\Component;
/**
* Add page and edit page (with {template}) of a workflow template: its name,
* work type and steps. Steps are added, moved and removed with buttons, and
* everything is saved at once.
* everything is saved at once. A step whose work type's service unit uses
* stock may have default materials, suggested on its tasks (spec 19.4).
*/
new class extends Component
{
@@ -54,7 +57,15 @@ new class extends Component
$this->storedWorkTypeIds = [$details->workTypeId];
foreach ($details->steps as $step) {
$this->form->addStep($step->title, $step->workTypeId === null ? '' : (string) $step->workTypeId, $step->description ?? '');
$this->form->addStep(
$step->title,
$step->workTypeId === null ? '' : (string) $step->workTypeId,
$step->description ?? '',
array_map(fn ($material): array => [
'stock_item_id' => (string) $material->stockItemId,
'quantity' => rtrim(rtrim(number_format($material->quantityMilli / 1000, 3, ',', ''), '0'), ','),
], $step->materials),
);
if ($step->workTypeId !== null) {
$this->storedWorkTypeIds[] = $step->workTypeId;
@@ -87,6 +98,77 @@ new class extends Component
return $workType === null ? [] : $this->groups($catalog->activeWorkTypesFor([$workType->serviceUnitId]));
}
/**
* Stock items in use, for default materials.
*
* @return list<StockItemSummary>
*/
#[Computed]
public function stockItems(): array
{
return app(StockQueries::class)->items();
}
/**
* Whether the step's work type (or the template's) belongs to a service
* unit that uses stock; a shared work type follows the template's unit.
*/
public function stepUsesStock(int $index): bool
{
$catalog = app(CatalogQueries::class);
$stockUnitIds = $catalog->stockServiceUnitIds();
if ($stockUnitIds === [] || $this->stockItems === []) {
return false;
}
$templateWorkType = $this->form->work_type_id === '' ? null : $catalog->findWorkType((int) $this->form->work_type_id);
$stepWorkTypeId = $this->form->steps[$index]['work_type_id'] ?? '';
$workType = $stepWorkTypeId === '' ? $templateWorkType : $catalog->findWorkType((int) $stepWorkTypeId);
if ($workType === null) {
return false;
}
$unitId = ($catalog->findServiceUnit($workType->serviceUnitId)?->isShared ?? false)
? $templateWorkType?->serviceUnitId
: $workType->serviceUnitId;
return $unitId !== null && in_array($unitId, $stockUnitIds, true);
}
public function addMaterial(int $index): void
{
$this->authorize('catalog.manage');
if (! isset($this->form->steps[$index])) {
return;
}
$key = $this->form->addMaterial($index);
$this->statusMessage = __('catalog.workflows.status.material_added', ['number' => $index + 1]);
$this->js("document.getElementById('material-{$key}-item')?.focus()");
}
public function removeMaterial(int $index, int $materialIndex): void
{
$this->authorize('catalog.manage');
$materials = array_values($this->form->steps[$index]['materials'] ?? []);
if (! isset($materials[$materialIndex])) {
return;
}
array_splice($materials, $materialIndex, 1);
$this->form->steps[$index]['materials'] = $materials;
$this->resetErrorBag();
$this->statusMessage = __('catalog.workflows.status.material_removed', ['number' => $index + 1]);
$stepKey = $this->form->steps[$index]['key'];
$this->js("document.getElementById('step-{$stepKey}-add-material')?.focus()");
}
public function addStep(): void
{
$this->authorize('catalog.manage');
@@ -303,6 +385,59 @@ new class extends Component
resize-auto
/>
@if ($this->stepUsesStock($index) || ($step['materials'] ?? []) !== [])
<fieldset class="space-y-3">
<legend class="text-sm font-semibold">{{ __('catalog.workflows.materials') }}</legend>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.materials_help') }}</p>
@foreach ($step['materials'] ?? [] as $materialIndex => $material)
<div wire:key="material-{{ $material['key'] }}-{{ $materialIndex }}" class="flex flex-wrap items-end gap-2">
<div class="min-w-48 flex-1">
<x-select.native
id="material-{{ $material['key'] }}-item"
wire:model="form.steps.{{ $index }}.materials.{{ $materialIndex }}.stock_item_id"
:label="__('catalog.workflows.material_item')"
:aria-label="__('catalog.workflows.material_item_named', ['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="material-{{ $material['key'] }}-quantity"
wire:model="form.steps.{{ $index }}.materials.{{ $materialIndex }}.quantity"
inputmode="decimal"
:label="__('catalog.workflows.material_quantity')"
autocomplete="off"
/>
</div>
<x-button
wire:click="removeMaterial({{ $index }}, {{ $materialIndex }})"
subtle
color="black"
sm
icon="trash"
:aria-label="__('catalog.workflows.remove_material_named', ['step' => $index + 1, 'number' => $materialIndex + 1])"
/>
</div>
@endforeach
<x-button
id="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])"
/>
</fieldset>
@endif
<div class="flex flex-wrap gap-2">
<x-button
id="step-{{ $step['key'] }}-up"