240 lines
9.8 KiB
PHP
240 lines
9.8 KiB
PHP
<?php
|
|
|
|
namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
|
|
|
|
use App\Modules\Inventory\Application\Contracts\StockQueries;
|
|
use App\Modules\Inventory\Application\DTOs\StockGroupSummary;
|
|
use App\Modules\Inventory\Application\DTOs\StockItemSummary;
|
|
use App\Modules\Inventory\Application\DTOs\StockMovementSummary;
|
|
use App\Modules\Inventory\Application\DTOs\TaskMaterialSuggestion;
|
|
use App\Modules\Inventory\Domain\Enums\StockUnit;
|
|
use App\Modules\Inventory\Domain\Services\StockSearch;
|
|
use App\Modules\Inventory\Domain\Services\StockValuation;
|
|
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemGroupModel;
|
|
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockItemModel;
|
|
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
|
|
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\TaskMaterialSuggestionModel;
|
|
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class EloquentStockQueries implements StockQueries
|
|
{
|
|
public function __construct(private UserAccountQueries $users) {}
|
|
|
|
public function groups(bool $includeInactive = true): array
|
|
{
|
|
return StockItemGroupModel::query()
|
|
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
|
|
->withCount('items')
|
|
->orderBy('sort_order')
|
|
->get()
|
|
->map(fn (StockItemGroupModel $model): StockGroupSummary => new StockGroupSummary($model->id, $model->name, $model->is_active, (int) $model->getAttribute('items_count')))
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array
|
|
{
|
|
$search = trim((string) $search);
|
|
|
|
return $this->itemQuery()
|
|
->when($groupId !== null, fn (Builder $query) => $query->where('stock_items.stock_item_group_id', $groupId))
|
|
->when(! $includeInactive, fn (Builder $query) => $query->where('stock_items.is_active', true))
|
|
->get()
|
|
->filter(fn (StockItemModel $model): bool => $search === '' || StockSearch::matches($search, $model->name, $model->code))
|
|
->map(fn (StockItemModel $model): StockItemSummary => $this->toSummary($model))
|
|
->filter(fn (StockItemSummary $item): bool => ! $onlyReorder || $item->needsReorder())
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
public function findItem(int $id): ?StockItemSummary
|
|
{
|
|
$model = $this->itemQuery()->where('stock_items.id', $id)->first();
|
|
|
|
return $model === null ? null : $this->toSummary($model);
|
|
}
|
|
|
|
public function itemsByIds(array $ids): array
|
|
{
|
|
if ($ids === []) {
|
|
return [];
|
|
}
|
|
|
|
return $this->itemQuery()
|
|
->whereIn('stock_items.id', $ids)
|
|
->get()
|
|
->mapWithKeys(fn (StockItemModel $model): array => [$model->id => $this->toSummary($model)])
|
|
->all();
|
|
}
|
|
|
|
public function movementsOf(int $itemId, int $limit = 200): array
|
|
{
|
|
$models = StockMovementModel::query()
|
|
->with('reversal:id,reverses_movement_id')
|
|
->where('stock_item_id', $itemId)
|
|
->orderByDesc('id')
|
|
->limit($limit)
|
|
->get();
|
|
|
|
$balance = (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
|
|
|
|
return $this->summaries($models, $balance);
|
|
}
|
|
|
|
public function findMovement(int $id): ?StockMovementSummary
|
|
{
|
|
$model = StockMovementModel::query()->with('reversal:id,reverses_movement_id')->find($id);
|
|
|
|
if ($model === null) {
|
|
return null;
|
|
}
|
|
|
|
$balance = (int) StockMovementModel::query()
|
|
->where('stock_item_id', $model->stock_item_id)
|
|
->where('id', '<=', $model->id)
|
|
->sum('quantity_milli');
|
|
|
|
return $this->summaries(collect([$model]), $balance)[0];
|
|
}
|
|
|
|
public function taskMovements(int $taskId): array
|
|
{
|
|
$models = StockMovementModel::query()
|
|
->with('reversal:id,reverses_movement_id')
|
|
->where('task_id', $taskId)
|
|
->orderByDesc('id')
|
|
->get();
|
|
|
|
return $this->summaries($models, 0, trackBalance: false);
|
|
}
|
|
|
|
public function taskSuggestions(int $taskId): array
|
|
{
|
|
return TaskMaterialSuggestionModel::query()
|
|
->join('stock_items', 'stock_items.id', '=', 'task_material_suggestions.stock_item_id')
|
|
->where('task_material_suggestions.task_id', $taskId)
|
|
->orderBy('task_material_suggestions.id')
|
|
->get(['task_material_suggestions.*', 'stock_items.name as item_name', 'stock_items.unit as item_unit'])
|
|
->map(fn (TaskMaterialSuggestionModel $model): TaskMaterialSuggestion => new TaskMaterialSuggestion(
|
|
$model->id,
|
|
$model->task_id,
|
|
$model->stock_item_id,
|
|
(string) $model->getAttribute('item_name'),
|
|
StockUnit::from((string) $model->getAttribute('item_unit')),
|
|
$model->quantity_milli,
|
|
))
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
public function machineFavourites(int $machineId, int $limit = 8): array
|
|
{
|
|
$uses = StockMovementModel::query()
|
|
->where('machine_id', $machineId)
|
|
->whereIn('kind', ['consumption', 'write_off'])
|
|
->whereNull('reverses_movement_id')
|
|
->where('recorded_at', '>=', now()->subDays(90))
|
|
->orderByDesc('id')
|
|
->get(['id', 'stock_item_id']);
|
|
|
|
$frequent = $uses->countBy('stock_item_id')->sortDesc()->keys()->take($limit)->map(fn ($id): int => (int) $id)->values()->all();
|
|
$recent = $uses->pluck('stock_item_id')->unique()->take($limit)->map(fn ($id): int => (int) $id)->values()->all();
|
|
|
|
return ['frequent' => $frequent, 'recent' => $recent];
|
|
}
|
|
|
|
public function imagePathOf(int $itemId, bool $thumbnail): ?string
|
|
{
|
|
$model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']);
|
|
|
|
return $thumbnail ? $model?->thumbnail_path : $model?->image_path;
|
|
}
|
|
|
|
/**
|
|
* @return Builder<StockItemModel>
|
|
*/
|
|
private function itemQuery(): Builder
|
|
{
|
|
return StockItemModel::query()
|
|
->join('stock_item_groups', 'stock_item_groups.id', '=', 'stock_items.stock_item_group_id')
|
|
->select('stock_items.*')
|
|
->addSelect('stock_item_groups.name as group_name')
|
|
->selectSub(
|
|
StockMovementModel::query()->selectRaw('COALESCE(SUM(quantity_milli), 0)')->whereColumn('stock_movements.stock_item_id', 'stock_items.id'),
|
|
'balance_milli',
|
|
)
|
|
->orderBy('stock_item_groups.sort_order')
|
|
->orderBy('stock_items.name');
|
|
}
|
|
|
|
private function toSummary(StockItemModel $model): StockItemSummary
|
|
{
|
|
$balance = (int) $model->getAttribute('balance_milli');
|
|
|
|
return new StockItemSummary(
|
|
id: $model->id,
|
|
groupId: $model->stock_item_group_id,
|
|
groupName: (string) $model->getAttribute('group_name'),
|
|
name: $model->name,
|
|
unit: $model->unit,
|
|
code: $model->code,
|
|
supplier: $model->supplier,
|
|
reorderLevelMilli: $model->reorder_level_milli,
|
|
balanceMilli: $balance,
|
|
averageCostHundredths: $model->average_cost_hundredths,
|
|
valueCents: StockValuation::valueCents($balance, $model->average_cost_hundredths),
|
|
hasImage: $model->thumbnail_path !== null,
|
|
isActive: $model->is_active,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int, StockMovementModel> $models Newest first.
|
|
* @param int $balance The balance after the newest of them.
|
|
* @return list<StockMovementSummary>
|
|
*/
|
|
private function summaries(Collection $models, int $balance, bool $trackBalance = true): array
|
|
{
|
|
$names = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all());
|
|
$items = StockItemModel::query()->whereIn('id', $models->pluck('stock_item_id')->unique())->get(['id', 'name', 'unit'])->keyBy('id');
|
|
$summaries = [];
|
|
|
|
foreach ($models as $model) {
|
|
$summaries[] = new StockMovementSummary(
|
|
id: $model->id,
|
|
itemId: $model->stock_item_id,
|
|
kind: $model->kind,
|
|
quantityMilli: $model->quantity_milli,
|
|
balanceAfterMilli: $balance,
|
|
valueCents: $model->value_cents,
|
|
occurredOn: $model->occurred_on->format('Y-m-d'),
|
|
recordedAt: Carbon::instance($model->recorded_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
|
|
userId: $model->user_id,
|
|
userName: $names[$model->user_id] ?? '',
|
|
taskId: $model->task_id,
|
|
jobId: $model->customer_job_id,
|
|
machineId: $model->machine_id,
|
|
orderLineId: $model->quick_sale_order_line_id,
|
|
maintenanceRecordId: $model->maintenance_record_id,
|
|
inventoryCountId: $model->inventory_count_id,
|
|
reason: $model->reason,
|
|
supplier: $model->supplier,
|
|
documentNumber: $model->document_number,
|
|
reversesMovementId: $model->reverses_movement_id,
|
|
reversedByMovementId: $model->reversal?->id,
|
|
itemName: (string) $items->get($model->stock_item_id)?->name,
|
|
unit: $items->get($model->stock_item_id)?->unit,
|
|
);
|
|
|
|
if ($trackBalance) {
|
|
$balance -= $model->quantity_milli;
|
|
}
|
|
}
|
|
|
|
return $summaries;
|
|
}
|
|
}
|