10 Commits
Author SHA1 Message Date
petri acf87aa3cd Calender test 2026-11-27 09:46:09 +02:00
petriandClaude Sonnet 5.5 3207d0064a Report stock usage and value, add material cost to profitability, document phase 5
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 17:24:07 +02:00
petriandClaude Sonnet 5.5 38b8075a9c Make quick sale products on machines as orders paid when ready
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 17:11:54 +02:00
petriandClaude Sonnet 5.5 920fecdeb2 Add the touch-screen machine console
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:57:56 +02:00
petriandClaude Sonnet 5.5 3e1c671949 Track machine counters and maintenance with counter and time intervals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:52:49 +02:00
petriandClaude Sonnet 5.5 aac579257a Add machines with day-by-day work lists for job tasks
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:43:55 +02:00
petriandClaude Sonnet 5.5 0de0e332b2 Count stock and correct the differences on confirmation
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:34:08 +02:00
petriandClaude Sonnet 5.5 bca1eed166 Record used material on tasks and suggest workflow steps' default materials
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:28:16 +02:00
petriandClaude Sonnet 5.5 30132deb0e Add stock items, groups and movements at a moving average cost
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:18:59 +02:00
petriandClaude Sonnet 5.5 361a2974cf Let a service unit use stock and machines
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-26 16:01:59 +02:00
339 changed files with 20361 additions and 198 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
@@ -38,6 +38,14 @@ interface CatalogQueries
*/
public function activeWorkTypesFor(array $serviceUnitIds): array;
/**
* Active service units where stock and machine features are in use
* (spec 19), in catalog order.
*
* @return list<int>
*/
public function stockServiceUnitIds(): array;
public function findServiceUnit(int $id): ?ServiceUnitSummary;
/**
@@ -11,5 +11,6 @@ final readonly class ServiceUnitSummary
public string $name,
public bool $isShared,
public bool $isActive,
public bool $usesStock = false,
) {}
}
@@ -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,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitCannotUseStock;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Turns the stock and machine features on or off in a service unit. Turning
* them off hides the features; recorded movements and work lists stay.
*/
final class SetServiceUnitUsesStock
{
public function __construct(
private ServiceUnitRepository $serviceUnits,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound
* @throws SharedUnitCannotUseStock
*/
public function execute(int $serviceUnitId, bool $usesStock): void
{
$this->transactions->run(function () use ($serviceUnitId, $usesStock): void {
$unit = $this->serviceUnits->findById($serviceUnitId) ?? throw new CatalogItemNotFound(CatalogLevel::ServiceUnit, $serviceUnitId);
$unit->useStock($usesStock);
$this->serviceUnits->save($unit);
});
}
}
@@ -4,32 +4,51 @@ declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\SharedUnitCannotUseStock;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
/**
* A service unit (palveluyksikkö), e.g. Mediatuotanto. The shared unit
* ("Kaikille yhteiset") holds work types offered in every unit and has no
* services.
* services. A unit may use stock and machines (varaston ja koneiden
* käyttö); the shared unit follows the job's units instead.
*/
final class ServiceUnit extends CatalogItem
{
private function __construct(?int $id, CatalogName $name, private bool $shared, bool $active, int $sortOrder)
private function __construct(?int $id, CatalogName $name, private bool $shared, bool $active, int $sortOrder, private bool $usesStock)
{
parent::__construct($id, $name, $active, $sortOrder);
}
public static function create(CatalogName $name, int $sortOrder, bool $shared = false): self
{
return new self(null, $name, $shared, true, $sortOrder);
return new self(null, $name, $shared, true, $sortOrder, false);
}
public static function reconstitute(int $id, CatalogName $name, bool $shared, bool $active, int $sortOrder): self
public static function reconstitute(int $id, CatalogName $name, bool $shared, bool $active, int $sortOrder, bool $usesStock = false): self
{
return new self($id, $name, $shared, $active, $sortOrder);
return new self($id, $name, $shared, $active, $sortOrder, $usesStock);
}
public function isShared(): bool
{
return $this->shared;
}
public function usesStock(): bool
{
return $this->usesStock;
}
/**
* @throws SharedUnitCannotUseStock
*/
public function useStock(bool $usesStock): void
{
if ($usesStock && $this->shared) {
throw new SharedUnitCannotUseStock;
}
$this->usesStock = $usesStock;
}
}
@@ -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.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class SharedUnitCannotUseStock extends DomainException
{
public function __construct()
{
parent::__construct('The shared service unit follows the job\'s units and cannot use stock by itself.');
}
}
@@ -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'));
}
}
@@ -15,11 +15,12 @@ use Illuminate\Database\Eloquent\Model;
* @property int $id
* @property string $name
* @property bool $is_shared
* @property bool $uses_stock
* @property bool $is_active
* @property int $sort_order
*/
#[Table('service_units')]
#[Fillable(['name', 'is_shared', 'is_active', 'sort_order'])]
#[Fillable(['name', 'is_shared', 'uses_stock', 'is_active', 'sort_order'])]
#[UseFactory(ServiceUnitFactory::class)]
class ServiceUnitModel extends Model
{
@@ -33,6 +34,7 @@ class ServiceUnitModel extends Model
{
return [
'is_shared' => 'boolean',
'uses_stock' => 'boolean',
'is_active' => 'boolean',
'sort_order' => 'integer',
];
@@ -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>
*/
@@ -42,6 +42,18 @@ class EloquentCatalogQueries implements CatalogQueries
return $this->buildTree($units, includeInactive: false);
}
public function stockServiceUnitIds(): array
{
return ServiceUnitModel::query()
->where('uses_stock', true)
->where('is_active', true)
->orderBy('sort_order')
->pluck('id')
->map(fn ($id): int => (int) $id)
->values()
->all();
}
public function findServiceUnit(int $id): ?ServiceUnitSummary
{
$model = ServiceUnitModel::query()->find($id);
@@ -139,7 +151,7 @@ class EloquentCatalogQueries implements CatalogQueries
private function toServiceUnitSummary(ServiceUnitModel $model): ServiceUnitSummary
{
return new ServiceUnitSummary($model->id, $model->name, $model->is_shared, $model->is_active);
return new ServiceUnitSummary($model->id, $model->name, $model->is_shared, $model->is_active, $model->uses_stock);
}
private function toServiceSummary(ServiceModel $model): ServiceSummary
@@ -24,6 +24,7 @@ class EloquentServiceUnitRepository implements ServiceUnitRepository
$model->fill([
'name' => $serviceUnit->name()->value,
'is_shared' => $serviceUnit->isShared(),
'uses_stock' => $serviceUnit->usesStock(),
'is_active' => $serviceUnit->isActive(),
'sort_order' => $serviceUnit->sortOrder(),
])->save();
@@ -56,6 +57,6 @@ class EloquentServiceUnitRepository implements ServiceUnitRepository
private function toEntity(ServiceUnitModel $model): ServiceUnit
{
return ServiceUnit::reconstitute($model->id, new CatalogName($model->name), $model->is_shared, $model->is_active, $model->sort_order);
return ServiceUnit::reconstitute($model->id, new CatalogName($model->name), $model->is_shared, $model->is_active, $model->sort_order, $model->uses_stock);
}
}
@@ -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'),
];
}
}
@@ -162,6 +162,13 @@ new class extends Component
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.shared') }}</p>
@endif
@if ($unit->usesStock)
<p class="flex items-center gap-1 text-sm text-zinc-600 dark:text-zinc-300">
<x-icon name="archive-box" class="size-4" aria-hidden="true" />
{{ __('catalog.service_units.uses_stock_on') }}
</p>
@endif
@foreach ($node->services as $serviceNode)
@php($service = $serviceNode->service)
@@ -249,4 +249,10 @@ new class extends Component
<x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
@if ($productId !== null && $form->is_consumer_product)
@can('machines.manage')
<livewire:machines::production-process :product-id="$productId" :wire:key="'process-'.$productId" />
@endcan
@endif
</div>
@@ -3,6 +3,7 @@
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\UseCases\AddServiceUnit;
use App\Modules\Catalog\Application\UseCases\RenameCatalogItem;
use App\Modules\Catalog\Application\UseCases\SetServiceUnitUsesStock;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\CatalogItemForm;
@@ -11,7 +12,8 @@ use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {serviceUnit}) and edit page (with {serviceUnit}) of a service unit.
* Add page (no {serviceUnit}) and edit page (with {serviceUnit}) of a service unit:
* its name and whether stock and machine features are used in it (spec 19).
*/
new class extends Component
{
@@ -21,6 +23,11 @@ new class extends Component
#[Locked]
public string $unitName = '';
#[Locked]
public bool $isShared = false;
public bool $usesStock = false;
public CatalogItemForm $form;
public function mount(CatalogQueries $catalogQueries, ?int $serviceUnit = null): void
@@ -37,9 +44,11 @@ new class extends Component
$this->serviceUnitId = $summary->id;
$this->form->name = $summary->name;
$this->isShared = $summary->isShared;
$this->usesStock = $summary->usesStock;
}
public function save(AddServiceUnit $addServiceUnit, RenameCatalogItem $renameItem): void
public function save(AddServiceUnit $addServiceUnit, RenameCatalogItem $renameItem, SetServiceUnitUsesStock $setUsesStock): void
{
$this->authorize('catalog.manage');
@@ -47,10 +56,12 @@ new class extends Component
try {
if ($this->serviceUnitId === null) {
$addServiceUnit->execute($name);
$id = $addServiceUnit->execute($name);
$setUsesStock->execute($id, $this->usesStock);
session()->flash('status', __('catalog.status.created', ['name' => trim($name)]));
} else {
$renameItem->execute(CatalogLevel::ServiceUnit, $this->serviceUnitId, $name);
$setUsesStock->execute($this->serviceUnitId, $this->usesStock && ! $this->isShared);
session()->flash('status', __('catalog.status.updated', ['name' => trim($name)]));
}
} catch (CatalogItemNotFound) {
@@ -85,6 +96,13 @@ new class extends Component
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@unless ($isShared)
<div class="space-y-1">
<x-checkbox id="uses-stock" wire:model="usesStock" :label="__('catalog.service_units.uses_stock')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.service_units.uses_stock_hint') }}</p>
</div>
@endunless
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.index')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
@@ -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"
@@ -5,8 +5,8 @@ declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts;
/**
* What the management panel needs from Billing, Sales, Users and the
* holiday calendar. Days are Y-m-d.
* What the management panel needs from Billing, Sales, Users, Machines,
* Inventory and the holiday calendar. Days are Y-m-d.
*/
interface DashboardAdmin
{
@@ -35,4 +35,16 @@ interface DashboardAdmin
* @return list<string>
*/
public function holidaysBetween(string $from, string $to): array;
/**
* Machine maintenance that is late (maintenance requests), by machine.
*
* @return list<array{machineId: int, machine: string, item: string}>
*/
public function lateMaintenance(): array;
/**
* How many stock items are at or below their reorder level.
*/
public function stockItemsToOrder(): int;
}
@@ -22,6 +22,7 @@ final readonly class ManagementOverview
* @param array<string, int> $jobCounts
* @param list<WorkTask> $oldestOverdueTasks
* @param list<PersonLoad> $workloads
* @param list<array{machineId: int, machine: string, item: string}> $lateMaintenance
*/
public function __construct(
public array $pendingApprovals,
@@ -42,5 +43,7 @@ final readonly class ManagementOverview
public string $thisMonday,
public string $nextMonday,
public array $workloads,
public array $lateMaintenance = [],
public int $stockItemsToOrder = 0,
) {}
}
@@ -62,6 +62,8 @@ final readonly class ManagementOverviewQuery
$thisMonday->format('Y-m-d'),
$nextMonday->format('Y-m-d'),
$this->workloads($thisMonday, $nextMonday),
$this->admin->lateMaintenance(),
$this->admin->stockItemsToOrder(),
);
}
@@ -5,14 +5,18 @@ namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Dashboard\Application\Contracts\DashboardAdmin;
use App\Modules\Inventory\Application\Contracts\StockQueries;
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
/**
* Billing drafts, cash days, people and holidays for the management panel
* through the Billing, Sales, Users and Shared modules.
* Billing drafts, cash days, people, holidays, late maintenance and stock
* to order for the management panel through the Billing, Sales, Users,
* Shared, Machines and Inventory modules.
*/
class AdminForDashboard implements DashboardAdmin
{
@@ -21,6 +25,8 @@ class AdminForDashboard implements DashboardAdmin
private QuickSaleQueries $sales,
private UserAccountQueries $users,
private HolidayCalendar $holidays,
private MaintenanceQueries $maintenance,
private StockQueries $stock,
) {}
public function openDraftId(): ?int
@@ -56,4 +62,22 @@ class AdminForDashboard implements DashboardAdmin
{
return $this->holidays->activeDatesBetween($from, $to);
}
public function lateMaintenance(): array
{
$late = [];
foreach ($this->maintenance->due() as $item) {
if ($item->level === MaintenanceLevel::Overdue) {
$late[] = ['machineId' => $item->machineId, 'machine' => $item->machineName, 'item' => $item->name];
}
}
return $late;
}
public function stockItemsToOrder(): int
{
return count($this->stock->items(onlyReorder: true));
}
}
@@ -104,6 +104,29 @@ new class extends Component
</li>
@endif
@endcan
@can('machines.use')
@if ($overview->lateMaintenance !== [])
<li>
<x-link :href="route('machines.show', $overview->lateMaintenance[0]['machineId']).'#maintenance-heading'" navigate>
{{ trans_choice('dashboard.todo.maintenance', count($overview->lateMaintenance), ['count' => count($overview->lateMaintenance)]) }}
</x-link>
<ul class="mt-1 ml-4 list-disc">
@foreach ($overview->lateMaintenance as $late)
<li>{{ __('dashboard.todo.maintenance_line', ['machine' => $late['machine'], 'item' => $late['item']]) }}</li>
@endforeach
</ul>
</li>
@endif
@endcan
@can('inventory.view')
@if ($overview->stockItemsToOrder > 0)
<li>
<x-link :href="route('inventory.index', ['tilattavat' => 1])" navigate>
{{ trans_choice('dashboard.todo.stock', $overview->stockItemsToOrder, ['count' => $overview->stockItemsToOrder]) }}
</x-link>
</li>
@endif
@endcan
@can('reports.view')
<li>
<x-link :href="route('reports.unbilled')" navigate>{{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }}</x-link>
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\InventoryCountLine;
use App\Modules\Inventory\Application\DTOs\InventoryCountSummary;
interface InventoryCountQueries
{
/**
* @return list<InventoryCountSummary> Newest first.
*/
public function counts(): array;
public function findCount(int $id): ?InventoryCountSummary;
/**
* The items of the count in group order and by name: those in its
* groups that are in use, and every item counted in it.
*
* @return list<InventoryCountLine>
*/
public function lines(int $countId): array;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
/**
* Keeps the image files of stock items, which help recognise them on a
* touch screen: an upright JPEG without metadata and its thumbnail.
*/
interface StockItemImages
{
/**
* @return array{path: string, thumbnailPath: string}
*
* @throws InvalidStockImage
*/
public function store(string $uploadedFilePath, int $itemId): array;
/**
* @param list<string> $paths
*/
public function delete(array $paths): void;
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
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
* sales, jobs' task material) read stock through this contract.
*/
interface StockQueries
{
/**
* @return list<StockGroupSummary> In order.
*/
public function groups(bool $includeInactive = true): array;
/**
* Items in group order and then by name. $search matches parts of the
* name or code regardless of case and Finnish letters.
*
* @return list<StockItemSummary>
*/
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array;
public function findItem(int $id): ?StockItemSummary;
/**
* @param list<int> $ids
* @return array<int, StockItemSummary> By id.
*/
public function itemsByIds(array $ids): array;
/**
* The item's movements, newest first, with the balance after each.
*
* @return list<StockMovementSummary>
*/
public function movementsOf(int $itemId, int $limit = 200): array;
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;
/**
* Items used most often on the machine in the last 90 days, then the
* ones used most recently, for the machine console (spec 19.6).
*
* @return array{frequent: list<int>, recent: list<int>}
*/
public function machineFavourites(int $machineId, int $limit = 8): array;
/**
* The private-disk path of the item's image or its thumbnail.
*/
public function imagePathOf(int $itemId, bool $thumbnail): ?string;
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\Contracts;
use App\Modules\Inventory\Application\DTOs\StockUsageEntry;
use App\Modules\Inventory\Application\DTOs\StockValueEntry;
/**
* Stock figures for management's reports (spec 19.8). Days are Y-m-d.
*/
interface StockReportQueries
{
/**
* Use, write-offs and stock count corrections between the days.
*
* @return list<StockUsageEntry>
*/
public function usage(string $from, string $to): array;
/**
* Every item with movements up to the day, or in use, in group order.
*
* @return list<StockValueEntry>
*/
public function valueOn(string $day): array;
/**
* The value of the stock used and written off on jobs' tasks between
* the days, by job id (spec 19.8: material cost in profitability).
*
* @return array<int, int>
*/
public function materialCostsByJob(string $from, string $to): array;
}
@@ -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;
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* An item on a stock count's list: its current balance and, once counted,
* the counted quantity and the book balance at the moment of counting.
* The unit cost is the one stored at confirmation, or the current average
* cost while the count is open.
*/
final readonly class InventoryCountLine
{
public function __construct(
public int $itemId,
public string $itemName,
public ?string $code,
public int $groupId,
public string $groupName,
public StockUnit $unit,
public int $currentBalanceMilli,
public ?int $bookMilli,
public ?int $countedMilli,
public int $unitCostHundredths,
public ?string $countedByName,
public ?string $countedAt,
) {}
public function isCounted(): bool
{
return $this->countedMilli !== null;
}
public function differenceMilli(): ?int
{
return $this->countedMilli === null || $this->bookMilli === null ? null : $this->countedMilli - $this->bookMilli;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A stock count as listed. $groupNames is empty for the whole stock;
* $confirmedAt is "Y-m-d H:i" in the company's time zone.
*/
final readonly class InventoryCountSummary
{
/**
* @param list<string> $groupNames
*/
public function __construct(
public int $id,
public string $countedOn,
public bool $isConfirmed,
public array $groupNames,
public string $startedByName,
public ?string $confirmedByName,
public ?string $confirmedAt,
public int $countedItems,
public ?int $valueBeforeCents,
public ?int $valueAfterCents,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A purchase (hankinta) as entered: the day (Y-m-d), the quantity, and the
* price without VAT either in total or per unit (the other left empty).
*/
final readonly class PurchaseData
{
public function __construct(
public int $itemId,
public string $occurredOn,
public string $quantity,
public string $totalPrice = '',
public string $unitPrice = '',
public ?string $supplier = null,
public ?string $documentNumber = null,
) {}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
final readonly class StockGroupSummary
{
public function __construct(
public int $id,
public string $name,
public bool $isActive,
public int $itemCount = 0,
) {}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* A stock item's details as entered: the unit key and the reorder level
* as typed ("2,5"; empty for none).
*/
final readonly class StockItemData
{
public function __construct(
public int $groupId,
public string $name,
public string $unit,
public ?string $code = null,
public ?string $supplier = null,
public string $reorderLevel = '',
) {}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
use App\Modules\Inventory\Domain\Enums\StockUnit;
/**
* A stock item with its balance (in thousandths), moving average cost (in
* hundredths of a cent per unit) and stock value (in cents). Costs and
* values are shown only to those who may see them.
*/
final readonly class StockItemSummary
{
public function __construct(
public int $id,
public int $groupId,
public string $groupName,
public string $name,
public StockUnit $unit,
public ?string $code,
public ?string $supplier,
public ?int $reorderLevelMilli,
public int $balanceMilli,
public int $averageCostHundredths,
public int $valueCents,
public bool $hasImage,
public bool $isActive,
) {}
/**
* At or below the reorder level: to be ordered (tilattava).
*/
public function needsReorder(): bool
{
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
}
public function isNegative(): bool
{
return $this->balanceMilli < 0;
}
}
@@ -0,0 +1,49 @@
<?php
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
* after it (in thousandths), its value in cents, when and by whom, and
* what it was for. $recordedAt is "Y-m-d H:i" in the company's time zone.
*/
final readonly class StockMovementSummary
{
public function __construct(
public int $id,
public int $itemId,
public StockMovementKind $kind,
public int $quantityMilli,
public int $balanceAfterMilli,
public int $valueCents,
public string $occurredOn,
public string $recordedAt,
public int $userId,
public string $userName,
public ?int $taskId,
public ?int $jobId,
public ?int $machineId,
public ?int $orderLineId,
public ?int $maintenanceRecordId,
public ?int $inventoryCountId,
public ?string $reason,
public ?string $supplier,
public ?string $documentNumber,
public ?int $reversesMovementId,
public ?int $reversedByMovementId,
public string $itemName = '',
public ?StockUnit $unit = null,
) {}
public function canBeReversed(): bool
{
return $this->reversedByMovementId === null
&& $this->kind !== StockMovementKind::Reversal
&& $this->kind !== StockMovementKind::Adjustment;
}
}
@@ -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,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Stock taken out in a period, summed by item, kind, machine and job: the
* quantity (in thousandths) and value (in cents) as positive amounts
* taken; a stock count correction that added stock is negative. Reversals
* count with the movement they reverse. $kind is consumption, write_off
* or adjustment.
*/
final readonly class StockUsageEntry
{
public function __construct(
public int $itemId,
public string $itemName,
public string $groupName,
public string $unit,
public string $kind,
public ?int $machineId,
public ?int $jobId,
public int $quantityMilli,
public int $valueCents,
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Stock used (käyttö) as entered: the quantity as typed and what it was
* used for; use without a target needs a reason.
*/
final readonly class StockUseData
{
public function __construct(
public int $itemId,
public string $quantity,
public ?int $taskId = null,
public ?int $jobId = null,
public ?int $machineId = null,
public ?int $orderLineId = null,
public ?int $maintenanceRecordId = null,
public ?string $reason = null,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* Recorded use or write-off: the movement, the item's name, the quantity
* taken and the item's new balance (in thousandths).
*/
final readonly class StockUseResult
{
public function __construct(
public int $movementId,
public string $itemName,
public int $quantityMilli,
public int $balanceMilli,
) {}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\DTOs;
/**
* An item's balance (in thousandths) and book value (in cents) at the end
* of a day: the sums of its movements up to the day, each at its own cost.
*/
final readonly class StockValueEntry
{
public function __construct(
public int $itemId,
public string $itemName,
public string $groupName,
public string $unit,
public int $balanceMilli,
public int $valueCents,
public ?int $reorderLevelMilli,
public bool $isActive,
) {}
public function needsReorder(): bool
{
return $this->reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli;
}
}
@@ -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,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Entities\StockItem;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item with a zero balance; stock comes in with purchases.
*/
final class AddStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockNameTaken
*/
public function execute(StockItemData $data): int
{
$fields = $this->fields->parse($data);
return $this->transactions->run(function () use ($data, $fields): int {
$this->fields->check($data, $fields['name']);
$item = StockItem::create($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
return (int) $this->items->save($item)->id();
});
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a stock item group last in order.
*/
final class AddStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
*/
public function execute(string $name): int
{
$name = new StockName($name);
return $this->transactions->run(function () use ($name): int {
if ($this->groups->isNameTaken($name->value)) {
throw new StockNameTaken;
}
return (int) $this->groups->save(StockItemGroup::create($name, $this->groups->nextSortOrder()))->id();
});
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Renames a stock item group, moves it one place up or down, or takes it
* out of use or back. Groups are never deleted.
*/
final class ChangeStockItemGroup
{
public function __construct(
private StockItemGroupRepository $groups,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws StockNameTaken
* @throws StockItemGroupNotFound
*/
public function rename(int $groupId, string $name): void
{
$name = new StockName($name);
$this->transactions->run(function () use ($groupId, $name): void {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
if ($this->groups->isNameTaken($name->value, $groupId)) {
throw new StockNameTaken;
}
$group->rename($name);
$this->groups->save($group);
});
}
/**
* @return bool False when the group already was first (up) or last.
*
* @throws StockItemGroupNotFound
*/
public function move(int $groupId, bool $up): bool
{
return $this->transactions->run(function () use ($groupId, $up): bool {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
$neighbour = $this->groups->neighbour($group, $up);
if ($neighbour === null) {
return false;
}
$group->swapOrderWith($neighbour);
$this->groups->save($group);
$this->groups->save($neighbour);
return true;
});
}
/**
* @throws StockItemGroupNotFound
*/
public function setActive(int $groupId, bool $active): void
{
$this->transactions->run(function () use ($groupId, $active): void {
$group = $this->groups->findById($groupId) ?? throw new StockItemGroupNotFound;
$active ? $group->activate() : $group->deactivate();
$this->groups->save($group);
});
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Sets or removes a stock item's image; the replaced files are deleted.
*/
final class ChangeStockItemImage
{
public function __construct(
private StockItemRepository $items,
private StockItemImages $images,
private TransactionManager $transactions,
) {}
/**
* @param string|null $uploadedFilePath Null removes the image.
*
* @throws StockItemNotFound
* @throws InvalidStockImage
*/
public function execute(int $itemId, ?string $uploadedFilePath): void
{
$this->items->findById($itemId) ?? throw new StockItemNotFound;
$stored = $uploadedFilePath === null ? null : $this->images->store($uploadedFilePath, $itemId);
/** @var list<string> $old */
$old = $this->transactions->run(function () use ($itemId, $stored): array {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$old = array_values(array_filter([$item->imagePath(), $item->thumbnailPath()]));
if ($stored === null) {
$item->removeImage();
} else {
$item->setImage($stored['path'], $stored['thumbnailPath']);
}
$this->items->save($item);
return $old;
});
$this->images->delete($old);
}
}
@@ -0,0 +1,129 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\InventoryCount;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountAlreadyOpen;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotInCount;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Stock counts (inventaario, spec 19.3): management starts one for the
* whole stock or chosen groups (one open at a time), anyone using stock
* enters counted quantities, possibly in parts and on several devices,
* and management confirms it: every difference becomes an adjustment at
* the average cost, and the stock value before and after is stored.
* Items not counted are left as they are.
*/
final class InventoryCounts
{
public function __construct(
private InventoryCountRepository $counts,
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @param list<int> $groupIds Empty: the whole stock.
*
* @throws InventoryCountAlreadyOpen
*/
public function start(array $groupIds, int $actorUserId): int
{
return $this->transactions->run(function () use ($groupIds, $actorUserId): int {
if ($this->counts->hasOpen()) {
throw new InventoryCountAlreadyOpen;
}
return (int) $this->counts->save(InventoryCount::start($this->clock->today(), array_values(array_unique($groupIds)), $actorUserId))->id();
});
}
/**
* Enters a counted quantity with the item's book balance now; an empty
* value takes the item back to not counted.
*
* @return int|null The book balance stored with the count, null when cleared.
*
* @throws InventoryCountNotFound
* @throws InventoryCountConfirmed
* @throws StockItemNotFound
* @throws StockItemNotInCount
* @throws InvalidStockQuantity
*/
public function record(int $countId, int $itemId, string $counted, int $actorUserId): ?int
{
$quantity = StockQuantity::parse($counted);
return $this->transactions->run(function () use ($countId, $itemId, $quantity, $actorUserId): ?int {
$count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound;
$count->ensureOpen();
$item = $this->items->lockById($itemId) ?? throw new StockItemNotFound;
if (! $count->covers($item->groupId())) {
throw new StockItemNotInCount;
}
if ($quantity === null) {
$this->counts->removeLine($countId, $itemId);
return null;
}
$book = $this->movements->balanceOf($itemId);
$this->counts->recordLine($countId, $itemId, $book, $quantity->milli, $actorUserId, $this->clock->now());
return $book;
});
}
/**
* @return int The number of adjustments made.
*
* @throws InventoryCountNotFound
* @throws InventoryCountConfirmed
*/
public function confirm(int $countId, int $actorUserId): int
{
return $this->transactions->run(function () use ($countId, $actorUserId): int {
$count = $this->counts->lockById($countId) ?? throw new InventoryCountNotFound;
$count->ensureOpen();
$valueBefore = $this->items->stockValueCents();
$now = $this->clock->now();
$adjustments = 0;
foreach ($this->counts->lines($countId) as $line) {
$item = $this->items->lockById($line['itemId']) ?? throw new StockItemNotFound;
$this->counts->setLineUnitCost($countId, $line['itemId'], $item->averageCostHundredths());
$difference = $line['countedMilli'] - $line['bookMilli'];
if ($difference !== 0) {
$this->movements->add(StockMovement::adjustment($item, $difference, $countId, $count->countedOn(), $now, $actorUserId));
$adjustments++;
}
}
$count->confirm($actorUserId, $now, $valueBefore, $this->items->stockValueCents());
$this->counts->save($count);
return $adjustments;
});
}
}
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\PurchaseData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockCost;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockDay;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Users\Application\Contracts\Clock;
use DateTimeImmutable;
/**
* Records a purchase (hankinta): stock comes in at its price without VAT,
* given in total or per unit, and the item's moving average cost is
* updated (spec 19.2).
*/
final class RecordStockPurchase
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The movement's id.
*
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws InvalidStockCost
* @throws InvalidStockDay
*/
public function execute(PurchaseData $data, int $actorUserId): int
{
$quantity = StockQuantity::parsePositive($data->quantity);
$valueCents = $this->valueCents($data, $quantity);
$occurredOn = $this->day($data->occurredOn);
return $this->transactions->run(function () use ($data, $quantity, $valueCents, $occurredOn, $actorUserId): int {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$balance = $this->movements->balanceOf($data->itemId);
$movement = StockMovement::purchase($item, $quantity, $valueCents, $occurredOn, $this->clock->now(), $actorUserId, $data->supplier ?? $item->supplier(), $data->documentNumber);
$item->receive($balance, $quantity->milli, $valueCents);
$this->items->save($item);
return (int) $this->movements->add($movement)->id();
});
}
/**
* @throws InvalidStockCost
*/
private function valueCents(PurchaseData $data, StockQuantity $quantity): int
{
try {
$total = Money::parse($data->totalPrice);
} catch (InvalidMoneyAmount) {
throw new InvalidStockCost;
}
if ($total !== null) {
return $total->cents;
}
return StockValuation::valueCents($quantity->milli, $this->unitCostHundredths($data->unitPrice));
}
/**
* A unit price with up to four decimals ("0,0123") in hundredths of a cent.
*
* @throws InvalidStockCost
*/
private function unitCostHundredths(string $value): int
{
$value = str_replace(',', '.', preg_replace('/[\s\x{00A0}\x{202F}€]+/u', '', $value) ?? '');
if (preg_match('/^(\d{1,7})(?:\.(\d{1,4}))?$/', $value, $matches) !== 1) {
throw new InvalidStockCost;
}
return (int) $matches[1] * 10_000 + (int) str_pad($matches[2] ?? '', 4, '0');
}
/**
* @throws InvalidStockDay
*/
private function day(string $value): DateTimeImmutable
{
if ($value === '') {
return $this->clock->today();
}
$day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($day === false || $day->format('Y-m-d') !== $value) {
throw new InvalidStockDay;
}
return $day;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
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\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records stock used (käyttö) today at the moving average cost, for a
* task, a machine, a quick sale order or a maintenance, or with a reason.
* Use is never refused for a low balance: a machine must not stop for the
* record, so the balance may go negative, which the stock list warns of
* (spec 19.2).
*/
final class RecordStockUse
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws StockItemInactive
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->quantity);
$target = new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $data->reason);
return $this->transactions->run(function () use ($data, $quantity, $target, $actorUserId): StockUseResult {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$item->ensureUsable();
$movement = $this->movements->add(StockMovement::consumption($item, $quantity, $target, $this->clock->today(), $this->clock->now(), $actorUserId));
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
});
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\DTOs\StockUseResult;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Records a write-off (hävikki / poisto) with its reason, e.g. damaged or
* expired stock, or a reprint in production; possibly for a target too.
*/
final class RecordStockWriteOff
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @throws StockItemNotFound
* @throws InvalidStockQuantity
* @throws StockReasonRequired
*/
public function execute(StockUseData $data, int $actorUserId): StockUseResult
{
$quantity = StockQuantity::parsePositive($data->quantity);
$reason = trim((string) $data->reason);
if ($reason === '') {
throw new StockReasonRequired;
}
$target = $data->taskId === null && $data->machineId === null && $data->orderLineId === null && $data->maintenanceRecordId === null
? null
: new StockUseTarget($data->taskId, $data->jobId, $data->machineId, $data->orderLineId, $data->maintenanceRecordId, $reason);
return $this->transactions->run(function () use ($data, $quantity, $reason, $target, $actorUserId): StockUseResult {
$item = $this->items->lockById($data->itemId) ?? throw new StockItemNotFound;
$movement = $this->movements->add(StockMovement::writeOff($item, $quantity, $reason, $this->clock->today(), $this->clock->now(), $actorUserId, $target));
return new StockUseResult((int) $movement->id(), $item->name()->value, $quantity->milli, $this->movements->balanceOf($data->itemId));
});
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
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\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Reverses a movement (vastakirjaus): the same movement negated, referring
* to the original, recorded today. Users may reverse their own use on the
* day it was recorded; other corrections need the right to correct any
* movement (management). Reversing a purchase also takes it out of the
* moving average cost.
*/
final class ReverseStockMovement
{
public function __construct(
private StockItemRepository $items,
private StockMovementRepository $movements,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The reversal's id.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $movementId, int $actorUserId, bool $mayReverseAny): int
{
$today = $this->clock->today();
return $this->transactions->run(function () use ($movementId, $actorUserId, $mayReverseAny, $today): int {
$original = $this->movements->findById($movementId) ?? throw new StockMovementNotFound;
if (! $mayReverseAny && ! $original->isOwnUseOf($actorUserId, $today)) {
throw new StockReversalNotAllowed;
}
$item = $this->items->lockById($original->itemId()) ?? throw new StockItemNotFound;
if ($this->movements->isReversed($movementId)) {
throw new StockMovementAlreadyReversed;
}
$reversal = StockMovement::reversalOf($original, $today, $this->clock->now(), $actorUserId);
if ($original->kind() === StockMovementKind::Purchase) {
$item->receive($this->movements->balanceOf($item->id() ?? 0), $reversal->quantityMilli(), $reversal->valueCents());
$this->items->save($item);
}
return (int) $this->movements->add($reversal)->id();
});
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a stock item out of use, or back. An item out of use cannot be
* used, but its movements stay.
*/
final class SetStockItemActive
{
public function __construct(
private StockItemRepository $items,
private TransactionManager $transactions,
) {}
/**
* @throws StockItemNotFound
*/
public function execute(int $itemId, bool $active): void
{
$this->transactions->run(function () use ($itemId, $active): void {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$active ? $item->activate() : $item->deactivate();
$this->items->save($item);
});
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemGroupRepository;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
/**
* Checks a stock item's entered details, shared by adding and updating.
*/
final class StockItemFields
{
public function __construct(
private StockItemRepository $items,
private StockItemGroupRepository $groups,
) {}
/**
* @return array{name: StockName, unit: StockUnit, reorderLevelMilli: ?int}
*
* @throws InvalidStockName
* @throws InvalidStockQuantity
*/
public function parse(StockItemData $data): array
{
return [
'name' => new StockName($data->name),
'unit' => StockUnit::tryFrom($data->unit) ?? StockUnit::Piece,
'reorderLevelMilli' => StockQuantity::parse($data->reorderLevel)?->milli,
];
}
/**
* A new item needs a group in use; an existing item may stay in its
* group after the group is taken out of use.
*
* @throws StockItemGroupNotFound
* @throws StockNameTaken
*/
public function check(StockItemData $data, StockName $name, ?int $exceptItemId = null): void
{
$group = $this->groups->findById($data->groupId);
if ($group === null || ($exceptItemId === null && ! $group->isActive())) {
throw new StockItemGroupNotFound;
}
if ($this->items->isNameTaken($name->value, $exceptItemId)) {
throw new StockNameTaken;
}
}
}
@@ -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,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Application\DTOs\StockItemData;
use App\Modules\Inventory\Domain\Contracts\StockItemRepository;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
use App\Modules\Inventory\Domain\Exceptions\StockItemGroupNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockItemNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockNameTaken;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a stock item's details. Its movements and balance stay.
*/
final class UpdateStockItem
{
public function __construct(
private StockItemRepository $items,
private StockItemFields $fields,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidStockName
* @throws InvalidStockQuantity
* @throws StockItemGroupNotFound
* @throws StockItemNotFound
* @throws StockNameTaken
*/
public function execute(int $itemId, StockItemData $data): void
{
$fields = $this->fields->parse($data);
$this->transactions->run(function () use ($itemId, $data, $fields): void {
$item = $this->items->findById($itemId) ?? throw new StockItemNotFound;
$this->fields->check($data, $fields['name'], $itemId);
$item->change($data->groupId, $fields['name'], $fields['unit'], $data->code, $data->supplier, $fields['reorderLevelMilli']);
$this->items->save($item);
});
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\InventoryCount;
use DateTimeImmutable;
interface InventoryCountRepository
{
public function findById(int $id): ?InventoryCount;
/**
* The count, locked until the end of the transaction.
*/
public function lockById(int $id): ?InventoryCount;
public function hasOpen(): bool;
public function save(InventoryCount $count): InventoryCount;
/**
* Stores a counted quantity with the book balance of the moment; a
* recount replaces the line.
*/
public function recordLine(int $countId, int $itemId, int $bookMilli, int $countedMilli, int $userId, DateTimeImmutable $at): void;
public function removeLine(int $countId, int $itemId): void;
/**
* @return list<array{itemId: int, bookMilli: int, countedMilli: int}>
*/
public function lines(int $countId): array;
public function setLineUnitCost(int $countId, int $itemId, int $unitCostHundredths): void;
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItemGroup;
interface StockItemGroupRepository
{
public function findById(int $id): ?StockItemGroup;
public function save(StockItemGroup $group): StockItemGroup;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
public function nextSortOrder(): int;
/**
* The group just before ($up) or after it in order, if any.
*/
public function neighbour(StockItemGroup $group, bool $up): ?StockItemGroup;
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockItem;
interface StockItemRepository
{
public function findById(int $id): ?StockItem;
/**
* The item, locked until the end of the transaction, so that its
* balance and average cost change one movement at a time.
*/
public function lockById(int $id): ?StockItem;
public function save(StockItem $item): StockItem;
public function isNameTaken(string $name, ?int $exceptId = null): bool;
/**
* The value of all stock: each item's balance at its average cost.
*/
public function stockValueCents(): int;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Contracts;
use App\Modules\Inventory\Domain\Entities\StockMovement;
interface StockMovementRepository
{
public function add(StockMovement $movement): StockMovement;
public function findById(int $id): ?StockMovement;
public function isReversed(int $movementId): bool;
/**
* The item's balance in thousandths: the sum of its movements.
*/
public function balanceOf(int $itemId): int;
}
@@ -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,121 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Exceptions\InventoryCountConfirmed;
use DateTimeImmutable;
/**
* A stock count (inventaario, spec 19.3) of the whole stock or of chosen
* item groups. It is open while counted and confirmed once by management;
* a confirmed count is never changed.
*/
final class InventoryCount
{
/**
* @param list<int>|null $groupIds Null: the whole stock.
*/
private function __construct(
private ?int $id,
private DateTimeImmutable $countedOn,
private ?array $groupIds,
private int $startedBy,
private ?int $confirmedBy,
private ?DateTimeImmutable $confirmedAt,
private ?int $valueBeforeCents,
private ?int $valueAfterCents,
) {}
/**
* @param list<int>|null $groupIds
*/
public static function start(DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy): self
{
return new self(null, $countedOn, $groupIds === [] ? null : $groupIds, $startedBy, null, null, null, null);
}
/**
* @param list<int>|null $groupIds
*/
public static function reconstitute(int $id, DateTimeImmutable $countedOn, ?array $groupIds, int $startedBy, ?int $confirmedBy, ?DateTimeImmutable $confirmedAt, ?int $valueBeforeCents, ?int $valueAfterCents): self
{
return new self($id, $countedOn, $groupIds, $startedBy, $confirmedBy, $confirmedAt, $valueBeforeCents, $valueAfterCents);
}
/**
* @throws InventoryCountConfirmed
*/
public function ensureOpen(): void
{
if ($this->isConfirmed()) {
throw new InventoryCountConfirmed;
}
}
/**
* @throws InventoryCountConfirmed
*/
public function confirm(int $userId, DateTimeImmutable $at, int $valueBeforeCents, int $valueAfterCents): void
{
$this->ensureOpen();
$this->confirmedBy = $userId;
$this->confirmedAt = $at;
$this->valueBeforeCents = $valueBeforeCents;
$this->valueAfterCents = $valueAfterCents;
}
public function covers(int $groupId): bool
{
return $this->groupIds === null || in_array($groupId, $this->groupIds, true);
}
public function isConfirmed(): bool
{
return $this->confirmedAt !== null;
}
public function id(): ?int
{
return $this->id;
}
public function countedOn(): DateTimeImmutable
{
return $this->countedOn;
}
/**
* @return list<int>|null
*/
public function groupIds(): ?array
{
return $this->groupIds;
}
public function startedBy(): int
{
return $this->startedBy;
}
public function confirmedBy(): ?int
{
return $this->confirmedBy;
}
public function confirmedAt(): ?DateTimeImmutable
{
return $this->confirmedAt;
}
public function valueBeforeCents(): ?int
{
return $this->valueBeforeCents;
}
public function valueAfterCents(): ?int
{
return $this->valueAfterCents;
}
}
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockUnit;
use App\Modules\Inventory\Domain\Exceptions\StockItemInactive;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A stock item (nimike), e.g. a photo paper or an ink, counted in its unit.
* Its balance is the sum of its movements and is not kept here; the item
* keeps its moving average cost, which only purchases change. Items are
* never deleted: one taken out of use cannot be used, but its movements
* stay.
*/
final class StockItem
{
private function __construct(
private ?int $id,
private int $groupId,
private StockName $name,
private StockUnit $unit,
private ?string $code,
private ?string $supplier,
private ?int $reorderLevelMilli,
private int $averageCostHundredths,
private ?string $imagePath,
private ?string $thumbnailPath,
private bool $active,
) {}
public static function create(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): self
{
return new self(null, $groupId, $name, $unit, self::text($code), self::text($supplier), $reorderLevelMilli, 0, null, null, true);
}
public static function reconstitute(
int $id,
int $groupId,
StockName $name,
StockUnit $unit,
?string $code,
?string $supplier,
?int $reorderLevelMilli,
int $averageCostHundredths,
?string $imagePath,
?string $thumbnailPath,
bool $active,
): self {
return new self($id, $groupId, $name, $unit, $code, $supplier, $reorderLevelMilli, $averageCostHundredths, $imagePath, $thumbnailPath, $active);
}
public function change(int $groupId, StockName $name, StockUnit $unit, ?string $code, ?string $supplier, ?int $reorderLevelMilli): void
{
$this->groupId = $groupId;
$this->name = $name;
$this->unit = $unit;
$this->code = self::text($code);
$this->supplier = self::text($supplier);
$this->reorderLevelMilli = $reorderLevelMilli;
}
/**
* Updates the moving average cost for a purchase (or, with a negative
* quantity and value, the reversal of one) received on top of the
* given balance.
*/
public function receive(int $balanceMilli, int $quantityMilli, int $valueCents): void
{
$this->averageCostHundredths = StockValuation::averageAfterPurchase($balanceMilli, $this->averageCostHundredths, $quantityMilli, $valueCents);
}
/**
* @throws StockItemInactive
*/
public function ensureUsable(): void
{
if (! $this->active) {
throw new StockItemInactive;
}
}
public function setImage(string $imagePath, string $thumbnailPath): void
{
$this->imagePath = $imagePath;
$this->thumbnailPath = $thumbnailPath;
}
public function removeImage(): void
{
$this->imagePath = null;
$this->thumbnailPath = null;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
public function id(): ?int
{
return $this->id;
}
public function groupId(): int
{
return $this->groupId;
}
public function name(): StockName
{
return $this->name;
}
public function unit(): StockUnit
{
return $this->unit;
}
public function code(): ?string
{
return $this->code;
}
public function supplier(): ?string
{
return $this->supplier;
}
public function reorderLevelMilli(): ?int
{
return $this->reorderLevelMilli;
}
public function averageCostHundredths(): int
{
return $this->averageCostHundredths;
}
public function imagePath(): ?string
{
return $this->imagePath;
}
public function thumbnailPath(): ?string
{
return $this->thumbnailPath;
}
public function isActive(): bool
{
return $this->active;
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : mb_substr($value, 0, 150);
}
}
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\ValueObjects\StockName;
/**
* A group of stock items (nimikeryhmä), e.g. Paperit ja kartongit. Groups
* are ordered, and never deleted, only taken out of use.
*/
final class StockItemGroup
{
private function __construct(
private ?int $id,
private StockName $name,
private int $sortOrder,
private bool $active,
) {}
public static function create(StockName $name, int $sortOrder): self
{
return new self(null, $name, $sortOrder, true);
}
public static function reconstitute(int $id, StockName $name, int $sortOrder, bool $active): self
{
return new self($id, $name, $sortOrder, $active);
}
public function rename(StockName $name): void
{
$this->name = $name;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
public function swapOrderWith(self $other): void
{
[$this->sortOrder, $other->sortOrder] = [$other->sortOrder, $this->sortOrder];
}
public function id(): ?int
{
return $this->id;
}
public function name(): StockName
{
return $this->name;
}
public function sortOrder(): int
{
return $this->sortOrder;
}
public function isActive(): bool
{
return $this->active;
}
}
@@ -0,0 +1,225 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Entities;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
use App\Modules\Inventory\Domain\Services\StockValuation;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use DateTimeImmutable;
/**
* A change in an item's balance (varastotapahtuma, spec 19.2). Movements
* are never changed or deleted: a mistake is corrected with a reversal,
* the same movement negated, which refers to the original. The quantity
* is signed (in thousandths) and the value is at the unit cost of the
* moment: the purchase price for a purchase, the moving average cost
* otherwise.
*/
final class StockMovement
{
private function __construct(
private ?int $id,
private int $itemId,
private StockMovementKind $kind,
private int $quantityMilli,
private int $unitCostHundredths,
private int $valueCents,
private DateTimeImmutable $occurredOn,
private DateTimeImmutable $recordedAt,
private int $userId,
private ?StockUseTarget $target,
private ?string $reason,
private ?string $supplier,
private ?string $documentNumber,
private ?int $inventoryCountId,
private ?int $reversesMovementId,
) {}
public static function purchase(StockItem $item, StockQuantity $quantity, int $valueCents, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?string $supplier, ?string $documentNumber): self
{
return new self(
null, (int) $item->id(), StockMovementKind::Purchase, $quantity->milli,
StockValuation::unitCostOf($quantity->milli, $valueCents), $valueCents,
$occurredOn, $recordedAt, $userId, null, null, self::text($supplier), self::text($documentNumber), null, null,
);
}
public static function consumption(StockItem $item, StockQuantity $quantity, StockUseTarget $target, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
return self::outgoing(StockMovementKind::Consumption, $item, $quantity, $target, $target->reason, $occurredOn, $recordedAt, $userId);
}
/**
* @throws StockReasonRequired
*/
public static function writeOff(StockItem $item, StockQuantity $quantity, string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId, ?StockUseTarget $target = null): self
{
$reason = self::text($reason) ?? throw new StockReasonRequired;
return self::outgoing(StockMovementKind::WriteOff, $item, $quantity, $target, $reason, $occurredOn, $recordedAt, $userId);
}
/**
* A stock count's correction: a signed difference at the average cost.
*/
public static function adjustment(StockItem $item, int $differenceMilli, int $inventoryCountId, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
$cost = $item->averageCostHundredths();
return new self(
null, (int) $item->id(), StockMovementKind::Adjustment, $differenceMilli, $cost,
StockValuation::valueCents($differenceMilli, $cost),
$occurredOn, $recordedAt, $userId, null, null, null, null, $inventoryCountId, null,
);
}
/**
* @throws StockMovementNotReversible
*/
public static function reversalOf(self $original, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
if (! $original->isReversible()) {
throw new StockMovementNotReversible;
}
return new self(
null, $original->itemId, StockMovementKind::Reversal, -$original->quantityMilli,
$original->unitCostHundredths, -$original->valueCents,
$occurredOn, $recordedAt, $userId, $original->target, $original->reason, null, null, null, $original->id,
);
}
public static function reconstitute(
int $id,
int $itemId,
StockMovementKind $kind,
int $quantityMilli,
int $unitCostHundredths,
int $valueCents,
DateTimeImmutable $occurredOn,
DateTimeImmutable $recordedAt,
int $userId,
?StockUseTarget $target,
?string $reason,
?string $supplier,
?string $documentNumber,
?int $inventoryCountId,
?int $reversesMovementId,
): self {
return new self($id, $itemId, $kind, $quantityMilli, $unitCostHundredths, $valueCents, $occurredOn, $recordedAt, $userId, $target, $reason, $supplier, $documentNumber, $inventoryCountId, $reversesMovementId);
}
public function isReversible(): bool
{
return $this->kind !== StockMovementKind::Reversal && $this->kind !== StockMovementKind::Adjustment;
}
/**
* Whether the user may reverse this movement without the right to
* correct anyone's: their own use, on the day it was recorded.
*/
public function isOwnUseOf(int $userId, DateTimeImmutable $today): bool
{
return $this->kind === StockMovementKind::Consumption
&& $this->userId === $userId
&& $this->occurredOn->format('Y-m-d') === $today->format('Y-m-d');
}
public function id(): ?int
{
return $this->id;
}
public function itemId(): int
{
return $this->itemId;
}
public function kind(): StockMovementKind
{
return $this->kind;
}
public function quantityMilli(): int
{
return $this->quantityMilli;
}
public function unitCostHundredths(): int
{
return $this->unitCostHundredths;
}
public function valueCents(): int
{
return $this->valueCents;
}
public function occurredOn(): DateTimeImmutable
{
return $this->occurredOn;
}
public function recordedAt(): DateTimeImmutable
{
return $this->recordedAt;
}
public function userId(): int
{
return $this->userId;
}
public function target(): ?StockUseTarget
{
return $this->target;
}
public function reason(): ?string
{
return $this->reason;
}
public function supplier(): ?string
{
return $this->supplier;
}
public function documentNumber(): ?string
{
return $this->documentNumber;
}
public function inventoryCountId(): ?int
{
return $this->inventoryCountId;
}
public function reversesMovementId(): ?int
{
return $this->reversesMovementId;
}
private static function outgoing(StockMovementKind $kind, StockItem $item, StockQuantity $quantity, ?StockUseTarget $target, ?string $reason, DateTimeImmutable $occurredOn, DateTimeImmutable $recordedAt, int $userId): self
{
$cost = $item->averageCostHundredths();
return new self(
null, (int) $item->id(), $kind, -$quantity->milli, $cost,
StockValuation::valueCents(-$quantity->milli, $cost),
$occurredOn, $recordedAt, $userId, $target, $reason, null, null, null, null,
);
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : mb_substr($value, 0, 255);
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Enums;
/**
* What a stock movement is (spec 19.2): a purchase adds stock, use and a
* write-off take it, a stock count adjusts it either way, and a reversal
* cancels an earlier movement with the opposite quantity.
*/
enum StockMovementKind: string
{
case Purchase = 'purchase';
case Consumption = 'consumption';
case WriteOff = 'write_off';
case Adjustment = 'adjustment';
case Reversal = 'reversal';
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Enums;
/**
* The unit a stock item is counted in (spec 19.1). Labels are in
* lang/*\/inventory.php under units.
*/
enum StockUnit: string
{
case Piece = 'piece';
case Sheet = 'sheet';
case Roll = 'roll';
case Metre = 'metre';
case SquareMetre = 'square_metre';
case Litre = 'litre';
case Package = 'package';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockCost extends DomainException
{
public function __construct()
{
parent::__construct('A purchase price must be zero or more, with at most four decimals for a unit price.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockDay extends DomainException
{
public function __construct()
{
parent::__construct('The day must be a valid date.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockImage extends DomainException
{
public function __construct()
{
parent::__construct('The file is not a supported image.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockName extends DomainException
{
public function __construct()
{
parent::__construct('A stock name must be 1-150 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidStockQuantity extends DomainException
{
public function __construct()
{
parent::__construct('A stock quantity must be a number with at most three decimals.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InventoryCountAlreadyOpen extends DomainException
{
public function __construct()
{
parent::__construct('Another stock count is open.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InventoryCountConfirmed extends DomainException
{
public function __construct()
{
parent::__construct('The stock count has been confirmed and cannot be changed.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InventoryCountNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock count was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemGroupNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock item group was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemInactive extends DomainException
{
public function __construct()
{
parent::__construct('The stock item is no longer in use.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock item was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockItemNotInCount extends DomainException
{
public function __construct()
{
parent::__construct('The item is not in this stock count.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementAlreadyReversed extends DomainException
{
public function __construct()
{
parent::__construct('The stock movement has already been reversed.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementNotFound extends DomainException
{
public function __construct()
{
parent::__construct('The stock movement was not found.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockMovementNotReversible extends DomainException
{
public function __construct()
{
parent::__construct('Reversals and stock count adjustments cannot be reversed.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('The name is already in use.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockReasonRequired extends DomainException
{
public function __construct()
{
parent::__construct('A reason is required.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class StockReversalNotAllowed extends DomainException
{
public function __construct()
{
parent::__construct('Only your own use recorded today may be reversed.');
}
}
@@ -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,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Matches stock items to a search typed on a keyboard or touch screen, or
* read by a barcode scanner: every word of the search must be found in the
* name or the code, regardless of case and of the dots of å, ä and ö
* (spec 19.6).
*/
final class StockSearch
{
public static function matches(string $search, string $name, ?string $code): bool
{
$words = preg_split('/\s+/u', self::normalize($search), -1, PREG_SPLIT_NO_EMPTY) ?: [];
$haystack = self::normalize($name.' '.($code ?? ''));
foreach ($words as $word) {
if (! str_contains($haystack, $word)) {
return false;
}
}
return true;
}
public static function normalize(string $value): string
{
return strtr(mb_strtolower(trim($value)), ['å' => 'a', 'ä' => 'a', 'ö' => 'o', 'é' => 'e', 'ü' => 'u']);
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Valuation of stock at a moving average cost (liukuva keskihinta, spec
* 19.2). Unit costs are in hundredths of a cent per whole unit, so that
* cheap units such as a millilitre of ink keep their precision; values
* are in cents, rounded half away from zero.
*/
final class StockValuation
{
/**
* The value of a quantity (in thousandths) at a unit cost.
*/
public static function valueCents(int $quantityMilli, int $unitCostHundredths): int
{
return self::divideRounded($quantityMilli * $unitCostHundredths, 100_000);
}
/**
* The unit cost of a purchase of a quantity for a total value.
*/
public static function unitCostOf(int $quantityMilli, int $valueCents): int
{
return $quantityMilli === 0 ? 0 : self::divideRounded($valueCents * 100_000, $quantityMilli);
}
/**
* The average unit cost after a purchase: (old balance × old average +
* purchase value) / new balance. When the stock before was empty or
* negative, or nothing is left after, the purchase's own unit cost.
*/
public static function averageAfterPurchase(int $balanceMilli, int $averageHundredths, int $purchasedMilli, int $purchaseValueCents): int
{
$newBalance = $balanceMilli + $purchasedMilli;
if ($balanceMilli <= 0 || $newBalance <= 0) {
return max(0, self::unitCostOf($purchasedMilli, $purchaseValueCents));
}
$oldValueHundredthsMilli = $balanceMilli * $averageHundredths;
return max(0, self::divideRounded($oldValueHundredthsMilli + $purchaseValueCents * 100_000, $newBalance));
}
private static function divideRounded(int $dividend, int $divisor): int
{
$sign = ($dividend < 0) !== ($divisor < 0) ? -1 : 1;
$dividend = abs($dividend);
$divisor = abs($divisor);
return $sign * intdiv($dividend + intdiv($divisor, 2), $divisor);
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockName;
/**
* Name of a stock item or an item group, e.g. "Valokuvapaperi 10×15".
*/
final readonly class StockName
{
public const int MAX_LENGTH = 150;
public string $value;
/**
* @throws InvalidStockName
*/
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidStockName;
}
$this->value = $value;
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockQuantity;
/**
* A quantity of stock in thousandths of the item's unit (e.g. 2,5 m² =
* 2500), so three decimals are kept exactly. Typed in as "2,5", "2.5" or
* "1 200".
*/
final readonly class StockQuantity
{
public const int MAX_MILLI = 9_999_999_999;
private function __construct(public int $milli) {}
/**
* @throws InvalidStockQuantity
*/
public static function ofMilli(int $milli): self
{
if (abs($milli) > self::MAX_MILLI) {
throw new InvalidStockQuantity;
}
return new self($milli);
}
/**
* A quantity greater than zero, as typed in.
*
* @throws InvalidStockQuantity
*/
public static function parsePositive(string $value): self
{
$quantity = self::parse($value);
if ($quantity === null || $quantity->milli <= 0) {
throw new InvalidStockQuantity;
}
return $quantity;
}
/**
* A quantity of zero or more as typed in, or null for an empty value.
*
* @throws InvalidStockQuantity
*/
public static function parse(string $value): ?self
{
$value = preg_replace('/[\s\x{00A0}\x{202F}]+/u', '', $value) ?? '';
$value = str_replace(',', '.', $value);
if ($value === '') {
return null;
}
if (preg_match('/^(\d{1,7})(?:\.(\d{1,3}))?$/', $value, $matches) !== 1) {
throw new InvalidStockQuantity;
}
return new self((int) $matches[1] * 1000 + (int) str_pad($matches[2] ?? '', 3, '0'));
}
public function negated(): self
{
return new self(-$this->milli);
}
/**
* Finnish format without trailing zeros: "2,5", "-1", "1 200".
*/
public static function format(int $milli): string
{
$whole = intdiv(abs($milli), 1000);
$fraction = rtrim(str_pad((string) (abs($milli) % 1000), 3, '0', STR_PAD_LEFT), '0');
return ($milli < 0 ? '-' : '').number_format($whole, 0, ',', "\u{00A0}").($fraction === '' ? '' : ','.$fraction);
}
/**
* The value for an input field: "2,5" without thousands separators.
*/
public static function inputValue(int $milli): string
{
return str_replace("\u{00A0}", '', self::format($milli));
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\ValueObjects;
use App\Modules\Inventory\Domain\Exceptions\StockReasonRequired;
/**
* What stock was used for (spec 19.2): a job's task, a machine, a quick
* sale order line or a machine's maintenance, each possibly with a reason.
* Use without a target (e.g. a test run) needs a reason.
*/
final readonly class StockUseTarget
{
public ?string $reason;
/**
* @throws StockReasonRequired
*/
public function __construct(
public ?int $taskId = null,
public ?int $jobId = null,
public ?int $machineId = null,
public ?int $orderLineId = null,
public ?int $maintenanceRecordId = null,
?string $reason = null,
) {
$reason = $reason === null ? null : trim($reason);
$this->reason = $reason === '' || $reason === null ? null : mb_substr($reason, 0, 255);
if ($this->reason === null && $taskId === null && $machineId === null && $orderLineId === null && $maintenanceRecordId === null) {
throw new StockReasonRequired;
}
}
/**
* @throws StockReasonRequired
*/
public static function reason(?string $reason): self
{
return new self(reason: $reason);
}
}
@@ -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,42 @@
<?php
namespace App\Modules\Inventory\Infrastructure\Files;
use App\Modules\Inventory\Application\Contracts\StockItemImages;
use App\Modules\Inventory\Domain\Exceptions\InvalidStockImage;
use App\Modules\Shared\Application\Contracts\ImageResizer;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
/**
* Stock item images on the private local disk under stock-items/: an
* upright JPEG without metadata and a thumbnail for touch-screen buttons.
*/
class StockItemImageFiles implements StockItemImages
{
public const string DISK = 'local';
public const int MAX_SIZE = 1280;
public const int THUMBNAIL_SIZE = 240;
public function __construct(private ImageResizer $resizer) {}
public function store(string $uploadedFilePath, int $itemId): array
{
$versions = $this->resizer->jpegVersions($uploadedFilePath, [self::MAX_SIZE, self::THUMBNAIL_SIZE]) ?? throw new InvalidStockImage;
$name = 'stock-items/'.$itemId.'/'.Str::uuid()->toString();
Storage::disk(self::DISK)->put($name.'.jpg', $versions[0]['bytes']);
Storage::disk(self::DISK)->put($name.'-thumb.jpg', $versions[1]['bytes']);
return ['path' => $name.'.jpg', 'thumbnailPath' => $name.'-thumb.jpg'];
}
public function delete(array $paths): void
{
if ($paths !== []) {
Storage::disk(self::DISK)->delete($paths);
}
}
}

Some files were not shown because too many files have changed in this diff Show More