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
+3 -3
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page) and `Jobs` (customer jobs: numbering, members, tags, links, history)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) and `TimeTracking` (hours on tasks: weekly sheet and task booking page)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`).
- `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`.
- Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files.
@@ -50,7 +50,7 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
- Make everything work with the keyboard alone, with a visible focus indicator and no focus traps. Use `<x-confirm-dialog>` for dialogs (not `<x-modal>`, see above) and check that focus moves in and returns. Drag and drop uses Livewire's `wire:sort` (see `jobs::board`), and every drag has a keyboard alternative (e.g. a status select on each card).
- The layout (`resources/views/layouts/app.blade.php`) provides a skip link and a `<main id="main-content">` landmark. Keep them, and add `<nav aria-label="…">` for navigation.
- One `h1` per page, logical heading order, and a descriptive page `#[Title]` on every page component.
- Data tables use `<x-table>` with `headers` (custom cells with `@interact('column_<index>', $row)`). Icon-only buttons need an `aria-label` (a `tooltip` alone is not a name). Decorative images get `alt=""`.
- Data tables use `<x-table>` with `headers` (custom cells with `@interact('column_<index>', $row)`). An input grid is a form, not a data table: the weekly time sheet (`time::week`) is a native `<table>` with `<caption>` and `th scope`, and its cells save with `wire:change` (two inputs bound to one property with `wire:model` do not save). Icon-only buttons need an `aria-label` (a `tooltip` alone is not a name). Decorative images get `alt=""`.
- Contrast is at least 4.5:1 for text and 3:1 for UI components and focus indicators, in both light and dark mode.
- Layouts must reflow at 320 px width and 400 % zoom without horizontal scrolling. Touch targets are at least 24×24 px.
- Every new page gets a browser test in `tests/Browser` that uses `assertNoAccessibilityIssues(level: 2)` in light and dark mode and on desktop and mobile. See `tests/Browser/AccessibilityTest.php`. Automated axe checks catch only part of WCAG: also check new flows manually with the keyboard and a screen reader (NVDA).
@@ -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])"
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
interface TimeEntryQueries
{
/**
* The user's week starting on the Monday: rows for the user's open
* tasks, tasks with hours that week, and the extra tasks asked for.
*
* @param list<int> $extraTaskIds
*/
public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet;
/**
* The user's entries on a task, newest day first.
*
* @return list<TimeEntrySummary>
*/
public function entriesForTask(int $taskId, int $userId): array;
public function hasEntries(int $taskId): bool;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
final readonly class TimeEntrySummary
{
public function __construct(
public int $id,
public string $workedOn,
public int $quarters,
public ?string $note,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
use App\Modules\Jobs\Application\DTOs\BookableTask;
/**
* One task of the weekly view with its hours per day.
*/
final readonly class WeekRow
{
/**
* @param array<string, int> $quartersByDay Y-m-d => quarters of an hour (days without hours left out)
*/
public function __construct(
public BookableTask $task,
public array $quartersByDay,
public int $totalQuarters,
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A user's week: days Monday to Sunday, one row per task, and totals.
*/
final readonly class WeekSheet
{
/**
* @param list<string> $days Y-m-d, Monday first
* @param list<WeekRow> $rows
* @param array<string, int> $dayTotals Y-m-d => quarters
*/
public function __construct(
public array $days,
public array $rows,
public array $dayTotals,
public int $totalQuarters,
) {}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Services;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\TaskNotBookable;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* The rules every change of hours follows: the task exists, its job is not
* locked, and the user's day stays within 24 hours.
*/
final class TimeBooking
{
public function __construct(
private TaskQueries $tasks,
private TimeEntryRepository $entries,
) {}
/**
* @throws TaskNotBookable
* @throws TimeLocked
*/
public function openTask(int $taskId): BookableTask
{
$task = $this->tasks->bookableTask($taskId) ?? throw new TaskNotBookable($taskId);
if ($task->isLocked()) {
throw new TimeLocked;
}
return $task;
}
/**
* @throws DailyHoursExceeded
*/
public function ensureDayFits(int $userId, DateTimeImmutable $day, WorkedHours $hours, ?int $exceptEntryId = null): void
{
if ($this->entries->quartersOn($userId, $day, $exceptEntryId) + $hours->quarters > WorkedHours::MAX_QUARTERS) {
throw new DailyHoursExceeded;
}
}
public static function day(string $value): DateTimeImmutable
{
$day = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($day === false || $day->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("Not a Y-m-d date: {$value}");
}
return $day;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TaskNotBookable;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
/**
* Records hours from a task's page. Hours on a day that already has an
* entry are added to it, and the note continues the earlier one.
*/
final class AddTaskHours
{
public function __construct(
private TimeEntryRepository $entries,
private TimeBooking $booking,
private TransactionManager $transactions,
) {}
/**
* @return string The day's total hours, e.g. "6,5".
*
* @throws InvalidWorkedHours
* @throws TaskNotBookable
* @throws TimeLocked
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $taskId, string $day, string $hours, ?string $note = null): string
{
$date = TimeBooking::day($day);
$parsed = WorkedHours::parse($hours) ?? throw new InvalidWorkedHours;
return $this->transactions->run(function () use ($userId, $taskId, $date, $parsed, $note): string {
$task = $this->booking->openTask($taskId);
$this->booking->ensureDayFits($userId, $date, $parsed);
$entry = $this->entries->findForDay($userId, $taskId, $date);
if ($entry === null) {
$entry = TimeEntry::create($userId, $taskId, $task->jobId, $task->workTypeId, $date, $parsed, $note);
} else {
$entry->addHours($parsed, $note);
}
return $this->entries->save($entry)->hours()->format();
});
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Exceptions\TimeEntryNotFound;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
/**
* Removes one of the user's own entries while the job is not locked.
*/
final class RemoveTimeEntry
{
public function __construct(
private TimeEntryRepository $entries,
private TimeBooking $booking,
private TransactionManager $transactions,
) {}
/**
* @throws TimeEntryNotFound
* @throws TimeLocked
*/
public function execute(int $userId, int $entryId): void
{
$this->transactions->run(function () use ($userId, $entryId): void {
$entry = $this->entries->findForUser($userId, $entryId) ?? throw new TimeEntryNotFound($entryId);
$this->booking->openTask($entry->taskId());
$this->entries->delete($entry);
});
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TaskNotBookable;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
/**
* One cell of the weekly view: sets the user's hours on a task for a day.
* An empty value (or 0) removes the day's entry.
*/
final class SetDayHours
{
public function __construct(
private TimeEntryRepository $entries,
private TimeBooking $booking,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidWorkedHours
* @throws TaskNotBookable
* @throws TimeLocked
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $taskId, string $day, string $hours): void
{
$date = TimeBooking::day($day);
$parsed = in_array(trim($hours), ['0', '0,0', '0.0', '0,00', '0.00'], true) ? null : WorkedHours::parse($hours);
$this->transactions->run(function () use ($userId, $taskId, $date, $parsed): void {
$task = $this->booking->openTask($taskId);
$entry = $this->entries->findForDay($userId, $taskId, $date);
if ($parsed === null) {
if ($entry !== null) {
$this->entries->delete($entry);
}
return;
}
$this->booking->ensureDayFits($userId, $date, $parsed, $entry?->id());
if ($entry === null) {
$entry = TimeEntry::create($userId, $taskId, $task->jobId, $task->workTypeId, $date, $parsed);
} else {
$entry->changeHours($parsed, $entry->note());
}
$this->entries->save($entry);
});
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TimeEntryNotFound;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
/**
* Changes the hours and note of one of the user's own entries.
*/
final class UpdateTimeEntry
{
public function __construct(
private TimeEntryRepository $entries,
private TimeBooking $booking,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidWorkedHours
* @throws TimeEntryNotFound
* @throws TimeLocked
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $entryId, string $hours, ?string $note): void
{
$parsed = WorkedHours::parse($hours) ?? throw new InvalidWorkedHours;
$this->transactions->run(function () use ($userId, $entryId, $parsed, $note): void {
$entry = $this->entries->findForUser($userId, $entryId) ?? throw new TimeEntryNotFound($entryId);
$this->booking->openTask($entry->taskId());
$this->booking->ensureDayFits($userId, $entry->workedOn(), $parsed, $entry->id());
$entry->changeHours($parsed, $note);
$this->entries->save($entry);
});
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Contracts;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use DateTimeImmutable;
interface TimeEntryRepository
{
public function findForDay(int $userId, int $taskId, DateTimeImmutable $day): ?TimeEntry;
/**
* Null when the entry does not exist or belongs to another user.
*/
public function findForUser(int $userId, int $entryId): ?TimeEntry;
public function save(TimeEntry $entry): TimeEntry;
public function delete(TimeEntry $entry): void;
/**
* The user's recorded quarters of an hour on the day, all tasks.
*/
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int;
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Entities;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use DateTimeImmutable;
/**
* A user's hours on one task on one day (one entry per day). The job and
* work type are copied from the task when the entry is made, for billing.
*/
final class TimeEntry
{
private function __construct(
private ?int $id,
private int $userId,
private int $taskId,
private int $jobId,
private int $workTypeId,
private DateTimeImmutable $workedOn,
private WorkedHours $hours,
private ?string $note,
) {}
public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self
{
return new self(null, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, self::text($note));
}
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note): self
{
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note);
}
public function changeHours(WorkedHours $hours, ?string $note): void
{
$this->hours = $hours;
$this->note = self::text($note);
}
/**
* Adds more hours to the day's entry; a new note continues the old one.
*/
public function addHours(WorkedHours $hours, ?string $note): void
{
$this->hours = $this->hours->plus($hours);
$note = self::text($note);
if ($note !== null) {
$this->note = $this->note === null ? $note : $this->note."\n".$note;
}
}
public function id(): ?int
{
return $this->id;
}
public function userId(): int
{
return $this->userId;
}
public function taskId(): int
{
return $this->taskId;
}
public function jobId(): int
{
return $this->jobId;
}
public function workTypeId(): int
{
return $this->workTypeId;
}
public function workedOn(): DateTimeImmutable
{
return $this->workedOn;
}
public function hours(): WorkedHours
{
return $this->hours;
}
public function note(): ?string
{
return $this->note;
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : $value;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class DailyHoursExceeded extends DomainException
{
public function __construct()
{
parent::__construct('The hours of one day cannot exceed 24.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidWorkedHours extends DomainException
{
public function __construct()
{
parent::__construct('Hours must be 0.25–24, in quarters of an hour.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class TaskNotBookable extends DomainException
{
public function __construct(public readonly int $taskId)
{
parent::__construct("Task {$taskId} was not found.");
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The entry does not exist or belongs to another user.
*/
final class TimeEntryNotFound extends DomainException
{
public function __construct(public readonly int $entryId)
{
parent::__construct("Time entry {$entryId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class TimeLocked extends DomainException
{
public function __construct()
{
parent::__construct('The job is done, so its hours are locked.');
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\ValueObjects;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
/**
* Hours worked on one day, 0.25–24 to the nearest quarter of an hour.
* Stored as quarters so sums stay exact.
*/
final readonly class WorkedHours
{
public const int MAX_QUARTERS = 96;
public int $quarters;
public function __construct(int $quarters)
{
if ($quarters < 1 || $quarters > self::MAX_QUARTERS) {
throw new InvalidWorkedHours;
}
$this->quarters = $quarters;
}
/**
* Parses "2,5", "2.5" or "2"; null for an empty value.
*
* @throws InvalidWorkedHours
*/
public static function parse(string $value): ?self
{
$value = str_replace(',', '.', trim($value));
if ($value === '') {
return null;
}
if (! is_numeric($value)) {
throw new InvalidWorkedHours;
}
$quarters = (float) $value * 4;
if (abs($quarters - round($quarters)) > 1e-9) {
throw new InvalidWorkedHours;
}
return new self((int) round($quarters));
}
public static function fromDecimal(float $hours): self
{
return new self((int) round($hours * 4));
}
public function decimal(): float
{
return $this->quarters / 4;
}
public function plus(self $other): self
{
return new self($this->quarters + $other->quarters);
}
/**
* Finnish notation without trailing zeros, e.g. "7,5" or "8".
*/
public function format(): string
{
return self::formatQuarters($this->quarters);
}
public static function formatQuarters(int $quarters): string
{
return str_replace('.', ',', rtrim(rtrim(number_format($quarters / 4, 2, '.', ''), '0'), '.'));
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent;
use Carbon\CarbonImmutable;
use Database\Factories\TimeEntryFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property int $user_id
* @property int $task_id
* @property int $customer_job_id
* @property int $work_type_id
* @property CarbonImmutable $worked_on
* @property string $hours
* @property string|null $note
*/
#[Table('time_entries')]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note'])]
#[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model
{
/** @use HasFactory<TimeEntryFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_id' => 'integer',
'task_id' => 'integer',
'customer_job_id' => 'integer',
'work_type_id' => 'integer',
'worked_on' => 'immutable_date',
];
}
public function quarters(): int
{
return (int) round((float) $this->hours * 4);
}
}
@@ -0,0 +1,73 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekRow;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Carbon\CarbonImmutable;
class EloquentTimeEntryQueries implements TimeEntryQueries
{
public function __construct(private TaskQueries $tasks) {}
public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet
{
$start = CarbonImmutable::parse($monday)->startOfWeek();
$days = [];
for ($i = 0; $i < 7; $i++) {
$days[] = $start->addDays($i)->toDateString();
}
$entries = TimeEntryModel::query()
->where('user_id', $userId)
->whereBetween('worked_on', [$days[0], $days[6]])
->get();
$taskIds = array_values(array_unique(array_merge(
$this->tasks->assignedOpenTaskIds($userId),
$entries->pluck('task_id')->map(fn ($id): int => (int) $id)->all(),
$extraTaskIds,
)));
$byTask = [];
foreach ($entries as $entry) {
$byTask[$entry->task_id][$entry->worked_on->toDateString()] = $entry->quarters();
}
$rows = [];
$dayTotals = array_fill_keys($days, 0);
foreach ($this->tasks->bookableTasks($taskIds) as $task) {
$quarters = $byTask[$task->taskId] ?? [];
foreach ($quarters as $day => $value) {
$dayTotals[$day] += $value;
}
$rows[] = new WeekRow($task, $quarters, array_sum($quarters));
}
return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals));
}
public function entriesForTask(int $taskId, int $userId): array
{
return TimeEntryModel::query()
->where('task_id', $taskId)
->where('user_id', $userId)
->orderByDesc('worked_on')
->get()
->map(fn (TimeEntryModel $model): TimeEntrySummary => new TimeEntrySummary($model->id, $model->worked_on->toDateString(), $model->quarters(), $model->note))
->values()
->all();
}
public function hasEntries(int $taskId): bool
{
return TimeEntryModel::query()->where('task_id', $taskId)->exists();
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use DateTimeImmutable;
class EloquentTimeEntryRepository implements TimeEntryRepository
{
public function findForDay(int $userId, int $taskId, DateTimeImmutable $day): ?TimeEntry
{
$model = TimeEntryModel::query()
->where('user_id', $userId)
->where('task_id', $taskId)
->whereDate('worked_on', $day->format('Y-m-d'))
->first();
return $model === null ? null : $this->toEntity($model);
}
public function findForUser(int $userId, int $entryId): ?TimeEntry
{
$model = TimeEntryModel::query()->where('user_id', $userId)->find($entryId);
return $model === null ? null : $this->toEntity($model);
}
public function save(TimeEntry $entry): TimeEntry
{
$model = $entry->id() === null ? new TimeEntryModel : TimeEntryModel::query()->findOrFail($entry->id());
$model->fill([
'user_id' => $entry->userId(),
'task_id' => $entry->taskId(),
'customer_job_id' => $entry->jobId(),
'work_type_id' => $entry->workTypeId(),
'worked_on' => $entry->workedOn()->format('Y-m-d'),
'hours' => $entry->hours()->decimal(),
'note' => $entry->note(),
])->save();
return $this->toEntity($model->refresh());
}
public function delete(TimeEntry $entry): void
{
TimeEntryModel::query()->whereKey($entry->id())->delete();
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{
return (int) round((float) TimeEntryModel::query()
->where('user_id', $userId)
->whereDate('worked_on', $day->format('Y-m-d'))
->when($exceptEntryId !== null, fn ($query) => $query->whereKeyNot($exceptEntryId))
->sum('hours') * 4);
}
private function toEntity(TimeEntryModel $model): TimeEntry
{
return TimeEntry::reconstitute(
$model->id,
$model->user_id,
$model->task_id,
$model->customer_job_id,
$model->work_type_id,
DateTimeImmutable::createFromFormat('!Y-m-d', $model->worked_on->format('Y-m-d')) ?: new DateTimeImmutable($model->worked_on->format('Y-m-d')),
new WorkedHours($model->quarters()),
$model->note,
);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryQueries;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\TaskUsageFromTimeEntries;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the TimeTracking module (hours on tasks) into Laravel.
*/
class TimeTrackingServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
TimeEntryRepository::class => EloquentTimeEntryRepository::class,
TimeEntryQueries::class => EloquentTimeEntryQueries::class,
TaskUsage::class => TaskUsageFromTimeEntries::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('time', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
Gate::define('time.use', fn (User $user): bool => true);
// Hours go on any task of an unlocked job; subcontractors only on jobs they are attached to (K12).
Gate::define('time.book', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor
|| app(CustomerJobQueries::class)->isMember($jobId, $user->id));
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
/**
* Tells the Jobs module that a task with time entries must not be removed.
*/
class TaskUsageFromTimeEntries implements TaskUsage
{
public function __construct(private TimeEntryQueries $entries) {}
public function hasTimeEntries(int $taskId): bool
{
return $this->entries->hasEntries($taskId);
}
}
@@ -0,0 +1,312 @@
<?php
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\TimeTracking\Application\UseCases\RemoveTimeEntry;
use App\Modules\TimeTracking\Application\UseCases\UpdateTimeEntry;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Hours on one task: a date, hours and a note, and the user's own entries
* on the task with edit and remove.
*/
new class extends Component
{
#[Locked]
public int $taskId;
public string $workedOn = '';
public string $hours = '';
public string $note = '';
#[Locked]
public ?int $editingEntryId = null;
public string $editHours = '';
public string $editNote = '';
#[Locked]
public ?int $removalEntryId = null;
public string $statusMessage = '';
public function mount(TaskQueries $tasks, Clock $clock, int $task): void
{
$this->authorize('time.use');
$bookable = $tasks->bookableTask($task);
abort_if($bookable === null, 404);
$this->authorize('time.book', $bookable->jobId);
$this->taskId = $bookable->taskId;
$this->workedOn = $clock->today()->format('Y-m-d');
}
#[Computed]
public function task(): BookableTask
{
return app(TaskQueries::class)->bookableTask($this->taskId) ?? abort(404);
}
/**
* @return list<TimeEntrySummary>
*/
#[Computed]
public function entries(): array
{
return app(TimeEntryQueries::class)->entriesForTask($this->taskId, (int) auth()->id());
}
public function save(AddTaskHours $addHours): void
{
$this->authorize('time.book', $this->task->jobId);
$this->validate(
['workedOn' => ['required', 'date_format:Y-m-d'], 'hours' => ['required', 'string', 'max:10'], 'note' => ['nullable', 'string', 'max:2000']],
['workedOn.required' => __('time.errors.date_required'), 'workedOn.date_format' => __('time.errors.invalid_date'), 'hours.required' => __('time.errors.invalid_hours'), 'hours.max' => __('time.errors.invalid_hours')],
);
try {
$total = $addHours->execute((int) auth()->id(), $this->taskId, $this->workedOn, $this->hours, $this->note);
} catch (DomainException $exception) {
$this->addError('hours', $this->messageFor($exception));
return;
}
$this->statusMessage = __('time.task_page.saved', [
'hours' => WorkedHours::parse($this->hours)?->format() ?? $this->hours,
'day' => $this->dayLabel($this->workedOn),
'total' => $total,
]);
$this->reset('hours', 'note');
unset($this->entries);
}
public function editEntry(int $entryId): void
{
$entry = collect($this->entries)->firstWhere('id', $entryId);
if ($entry === null) {
return;
}
$this->editingEntryId = $entry->id;
$this->editHours = WorkedHours::formatQuarters($entry->quarters);
$this->editNote = $entry->note ?? '';
$this->resetErrorBag('editHours');
$this->js("document.getElementById('edit-hours-{$entryId}')?.focus()");
}
public function cancelEdit(): void
{
$entryId = $this->editingEntryId;
$this->reset('editingEntryId', 'editHours', 'editNote');
$this->js("document.getElementById('edit-entry-{$entryId}')?.focus()");
}
public function updateEntry(UpdateTimeEntry $updateEntry): void
{
$this->authorize('time.book', $this->task->jobId);
$entry = collect($this->entries)->firstWhere('id', $this->editingEntryId);
if ($entry === null) {
return;
}
try {
$updateEntry->execute((int) auth()->id(), $entry->id, $this->editHours, $this->editNote);
} catch (DomainException $exception) {
$this->addError('editHours', $this->messageFor($exception));
return;
}
$this->statusMessage = __('time.task_page.updated', ['day' => $this->dayLabel($entry->workedOn)]);
$this->reset('editingEntryId', 'editHours', 'editNote');
unset($this->entries);
$this->js("document.getElementById('edit-entry-{$entry->id}')?.focus()");
}
public function confirmRemoval(int $entryId): void
{
if (collect($this->entries)->firstWhere('id', $entryId) === null) {
return;
}
$this->removalEntryId = $entryId;
$this->js("document.getElementById('remove-entry-dialog').showModal()");
}
public function removeEntry(RemoveTimeEntry $removeEntry): void
{
$this->authorize('time.book', $this->task->jobId);
$entry = collect($this->entries)->firstWhere('id', $this->removalEntryId);
if ($entry !== null) {
try {
$removeEntry->execute((int) auth()->id(), $entry->id);
$this->statusMessage = __('time.task_page.entry_removed', ['day' => $this->dayLabel($entry->workedOn)]);
} catch (DomainException $exception) {
$this->statusMessage = $this->messageFor($exception);
}
}
$this->reset('removalEntryId');
unset($this->entries);
$this->js("document.getElementById('remove-entry-dialog').close(); document.getElementById('entries-heading').focus()");
}
public function dayLabel(string $day): string
{
$date = CarbonImmutable::parse($day);
return __('time.days')[$date->dayOfWeekIso - 1].' '.$date->format('j.n.Y');
}
public function render(): mixed
{
return $this->view()->title(__('time.task_page.title', ['task' => $this->task->taskTitle]));
}
private function messageFor(DomainException $exception): string
{
return __(match (true) {
$exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours',
$exception instanceof DailyHoursExceeded => 'time.errors.day_full',
$exception instanceof TimeLocked => 'time.errors.locked',
default => 'time.errors.not_found',
});
}
};
?>
@php($task = $this->task)
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold break-words">{{ __('time.task_page.title', ['task' => $task->taskTitle]) }}</h1>
<dl class="grid gap-x-6 gap-y-1 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('time.task_page.job') }}</dt>
<dd><x-link :href="route('jobs.show', $task->jobId)" navigate>{{ $task->jobNumber }} {{ $task->jobName }}</x-link></dd>
<dt class="font-medium">{{ __('time.task_page.work_type') }}</dt>
<dd>{{ $task->workTypeName }}</dd>
</dl>
<x-link :href="route('time.week')" navigate class="text-sm">{{ __('time.task_page.back_to_week') }}</x-link>
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
@if ($task->isLocked())
<p class="flex items-start gap-2 rounded-lg border border-zinc-300 p-3 text-sm dark:border-zinc-600">
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('time.task_page.locked') }}
</p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model="workedOn" type="date" :label="__('time.task_page.worked_on')" required />
<x-input wire:model="hours" inputmode="decimal" :label="__('time.task_page.hours')" :hint="__('time.task_page.hours_description')" autocomplete="off" required />
</div>
<x-textarea wire:model="note" :label="__('time.task_page.note')" resize-auto />
<x-button submit :text="__('time.task_page.save')" />
</form>
@endif
<section aria-labelledby="entries-heading" class="space-y-3">
<h2 id="entries-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('time.task_page.own_entries') }}</h2>
@if ($this->entries === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.task_page.no_entries') }}</p>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 text-sm dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->entries as $entry)
<li wire:key="entry-{{ $entry->id }}" class="space-y-2 p-3">
@if ($editingEntryId === $entry->id)
<form wire:submit="updateEntry" class="space-y-3" novalidate>
<p class="font-medium">{{ $this->dayLabel($entry->workedOn) }}</p>
<x-input id="edit-hours-{{ $entry->id }}" wire:model="editHours" inputmode="decimal" :label="__('time.task_page.hours')" autocomplete="off" required />
<x-textarea id="edit-note-{{ $entry->id }}" wire:model="editNote" :label="__('time.task_page.note')" resize-auto />
<div class="flex flex-wrap gap-2">
<x-button submit sm :text="__('jobs.save')" />
<x-button wire:click="cancelEdit" subtle color="black" sm :text="__('jobs.cancel')" />
</div>
</form>
@else
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<p class="font-medium">{{ $this->dayLabel($entry->workedOn) }}: {{ __('time.hours_suffix', ['hours' => WorkedHours::formatQuarters($entry->quarters)]) }}</p>
@if ($entry->note !== null)
<p class="whitespace-pre-line text-zinc-700 dark:text-zinc-300">{{ $entry->note }}</p>
@endif
</div>
@unless ($task->isLocked())
<div class="flex flex-wrap gap-2">
<x-button
id="edit-entry-{{ $entry->id }}"
wire:click="editEntry({{ $entry->id }})"
subtle
color="black"
sm
icon="pencil"
:text="__('time.task_page.edit')"
:aria-label="__('time.task_page.edit_named', ['day' => $this->dayLabel($entry->workedOn)])"
/>
<x-button
wire:click="confirmRemoval({{ $entry->id }})"
subtle
color="black"
sm
icon="trash"
:text="__('time.task_page.remove')"
:aria-label="__('time.task_page.remove_named', ['day' => $this->dayLabel($entry->workedOn)])"
/>
</div>
@endunless
</div>
@endif
</li>
@endforeach
</ul>
@endif
</section>
<x-confirm-dialog id="remove-entry-dialog" :title="__('customers.removal.title')">
<p>
@php($removal = collect($this->entries)->firstWhere('id', $removalEntryId))
@if ($removal !== null)
{{ __('time.task_page.remove_question', ['day' => $this->dayLabel($removal->workedOn), 'hours' => WorkedHours::formatQuarters($removal->quarters)]) }}
@endif
</p>
<x-slot:actions>
<x-button wire:click="removeEntry" color="red" icon="trash" :text="__('time.task_page.remove')" />
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -0,0 +1,428 @@
<?php
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
use App\Modules\TimeTracking\Application\UseCases\SetDayHours;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The weekly time sheet: tasks as rows, days as columns. A cell saves when
* focus leaves it; an empty cell removes the day's entry. On a phone one
* day is shown at a time.
*/
new class extends Component
{
/**
* The Monday of the week shown (Y-m-d).
*/
#[Url(as: 'viikko', except: '')]
public string $week = '';
/**
* Stored hours as shown, by task id and day: [taskId => [Y-m-d => "2,5"]].
* The cells send their value with wire:change; the desktop grid and the
* phone list both have an input for the same cell.
*
* @var array<int|string, array<string, string>>
*/
#[Locked]
public array $cells = [];
/**
* Tasks added to this week by search, besides the user's own.
*
* @var list<int>
*/
#[Locked]
public array $extraTaskIds = [];
/**
* Values that were not saved, shown back in their cell with the error.
*
* @var array<string, string>
*/
#[Locked]
public array $rejected = [];
public string $selectedDay = '';
public string $taskSearch = '';
public string $statusMessage = '';
public string $errorMessage = '';
public function mount(Clock $clock): void
{
$this->authorize('time.use');
$this->week = $this->mondayOf($this->week !== '' ? $this->week : $clock->today()->format('Y-m-d'));
$today = $clock->today()->format('Y-m-d');
$this->selectedDay = in_array($today, $this->sheet->days, true) ? $today : $this->week;
$this->loadCells();
}
#[Computed]
public function sheet(): WeekSheet
{
return app(TimeEntryQueries::class)->week((int) auth()->id(), $this->week, $this->extraTaskIds);
}
/**
* @return list<BookableTask>
*/
#[Computed]
public function searchResults(): array
{
$term = trim($this->taskSearch);
if (mb_strlen($term) < 2) {
return [];
}
$shown = array_map(fn ($row): int => $row->task->taskId, $this->sheet->rows);
return array_values(array_filter(
app(TaskQueries::class)->searchBookableTasks($term, $this->isSubcontractor() ? (int) auth()->id() : null),
fn (BookableTask $task): bool => ! in_array($task->taskId, $shown, true),
));
}
public function saveCell(int $taskId, string $day, string $value): void
{
$this->authorize('time.use');
$row = collect($this->sheet->rows)->first(fn ($row): bool => $row->task->taskId === $taskId);
if ($row === null || ! in_array($day, $this->sheet->days, true)) {
return;
}
$this->authorize('time.book', $row->task->jobId);
$this->resetErrorBag("cells.{$taskId}.{$day}");
unset($this->rejected["{$taskId}.{$day}"]);
$this->errorMessage = '';
try {
app(SetDayHours::class)->execute((int) auth()->id(), $taskId, $day, $value);
} catch (DomainException $exception) {
$message = __(match (true) {
$exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours',
$exception instanceof DailyHoursExceeded => 'time.errors.day_full',
$exception instanceof TimeLocked => 'time.errors.locked',
default => 'time.errors.not_found',
});
$this->addError("cells.{$taskId}.{$day}", $message);
$this->errorMessage = $row->task->taskTitle.', '.$this->dayLabel($day).': '.$message;
$this->rejected["{$taskId}.{$day}"] = $value;
return;
}
unset($this->sheet);
$this->loadCells();
$hours = $this->cells[$taskId][$day] ?? '';
$this->statusMessage = $hours === ''
? __('time.removed', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day)])
: __('time.saved', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day), 'hours' => $hours]);
}
public function addTask(int $taskId): void
{
$this->authorize('time.use');
$task = app(TaskQueries::class)->bookableTask($taskId);
if ($task === null || $task->isLocked() || Gate::denies('time.book', $task->jobId)) {
return;
}
if (! in_array($taskId, $this->extraTaskIds, true)) {
$this->extraTaskIds[] = $taskId;
}
$this->taskSearch = '';
unset($this->sheet);
$this->loadCells();
$this->statusMessage = __('time.add.added', ['task' => $task->label()]);
$this->js("(document.getElementById('cell-{$taskId}-{$this->selectedDay}')?.offsetParent ? document.getElementById('cell-{$taskId}-{$this->selectedDay}') : document.getElementById('mcell-{$taskId}-{$this->selectedDay}'))?.focus()");
}
public function selectDay(string $day): void
{
if (in_array($day, $this->sheet->days, true)) {
$this->selectedDay = $day;
}
}
public function showWeek(string $which, Clock $clock): void
{
$this->week = match ($which) {
'previous' => CarbonImmutable::parse($this->week)->subWeek()->toDateString(),
'next' => CarbonImmutable::parse($this->week)->addWeek()->toDateString(),
default => $this->mondayOf($clock->today()->format('Y-m-d')),
};
unset($this->sheet);
$this->selectedDay = $this->week;
$this->statusMessage = $this->weekHeading();
$this->errorMessage = '';
$this->resetErrorBag();
$this->rejected = [];
$this->loadCells();
}
public function weekHeading(): string
{
$monday = CarbonImmutable::parse($this->week);
return __('time.week_heading', [
'number' => $monday->isoWeek(),
'from' => $monday->format('j.n.'),
'to' => $monday->addDays(6)->format('j.n.Y'),
]);
}
public function dayLabel(string $day): string
{
$date = CarbonImmutable::parse($day);
return __('time.days')[$date->dayOfWeekIso - 1].' '.$date->format('j.n.');
}
public function hours(int $quarters): string
{
return WorkedHours::formatQuarters($quarters);
}
public function isSubcontractor(): bool
{
return auth()->user()?->role === Role::Subcontractor;
}
public function render(): mixed
{
return $this->view()->title(__('time.title'));
}
private function loadCells(): void
{
$cells = [];
foreach ($this->sheet->rows as $row) {
foreach ($this->sheet->days as $day) {
$quarters = $row->quartersByDay[$day] ?? 0;
$cells[$row->task->taskId][$day] = $quarters === 0 ? '' : WorkedHours::formatQuarters($quarters);
}
}
$this->cells = $cells;
}
private function mondayOf(string $date): string
{
try {
return CarbonImmutable::parse($date)->startOfWeek()->toDateString();
} catch (\Throwable) {
return CarbonImmutable::now()->startOfWeek()->toDateString();
}
}
};
?>
@php($sheet = $this->sheet)
<div class="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('time.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.intro') }}</p>
</div>
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold">{{ $this->weekHeading() }}</h2>
<div class="flex flex-wrap gap-2">
<x-button wire:click="showWeek('previous')" subtle color="black" sm icon="chevron-left" :text="__('time.previous_week')" />
<x-button wire:click="showWeek('this')" subtle color="black" sm :text="__('time.this_week')" />
<x-button wire:click="showWeek('next')" subtle color="black" sm icon="chevron-right" position="right" :text="__('time.next_week')" />
</div>
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
<p role="alert" class="text-sm font-medium text-red-700 dark:text-red-400">{{ $errorMessage }}</p>
@if ($sheet->rows === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.no_rows') }}</p>
@else
{{-- Desktop: the whole week as an input grid (a form, so a native table rather than <x-table>). --}}
<div class="hidden lg:block">
<table class="w-full border-collapse text-sm">
<caption class="sr-only">{{ __('time.table_caption') }}</caption>
<thead>
<tr class="border-b border-zinc-300 dark:border-zinc-600">
<th scope="col" class="py-2 pr-3 text-left font-semibold">{{ __('time.task') }}</th>
@foreach ($sheet->days as $day)
<th scope="col" class="w-20 px-1 py-2 text-center font-semibold">{{ $this->dayLabel($day) }}</th>
@endforeach
<th scope="col" class="w-20 py-2 pl-3 text-right font-semibold">{{ __('time.total') }}</th>
</tr>
</thead>
<tbody>
@foreach ($sheet->rows as $row)
<tr wire:key="row-{{ $row->task->taskId }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal">
<x-link :href="route('time.task', $row->task->taskId)" navigate class="font-medium">{{ $row->task->label() }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $row->task->workTypeName }}</span>
@if ($row->task->isLocked())
<span class="mt-1 inline-flex items-center gap-1 text-zinc-700 dark:text-zinc-300">
<x-icon name="lock-closed" class="size-4" aria-hidden="true" /> {{ __('time.locked') }}
</span>
@endif
</th>
@foreach ($sheet->days as $day)
<td class="px-1 py-2 text-center">
@if ($row->task->isLocked())
{{ isset($row->quartersByDay[$day]) ? $this->hours($row->quartersByDay[$day]) : '' }}
@else
<input
id="cell-{{ $row->task->taskId }}-{{ $day }}"
type="text"
inputmode="decimal"
autocomplete="off"
value="{{ $rejected[$row->task->taskId.'.'.$day] ?? $cells[$row->task->taskId][$day] ?? '' }}"
wire:change="saveCell({{ $row->task->taskId }}, '{{ $day }}', $event.target.value)"
aria-label="{{ __('time.cell_label', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($day)]) }}"
@error('cells.'.$row->task->taskId.'.'.$day) aria-invalid="true" aria-describedby="cell-{{ $row->task->taskId }}-{{ $day }}-error" @enderror
class="w-16 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-center text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/>
@error('cells.'.$row->task->taskId.'.'.$day)
<p id="cell-{{ $row->task->taskId }}-{{ $day }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
@endif
</td>
@endforeach
<td class="py-2 pl-3 text-right font-medium">{{ $this->hours($row->totalQuarters) }}</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr>
<th scope="row" class="py-2 pr-3 text-left font-semibold">{{ __('time.day_total') }}</th>
@foreach ($sheet->days as $day)
<td class="px-1 py-2 text-center font-semibold">{{ $this->hours($sheet->dayTotals[$day]) }}</td>
@endforeach
<td class="py-2 pl-3 text-right font-semibold">{{ $this->hours($sheet->totalQuarters) }}</td>
</tr>
</tfoot>
</table>
</div>
{{-- Phone: one day at a time. --}}
<div class="space-y-4 lg:hidden">
<div role="group" aria-label="{{ __('time.choose_day') }}" class="grid grid-cols-4 gap-2 sm:grid-cols-7">
@foreach ($sheet->days as $day)
<button
type="button"
wire:click="selectDay('{{ $day }}')"
aria-pressed="{{ $day === $selectedDay ? 'true' : 'false' }}"
aria-label="{{ __('time.day_button', ['day' => $this->dayLabel($day), 'hours' => $this->hours($sheet->dayTotals[$day])]) }}"
@class([
'rounded-md border px-2 py-2 text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700',
'border-primary-700 bg-primary-700 font-semibold text-white' => $day === $selectedDay,
'border-zinc-300 bg-white text-zinc-900 dark:border-zinc-600 dark:bg-zinc-900 dark:text-zinc-100' => $day !== $selectedDay,
])
>
<span class="block">{{ $this->dayLabel($day) }}</span>
<span class="block text-xs">{{ __('time.hours_suffix', ['hours' => $this->hours($sheet->dayTotals[$day])]) }}</span>
</button>
@endforeach
</div>
<ul class="space-y-3">
@foreach ($sheet->rows as $row)
<li wire:key="mrow-{{ $row->task->taskId }}" class="rounded-lg border border-zinc-200 p-3 text-sm dark:border-zinc-700">
<x-link :href="route('time.task', $row->task->taskId)" navigate class="font-medium break-words">{{ $row->task->label() }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $row->task->workTypeName }}</span>
@if ($row->task->isLocked())
<p class="mt-2 inline-flex items-center gap-1">
<x-icon name="lock-closed" class="size-4" aria-hidden="true" /> {{ __('time.locked') }}
@isset($row->quartersByDay[$selectedDay])
– {{ __('time.hours_suffix', ['hours' => $this->hours($row->quartersByDay[$selectedDay])]) }}
@endisset
</p>
@else
<label for="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}" class="mt-2 block font-medium">
{{ __('time.cell_label', ['task' => $row->task->taskTitle, 'day' => $this->dayLabel($selectedDay)]) }}
</label>
<input
id="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}"
type="text"
inputmode="decimal"
autocomplete="off"
value="{{ $rejected[$row->task->taskId.'.'.$selectedDay] ?? $cells[$row->task->taskId][$selectedDay] ?? '' }}"
wire:change="saveCell({{ $row->task->taskId }}, '{{ $selectedDay }}', $event.target.value)"
@error('cells.'.$row->task->taskId.'.'.$selectedDay) aria-invalid="true" aria-describedby="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}-error" @enderror
class="mt-1 w-24 rounded-md border border-zinc-400 bg-white px-2 py-2 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/>
@error('cells.'.$row->task->taskId.'.'.$selectedDay)
<p id="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
@endif
</li>
@endforeach
</ul>
</div>
<p class="text-sm font-semibold">{{ __('time.week_total', ['hours' => $this->hours($sheet->totalQuarters)]) }}</p>
@endif
<section aria-labelledby="add-task-heading" class="space-y-2">
<h2 id="add-task-heading" class="sr-only">{{ __('time.add.search') }}</h2>
<x-input
id="task-search"
wire:model.live.debounce.300ms="taskSearch"
type="search"
icon="magnifying-glass"
:label="__('time.add.search')"
:hint="__('time.add.search_description')"
autocomplete="off"
/>
@if (mb_strlen(trim($taskSearch)) >= 2)
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('time.add.results', count($this->searchResults), ['count' => count($this->searchResults)]) }}
</p>
<ul class="space-y-1">
@foreach ($this->searchResults as $task)
<li wire:key="result-{{ $task->taskId }}">
<button
type="button"
wire:click="addTask({{ $task->taskId }})"
aria-label="{{ __('time.add.choose', ['task' => $task->label()]) }}"
class="w-full rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
>
<span class="font-medium">{{ $task->label() }}</span>
<span class="text-zinc-600 dark:text-zinc-300">{{ $task->workTypeName }}</span>
</button>
</li>
@endforeach
</ul>
@endif
</section>
</div>
@@ -0,0 +1,11 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:time.use'])
->prefix('time')
->name('time.')
->group(function () {
Route::livewire('/', 'time::week')->name('week');
Route::livewire('/tasks/{task}', 'time::task')->whereNumber('task')->name('task');
});
+3
View File
@@ -4,6 +4,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider;
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider;
use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider;
use App\Providers\AppServiceProvider;
@@ -15,4 +16,6 @@ return [
CatalogServiceProvider::class,
// After Customers: replaces its CustomerRowUsage binding.
JobsServiceProvider::class,
// After Jobs: replaces its TaskUsage binding.
TimeTrackingServiceProvider::class,
];
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace Database\Factories;
use App\Models\User;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<TimeEntryModel>
*/
class TimeEntryFactory extends Factory
{
protected $model = TimeEntryModel::class;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'user_id' => User::factory(),
'task_id' => TaskModel::factory(),
'customer_job_id' => fn (array $attributes) => TaskModel::query()->findOrFail($attributes['task_id'])->customer_job_id,
'work_type_id' => fn (array $attributes) => TaskModel::query()->findOrFail($attributes['task_id'])->work_type_id,
'worked_on' => now()->toDateString(),
'hours' => 2,
];
}
}
@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Hours on tasks: one entry per user, task and day. Approval and the
* billing export reference come in phase 2.
*/
public function up(): void
{
Schema::create('time_entries', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->restrictOnDelete();
$table->foreignId('task_id')->constrained()->restrictOnDelete();
$table->foreignId('customer_job_id')->constrained()->restrictOnDelete();
$table->foreignId('work_type_id')->constrained()->restrictOnDelete();
$table->date('worked_on');
$table->decimal('hours', 5, 2);
$table->text('note')->nullable();
$table->timestamps();
$table->unique(['user_id', 'task_id', 'worked_on']);
$table->index(['user_id', 'worked_on']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('time_entries');
}
};
+7 -4
View File
@@ -246,7 +246,10 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä
- Kaksi tapaa:
- **Viikkonäkymä**: rivit ovat käyttäjän tehtävät, sarakkeet viikonpäivät, soluun kesto tunteina (esim. 1,5). Rivin voi lisätä hakemalla tehtävän.
- **Tehtävältä**: päivämäärä, kesto ja vapaaehtoinen selite.
- Kesto kirjataan tunteina; tarkkuus 0,25 h.
- Kesto kirjataan tunteina; tarkkuus 0,25 h. Käyttäjällä on tehtävällä enintään yksi kirjaus päivää kohden (tunnit ja selite): viikkonäkymän solu muuttaa sitä, tyhjä solu poistaa sen, ja tehtävän sivulta samalle päivälle kirjatut tunnit lisätään päivän kirjaukseen.
- Käyttäjän kirjausten summa voi olla enintään 24 h päivässä.
- Tunteja voi kirjata kaikille tehtäville, joiden työ ei ole lukittu; viikkonäkymässä ovat oletuksena omat avoimet tehtävät ja viikon kirjausten tehtävät, ja muita voi lisätä hakemalla. Alihankkija kirjaa vain liitettyjen töidensä tehtäville.
- Kun työ on Valmis, Lasku luotu, Laskutettu tai Arkistoitu, sen tunteja ei voi lisätä eikä muuttaa. Tehtävää, jolle on kirjattu tunteja, ei voi poistaa.
- Sisäinen työ kirjataan sisäisen asiakkaan asiakastöille.
- Työajanseuranta (esim. tehdyt tunnit vs. työaika) on asetuksen takana, oletuksena pois.
- Tunnit eivät suoraan ole laskutusperuste: laskutettavuus määräytyy työn maksuperusteesta, ja laskutettava tuntimäärä päätetään laskutusvaiheessa (luku 12) *(K40, K41)*.
@@ -346,7 +349,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `workflow_templates` *(V3)*: `work_type_id`, `name`; `workflow_template_steps`: `workflow_template_id`, `title`, `description`, `sort_order`
**TimeTracking**
- `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id`, `worked_on`, `hours`, `note`, `approved_at` *(V2)*, `approved_by` *(V2)*, `billing_export_id` *(V2)*
- `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at` *(V2)*, `approved_by` *(V2)*, `billing_export_id` *(V2)*
**Expenses** *(V2)*
- `expenses`: `customer_job_id`, `user_id`, `category` (`materials`/`mileage`/`other`), `kind` (`direct_cost`/`reimbursement`), `spent_on`, `description`, `amount_cents`, `kilometers`, `destination`, `purpose`, `billing_export_id`
@@ -426,8 +429,8 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Tehtävät näkyvät työn sivulla: avoimet määräpäivän mukaan, valmiit viimeisenä. Tilan voi vaihtaa suoraan listalta (myös alihankkija liitettyjen töidensä tehtävissä); lisäys, muokkaus ja poisto ovat muille kuin alihankkijoille. Poisto vahvistetaan dialogissa, ja se estetään tuntikirjauksen osassa, jos tehtävällä on kirjauksia.
- Tehtävän tila: odottaa, työn alla, tarkastettavana, valmis. Myöhässä oleva tehtävä näytetään tekstillä ja kuvakkeella.
### 16.8 Tuntikirjaus
- Viikkonäkymä: viikon valinta, rivit omista tehtävistä, kesto tunteina 0,25 h tarkkuudella, rivi- ja päiväsummat. Toimii puhelimella (päivä kerrallaan).
### 16.8 Tuntikirjaus *(valmis)*
- Viikkonäkymä (`/time`, valikossa Tuntikirjaus): viikon valinta, rivit omista tehtävistä, kesto tunteina 0,25 h tarkkuudella, rivi-, päivä- ja viikkosummat. Solu tallentuu, kun siitä siirrytään pois. Toimii puhelimella (päivä kerrallaan).
- Kirjauksen voi lisätä myös tehtävän sivulta (pvm + kesto + selite).
- Valmiin työn tehtäville ei voi kirjata eikä niiden kirjauksia muuttaa.
+3
View File
@@ -31,6 +31,9 @@ return [
'edit_named' => 'Muokkaa tehtävää :title',
'remove_named' => 'Poista tehtävä :title',
'remove_question' => 'Poistetaanko tehtävä :title? Poistoa ei voi perua.',
'has_time_entries' => 'Tehtävää :title ei poistettu, koska sille on kirjattu tunteja.',
'book_time' => 'Kirjaa tunnit',
'book_time_named' => 'Kirjaa tunnit tehtävälle :title',
'fields' => [
'title' => 'Nimi',
'work_type' => 'Työtehtävä',
+1
View File
@@ -7,6 +7,7 @@ return [
'jobs' => 'Asiakastyöt',
'quick_intake' => 'Pikavastaanotto',
'board' => 'Kanban',
'time' => 'Tuntikirjaus',
'customers' => 'Asiakkaat',
'users' => 'Käyttäjät',
'catalog' => 'Pohjatiedot',
+66
View File
@@ -0,0 +1,66 @@
<?php
return [
'title' => 'Tuntikirjaus',
'week_heading' => 'Viikko :number: :from–:to',
'previous_week' => 'Edellinen viikko',
'this_week' => 'Tämä viikko',
'next_week' => 'Seuraava viikko',
'intro' => 'Kirjaa tunnit tehtäville vartin tarkkuudella, esimerkiksi 2,5. Tyhjä kenttä poistaa päivän kirjauksen. Kenttä tallentuu, kun siirryt pois siitä.',
'table_caption' => 'Viikon tunnit tehtävittäin',
'task' => 'Tehtävä',
'total' => 'Yhteensä',
'day_total' => 'Päivä yhteensä',
'week_total' => 'Viikko yhteensä: :hours h',
'hours_suffix' => ':hours h',
'no_rows' => 'Ei tehtäviä tällä viikolla. Lisää tehtävä hakemalla alta.',
'locked' => 'Lukittu – työ on valmis',
'cell_label' => 'Tunnit: :task, :day',
'choose_day' => 'Valitse päivä',
'day_button' => ':day, :hours h',
'saved' => 'Tallennettu: :task :day :hours h.',
'removed' => 'Poistettu: :task :day.',
'days' => ['ma', 'ti', 'ke', 'to', 'pe', 'la', 'su'],
'add' => [
'search' => 'Lisää tehtävä viikolle',
'search_description' => 'Hae työn numerolla, työn nimellä tai tehtävän nimellä.',
'results' => '{0} Ei osumia.|{1} :count osuma.|[2,*] :count osumaa.',
'choose' => 'Lisää viikolle: :task',
'added' => 'Tehtävä :task lisätty viikolle.',
],
'task_page' => [
'title' => 'Kirjaa tunnit: :task',
'job' => 'Asiakastyö',
'work_type' => 'Työtehtävä',
'worked_on' => 'Päivä',
'hours' => 'Tunnit',
'hours_description' => 'Vartin tarkkuudella, esimerkiksi 1,75. Samalle päivälle kirjatut tunnit lisätään päivän kirjaukseen.',
'note' => 'Selite',
'save' => 'Kirjaa tunnit',
'saved' => 'Kirjattu :hours h. Päivän :day kirjaus on nyt :total h.',
'own_entries' => 'Omat kirjaukset',
'no_entries' => 'Et ole vielä kirjannut tunteja tälle tehtävälle.',
'edit' => 'Muokkaa',
'edit_named' => 'Muokkaa kirjausta :day',
'remove' => 'Poista',
'remove_named' => 'Poista kirjaus :day',
'remove_question' => 'Poistetaanko päivän :day kirjaus (:hours h)? Poistoa ei voi perua.',
'updated' => 'Päivän :day kirjaus tallennettu.',
'entry_removed' => 'Päivän :day kirjaus poistettu.',
'back_to_week' => 'Viikkonäkymään',
'back_to_job' => 'Asiakastyöhön',
'locked' => 'Työ on valmis, joten sen tunnit on lukittu. Kirjauksia ei voi lisätä eikä muuttaa.',
],
'errors' => [
'invalid_hours' => 'Anna tunnit vartin tarkkuudella väliltä 0,25–24, esimerkiksi 2,5.',
'day_full' => 'Päivän tunnit voivat olla yhteensä enintään 24.',
'locked' => 'Työ on valmis, joten sen tunnit on lukittu.',
'not_found' => 'Tehtävää tai kirjausta ei löytynyt. Päivitä sivu.',
'date_required' => 'Anna päivä.',
'invalid_date' => 'Anna päivämäärä muodossa pp.kk.vvvv.',
],
];
+2
View File
@@ -59,6 +59,8 @@
@include('partials.nav-item', ['route' => 'jobs.board', 'pattern' => 'jobs.board', 'label' => __('layout.board')])
@include('partials.nav-item', ['route' => 'time.week', 'pattern' => 'time.*', 'label' => __('layout.time')])
@can('jobs.manage')
@include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')])
@endcan
@@ -0,0 +1,78 @@
<?php
use App\Models\User;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->create();
$this->actingAs($this->user);
$this->task = TaskModel::factory()->assignedTo([$this->user->id])->create(['title' => 'Mainoskuvat']);
$this->monday = now()->startOfWeek()->toDateString();
TimeEntryModel::factory()->create(['task_id' => $this->task->id, 'user_id' => $this->user->id, 'worked_on' => $this->monday, 'hours' => 1.5, 'note' => 'Luonnokset']);
});
it('has no accessibility issues on the time pages and no sideways scrolling', function (string $page, string $device, string $colorScheme) {
$url = $page === 'week' ? route('time.week') : route('time.task', $this->task->id);
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee('Mainoskuvat')
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['week', 'task page'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('records hours in the weekly view with the keyboard', function () {
$tuesday = now()->startOfWeek()->addDay()->toDateString();
$cell = '#cell-'.$this->task->id.'-'.$tuesday;
visit(route('time.week'))
->on()->desktop()
->type($cell, '2,5')
->keys($cell, 'Tab')
->assertSee('Tallennettu: Mainoskuvat')
->assertSee('Viikko yhteensä: 4 h')
->assertNoAccessibilityIssues(level: 2);
expect((float) TimeEntryModel::query()->whereDate('worked_on', $tuesday)->sole()->hours)->toBe(2.5);
});
it('shows an invalid value as an error at the field', function (string $device) {
$selector = $device === 'mobile'
? '#mcell-'.$this->task->id.'-'.$this->monday
: '#cell-'.$this->task->id.'-'.$this->monday;
$visit = visit(route('time.week'));
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
if ($device === 'mobile') {
$visit->click('[aria-pressed][wire\\:click="selectDay(\''.$this->monday.'\')"]');
}
$visit->clear($selector)
->type($selector, '1,1')
->keys($selector, 'Tab')
->assertSee('Anna tunnit vartin tarkkuudella')
->assertAttribute($selector, 'aria-invalid', 'true')
->assertNoAccessibilityIssues(level: 2);
})->with(['desktop', 'mobile']);
it('records hours from the task page', function () {
visit(route('time.task', $this->task->id))
->fill('[wire\\:model="workedOn"]', $this->monday)
->fill('[wire\\:model="hours"]', '2')
->press('Kirjaa tunnit')
->assertSee('kirjaus on nyt 3,5 h.')
->assertNoAccessibilityIssues(level: 2);
});
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* Tasks for unit tests of other modules, as time is recorded on them.
*/
class FakeTaskQueries implements TaskQueries
{
/** @var array<int, BookableTask> */
public array $tasks = [];
public function addTask(int $taskId, int $jobId = 1, JobStatus $jobStatus = JobStatus::Order, int $workTypeId = 7): void
{
$this->tasks[$taskId] = new BookableTask($taskId, $jobId, '2026-0001', 'Kampanja', 'Tehtävä '.$taskId, $workTypeId, 'graafinen työ', $jobStatus, TaskStatus::Waiting);
}
public function tasksOf(int $jobId): array
{
return [];
}
public function findTask(int $jobId, int $taskId): ?TaskSummary
{
return null;
}
public function bookableTask(int $taskId): ?BookableTask
{
return $this->tasks[$taskId] ?? null;
}
public function bookableTasks(array $taskIds): array
{
return array_values(array_intersect_key($this->tasks, array_flip($taskIds)));
}
public function assignedOpenTaskIds(int $userId): array
{
return [];
}
public function searchBookableTasks(string $term, ?int $onlyMemberUserId = null, int $limit = 8): array
{
return [];
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
class FakeTaskUsage implements TaskUsage
{
/** @var list<int> */
public array $tasksWithTime = [];
public function hasTimeEntries(int $taskId): bool
{
return in_array($taskId, $this->tasksWithTime, true);
}
}
@@ -0,0 +1,59 @@
<?php
namespace Tests\Fakes;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use DateTimeImmutable;
class InMemoryTimeEntryRepository implements TimeEntryRepository
{
/** @var array<int, TimeEntry> */
public array $entries = [];
private int $nextId = 1;
public function findForDay(int $userId, int $taskId, DateTimeImmutable $day): ?TimeEntry
{
foreach ($this->entries as $entry) {
if ($entry->userId() === $userId && $entry->taskId() === $taskId && $entry->workedOn()->format('Y-m-d') === $day->format('Y-m-d')) {
return clone $entry;
}
}
return null;
}
public function findForUser(int $userId, int $entryId): ?TimeEntry
{
$entry = $this->entries[$entryId] ?? null;
return $entry !== null && $entry->userId() === $userId ? clone $entry : null;
}
public function save(TimeEntry $entry): TimeEntry
{
$id = $entry->id() ?? $this->nextId++;
$this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note());
return clone $this->entries[$id];
}
public function delete(TimeEntry $entry): void
{
unset($this->entries[$entry->id()]);
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{
$quarters = 0;
foreach ($this->entries as $id => $entry) {
if ($id !== $exceptEntryId && $entry->userId() === $userId && $entry->workedOn()->format('Y-m-d') === $day->format('Y-m-d')) {
$quarters += $entry->hours()->quarters;
}
}
return $quarters;
}
}
@@ -0,0 +1,61 @@
<?php
use App\Models\User;
use App\Modules\Jobs\Application\UseCases\RemoveTask;
use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->create();
$this->actingAs($this->employee);
$this->task = TaskModel::factory()->assignedTo([$this->employee->id])->create(['title' => 'Mainoskuvat']);
$this->monday = now()->startOfWeek()->toDateString();
});
it('saves and clears a cell of the weekly view', function () {
$this->get(route('time.week'))->assertOk()->assertSee('Mainoskuvat');
Livewire::test('time::week')
->call('saveCell', $this->task->id, $this->monday, '2,5')
->assertSee('2,5 h.')
->call('saveCell', $this->task->id, $this->monday, '1,1')
->assertHasErrors(["cells.{$this->task->id}.{$this->monday}"]);
expect((float) TimeEntryModel::query()->sole()->hours)->toBe(2.5);
Livewire::test('time::week')->call('saveCell', $this->task->id, $this->monday, '');
expect(TimeEntryModel::query()->count())->toBe(0);
});
it('adds hours from the task page to the day entry and locks done jobs', function () {
Livewire::test('time::task', ['task' => $this->task->id])
->set('workedOn', $this->monday)
->set('hours', '2')
->call('save')
->set('hours', '1,5')
->set('note', 'Lisää kuvia')
->call('save')
->assertSee('kirjaus on nyt 3,5 h.');
expect(TimeEntryModel::query()->count())->toBe(1);
$this->task->customer_job_id && DB::table('customer_jobs')->where('id', $this->task->customer_job_id)->update(['status' => 'done']);
Livewire::test('time::task', ['task' => $this->task->id])->assertSee('tunnit on lukittu');
});
it('keeps subcontractors to their own jobs and blocks removing tasks with hours', function () {
TimeEntryModel::factory()->create(['task_id' => $this->task->id, 'user_id' => $this->employee->id]);
expect(fn () => app(RemoveTask::class)->execute($this->task->customer_job_id, $this->task->id))
->toThrow(TaskHasTimeEntries::class);
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('time.task', $this->task->id))->assertForbidden();
});
@@ -14,12 +14,14 @@ use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle;
use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use Tests\Fakes\FakeCatalogQueries;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeTaskUsage;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\FakeUserAccountQueries;
use Tests\Fakes\InMemoryCustomerJobRepository;
@@ -51,7 +53,8 @@ beforeEach(function () {
$this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $transactions);
$this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $transactions);
$this->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions);
$this->removeTask = new RemoveTask($this->tasks, $transactions);
$this->usage = new FakeTaskUsage;
$this->removeTask = new RemoveTask($this->tasks, $this->usage, $transactions);
$this->changeJobStatus = new ChangeJobStatus($this->jobs, $transactions);
});
@@ -123,3 +126,13 @@ it('does not touch a task of another job', function (string $action) {
'remove' => $this->removeTask->execute($this->tentativeJobId, $taskId),
};
})->throws(TaskNotFound::class)->with(['update', 'status', 'remove']);
it('does not remove a task with time entries', function () {
$taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10);
$this->usage->tasksWithTime = [$taskId];
expect(fn () => $this->removeTask->execute($this->jobId, $taskId))->toThrow(TaskHasTimeEntries::class)
->and($this->tasks->tasks)->toHaveCount(1)
->and(JobStatus::Done->locksTime())->toBeTrue()
->and(JobStatus::OnHold->locksTime())->toBeFalse();
});
@@ -0,0 +1,121 @@
<?php
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\TimeTracking\Application\UseCases\RemoveTimeEntry;
use App\Modules\TimeTracking\Application\UseCases\SetDayHours;
use App\Modules\TimeTracking\Application\UseCases\UpdateTimeEntry;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use App\Modules\TimeTracking\Domain\Exceptions\DailyHoursExceeded;
use App\Modules\TimeTracking\Domain\Exceptions\InvalidWorkedHours;
use App\Modules\TimeTracking\Domain\Exceptions\TaskNotBookable;
use App\Modules\TimeTracking\Domain\Exceptions\TimeEntryNotFound;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use Tests\Fakes\FakeTaskQueries;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryTimeEntryRepository;
beforeEach(function () {
$this->tasks = new FakeTaskQueries;
$this->entries = new InMemoryTimeEntryRepository;
$booking = new TimeBooking($this->tasks, $this->entries);
$transactions = new FakeTransactionManager;
$this->setDayHours = new SetDayHours($this->entries, $booking, $transactions);
$this->addTaskHours = new AddTaskHours($this->entries, $booking, $transactions);
$this->updateEntry = new UpdateTimeEntry($this->entries, $booking, $transactions);
$this->removeEntry = new RemoveTimeEntry($this->entries, $booking, $transactions);
$this->tasks->addTask(1);
$this->tasks->addTask(2);
$this->tasks->addTask(3, jobStatus: JobStatus::Done);
});
it('parses hours in quarters, with a comma or a point', function (string $input, ?string $formatted) {
expect(WorkedHours::parse($input)?->format())->toBe($formatted);
})->with([
'quarter' => ['0,25', '0,25'],
'comma' => ['7,5', '7,5'],
'point' => ['7.50', '7,5'],
'whole day' => ['24', '24'],
'empty' => ['', null],
]);
it('rejects hours that are not quarters or out of range', function (string $input) {
WorkedHours::parse($input);
})->throws(InvalidWorkedHours::class)->with(['0,1', '24,25', '-1', 'kaksi', '0']);
it('adds hours and continues the note of a day entry', function () {
$entry = TimeEntry::create(10, 1, 1, 7, new DateTimeImmutable('2026-05-18'), new WorkedHours(8), 'Luonnokset');
$entry->addHours(new WorkedHours(2), 'Korjaukset');
$entry->addHours(new WorkedHours(1), ' ');
expect($entry->hours()->format())->toBe('2,75')
->and($entry->note())->toBe("Luonnokset\nKorjaukset");
});
it('sets a cell, changes it and clears it', function () {
$this->setDayHours->execute(10, 1, '2026-05-18', '2,5');
$this->setDayHours->execute(10, 1, '2026-05-18', '3');
expect($this->entries->entries)->toHaveCount(1)
->and(array_values($this->entries->entries)[0]->hours()->format())->toBe('3')
->and(array_values($this->entries->entries)[0]->workTypeId())->toBe(7);
$this->setDayHours->execute(10, 1, '2026-05-18', '0');
expect($this->entries->entries)->toBeEmpty();
$this->setDayHours->execute(10, 1, '2026-05-18', '');
expect($this->entries->entries)->toBeEmpty();
});
it('adds hours from the task page to the day entry', function () {
$this->addTaskHours->execute(10, 1, '2026-05-18', '2', 'Aamu');
$total = $this->addTaskHours->execute(10, 1, '2026-05-18', '1,5', 'Iltapäivä');
expect($total)->toBe('3,5')
->and($this->entries->entries)->toHaveCount(1);
});
it('keeps a day within 24 hours across tasks', function () {
$this->setDayHours->execute(10, 1, '2026-05-18', '20');
expect(fn () => $this->setDayHours->execute(10, 2, '2026-05-18', '4,25'))->toThrow(DailyHoursExceeded::class);
$this->setDayHours->execute(10, 2, '2026-05-18', '4');
$this->setDayHours->execute(10, 1, '2026-05-18', '19');
$this->setDayHours->execute(11, 1, '2026-05-18', '8');
expect($this->entries->quartersOn(10, new DateTimeImmutable('2026-05-18')))->toBe(92);
});
it('does not record or change hours on a locked job or an unknown task', function () {
expect(fn () => $this->setDayHours->execute(10, 3, '2026-05-18', '1'))->toThrow(TimeLocked::class)
->and(fn () => $this->addTaskHours->execute(10, 99, '2026-05-18', '1'))->toThrow(TaskNotBookable::class);
$this->setDayHours->execute(10, 1, '2026-05-18', '2');
$entryId = array_key_first($this->entries->entries);
$this->tasks->addTask(1, jobStatus: JobStatus::Invoiced);
expect(fn () => $this->updateEntry->execute(10, $entryId, '3', null))->toThrow(TimeLocked::class)
->and(fn () => $this->removeEntry->execute(10, $entryId))->toThrow(TimeLocked::class)
->and($this->entries->entries)->toHaveCount(1);
});
it('lets users change only their own entries', function () {
$this->setDayHours->execute(10, 1, '2026-05-18', '2');
$entryId = array_key_first($this->entries->entries);
expect(fn () => $this->updateEntry->execute(11, $entryId, '3', null))->toThrow(TimeEntryNotFound::class)
->and(fn () => $this->removeEntry->execute(11, $entryId))->toThrow(TimeEntryNotFound::class);
$this->updateEntry->execute(10, $entryId, '3,75', 'Muutettu');
expect($this->entries->entries[$entryId]->hours()->format())->toBe('3,75')
->and($this->entries->entries[$entryId]->note())->toBe('Muutettu');
$this->removeEntry->execute(10, $entryId);
expect($this->entries->entries)->toBeEmpty();
});