From bca1eed166e3a66b94399cf45d5e5b1e4623a842 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Thu, 26 Nov 2026 16:28:16 +0200 Subject: [PATCH] Record used material on tasks and suggest workflow steps' default materials Co-Authored-By: Claude Sonnet 5.5 --- .../Application/DTOs/WorkflowStepData.php | 22 +- .../DTOs/WorkflowStepMaterialSummary.php | 17 + .../Application/DTOs/WorkflowStepSummary.php | 7 +- .../Services/WorkflowStepBuilder.php | 15 +- .../InvalidWorkflowStepMaterial.php | 19 + .../Domain/ValueObjects/WorkflowStep.php | 6 +- .../ValueObjects/WorkflowStepMaterial.php | 41 ++ .../WorkflowTemplateStepMaterialModel.php | 34 ++ .../Eloquent/WorkflowTemplateStepModel.php | 9 + .../EloquentWorkflowTemplateQueries.php | 7 + .../EloquentWorkflowTemplateRepository.php | 21 +- .../Livewire/Forms/WorkflowTemplateForm.php | 31 +- .../⚡workflow-template-form.blade.php | 139 ++++++- .../Application/Contracts/StockQueries.php | 14 + .../Application/Contracts/StockTasks.php | 23 ++ .../Application/DTOs/StockMovementSummary.php | 3 + .../Application/DTOs/StockTaskContext.php | 20 + .../DTOs/TaskMaterialSuggestion.php | 22 + .../Application/UseCases/TaskMaterials.php | 103 +++++ .../TaskMaterialSuggestionRepository.php | 21 + .../Exceptions/StockTaskNotAvailable.php | 15 + .../StockTaskSuggestionNotFound.php | 15 + .../Adapters/TaskUsageWithStock.php | 21 + .../Infrastructure/Adapters/TasksForStock.php | 70 ++++ .../Eloquent/TaskMaterialSuggestionModel.php | 32 ++ .../Repositories/EloquentStockQueries.php | 42 +- ...oquentTaskMaterialSuggestionRepository.php | 35 ++ .../Providers/InventoryServiceProvider.php | 19 + .../Livewire/⚡task-materials.blade.php | 391 ++++++++++++++++++ .../UseCases/AddTasksFromWorkflowTemplate.php | 12 +- .../Domain/Events/TaskMaterialsSuggested.php | 22 + .../Presentation/Livewire/⚡show.blade.php | 1 + ...workflow_template_step_materials_table.php | 40 ++ lang/en/catalog.php | 12 + lang/en/inventory.php | 26 ++ lang/en/jobs.php | 2 +- lang/fi/catalog.php | 12 + lang/fi/inventory.php | 26 ++ lang/fi/jobs.php | 2 +- tests/Browser/InventoryAccessibilityTest.php | 35 +- .../Modules/Inventory/TaskMaterialsTest.php | 136 ++++++ 41 files changed, 1521 insertions(+), 19 deletions(-) create mode 100644 app/Modules/Catalog/Application/DTOs/WorkflowStepMaterialSummary.php create mode 100644 app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepMaterial.php create mode 100644 app/Modules/Catalog/Domain/ValueObjects/WorkflowStepMaterial.php create mode 100644 app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepMaterialModel.php create mode 100644 app/Modules/Inventory/Application/Contracts/StockTasks.php create mode 100644 app/Modules/Inventory/Application/DTOs/StockTaskContext.php create mode 100644 app/Modules/Inventory/Application/DTOs/TaskMaterialSuggestion.php create mode 100644 app/Modules/Inventory/Application/UseCases/TaskMaterials.php create mode 100644 app/Modules/Inventory/Domain/Contracts/TaskMaterialSuggestionRepository.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockTaskNotAvailable.php create mode 100644 app/Modules/Inventory/Domain/Exceptions/StockTaskSuggestionNotFound.php create mode 100644 app/Modules/Inventory/Infrastructure/Adapters/TaskUsageWithStock.php create mode 100644 app/Modules/Inventory/Infrastructure/Adapters/TasksForStock.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Eloquent/TaskMaterialSuggestionModel.php create mode 100644 app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentTaskMaterialSuggestionRepository.php create mode 100644 app/Modules/Inventory/Presentation/Livewire/⚡task-materials.blade.php create mode 100644 app/Modules/Jobs/Domain/Events/TaskMaterialsSuggested.php create mode 100644 database/migrations/2026_11_26_141953_create_workflow_template_step_materials_table.php create mode 100644 tests/Feature/Modules/Inventory/TaskMaterialsTest.php diff --git a/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php b/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php index ce3593a..3dfc52f 100644 --- a/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php +++ b/app/Modules/Catalog/Application/DTOs/WorkflowStepData.php @@ -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 $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} $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, ); } } diff --git a/app/Modules/Catalog/Application/DTOs/WorkflowStepMaterialSummary.php b/app/Modules/Catalog/Application/DTOs/WorkflowStepMaterialSummary.php new file mode 100644 index 0000000..2a10ef2 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/WorkflowStepMaterialSummary.php @@ -0,0 +1,17 @@ + $materials + */ public function __construct( public string $title, public ?string $description, public ?int $workTypeId, public int $effectiveWorkTypeId, public string $workTypeName, + public array $materials = [], ) {} } diff --git a/app/Modules/Catalog/Application/Services/WorkflowStepBuilder.php b/app/Modules/Catalog/Application/Services/WorkflowStepBuilder.php index 4e1305f..b1e6a8a 100644 --- a/app/Modules/Catalog/Application/Services/WorkflowStepBuilder.php +++ b/app/Modules/Catalog/Application/Services/WorkflowStepBuilder.php @@ -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 * * @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; diff --git a/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepMaterial.php b/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepMaterial.php new file mode 100644 index 0000000..0528d03 --- /dev/null +++ b/app/Modules/Catalog/Domain/Exceptions/InvalidWorkflowStepMaterial.php @@ -0,0 +1,19 @@ + $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; diff --git a/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepMaterial.php b/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepMaterial.php new file mode 100644 index 0000000..bf050cf --- /dev/null +++ b/app/Modules/Catalog/Domain/ValueObjects/WorkflowStepMaterial.php @@ -0,0 +1,41 @@ + 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')); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepMaterialModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepMaterialModel.php new file mode 100644 index 0000000..2cfe7db --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepMaterialModel.php @@ -0,0 +1,34 @@ + + */ + protected function casts(): array + { + return [ + 'workflow_template_step_id' => 'integer', + 'stock_item_id' => 'integer', + 'quantity_milli' => 'integer', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php index 3b4c04a..b0dccc6 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/WorkflowTemplateStepModel.php @@ -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 + */ + public function materials(): HasMany + { + return $this->hasMany(WorkflowTemplateStepMaterialModel::class, 'workflow_template_step_id')->orderBy('sort_order'); + } + /** * @return array */ diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php index c5fc3f9..71d440a 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateQueries.php @@ -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(), diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php index 217beba..3e8e41d 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentWorkflowTemplateRepository.php @@ -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(), diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php index d86c75e..eef6ec9 100644 --- a/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/WorkflowTemplateForm.php @@ -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 + * @var list}> */ public array $steps = []; public int $nextKey = 1; - public function addStep(string $title = '', string $workTypeId = '', string $description = ''): int + /** + * @param list $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'), ]; } } diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php index a4a4cb9..5c199a0 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡workflow-template-form.blade.php @@ -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 + */ + #[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'] ?? []) !== []) +
+ {{ __('catalog.workflows.materials') }} +

{{ __('catalog.workflows.materials_help') }}

+ + @foreach ($step['materials'] ?? [] as $materialIndex => $material) +
+
+ + + @foreach ($this->stockItems as $stockItem) + + @endforeach + +
+
+ +
+ +
+ @endforeach + + +
+ @endif +
+ */ + public function taskMovements(int $taskId): array; + + /** + * @return list + */ + public function taskSuggestions(int $taskId): array; + /** * The private-disk path of the item's image or its thumbnail. */ diff --git a/app/Modules/Inventory/Application/Contracts/StockTasks.php b/app/Modules/Inventory/Application/Contracts/StockTasks.php new file mode 100644 index 0000000..e25b344 --- /dev/null +++ b/app/Modules/Inventory/Application/Contracts/StockTasks.php @@ -0,0 +1,23 @@ + $taskIds + * @return array + */ + public function labels(array $taskIds): array; +} diff --git a/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php b/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php index b7f8c4f..d09577d 100644 --- a/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php +++ b/app/Modules/Inventory/Application/DTOs/StockMovementSummary.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\Inventory\Application\DTOs; use App\Modules\Inventory\Domain\Enums\StockMovementKind; +use App\Modules\Inventory\Domain\Enums\StockUnit; /** * A stock movement in an item's history: signed quantity and the balance @@ -35,6 +36,8 @@ final readonly class StockMovementSummary public ?string $documentNumber, public ?int $reversesMovementId, public ?int $reversedByMovementId, + public string $itemName = '', + public ?StockUnit $unit = null, ) {} public function canBeReversed(): bool diff --git a/app/Modules/Inventory/Application/DTOs/StockTaskContext.php b/app/Modules/Inventory/Application/DTOs/StockTaskContext.php new file mode 100644 index 0000000..5ae3ee9 --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/StockTaskContext.php @@ -0,0 +1,20 @@ + $materials + */ + public function suggest(int $taskId, array $materials): void + { + $this->transactions->run(function () use ($taskId, $materials): void { + foreach ($materials as $material) { + $this->suggestions->add($taskId, $material['stockItemId'], $material['quantityMilli']); + } + }); + } + + /** + * @throws StockTaskNotAvailable + * @throws StockItemNotFound + * @throws StockItemInactive + * @throws InvalidStockQuantity + */ + public function record(int $taskId, int $stockItemId, string $quantity, int $actorUserId): StockUseResult + { + $context = $this->tasks->context($taskId); + + if ($context === null || ! $context->usesStock || $context->isLocked) { + throw new StockTaskNotAvailable; + } + + return $this->recordUse->execute(new StockUseData($stockItemId, $quantity, taskId: $taskId, jobId: $context->jobId), $actorUserId); + } + + /** + * Records a suggested material with the quantity confirmed (possibly + * changed) and removes the suggestion. + * + * @throws StockTaskSuggestionNotFound + * @throws StockTaskNotAvailable + * @throws StockItemNotFound + * @throws StockItemInactive + * @throws InvalidStockQuantity + */ + public function confirm(int $taskId, int $suggestionId, string $quantity, int $actorUserId): StockUseResult + { + return $this->transactions->run(function () use ($taskId, $suggestionId, $quantity, $actorUserId): StockUseResult { + $suggestion = $this->suggestions->find($suggestionId); + + if ($suggestion === null || $suggestion['taskId'] !== $taskId) { + throw new StockTaskSuggestionNotFound; + } + + $result = $this->record($taskId, $suggestion['stockItemId'], $quantity, $actorUserId); + $this->suggestions->remove($suggestionId); + + return $result; + }); + } + + /** + * @throws StockTaskSuggestionNotFound + */ + public function dismiss(int $taskId, int $suggestionId): void + { + $suggestion = $this->suggestions->find($suggestionId); + + if ($suggestion === null || $suggestion['taskId'] !== $taskId) { + throw new StockTaskSuggestionNotFound; + } + + $this->suggestions->remove($suggestionId); + } +} diff --git a/app/Modules/Inventory/Domain/Contracts/TaskMaterialSuggestionRepository.php b/app/Modules/Inventory/Domain/Contracts/TaskMaterialSuggestionRepository.php new file mode 100644 index 0000000..b03fb04 --- /dev/null +++ b/app/Modules/Inventory/Domain/Contracts/TaskMaterialSuggestionRepository.php @@ -0,0 +1,21 @@ +inner->hasTimeEntries($taskId) + || StockMovementModel::query()->where('task_id', $taskId)->exists(); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Adapters/TasksForStock.php b/app/Modules/Inventory/Infrastructure/Adapters/TasksForStock.php new file mode 100644 index 0000000..94485f6 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Adapters/TasksForStock.php @@ -0,0 +1,70 @@ +tasks->bookableTask($taskId); + + if ($task === null) { + return null; + } + + return new StockTaskContext($task->taskId, $task->jobId, $task->label(), $this->usesStock($task), $task->isLocked()); + } + + public function labels(array $taskIds): array + { + $labels = []; + + foreach ($this->tasks->bookableTasks($taskIds) as $task) { + $labels[$task->taskId] = $task->label(); + } + + return $labels; + } + + private function usesStock(BookableTask $task): bool + { + $stockUnitIds = $this->catalog->stockServiceUnitIds(); + + if ($stockUnitIds === []) { + return false; + } + + $workType = $this->catalog->findWorkType($task->workTypeId); + $unit = $workType === null ? null : $this->catalog->findServiceUnit($workType->serviceUnitId); + + if ($unit === null) { + return false; + } + + if (! $unit->isShared) { + return in_array($unit->id, $stockUnitIds, true); + } + + $jobUnitIds = array_map(fn ($unit): int => $unit->id, $this->jobs->findDetails($task->jobId)->serviceUnits ?? []); + + return array_intersect($jobUnitIds, $stockUnitIds) !== []; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/TaskMaterialSuggestionModel.php b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/TaskMaterialSuggestionModel.php new file mode 100644 index 0000000..beadb89 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Eloquent/TaskMaterialSuggestionModel.php @@ -0,0 +1,32 @@ + + */ + protected function casts(): array + { + return [ + 'task_id' => 'integer', + 'stock_item_id' => 'integer', + 'quantity_milli' => 'integer', + ]; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php index 7acbc26..164b2c9 100644 --- a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockQueries.php @@ -6,11 +6,14 @@ use App\Modules\Inventory\Application\Contracts\StockQueries; use App\Modules\Inventory\Application\DTOs\StockGroupSummary; use App\Modules\Inventory\Application\DTOs\StockItemSummary; use App\Modules\Inventory\Application\DTOs\StockMovementSummary; +use App\Modules\Inventory\Application\DTOs\TaskMaterialSuggestion; +use App\Modules\Inventory\Domain\Enums\StockUnit; use App\Modules\Inventory\Domain\Services\StockSearch; use App\Modules\Inventory\Domain\Services\StockValuation; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel; +use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\TaskMaterialSuggestionModel; use App\Modules\Users\Application\Contracts\UserAccountQueries; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Carbon; @@ -97,6 +100,36 @@ class EloquentStockQueries implements StockQueries return $this->summaries(collect([$model]), $balance)[0]; } + public function taskMovements(int $taskId): array + { + $models = StockMovementModel::query() + ->with('reversal:id,reverses_movement_id') + ->where('task_id', $taskId) + ->orderByDesc('id') + ->get(); + + return $this->summaries($models, 0, trackBalance: false); + } + + public function taskSuggestions(int $taskId): array + { + return TaskMaterialSuggestionModel::query() + ->join('stock_items', 'stock_items.id', '=', 'task_material_suggestions.stock_item_id') + ->where('task_material_suggestions.task_id', $taskId) + ->orderBy('task_material_suggestions.id') + ->get(['task_material_suggestions.*', 'stock_items.name as item_name', 'stock_items.unit as item_unit']) + ->map(fn (TaskMaterialSuggestionModel $model): TaskMaterialSuggestion => new TaskMaterialSuggestion( + $model->id, + $model->task_id, + $model->stock_item_id, + (string) $model->getAttribute('item_name'), + StockUnit::from((string) $model->getAttribute('item_unit')), + $model->quantity_milli, + )) + ->values() + ->all(); + } + public function imagePathOf(int $itemId, bool $thumbnail): ?string { $model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']); @@ -147,9 +180,10 @@ class EloquentStockQueries implements StockQueries * @param int $balance The balance after the newest of them. * @return list */ - private function summaries(Collection $models, int $balance): array + private function summaries(Collection $models, int $balance, bool $trackBalance = true): array { $names = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); + $items = StockItemModel::query()->whereIn('id', $models->pluck('stock_item_id')->unique())->get(['id', 'name', 'unit'])->keyBy('id'); $summaries = []; foreach ($models as $model) { @@ -175,9 +209,13 @@ class EloquentStockQueries implements StockQueries documentNumber: $model->document_number, reversesMovementId: $model->reverses_movement_id, reversedByMovementId: $model->reversal?->id, + itemName: (string) $items->get($model->stock_item_id)?->name, + unit: $items->get($model->stock_item_id)?->unit, ); - $balance -= $model->quantity_milli; + if ($trackBalance) { + $balance -= $model->quantity_milli; + } } return $summaries; diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentTaskMaterialSuggestionRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentTaskMaterialSuggestionRepository.php new file mode 100644 index 0000000..3864465 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentTaskMaterialSuggestionRepository.php @@ -0,0 +1,35 @@ +create([ + 'task_id' => $taskId, + 'stock_item_id' => $stockItemId, + 'quantity_milli' => $quantityMilli, + ]); + } + + public function find(int $id): ?array + { + $model = TaskMaterialSuggestionModel::query()->find($id); + + return $model === null ? null : [ + 'id' => $model->id, + 'taskId' => $model->task_id, + 'stockItemId' => $model->stock_item_id, + 'quantityMilli' => $model->quantity_milli, + ]; + } + + public function remove(int $id): void + { + TaskMaterialSuggestionModel::query()->whereKey($id)->delete(); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php index 93159b5..6ed86c9 100644 --- a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php +++ b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php @@ -6,15 +6,24 @@ use App\Models\User; use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Inventory\Application\Contracts\StockItemImages; use App\Modules\Inventory\Application\Contracts\StockQueries; +use App\Modules\Inventory\Application\Contracts\StockTasks; +use App\Modules\Inventory\Application\UseCases\TaskMaterials; use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository; use App\Modules\Inventory\Domain\Contracts\StockItemRepository; use App\Modules\Inventory\Domain\Contracts\StockMovementRepository; +use App\Modules\Inventory\Domain\Contracts\TaskMaterialSuggestionRepository; +use App\Modules\Inventory\Infrastructure\Adapters\TasksForStock; +use App\Modules\Inventory\Infrastructure\Adapters\TaskUsageWithStock; use App\Modules\Inventory\Infrastructure\Files\StockItemImageFiles; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemGroupRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockMovementRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockQueries; +use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentTaskMaterialSuggestionRepository; +use App\Modules\Jobs\Application\Contracts\TaskUsage; +use App\Modules\Jobs\Domain\Events\TaskMaterialsSuggested; use App\Modules\Users\Domain\Enums\Role; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Livewire\Livewire; @@ -35,10 +44,20 @@ class InventoryServiceProvider extends ServiceProvider StockMovementRepository::class => EloquentStockMovementRepository::class, StockQueries::class => EloquentStockQueries::class, StockItemImages::class => StockItemImageFiles::class, + TaskMaterialSuggestionRepository::class => EloquentTaskMaterialSuggestionRepository::class, + StockTasks::class => TasksForStock::class, ]; + public function register(): void + { + // Registered after TimeTracking: a task with material is kept like one with hours. + $this->app->extend(TaskUsage::class, fn (TaskUsage $usage): TaskUsage => new TaskUsageWithStock($usage)); + } + public function boot(): void { + Event::listen(TaskMaterialsSuggested::class, fn (TaskMaterialsSuggested $event) => app(TaskMaterials::class)->suggest($event->taskId, $event->materials)); + $presentationPath = dirname(__DIR__, 2).'/Presentation'; Livewire::addNamespace('inventory', viewPath: $presentationPath.'/Livewire'); diff --git a/app/Modules/Inventory/Presentation/Livewire/⚡task-materials.blade.php b/app/Modules/Inventory/Presentation/Livewire/⚡task-materials.blade.php new file mode 100644 index 0000000..1efe012 --- /dev/null +++ b/app/Modules/Inventory/Presentation/Livewire/⚡task-materials.blade.php @@ -0,0 +1,391 @@ + + */ + public array $suggestionQuantities = []; + + #[Locked] + public string $message = ''; + + public function mount(): void + { + $this->authorize('jobs.view-job', $this->jobId); + + $context = $this->context; + abort_if($context !== null && $context->jobId !== $this->jobId, 404); + + foreach ($this->suggestions as $suggestion) { + $this->suggestionQuantities[$suggestion->id] = StockQuantity::inputValue($suggestion->quantityMilli); + } + } + + #[Computed] + public function context(): ?StockTaskContext + { + return app(StockTasks::class)->context($this->taskId); + } + + /** + * @return list + */ + #[Computed] + public function movements(): array + { + return app(StockQueries::class)->taskMovements($this->taskId); + } + + /** + * @return list + */ + #[Computed] + public function suggestions(): array + { + return app(StockQueries::class)->taskSuggestions($this->taskId); + } + + /** + * @return list + */ + #[Computed] + public function results(): array + { + $term = trim($this->search); + + return mb_strlen($term) < 2 ? [] : array_slice(app(StockQueries::class)->items($term), 0, self::RESULT_LIMIT); + } + + #[Computed] + public function selectedItem(): ?StockItemSummary + { + return $this->selectedItemId === null ? null : app(StockQueries::class)->findItem($this->selectedItemId); + } + + public function canRecord(): bool + { + $context = $this->context; + + return $context !== null && $context->usesStock && ! $context->isLocked && Gate::allows('inventory.record-use'); + } + + public function selectItem(int $itemId): void + { + $this->authorizeRecording(); + + $this->selectedItemId = $itemId; + $this->quantity = '1'; + $this->search = ''; + $this->resetErrorBag(); + $this->js("document.getElementById('task-{$this->taskId}-material-quantity')?.focus()"); + } + + public function clearItem(): void + { + $this->selectedItemId = null; + $this->js("document.getElementById('task-{$this->taskId}-material-search')?.focus()"); + } + + public function record(TaskMaterials $materials): void + { + $this->authorizeRecording(); + $this->resetErrorBag(); + + if ($this->selectedItemId === null) { + return; + } + + try { + $result = $materials->record($this->taskId, $this->selectedItemId, $this->quantity, (int) auth()->id()); + } catch (InvalidStockQuantity) { + $this->addError('quantity', __('inventory.errors.quantity')); + + return; + } catch (StockItemInactive) { + $this->addError('quantity', __('inventory.errors.inactive')); + + return; + } catch (StockItemNotFound|StockTaskNotAvailable) { + $this->message = __('inventory.errors.not_found'); + + return; + } + + $unit = $this->selectedItem?->unit; + $this->message = __('inventory.task.recorded', [ + 'item' => $result->itemName, + 'quantity' => $this->quantity($result->quantityMilli, $unit), + 'balance' => $this->quantity($result->balanceMilli, $unit), + ]); + $this->selectedItemId = null; + $this->quantity = '1'; + unset($this->movements); + $this->js("document.getElementById('task-{$this->taskId}-material-search')?.focus()"); + } + + public function confirmSuggestion(int $suggestionId, TaskMaterials $materials): void + { + $this->authorizeRecording(); + $this->resetErrorBag(); + + $suggestion = collect($this->suggestions)->firstWhere('id', $suggestionId); + + try { + $result = $materials->confirm($this->taskId, $suggestionId, $this->suggestionQuantities[$suggestionId] ?? '', (int) auth()->id()); + } catch (InvalidStockQuantity) { + $this->addError('suggestionQuantities.'.$suggestionId, __('inventory.errors.quantity')); + + return; + } catch (StockItemInactive) { + $this->addError('suggestionQuantities.'.$suggestionId, __('inventory.errors.inactive')); + + return; + } catch (StockItemNotFound|StockTaskNotAvailable|StockTaskSuggestionNotFound) { + $this->message = __('inventory.errors.not_found'); + unset($this->suggestions); + + return; + } + + $this->message = __('inventory.task.recorded', [ + 'item' => $result->itemName, + 'quantity' => $this->quantity($result->quantityMilli, $suggestion?->unit), + 'balance' => $this->quantity($result->balanceMilli, $suggestion?->unit), + ]); + unset($this->suggestions, $this->movements, $this->suggestionQuantities[$suggestionId]); + $this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()"); + } + + public function dismissSuggestion(int $suggestionId, TaskMaterials $materials): void + { + $this->authorizeRecording(); + + $suggestion = collect($this->suggestions)->firstWhere('id', $suggestionId); + + try { + $materials->dismiss($this->taskId, $suggestionId); + } catch (StockTaskSuggestionNotFound) { + // Already handled elsewhere: the list is refreshed below. + } + + $this->message = __('inventory.task.dismissed', ['item' => $suggestion?->itemName ?? '']); + unset($this->suggestions, $this->suggestionQuantities[$suggestionId]); + $this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()"); + } + + public function undo(int $movementId, ReverseStockMovement $reverse): void + { + $this->authorize('inventory.record-use'); + + $movement = collect($this->movements)->firstWhere('id', $movementId); + abort_if($movement === null || ! $this->mayUndo($movement), 403); + + try { + $reverse->execute($movementId, (int) auth()->id(), Gate::allows('inventory.reverse-any')); + $this->message = __('inventory.task.undone', ['item' => $movement->itemName, 'quantity' => $this->quantity(-$movement->quantityMilli, $movement->unit)]); + } catch (StockMovementNotFound|StockMovementAlreadyReversed) { + $this->message = __('inventory.errors.already_reversed'); + } catch (StockReversalNotAllowed) { + $this->message = __('inventory.errors.reversal_not_allowed'); + } + + unset($this->movements); + $this->js("document.getElementById('task-{$this->taskId}-materials-status')?.focus()"); + } + + /** + * Users undo their own use on the day it was recorded; management any use. + */ + public function mayUndo(StockMovementSummary $movement): bool + { + if (! $movement->canBeReversed() || $movement->kind->value !== 'consumption' || ! $this->canRecord()) { + return false; + } + + return Gate::allows('inventory.reverse-any') + || ($movement->userId === (int) auth()->id() && $movement->occurredOn === app(Clock::class)->today()->format('Y-m-d')); + } + + private function authorizeRecording(): void + { + $this->authorize('jobs.view-job', $this->jobId); + abort_unless($this->canRecord(), 403); + } +}; +?> + +
+ @if (($this->context?->usesStock ?? false) || $this->movements !== []) +
+

{{ __('inventory.task.title') }}

+ +

{{ $message }}

+ + @if ($this->canRecord()) + @if ($this->suggestions !== []) +
+

{{ __('inventory.task.suggestions') }}

+
    + @foreach ($this->suggestions as $suggestion) +
  • +
    + +
    + + +
  • + @endforeach +
+
+ @endif + + @if ($this->selectedItem !== null) +
+

+ {{ $this->selectedItem->name }} + ({{ __('inventory.task.balance', ['balance' => $this->quantity($this->selectedItem->balanceMilli, $this->selectedItem->unit)]) }}) +

+
+ +
+ + + + @else +
+ + + @if (mb_strlen(trim($search)) >= 2) +

+ {{ trans_choice('inventory.task.results', count($this->results), ['count' => count($this->results)]) }} +

+
    + @foreach ($this->results as $result) +
  • + +
  • + @endforeach +
+ @endif +
+ @endif + @endif + + @if ($this->movements === []) +

{{ __('inventory.task.none') }}

+ @else +
    + @foreach ($this->movements as $movement) +
  • + + {{ $movement->itemName }} + {{ $this->quantity(-$movement->quantityMilli, $movement->unit) }} + + · {{ __('inventory.kinds.'.$movement->kind->value) }} · {{ $movement->userName }}, {{ $this->dateLabel($movement->recordedAt) }} + @if ($movement->reversedByMovementId !== null) + · {{ __('inventory.task.undone_mark') }} + @endif + + + @if ($this->mayUndo($movement)) + + @endif +
  • + @endforeach +
+ @endif +
+ @endif +
diff --git a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php index 1160538..597dc57 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php +++ b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php @@ -15,6 +15,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\TaskMaterialsSuggested; use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound; use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; @@ -31,7 +32,8 @@ use App\Modules\Users\Application\Contracts\Clock; * assignee entered for it (without an entry, the adder is the assignee). * When asked, a task with a due date is scheduled to end on it, booked * backwards from the due date (TaskPlanner::planBackwards). The tasks are - * copies, so later changes to the template do not touch them. + * copies, so later changes to the template do not touch them. A step's + * default materials are published as suggestions for its task. */ final class AddTasksFromWorkflowTemplate { @@ -98,6 +100,14 @@ final class AddTasksFromWorkflowTemplate if ($added !== null) { $this->events->dispatch($added); } + + if ($step->materials !== []) { + $this->events->dispatch(new TaskMaterialsSuggested( + (int) $task->id(), + $jobId, + array_map(fn ($material): array => ['stockItemId' => $material->stockItemId, 'quantityMilli' => $material->quantityMilli], $step->materials), + )); + } } return new TemplateTasksResult(count($template->steps), $scheduled, $late); diff --git a/app/Modules/Jobs/Domain/Events/TaskMaterialsSuggested.php b/app/Modules/Jobs/Domain/Events/TaskMaterialsSuggested.php new file mode 100644 index 0000000..da3b581 --- /dev/null +++ b/app/Modules/Jobs/Domain/Events/TaskMaterialsSuggested.php @@ -0,0 +1,22 @@ + $materials + */ + public function __construct( + public int $taskId, + public int $jobId, + public array $materials, + ) {} +} diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index ef16d65..16aca72 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -475,6 +475,7 @@ new class extends Component +
@if ($canChangeStatus) diff --git a/database/migrations/2026_11_26_141953_create_workflow_template_step_materials_table.php b/database/migrations/2026_11_26_141953_create_workflow_template_step_materials_table.php new file mode 100644 index 0000000..0eaced3 --- /dev/null +++ b/database/migrations/2026_11_26_141953_create_workflow_template_step_materials_table.php @@ -0,0 +1,40 @@ +id(); + // Short constraint names: MySQL allows at most 64 characters. + $table->foreignId('workflow_template_step_id')->constrained(indexName: 'wtsm_step_foreign')->cascadeOnDelete(); + $table->foreignId('stock_item_id')->constrained(indexName: 'wtsm_item_foreign')->restrictOnDelete(); + $table->bigInteger('quantity_milli'); + $table->unsignedInteger('sort_order'); + $table->timestamps(); + }); + + Schema::create('task_material_suggestions', function (Blueprint $table) { + $table->id(); + $table->foreignId('task_id')->constrained()->cascadeOnDelete(); + $table->foreignId('stock_item_id')->constrained()->restrictOnDelete(); + $table->bigInteger('quantity_milli'); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('task_material_suggestions'); + Schema::dropIfExists('workflow_template_step_materials'); + } +}; diff --git a/lang/en/catalog.php b/lang/en/catalog.php index 7423e63..b4bc29b 100644 --- a/lang/en/catalog.php +++ b/lang/en/catalog.php @@ -15,6 +15,15 @@ return [ 'workflows_link' => 'Workflow templates: ready-made task lists for work types', 'workflows' => [ + 'materials' => 'Default materials', + 'materials_help' => 'The materials are prefilled in the Used material section of the task made of the step. They are taken from stock only when the assignee confirms them.', + 'material_item' => 'Item', + 'material_item_named' => 'Material :number of step :step', + 'choose_material' => 'Choose an item', + 'material_quantity' => 'Quantity', + 'remove_material_named' => 'Remove material :number of step :step', + 'add_material' => 'Add material', + 'add_material_named' => 'Add material to step :number', 'title' => 'Workflow templates', 'intro' => 'A template creates a ready-made task list for a customer job, e.g. video shoot: planning → shooting → editing → review → delivery. Changing a template does not change tasks already created. Templates are not deleted but taken out of use.', 'back_to_catalog' => 'Back to basic data', @@ -44,6 +53,8 @@ return [ 'remove_step' => 'Remove step', 'remove_step_named' => 'Remove step :number', 'status' => [ + 'material_added' => 'Material row added to step :number.', + 'material_removed' => 'Material row removed from step :number.', 'step_added' => 'Step :number added.', 'step_moved' => 'Step :from moved to position :to.', 'step_removed' => 'Step :number removed.', @@ -52,6 +63,7 @@ return [ 'deactivated' => ':name taken out of use. It is not offered for jobs.', ], 'errors' => [ + 'invalid_material' => 'Choose an item and enter a quantity greater than zero, at most three decimals.', 'name_taken' => 'The work type already has a template with this name.', 'work_type_required' => 'Choose a work type.', 'steps_required' => 'Add at least one step to the template.', diff --git a/lang/en/inventory.php b/lang/en/inventory.php index 04d37cd..80f915b 100644 --- a/lang/en/inventory.php +++ b/lang/en/inventory.php @@ -168,6 +168,32 @@ return [ 'negative_warning' => 'The balance is negative. Correct it with a purchase or a stock count.', ], + 'task' => [ + 'title' => 'Used material', + 'list_of' => 'Used material: :title', + 'search' => 'Search material', + 'search_hint' => 'Type part of the name or code, or scan a barcode.', + 'results' => '{0} No matches|{1} 1 match|[2,*] :count matches', + 'choose' => 'Choose :item, balance :balance', + 'balance' => 'balance :balance', + 'quantity' => 'Quantity (:unit)', + 'quantity_of' => ':item (:unit)', + 'record' => 'Record use', + 'change_item' => 'Change item', + 'recorded' => 'Recorded :item :quantity. Balance now :balance.', + 'suggestions' => 'Default materials of the workflow template: check the quantity and record.', + 'confirm' => 'Record', + 'confirm_named' => 'Record default material :item', + 'dismiss' => 'Skip', + 'dismiss_named' => 'Skip default material :item', + 'dismissed' => 'Default material :item skipped.', + 'none' => 'No material has been recorded on the task.', + 'undo' => 'Undo', + 'undo_named' => 'Undo use :item :quantity', + 'undone' => 'Use undone: :item :quantity.', + 'undone_mark' => 'undone', + ], + 'errors' => [ 'name' => 'Enter a name (1–150 characters).', 'name_taken' => 'The name is already in use.', diff --git a/lang/en/jobs.php b/lang/en/jobs.php index d5cd724..3e257f5 100644 --- a/lang/en/jobs.php +++ b/lang/en/jobs.php @@ -37,7 +37,7 @@ return [ 'edit_named' => 'Edit task :title', 'remove_named' => 'Remove task :title', 'remove_question' => 'Remove task :title? This cannot be undone.', - 'has_time_entries' => 'Task :title was not removed because hours have been entered on it.', + 'has_time_entries' => 'Task :title was not removed because hours or used material have been recorded on it.', 'book_time' => 'Enter hours', 'book_time_named' => 'Enter hours on task :title', 'from_template' => [ diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index 71ad054..054ffe7 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -15,6 +15,15 @@ return [ 'workflows_link' => 'Työnkulkupohjat: valmiit tehtävälistat työtehtäville', 'workflows' => [ + 'materials' => 'Oletusmateriaalit', + 'materials_help' => 'Materiaalit esitäytetään vaiheesta tehdyn tehtävän Käytetty materiaali -osioon. Ne kirjataan varastosta vasta, kun tekijä vahvistaa ne.', + 'material_item' => 'Nimike', + 'material_item_named' => 'Vaiheen :step materiaali :number', + 'choose_material' => 'Valitse nimike', + 'material_quantity' => 'Määrä', + 'remove_material_named' => 'Poista vaiheen :step materiaali :number', + 'add_material' => 'Lisää materiaali', + 'add_material_named' => 'Lisää materiaali vaiheeseen :number', 'title' => 'Työnkulkupohjat', 'intro' => 'Pohjasta luodaan asiakastyölle valmis tehtävälista, esim. videokuvaus: suunnittelu → kuvaus → editointi → tarkastus → toimitus. Pohjan muutos ei muuta jo luotuja tehtäviä. Pohjia ei poisteta, vaan ne poistetaan käytöstä.', 'back_to_catalog' => 'Takaisin pohjatietoihin', @@ -44,6 +53,8 @@ return [ 'remove_step' => 'Poista vaihe', 'remove_step_named' => 'Poista vaihe :number', 'status' => [ + 'material_added' => 'Materiaalirivi lisätty vaiheeseen :number.', + 'material_removed' => 'Materiaalirivi poistettu vaiheesta :number.', 'step_added' => 'Vaihe :number lisätty.', 'step_moved' => 'Vaihe :from siirretty kohtaan :to.', 'step_removed' => 'Vaihe :number poistettu.', @@ -52,6 +63,7 @@ return [ 'deactivated' => ':name poistettu käytöstä. Sitä ei tarjota töille.', ], 'errors' => [ + 'invalid_material' => 'Valitse nimike ja anna määrä nollaa suurempana lukuna, enintään kolme desimaalia.', 'name_taken' => 'Työtehtävällä on jo tämänniminen pohja.', 'work_type_required' => 'Valitse työtehtävä.', 'steps_required' => 'Lisää pohjaan vähintään yksi vaihe.', diff --git a/lang/fi/inventory.php b/lang/fi/inventory.php index c56c755..169433f 100644 --- a/lang/fi/inventory.php +++ b/lang/fi/inventory.php @@ -168,6 +168,32 @@ return [ 'negative_warning' => 'Saldo on negatiivinen. Korjaa se hankinnalla tai inventaariolla.', ], + 'task' => [ + 'title' => 'Käytetty materiaali', + 'list_of' => 'Käytetty materiaali: :title', + 'search' => 'Hae materiaali', + 'search_hint' => 'Kirjoita nimen tai koodin osa, tai lue viivakoodi.', + 'results' => '{0} Ei osumia|{1} 1 osuma|[2,*] :count osumaa', + 'choose' => 'Valitse :item, saldo :balance', + 'balance' => 'saldo :balance', + 'quantity' => 'Määrä (:unit)', + 'quantity_of' => ':item (:unit)', + 'record' => 'Kirjaa käyttö', + 'change_item' => 'Vaihda nimike', + 'recorded' => 'Kirjattu :item :quantity. Saldo nyt :balance.', + 'suggestions' => 'Työnkulkupohjan oletusmateriaalit: tarkista määrä ja kirjaa.', + 'confirm' => 'Kirjaa', + 'confirm_named' => 'Kirjaa oletusmateriaali :item', + 'dismiss' => 'Ohita', + 'dismiss_named' => 'Ohita oletusmateriaali :item', + 'dismissed' => 'Oletusmateriaali :item ohitettu.', + 'none' => 'Tehtävälle ei ole kirjattu materiaalia.', + 'undo' => 'Peru', + 'undo_named' => 'Peru käyttö :item :quantity', + 'undone' => 'Käyttö peruttu: :item :quantity.', + 'undone_mark' => 'peruttu', + ], + 'errors' => [ 'name' => 'Anna nimi (1–150 merkkiä).', 'name_taken' => 'Nimi on jo käytössä.', diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index f346038..a31fc4e 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -37,7 +37,7 @@ return [ 'edit_named' => 'Muokkaa tehtävää :title', 'remove_named' => 'Poista tehtävä :title', 'remove_question' => 'Poistetaanko tehtävä :title? Poistoa ei voi perua.', - 'has_time_entries' => 'Tehtävää :title ei poistettu, koska sille on kirjattu tunteja.', + 'has_time_entries' => 'Tehtävää :title ei poistettu, koska sille on kirjattu tunteja tai käytettyä materiaalia.', 'book_time' => 'Kirjaa tunnit', 'book_time_named' => 'Kirjaa tunnit tehtävälle :title', 'from_template' => [ diff --git a/tests/Browser/InventoryAccessibilityTest.php b/tests/Browser/InventoryAccessibilityTest.php index b8fd908..532d6d0 100644 --- a/tests/Browser/InventoryAccessibilityTest.php +++ b/tests/Browser/InventoryAccessibilityTest.php @@ -2,17 +2,21 @@ use App\Models\User; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel; +use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel; use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel; +use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; +use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\DB; uses(RefreshDatabase::class); beforeEach(function () { $this->user = User::factory()->management()->create(['name' => 'Johtaja']); $this->actingAs($this->user); - ServiceUnitModel::factory()->usingStock()->create(['name' => 'Painotuotanto']); + ServiceUnitModel::query()->where('name', 'Painotuotanto')->update(['uses_stock' => true]); $group = StockItemGroupModel::factory()->create(['name' => 'Paperit']); $this->item = StockItemModel::factory()->create([ 'stock_item_group_id' => $group->id, @@ -61,3 +65,32 @@ it('reverses a movement in a dialog that returns focus', function () { ->assertSee('Vastakirjaus kirjattu') ->assertScript('document.activeElement.id', 'item-status'); }); + +it('records material on a task card with the keyboard and without accessibility issues', function (string $device, string $colorScheme) { + $print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole(); + $print->update(['uses_stock' => true]); + $job = CustomerJobModel::factory()->create(['name' => 'Ikkunateippaus', 'status' => 'order']); + DB::table('customer_job_service_unit')->where('customer_job_id', $job->id)->update(['service_unit_id' => $print->id]); + $task = TaskModel::factory()->create([ + 'customer_job_id' => $job->id, + 'work_type_id' => WorkTypeModel::query()->where('name', 'asennus')->value('id'), + 'title' => 'Asennus', + ]); + + $visit = visit(route('jobs.show', $job->id).'#task-'.$task->id); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee(__('inventory.task.title')) + ->fill('#task-'.$task->id.'-material-search', 'valoku') + ->assertSee('1 osuma') + ->click('[wire\:click="selectItem('.$this->item->id.')"]') + ->fill('#task-'.$task->id.'-material-quantity', '2') + ->keys('#task-'.$task->id.'-material-quantity', 'Enter') + ->assertSee('Kirjattu Valokuvapaperi 2') + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Feature/Modules/Inventory/TaskMaterialsTest.php b/tests/Feature/Modules/Inventory/TaskMaterialsTest.php new file mode 100644 index 0000000..2ca6a29 --- /dev/null +++ b/tests/Feature/Modules/Inventory/TaskMaterialsTest.php @@ -0,0 +1,136 @@ +employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']); + $this->actingAs($this->employee); + + $this->print = ServiceUnitModel::query()->where('name', 'Painotuotanto')->sole(); + $this->print->update(['uses_stock' => true]); + $this->installation = WorkTypeModel::query()->where('name', 'asennus')->sole(); + $this->printing = WorkTypeModel::query()->where('name', 'painotyö')->sole(); + + $this->job = CustomerJobModel::factory()->create(['name' => 'Ikkunateippaus', 'status' => 'order']); + DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $this->print->id]); + $this->task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->installation->id, 'title' => 'Asennus']); + + $this->transfer = StockItemModel::factory()->create(['name' => 'Siirtotarrapaperi', 'unit' => 'square_metre']); +}); + +function materials(object $test): mixed +{ + return Livewire::test('inventory::task-materials', ['jobId' => $test->job->id, 'taskId' => $test->task->id, 'taskTitle' => 'Asennus']); +} + +it('records material used on a task found by search, and undoes it the same day', function () { + materials($this) + ->assertSee(__('inventory.task.title')) + ->set('search', 'siirto') + ->assertSee('Siirtotarrapaperi') + ->call('selectItem', $this->transfer->id) + ->set('quantity', '2,5') + ->call('record') + ->assertHasNoErrors() + ->assertSet('message', "Kirjattu Siirtotarrapaperi 2,5\u{00A0}m². Saldo nyt -2,5\u{00A0}m²."); + + $use = StockMovementModel::query()->sole(); + + expect($use->only(['task_id', 'customer_job_id', 'quantity_milli', 'user_id'])) + ->toBe(['task_id' => $this->task->id, 'customer_job_id' => $this->job->id, 'quantity_milli' => -2_500, 'user_id' => $this->employee->id]); + + materials($this)->call('undo', $use->id)->assertSet('message', "Käyttö peruttu: Siirtotarrapaperi 2,5\u{00A0}m²."); + + expect((int) StockMovementModel::query()->where('task_id', $this->task->id)->sum('quantity_milli'))->toBe(0); +}); + +it('keeps a task with material from being removed', function () { + materials($this)->call('selectItem', $this->transfer->id)->call('record'); + + $this->actingAs(User::factory()->management()->create()); + Livewire::test('jobs::show', ['job' => $this->job->id]) + ->call('confirmTaskRemoval', $this->task->id) + ->call('removeTask') + ->assertSee('Tehtävää Asennus ei poistettu, koska sille on kirjattu tunteja tai käytettyä materiaalia.'); + + expect(TaskModel::query()->whereKey($this->task->id)->exists())->toBeTrue(); +}); + +it('hides the section in units without stock and shows earlier use read-only', function () { + materials($this)->call('selectItem', $this->transfer->id)->call('record'); + $this->print->update(['uses_stock' => false]); + + materials($this) + ->assertSee('Siirtotarrapaperi') + ->assertDontSee(__('inventory.task.search')) + ->call('selectItem', $this->transfer->id) + ->assertForbidden(); + + StockMovementModel::query()->delete(); + materials($this)->assertDontSee(__('inventory.task.title')); +}); + +it('suggests the default materials of a workflow step and records them only when confirmed', function () { + $templateId = app(AddWorkflowTemplate::class)->execute(new WorkflowTemplateData('Ikkunateippaus', $this->printing->id, [ + new WorkflowStepData('Tulostus ja leikkaus'), + new WorkflowStepData('Asennus', null, $this->installation->id, [['stockItemId' => $this->transfer->id, 'quantity' => '3']]), + ])); + + app(AddTasksFromWorkflowTemplate::class)->execute($this->job->id, $templateId, $this->employee->id); + $this->task = TaskModel::query()->where('title', 'Asennus')->latest('id')->first(); + + expect(StockMovementModel::query()->count())->toBe(0); + + $component = materials($this) + ->assertSee(__('inventory.task.suggestions')) + ->assertSet('suggestionQuantities', fn (array $quantities) => array_values($quantities) === ['3']); + + $suggestionId = (int) array_key_first($component->get('suggestionQuantities')); + + $component->set('suggestionQuantities.'.$suggestionId, '3,5') + ->call('confirmSuggestion', $suggestionId) + ->assertHasNoErrors() + ->assertDontSee(__('inventory.task.suggestions')); + + expect(StockMovementModel::query()->sole()->quantity_milli)->toBe(-3_500) + ->and(DB::table('task_material_suggestions')->count())->toBe(0); +}); + +it('edits default materials on the workflow template form', function () { + $this->actingAs(User::factory()->management()->create()); + + Livewire::test('catalog::workflow-template-form') + ->set('form.name', 'Teippaus') + ->set('form.work_type_id', (string) $this->installation->id) + ->set('form.steps.0.title', 'Asennus') + ->assertSee(__('catalog.workflows.materials')) + ->call('addMaterial', 0) + ->set('form.steps.0.materials.0.stock_item_id', (string) $this->transfer->id) + ->set('form.steps.0.materials.0.quantity', 'abc') + ->call('save') + ->assertHasErrors('form.steps.0.materials.0.quantity') + ->set('form.steps.0.materials.0.quantity', '1,25') + ->call('save') + ->assertHasNoErrors(); + + expect(DB::table('workflow_template_step_materials')->sole()->quantity_milli)->toBe(1_250); + + $templateId = (int) DB::table('workflow_templates')->where('name', 'Teippaus')->value('id'); + Livewire::test('catalog::workflow-template-form', ['template' => $templateId]) + ->assertSet('form.steps.0.materials.0.quantity', '1,25'); +});