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:
@@ -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) !== [];
|
||||
}
|
||||
}
|
||||
+32
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
+40
-2
@@ -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,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;
|
||||
|
||||
+35
@@ -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>
|
||||
Reference in New Issue
Block a user