Track machine counters and maintenance with counter and time intervals
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use App\Modules\Machines\Domain\Enums\MaintenancePeriod;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Machines Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $machine_id
|
||||
* @property string $name
|
||||
* @property int|null $machine_counter_id
|
||||
* @property int|null $interval_milli
|
||||
* @property int $counter_baseline_milli
|
||||
* @property MaintenancePeriod|null $period
|
||||
* @property int $period_count
|
||||
* @property string $starts_on Y-m-d
|
||||
* @property int $warning_percent
|
||||
* @property string|null $instructions
|
||||
* @property int|null $stock_item_id
|
||||
* @property int|null $stock_quantity_milli
|
||||
* @property bool $is_active
|
||||
*/
|
||||
#[Table('maintenance_items')]
|
||||
#[Fillable([
|
||||
'machine_id', 'name', 'machine_counter_id', 'interval_milli', 'counter_baseline_milli', 'period', 'period_count',
|
||||
'starts_on', 'warning_percent', 'instructions', 'stock_item_id', 'stock_quantity_milli', 'is_active',
|
||||
])]
|
||||
class MaintenanceItemModel extends Model
|
||||
{
|
||||
/**
|
||||
* The latest maintenance that was not cancelled.
|
||||
*
|
||||
* @return HasOne<MaintenanceRecordModel, $this>
|
||||
*/
|
||||
public function lastRecord(): HasOne
|
||||
{
|
||||
return $this->hasOne(MaintenanceRecordModel::class, 'maintenance_item_id')
|
||||
->ofMany(['performed_at' => 'max', 'id' => 'max'], fn ($query) => $query->whereNull('cancelled_at'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'machine_id' => 'integer',
|
||||
'machine_counter_id' => 'integer',
|
||||
'interval_milli' => 'integer',
|
||||
'counter_baseline_milli' => 'integer',
|
||||
'period' => MaintenancePeriod::class,
|
||||
'period_count' => 'integer',
|
||||
'warning_percent' => 'integer',
|
||||
'stock_item_id' => 'integer',
|
||||
'stock_quantity_milli' => 'integer',
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Persistence model, used only inside the Machines Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $maintenance_item_id
|
||||
* @property Carbon $performed_at
|
||||
* @property int $user_id
|
||||
* @property int|null $counter_reading_milli
|
||||
* @property string|null $note
|
||||
* @property Carbon|null $cancelled_at
|
||||
* @property int|null $cancelled_by
|
||||
*/
|
||||
#[Table('maintenance_records')]
|
||||
#[Fillable(['maintenance_item_id', 'performed_at', 'user_id', 'counter_reading_milli', 'note', 'cancelled_at', 'cancelled_by'])]
|
||||
class MaintenanceRecordModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'maintenance_item_id' => 'integer',
|
||||
'performed_at' => 'immutable_datetime',
|
||||
'user_id' => 'integer',
|
||||
'counter_reading_milli' => 'integer',
|
||||
'cancelled_at' => 'immutable_datetime',
|
||||
'cancelled_by' => 'integer',
|
||||
];
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Machines\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Machines\Domain\Contracts\MaintenanceRepository;
|
||||
use App\Modules\Machines\Domain\Entities\MaintenanceItem;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MachineCounterReadingModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceItemModel;
|
||||
use App\Modules\Machines\Infrastructure\Persistence\Eloquent\MaintenanceRecordModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentMaintenanceRepository implements MaintenanceRepository
|
||||
{
|
||||
public function findItem(int $id): ?MaintenanceItem
|
||||
{
|
||||
$model = MaintenanceItemModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : MaintenanceItem::reconstitute(
|
||||
$model->id,
|
||||
$model->machine_id,
|
||||
$model->name,
|
||||
$model->machine_counter_id,
|
||||
$model->interval_milli,
|
||||
$model->counter_baseline_milli,
|
||||
$model->period,
|
||||
$model->period_count,
|
||||
new DateTimeImmutable(substr($model->starts_on, 0, 10)),
|
||||
$model->warning_percent,
|
||||
$model->instructions,
|
||||
$model->stock_item_id,
|
||||
$model->stock_quantity_milli,
|
||||
$model->is_active,
|
||||
);
|
||||
}
|
||||
|
||||
public function saveItem(MaintenanceItem $item): MaintenanceItem
|
||||
{
|
||||
$model = $item->id() === null ? new MaintenanceItemModel : MaintenanceItemModel::query()->findOrFail($item->id());
|
||||
|
||||
$model->fill([
|
||||
'machine_id' => $item->machineId(),
|
||||
'name' => $item->name(),
|
||||
'machine_counter_id' => $item->counterId(),
|
||||
'interval_milli' => $item->intervalMilli(),
|
||||
'counter_baseline_milli' => $item->baselineMilli(),
|
||||
'period' => $item->period(),
|
||||
'period_count' => $item->periodCount(),
|
||||
'starts_on' => $item->startsOn()->format('Y-m-d'),
|
||||
'warning_percent' => $item->warningPercent(),
|
||||
'instructions' => $item->instructions(),
|
||||
'stock_item_id' => $item->stockItemId(),
|
||||
'stock_quantity_milli' => $item->stockQuantityMilli(),
|
||||
'is_active' => $item->isActive(),
|
||||
])->save();
|
||||
|
||||
return $this->findItem($model->id) ?? $item;
|
||||
}
|
||||
|
||||
public function machineOfCounter(int $counterId): ?int
|
||||
{
|
||||
$machineId = MachineCounterModel::query()->whereKey($counterId)->value('machine_id');
|
||||
|
||||
return $machineId === null ? null : (int) $machineId;
|
||||
}
|
||||
|
||||
public function latestReading(int $counterId): ?int
|
||||
{
|
||||
$reading = MachineCounterReadingModel::query()
|
||||
->where('machine_counter_id', $counterId)
|
||||
->orderByDesc('read_at')
|
||||
->orderByDesc('id')
|
||||
->value('reading_milli');
|
||||
|
||||
return $reading === null ? null : (int) $reading;
|
||||
}
|
||||
|
||||
public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void
|
||||
{
|
||||
MachineCounterReadingModel::query()->create([
|
||||
'machine_counter_id' => $counterId,
|
||||
'reading_milli' => $readingMilli,
|
||||
'user_id' => $userId,
|
||||
'read_at' => $at->format('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function addRecord(int $itemId, DateTimeImmutable $performedAt, int $userId, ?int $readingMilli, ?string $note): int
|
||||
{
|
||||
return MaintenanceRecordModel::query()->create([
|
||||
'maintenance_item_id' => $itemId,
|
||||
'performed_at' => $performedAt->format('Y-m-d H:i:s'),
|
||||
'user_id' => $userId,
|
||||
'counter_reading_milli' => $readingMilli,
|
||||
'note' => $note,
|
||||
])->id;
|
||||
}
|
||||
|
||||
public function findRecord(int $id): ?array
|
||||
{
|
||||
$model = MaintenanceRecordModel::query()->find($id);
|
||||
|
||||
return $model === null ? null : ['id' => $model->id, 'itemId' => $model->maintenance_item_id, 'cancelled' => $model->cancelled_at !== null];
|
||||
}
|
||||
|
||||
public function cancelRecord(int $id, int $userId, DateTimeImmutable $at): void
|
||||
{
|
||||
MaintenanceRecordModel::query()->whereKey($id)->update(['cancelled_at' => $at->format('Y-m-d H:i:s'), 'cancelled_by' => $userId]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user