Files
Toiminnanohjaus/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php
T
petriandClaude Opus 5.5 3922c744a7 Add time tracking on tasks with a weekly sheet
Phase 1, item 8 (last of phase 1). New TimeTracking module:
- One entry per user, task and day (0.25-24 h in quarters, with a note);
  the job and work type are copied from the task. A user's day cannot
  exceed 24 h, and hours on a done, invoiced, billed or archived job
  cannot be added or changed.
- Weekly sheet /time: tasks as rows (own open tasks, tasks with hours
  that week, tasks added by search), days as columns, row, day and week
  totals, week navigation. A cell saves on change and an empty cell
  removes the entry; on phones one day at a time. Saves and errors are
  announced, errors are tied to their cell.
- Task booking page /time/tasks/{task}: date, hours and note, added to
  the day's entry; own entries with edit and remove.
- Anyone but subcontractors may book on any unlocked task;
  subcontractors only on jobs they are attached to.

Jobs module:
- JobStatus::locksTime(), BookableTask and task queries for booking.
- A task with time entries cannot be removed (TaskUsage contract,
  provided by TimeTracking); the job page links tasks to booking.
- The "involved in a job" rule is shared in JobInvolvement.

Spec and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 05:52:45 +02:00

170 lines
6.3 KiB
PHP

<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class EloquentTaskQueries implements TaskQueries
{
public function __construct(
private CatalogQueries $catalog,
private UserAccountQueries $users,
) {}
public function tasksOf(int $jobId): array
{
$models = TaskModel::query()
->where('customer_job_id', $jobId)
->orderByRaw('status = ?', [TaskStatus::Done->value])
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderBy('id')
->get();
return $this->summaries($models);
}
public function findTask(int $jobId, int $taskId): ?TaskSummary
{
$model = TaskModel::query()->where('customer_job_id', $jobId)->find($taskId);
return $model === null ? null : $this->summaries(collect([$model]))[0];
}
public function bookableTask(int $taskId): ?BookableTask
{
return $this->bookableTasks([$taskId])[0] ?? null;
}
public function bookableTasks(array $taskIds): array
{
if ($taskIds === []) {
return [];
}
return $this->bookableRows(DB::table('tasks')->whereIn('tasks.id', $taskIds));
}
public function assignedOpenTaskIds(int $userId): array
{
return DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->where('task_assignees.user_id', $userId)
->where('tasks.status', '!=', TaskStatus::Done->value)
->whereNotIn('customer_jobs.status', self::lockedStatuses())
->orderBy('tasks.id')
->pluck('tasks.id')
->map(fn ($id): int => (int) $id)
->all();
}
public function searchBookableTasks(string $term, ?int $onlyMemberUserId = null, int $limit = 8): array
{
$term = trim($term);
if ($term === '') {
return [];
}
$pattern = '%'.addcslashes($term, '%_\\').'%';
$query = DB::table('tasks')
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->whereNotIn('customer_jobs.status', self::lockedStatuses())
->where(fn ($query) => $query
->where('customer_jobs.number', 'like', $pattern)
->orWhere('customer_jobs.name', 'like', $pattern)
->orWhere('tasks.title', 'like', $pattern))
->limit($limit);
if ($onlyMemberUserId !== null) {
JobInvolvement::restrict($query, $onlyMemberUserId);
}
return $this->bookableRows(DB::table('tasks')->whereIn('tasks.id', $query->pluck('tasks.id')->all()));
}
/**
* @return list<BookableTask>
*/
private function bookableRows(Builder $tasks): array
{
$rows = $tasks
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->orderBy('customer_jobs.number')
->orderBy('tasks.id')
->get(['tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.work_type_id', 'tasks.status', 'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.status as job_status']);
$workTypeNames = [];
foreach ($rows->pluck('work_type_id')->unique() as $workTypeId) {
$workTypeNames[(int) $workTypeId] = $this->catalog->findWorkType((int) $workTypeId)->name ?? '';
}
return $rows->map(fn ($row): BookableTask => new BookableTask(
(int) $row->id,
(int) $row->customer_job_id,
(string) $row->number,
(string) $row->name,
(string) $row->title,
(int) $row->work_type_id,
$workTypeNames[(int) $row->work_type_id] ?? '',
JobStatus::from((string) $row->job_status),
TaskStatus::from((string) $row->status),
))->values()->all();
}
/**
* @return list<string>
*/
private static function lockedStatuses(): array
{
return array_values(array_map(fn (JobStatus $status): string => $status->value, array_filter(JobStatus::cases(), fn (JobStatus $status): bool => $status->locksTime())));
}
/**
* @param Collection<int, TaskModel> $models
* @return list<TaskSummary>
*/
private function summaries(Collection $models): array
{
$assignees = DB::table('task_assignees')
->whereIn('task_id', $models->pluck('id')->all())
->get()
->groupBy('task_id');
$userNames = $this->users->namesByIds($assignees->flatten()->pluck('user_id')->map(fn ($id): int => (int) $id)->unique()->values()->all());
$workTypeNames = [];
foreach ($models->pluck('work_type_id')->unique() as $workTypeId) {
$workTypeNames[$workTypeId] = $this->catalog->findWorkType((int) $workTypeId)->name ?? '';
}
return $models->map(fn (TaskModel $model): TaskSummary => new TaskSummary(
id: $model->id,
jobId: $model->customer_job_id,
title: $model->title,
description: $model->description,
status: $model->status,
dueOn: $model->due_on?->format('Y-m-d'),
estimatedHours: $model->estimated_hours === null ? null : rtrim(rtrim($model->estimated_hours, '0'), '.'),
workType: new NamedId($model->work_type_id, $workTypeNames[$model->work_type_id] ?? ''),
assignees: ($assignees->get($model->id) ?? collect())
->map(fn ($row): NamedId => new NamedId((int) $row->user_id, $userNames[(int) $row->user_id] ?? ''))
->sortBy('name')
->values()
->all(),
))->values()->all();
}
}