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"
@@ -7,6 +7,7 @@ namespace App\Modules\Inventory\Application\Contracts;
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;
/**
* Reads stock items, groups and movements. Other modules (machines, quick
@@ -44,6 +45,19 @@ interface StockQueries
public function findMovement(int $id): ?StockMovementSummary;
/**
* Material recorded on a task: its use, write-offs and their reversals,
* newest first. The balance after each is not set (0).
*
* @return list<StockMovementSummary>
*/
public function taskMovements(int $taskId): array;
/**
* @return list<TaskMaterialSuggestion>
*/
public function taskSuggestions(int $taskId): array;
/**
* The private-disk path of the item's image or its thumbnail.
*/
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockTaskContext;
/**
* Inventory's view of job tasks, read from the Jobs and Catalog modules.
*/
interface StockTasks
{
public function context(int $taskId): ?StockTaskContext;
/**
* Labels such as "2026-0005 Messuvideo – Tulostus" by task id.
*
* @param list<int> $taskIds
* @return array<int, string>
*/
public function labels(array $taskIds): array;
}
@@ -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
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A job's task as stock sees it: whether material may be recorded on it
* (its service unit uses stock, spec 19) and whether its job is locked.
*/
final readonly class StockTaskContext
{
public function __construct(
public int $taskId,
public int $jobId,
public string $label,
public bool $usesStock,
public bool $isLocked,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A default material suggested on a task, waiting to be confirmed.
*/
final readonly class TaskMaterialSuggestion
{
public function __construct(
public int $id,
public int $taskId,
public int $stockItemId,
public string $itemName,
public StockUnit $unit,
public int $quantityMilli,
) {}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockTasks;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\TaskMaterialSuggestionRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockTaskNotAvailable;
use App\Modules\Inventory\Domain\Exceptions\StockTaskSuggestionNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Material used on a job's task (Käytetty materiaali, spec 19.4): recorded
* from a search, or from the default materials suggested by the workflow
* step the task was made of. Material is recorded only on tasks whose
* service unit uses stock and whose job is not locked.
*/
final class TaskMaterials
{
public function __construct(
private RecordStockUse $recordUse,
private StockTasks $tasks,
private TaskMaterialSuggestionRepository $suggestions,
private TransactionManager $transactions,
) {}
/**
* Stores a workflow step's default materials as suggestions.
*
* @param list<array{stockItemId: int, quantityMilli: int}> $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);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
/**
* Default materials of workflow steps waiting on the tasks made of them,
* until the assignee records or dismisses them (spec 19.4).
*/
interface TaskMaterialSuggestionRepository
{
public function add(int $taskId, int $stockItemId, int $quantityMilli): void;
/**
* @return array{id: int, taskId: int, stockItemId: int, quantityMilli: int}|null
*/
public function find(int $id): ?array;
public function remove(int $id): void;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockTaskNotAvailable extends DomainException
{
public function __construct()
{
parent::__construct('Material cannot be recorded on this task.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockTaskSuggestionNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The suggested material was not found.');
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Adapters;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
/**
* A task with recorded material is kept like one with hours: the stock
* movements refer to it.
*/
class TaskUsageWithStock implements TaskUsage
{
public function __construct(private TaskUsage $inner) {}
public function hasTimeEntries(int $taskId): bool
{
return $this->inner->hasTimeEntries($taskId)
|| StockMovementModel::query()->where('task_id', $taskId)->exists();
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Adapters;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Inventory\Application\Contracts\StockTasks;
use App\Modules\Inventory\Application\DTOs\StockTaskContext;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
/**
* Reads tasks from Jobs and the stock setting of their service units from
* Catalog. A task's work type decides: its unit must use stock, and a
* shared work type's task follows the job's units (spec 19).
*/
class TasksForStock implements StockTasks
{
public function __construct(
private TaskQueries $tasks,
private CustomerJobQueries $jobs,
private CatalogQueries $catalog,
) {}
public function context(int $taskId): ?StockTaskContext
{
$task = $this->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) !== [];
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Modules\Inventory\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 Inventory Infrastructure layer.
*
* @property int $id
* @property int $task_id
* @property int $stock_item_id
* @property int $quantity_milli
*/
#[Table('task_material_suggestions')]
#[Fillable(['task_id', 'stock_item_id', 'quantity_milli'])]
class TaskMaterialSuggestionModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'task_id' => 'integer',
'stock_item_id' => 'integer',
'quantity_milli' => 'integer',
];
}
}
@@ -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<StockMovementSummary>
*/
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,10 +209,14 @@ 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,
);
if ($trackBalance) {
$balance -= $model->quantity_milli;
}
}
return $summaries;
}
@@ -0,0 +1,35 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\TaskMaterialSuggestionRepository;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\TaskMaterialSuggestionModel;
class EloquentTaskMaterialSuggestionRepository implements TaskMaterialSuggestionRepository
{
public function add(int $taskId, int $stockItemId, int $quantityMilli): void
{
TaskMaterialSuggestionModel::query()->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();
}
}
@@ -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');
@@ -0,0 +1,391 @@
<?php
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Inventory\Application\Contracts\StockTasks;
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
use App\Modules\Inventory\Application\DTOs\StockTaskContext;
use App\Modules\Inventory\Application\DTOs\TaskMaterialSuggestion;
use App\Modules\Inventory\Application\UseCases\ReverseStockMovement;
use App\Modules\Inventory\Application\UseCases\TaskMaterials;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Inventory\Domain\Exceptions\StockTaskNotAvailable;
use App\Modules\Inventory\Domain\Exceptions\StockTaskSuggestionNotFound;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Presentation\Livewire\Concerns\FormatsStock;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Used material of a job's task (Käytetty materiaali, spec 19.4), shown in
* the task's card on the job page and made for phones too, as installation
* is often done at the customer's. Material is searched by name or code
* and recorded as used on the task; a workflow step's default materials
* wait as suggestions until confirmed. Users undo their own use of today.
* Shown only when the task's service unit uses stock; earlier use stays
* visible read-only.
*/
new class extends Component
{
use FormatsStock;
public const int RESULT_LIMIT = 8;
#[Locked]
public int $jobId;
#[Locked]
public int $taskId;
#[Locked]
public string $taskTitle = '';
public string $search = '';
#[Locked]
public ?int $selectedItemId = null;
public string $quantity = '1';
/**
* Quantities of the suggestions as edited, by suggestion id.
*
* @var array<int, string>
*/
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<StockMovementSummary>
*/
#[Computed]
public function movements(): array
{
return app(StockQueries::class)->taskMovements($this->taskId);
}
/**
* @return list<TaskMaterialSuggestion>
*/
#[Computed]
public function suggestions(): array
{
return app(StockQueries::class)->taskSuggestions($this->taskId);
}
/**
* @return list<StockItemSummary>
*/
#[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);
}
};
?>
<div>
@if (($this->context?->usesStock ?? false) || $this->movements !== [])
<section aria-label="{{ __('inventory.task.list_of', ['title' => $taskTitle]) }}" class="space-y-3">
<h4 class="font-medium">{{ __('inventory.task.title') }}</h4>
<p id="task-{{ $taskId }}-materials-status" tabindex="-1" role="status" aria-live="polite" class="text-sm focus:outline-none">{{ $message }}</p>
@if ($this->canRecord())
@if ($this->suggestions !== [])
<div class="space-y-2 rounded-md border border-zinc-300 p-3 dark:border-zinc-600">
<p class="text-sm font-medium">{{ __('inventory.task.suggestions') }}</p>
<ul class="space-y-2">
@foreach ($this->suggestions as $suggestion)
<li wire:key="suggestion-{{ $suggestion->id }}" class="flex flex-wrap items-end gap-2">
<div class="w-28">
<x-input
id="suggestion-{{ $suggestion->id }}-quantity"
wire:model="suggestionQuantities.{{ $suggestion->id }}"
inputmode="decimal"
:label="__('inventory.task.quantity_of', ['item' => $suggestion->itemName, 'unit' => __('inventory.units.'.$suggestion->unit->value)])"
autocomplete="off"
/>
</div>
<x-button wire:click="confirmSuggestion({{ $suggestion->id }})" sm icon="check" :text="__('inventory.task.confirm')" :aria-label="__('inventory.task.confirm_named', ['item' => $suggestion->itemName])" />
<x-button wire:click="dismissSuggestion({{ $suggestion->id }})" subtle color="black" sm icon="x-mark" :text="__('inventory.task.dismiss')" :aria-label="__('inventory.task.dismiss_named', ['item' => $suggestion->itemName])" />
</li>
@endforeach
</ul>
</div>
@endif
@if ($this->selectedItem !== null)
<form wire:submit="record" class="flex flex-wrap items-end gap-2" novalidate>
<p class="w-full text-sm">
<span class="font-medium">{{ $this->selectedItem->name }}</span>
({{ __('inventory.task.balance', ['balance' => $this->quantity($this->selectedItem->balanceMilli, $this->selectedItem->unit)]) }})
</p>
<div class="w-32">
<x-input
id="task-{{ $taskId }}-material-quantity"
wire:model="quantity"
inputmode="decimal"
:label="__('inventory.task.quantity', ['unit' => __('inventory.units.'.$this->selectedItem->unit->value)])"
autocomplete="off"
/>
</div>
<x-button submit icon="check" :text="__('inventory.task.record')" />
<x-button wire:click="clearItem" subtle color="black" :text="__('inventory.task.change_item')" />
</form>
@else
<div class="space-y-2">
<x-input
id="task-{{ $taskId }}-material-search"
wire:model.live.debounce.300ms="search"
type="search"
icon="magnifying-glass"
:label="__('inventory.task.search')"
:hint="__('inventory.task.search_hint')"
autocomplete="off"
/>
@if (mb_strlen(trim($search)) >= 2)
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('inventory.task.results', count($this->results), ['count' => count($this->results)]) }}
</p>
<ul class="space-y-1">
@foreach ($this->results as $result)
<li wire:key="material-result-{{ $taskId }}-{{ $result->id }}">
<button
type="button"
wire:click="selectItem({{ $result->id }})"
class="flex min-h-11 w-full flex-wrap items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
aria-label="{{ __('inventory.task.choose', ['item' => $result->name, 'balance' => $this->quantity($result->balanceMilli, $result->unit)]) }}"
>
<span class="font-medium">{{ $result->name }}</span>
<span class="text-zinc-700 dark:text-zinc-300">{{ $this->quantity($result->balanceMilli, $result->unit) }}</span>
</button>
</li>
@endforeach
</ul>
@endif
</div>
@endif
@endif
@if ($this->movements === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.task.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 text-sm dark:divide-zinc-700">
@foreach ($this->movements as $movement)
<li wire:key="task-material-{{ $movement->id }}" class="flex flex-wrap items-center justify-between gap-2 py-2">
<span>
<span class="font-medium">{{ $movement->itemName }}</span>
{{ $this->quantity(-$movement->quantityMilli, $movement->unit) }}
<span class="text-zinc-600 dark:text-zinc-300">
· {{ __('inventory.kinds.'.$movement->kind->value) }} · {{ $movement->userName }}, {{ $this->dateLabel($movement->recordedAt) }}
@if ($movement->reversedByMovementId !== null)
· {{ __('inventory.task.undone_mark') }}
@endif
</span>
</span>
@if ($this->mayUndo($movement))
<x-button
wire:click="undo({{ $movement->id }})"
subtle
color="black"
sm
icon="arrow-uturn-left"
:text="__('inventory.task.undo')"
:aria-label="__('inventory.task.undo_named', ['item' => $movement->itemName, 'quantity' => $this->quantity(-$movement->quantityMilli, $movement->unit)])"
/>
@endif
</li>
@endforeach
</ul>
@endif
</section>
@endif
</div>
@@ -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);
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Events;
/**
* A task was made of a workflow step with default materials (spec 19.4):
* the stock items and quantities (in thousandths) suggested to be recorded
* as used on the task once its assignee confirms them.
*/
final readonly class TaskMaterialsSuggested
{
/**
* @param list<array{stockItemId: int, quantityMilli: int}> $materials
*/
public function __construct(
public int $taskId,
public int $jobId,
public array $materials,
) {}
}
@@ -475,6 +475,7 @@ new class extends Component
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
<livewire:inventory::task-materials :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'materials-'.$task->id" />
<div class="flex flex-wrap items-end gap-3">
@if ($canChangeStatus)
@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Default materials of workflow template steps (spec 19.4): suggested on
* the tasks made of the step, recorded only when confirmed. Also the
* suggestions waiting on such tasks, kept by the Inventory module.
*/
public function up(): void
{
Schema::create('workflow_template_step_materials', function (Blueprint $table) {
$table->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');
}
};
+12
View File
@@ -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.',
+26
View File
@@ -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.',
+1 -1
View File
@@ -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' => [
+12
View File
@@ -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.',
+26
View File
@@ -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ä.',
+1 -1
View File
@@ -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' => [
+34 -1
View File
@@ -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'],
]);
@@ -0,0 +1,136 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Application\UseCases\AddWorkflowTemplate;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use App\Modules\Jobs\Application\UseCases\AddTasksFromWorkflowTemplate;
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;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->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');
});