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]>
This commit is contained in:
2026-11-24 05:52:45 +02:00
co-authored by Claude Opus 5.5
parent 02a62eb16e
commit 3922c744a7
53 changed files with 2496 additions and 19 deletions
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
interface TaskQueries
@@ -19,4 +20,31 @@ interface TaskQueries
* Null when the task does not exist or belongs to another job.
*/
public function findTask(int $jobId, int $taskId): ?TaskSummary;
/**
* A task as time is recorded on it, or null when there is no such task.
*/
public function bookableTask(int $taskId): ?BookableTask;
/**
* @param list<int> $taskIds
* @return list<BookableTask> In job number, then task id order.
*/
public function bookableTasks(array $taskIds): array;
/**
* Ids of tasks assigned to the user that are not done, on jobs that are
* not locked.
*
* @return list<int>
*/
public function assignedOpenTaskIds(int $userId): array;
/**
* Tasks on unlocked jobs whose job number, job name or task name
* contains the term; only jobs the user is a member of when given.
*
* @return list<BookableTask>
*/
public function searchBookableTasks(string $term, ?int $onlyMemberUserId = null, int $limit = 8): array;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
/**
* Whether other modules refer to a task, so it is not removed while in
* use. The TimeTracking module provides the real answer.
*/
interface TaskUsage
{
public function hasTimeEntries(int $taskId): bool;
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task as time is recorded on it: which job and work type it belongs to,
* and whether the job is locked for time entries.
*/
final readonly class BookableTask
{
public function __construct(
public int $taskId,
public int $jobId,
public string $jobNumber,
public string $jobName,
public string $taskTitle,
public int $workTypeId,
public string $workTypeName,
public JobStatus $jobStatus,
public TaskStatus $taskStatus,
) {}
public function isLocked(): bool
{
return $this->jobStatus->locksTime();
}
/**
* E.g. "2026-0005 Messuvideo – Mainoskuvat".
*/
public function label(): string
{
return $this->jobNumber.' '.$this->jobName.' – '.$this->taskTitle;
}
}
@@ -4,28 +4,36 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Deletes a task. Once time is recorded on tasks, a task with time entries
* cannot be removed.
* Deletes a task that has no time entries.
*/
final class RemoveTask
{
public function __construct(
private TaskRepository $tasks,
private TaskUsage $usage,
private TransactionManager $transactions,
) {}
/**
* @throws TaskNotFound
* @throws TaskHasTimeEntries
*/
public function execute(int $jobId, int $taskId): void
{
$this->transactions->run(function () use ($jobId, $taskId): void {
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
if ($this->usage->hasTimeEntries($taskId)) {
throw new TaskHasTimeEntries;
}
$this->tasks->delete($task);
});
}
@@ -38,6 +38,14 @@ enum JobStatus: string
return ! in_array($this, [self::Prospect, self::Tentative, self::Archived], true);
}
/**
* Once a job is done its hours and expenses are locked (K21).
*/
public function locksTime(): bool
{
return in_array($this, [self::Done, self::Invoiced, self::Billed, self::Archived], true);
}
/**
* The Kanban columns: every status except archived.
*
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class TaskHasTimeEntries extends DomainException
{
public function __construct()
{
parent::__construct('The task has time entries and cannot be removed.');
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Modules\Jobs\Infrastructure;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
/**
* Default when no module refers to tasks.
*/
class NothingUsesTasks implements TaskUsage
{
public function hasTimeEntries(int $taskId): bool
{
return false;
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
/**
* The jobs a user is involved in: responsible, contact person, biller,
* member, or assignee of one of the job's tasks. Used for "my jobs" and
* for what a subcontractor may see.
*/
final class JobInvolvement
{
/**
* Restricts a query on customer_jobs (under the given table name or alias).
*
* @template TBuilder of Builder
*
* @param TBuilder $query
* @return TBuilder
*/
public static function restrict(Builder $query, int $userId, string $table = 'customer_jobs'): Builder
{
$query->where(fn ($query) => $query
->where($table.'.responsible_user_id', $userId)
->orWhere($table.'.contact_user_id', $userId)
->orWhere($table.'.biller_user_id', $userId)
->orWhereIn($table.'.id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId))
->orWhereIn($table.'.id', DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->select('tasks.customer_job_id')
->where('task_assignees.user_id', $userId)));
return $query;
}
}
@@ -12,6 +12,7 @@ use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
@@ -244,14 +245,6 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
*/
private function involving(Builder $query, int $userId): Builder
{
return $query->where(fn (Builder $query) => $query
->where('responsible_user_id', $userId)
->orWhere('contact_user_id', $userId)
->orWhere('biller_user_id', $userId)
->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId))
->orWhereIn('id', DB::table('tasks')
->join('task_assignees', 'task_assignees.task_id', '=', 'tasks.id')
->select('tasks.customer_job_id')
->where('task_assignees.user_id', $userId)));
return JobInvolvement::restrict($query, $userId);
}
}
@@ -4,11 +4,15 @@ 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;
@@ -39,6 +43,96 @@ class EloquentTaskQueries implements TaskQueries
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>
@@ -6,10 +6,12 @@ use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs;
use App\Modules\Jobs\Infrastructure\NothingUsesTasks;
use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
@@ -36,6 +38,8 @@ class JobsServiceProvider extends ServiceProvider
CustomerRowUsage::class => CustomerRowUsageFromJobs::class,
TaskRepository::class => EloquentTaskRepository::class,
TaskQueries::class => EloquentTaskQueries::class,
// Replaced by the TimeTracking module, which knows which tasks have time entries.
TaskUsage::class => NothingUsesTasks::class,
];
public function boot(): void
@@ -10,6 +10,7 @@ use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus;
use App\Modules\Jobs\Application\UseCases\RemoveTask;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
@@ -131,6 +132,8 @@ new class extends Component
$this->taskStatusMessage = __('jobs.tasks.removed', ['title' => $this->removalTaskTitle]);
} catch (TaskNotFound) {
$this->taskStatusMessage = __('jobs.tasks.not_found');
} catch (TaskHasTimeEntries) {
$this->taskStatusMessage = __('jobs.tasks.has_time_entries', ['title' => $this->removalTaskTitle]);
}
unset($this->tasks);
@@ -348,6 +351,19 @@ new class extends Component
</div>
@endif
@if (! $job->status->locksTime() && Gate::allows('time.book', $job->id))
<x-button
:href="route('time.task', $task->id)"
wire:navigate
subtle
color="black"
sm
icon="clock"
:text="__('jobs.tasks.book_time')"
:aria-label="__('jobs.tasks.book_time_named', ['title' => $task->title])"
/>
@endif
@if ($canManageTasks)
<x-button
:href="route('jobs.tasks.edit', [$job->id, $task->id])"