Files

173 lines
8.3 KiB
PHP

<?php
namespace App\Modules\Machines\Infrastructure\Persistence\Repositories;
use App\Modules\Machines\Application\Contracts\MaintenanceQueries;
use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus;
use App\Modules\Machines\Application\DTOs\MaintenanceRecordSummary;
use App\Modules\Machines\Domain\Enums\MaintenanceLevel;
use App\Modules\Machines\Domain\Services\MaintenanceStatus;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel;
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceRecordModel;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use DateTimeImmutable;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class EloquentMaintenanceQueries implements MaintenanceQueries
{
public function __construct(
private UserAccountQueries $users,
private Clock $clock,
) {}
public function itemsOf(int $machineId, bool $includeInactive = false): array
{
$models = MaintenanceItemModel::query()
->with('lastRecord')
->where('machine_id', $machineId)
->when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true))
->orderBy('name')
->get();
return $this->sorted($this->statuses($models));
}
public function findItem(int $itemId): ?MaintenanceItemStatus
{
$model = MaintenanceItemModel::query()->with('lastRecord')->find($itemId);
return $model === null ? null : $this->statuses(collect([$model]))[0];
}
public function due(): array
{
$models = MaintenanceItemModel::query()
->with('lastRecord')
->where('is_active', true)
->whereIn('machine_id', MachineModel::query()->select('id')->where('is_active', true))
->get();
return $this->sorted(array_values(array_filter(
$this->statuses($models),
fn (MaintenanceItemStatus $item): bool => $item->level !== MaintenanceLevel::Ok,
)));
}
public function history(int $machineId, ?int $itemId = null, ?string $from = null, ?string $to = null, int $limit = 200): array
{
$timezone = (string) config('app.business_timezone');
$models = MaintenanceRecordModel::query()
->join('maintenance_items', 'maintenance_items.id', '=', 'maintenance_records.maintenance_item_id')
->where('maintenance_items.machine_id', $machineId)
->when($itemId !== null, fn (Builder $query) => $query->where('maintenance_records.maintenance_item_id', $itemId))
->when($from !== null, fn (Builder $query) => $query->where('maintenance_records.performed_at', '>=', Carbon::parse((string) $from, $timezone)->startOfDay()->utc()))
->when($to !== null, fn (Builder $query) => $query->where('maintenance_records.performed_at', '<=', Carbon::parse((string) $to, $timezone)->endOfDay()->utc()))
->orderByDesc('maintenance_records.performed_at')
->orderByDesc('maintenance_records.id')
->limit($limit)
->get(['maintenance_records.*', 'maintenance_items.name as item_name']);
$names = $this->users->namesByIds($models->flatMap(fn (MaintenanceRecordModel $model): array => array_filter([$model->user_id, $model->cancelled_by]))->unique()->values()->all());
return $models->map(fn (MaintenanceRecordModel $model): MaintenanceRecordSummary => new MaintenanceRecordSummary(
id: $model->id,
itemId: $model->maintenance_item_id,
itemName: (string) $model->getAttribute('item_name'),
performedAt: $this->localTime($model->performed_at),
userName: $names[$model->user_id] ?? '',
readingMilli: $model->counter_reading_milli,
note: $model->note,
cancelledAt: $model->cancelled_at === null ? null : $this->localTime($model->cancelled_at),
cancelledByName: $model->cancelled_by === null ? null : ($names[$model->cancelled_by] ?? ''),
))->values()->all();
}
/**
* @param Collection<int, MaintenanceItemModel> $models
* @return list<MaintenanceItemStatus>
*/
private function statuses(Collection $models): array
{
if ($models->isEmpty()) {
return [];
}
$today = $this->clock->today();
$machines = MachineModel::query()->whereIn('id', $models->pluck('machine_id')->unique())->get(['id', 'name', 'responsible_user_id'])->keyBy('id');
$counterIds = $models->pluck('machine_counter_id')->filter()->unique()->values();
$counters = MachineCounterModel::query()->whereIn('id', $counterIds)->get()->keyBy('id');
$readings = MachineCounterReadingModel::query()
->whereIn('machine_counter_id', $counterIds)
->orderBy('read_at')
->orderBy('id')
->get()
->groupBy('machine_counter_id')
->map(fn (Collection $rows): int => (int) $rows->last()?->reading_milli);
$names = $this->users->namesByIds($models->map(fn (MaintenanceItemModel $model): ?int => $model->lastRecord?->user_id)->filter()->unique()->values()->all());
return $models->map(function (MaintenanceItemModel $model) use ($today, $machines, $counters, $readings, $names): MaintenanceItemStatus {
$last = $model->lastRecord;
$counter = $model->machine_counter_id === null ? null : $counters->get($model->machine_counter_id);
$reading = $model->machine_counter_id === null ? null : $readings->get($model->machine_counter_id);
$baseline = $last->counter_reading_milli ?? $model->counter_baseline_milli;
$since = $last === null
? new DateTimeImmutable(substr($model->starts_on, 0, 10))
: new DateTimeImmutable(Carbon::instance($last->performed_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d'));
$state = MaintenanceStatus::evaluate($model->interval_milli, $baseline, $reading, $model->period, $model->period_count, $since, $model->warning_percent, $today);
$machine = $machines->get($model->machine_id);
return new MaintenanceItemStatus(
id: $model->id,
machineId: $model->machine_id,
machineName: (string) $machine?->name,
responsibleUserId: $machine?->responsible_user_id,
name: $model->name,
counterId: $model->machine_counter_id,
counterName: $counter?->name,
counterUnit: $counter?->unit,
intervalMilli: $model->interval_milli,
period: $model->period,
periodCount: $model->period_count,
warningPercent: $model->warning_percent,
instructions: $model->instructions,
stockItemId: $model->stock_item_id,
stockQuantityMilli: $model->stock_quantity_milli,
isActive: $model->is_active,
level: $state->level,
remainingMilli: $state->remainingMilli,
dueOn: $state->dueOn,
readingMilli: $reading,
lastRecordId: $last?->id,
lastPerformedAt: $last === null ? null : $this->localTime($last->performed_at),
lastPerformedByName: $last === null ? null : ($names[$last->user_id] ?? ''),
);
})->values()->all();
}
/**
* Late items first, then those coming up, then by name.
*
* @param list<MaintenanceItemStatus> $items
* @return list<MaintenanceItemStatus>
*/
private function sorted(array $items): array
{
usort($items, fn (MaintenanceItemStatus $a, MaintenanceItemStatus $b): int => [$b->level->rank(), $a->machineName, $a->name] <=> [$a->level->rank(), $b->machineName, $b->name]);
return $items;
}
private function localTime(DateTimeInterface $moment): string
{
return Carbon::instance($moment)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i');
}
}