Add approval of hours and lock opening for management

- Time entries store who approved them and when. Approved hours are
  locked: cells, task page edits and removals are refused.
- "Hyväksy viikko" in the weekly view approves the user's own week;
  subcontractors' hours are approved by management.
- Management gets an approval page (unapproved weeks by person, recently
  approved weeks) and can open anyone's week read-only to approve it or
  cancel its approval, which only management may do.
- Only management may move a done job back to an earlier status, which
  opens the lock on its hours and expenses; the history marks it.
- The Clock contract gets now() for approval times.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 08:24:34 +02:00
co-authored by Claude Opus 5.5
parent 54d98d9d2f
commit d5cbf9d6eb
43 changed files with 1183 additions and 34 deletions
@@ -46,6 +46,14 @@ enum JobStatus: string
return in_array($this, [self::Done, self::Invoiced, self::Billed, self::Archived], true);
}
/**
* Whether moving from this status to $to opens the lock on hours and expenses.
*/
public function unlocksTo(self $to): bool
{
return $this->locksTime() && ! $to->locksTime();
}
/**
* The Kanban columns: every status except archived.
*
@@ -65,6 +65,10 @@ class JobsServiceProvider extends ServiceProvider
Gate::define('jobs.archive', $isManager);
// A done job's hours and expenses are locked; only management moves it back
// to an earlier status, which opens the lock (spec 5.3).
Gate::define('jobs.unlock', $isManager);
// Adding, changing and removing tasks: everyone but subcontractors.
Gate::define('jobs.manage-tasks', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor);
@@ -68,8 +68,8 @@ new class extends Component
return array_values(array_filter(
JobStatus::kanbanStatuses(),
fn (JobStatus $status): bool => $status === $job->status
|| ! $status->isBillingStatus()
|| Gate::allows('jobs.set-billing-status', [$job->billerUserId]),
|| ((! $status->isBillingStatus() || Gate::allows('jobs.set-billing-status', [$job->billerUserId]))
&& (! $job->status->unlocksTo($status) || Gate::allows('jobs.unlock'))),
));
}
@@ -115,6 +115,13 @@ new class extends Component
return;
}
if ($job->status->unlocksTo($status) && ! Gate::allows('jobs.unlock')) {
$this->statusMessage = __('jobs.board.unlock_not_allowed', ['job' => $job->number.' '.$job->name, 'status' => __('jobs.statuses.'.$status->value)]);
unset($this->board);
return;
}
try {
$changeStatus->execute($jobId, $status, (int) auth()->id());
} catch (CustomerJobNotFound) {
@@ -242,6 +242,12 @@ new class extends Component
private function maySetStatus(JobStatus $status): bool
{
$stored = $this->storedStatus === null ? null : JobStatus::tryFrom($this->storedStatus);
if ($stored !== null && $stored->unlocksTo($status) && ! Gate::allows('jobs.unlock')) {
return false;
}
if ($status === JobStatus::Archived) {
return Gate::allows('jobs.archive');
}
@@ -452,6 +452,9 @@ new class extends Component
'old' => $this->historyValue($change->field, $change->oldValue),
'new' => $this->historyValue($change->field, $change->newValue),
]) }}</span>
@if ($change->field === 'status' && \App\Modules\Jobs\Domain\Enums\JobStatus::tryFrom((string) $change->oldValue)?->unlocksTo(\App\Modules\Jobs\Domain\Enums\JobStatus::from((string) $change->newValue)))
<span class="font-medium">{{ __('jobs.history.unlocked') }}</span>
@endif
@endif
<span class="block text-zinc-600 dark:text-zinc-300">
{{ __('jobs.history.by', ['user' => $change->userName, 'time' => CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i')]) }}
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
@@ -25,4 +26,19 @@ interface TimeEntryQueries
public function entriesForTask(int $taskId, int $userId): array;
public function hasEntries(int $taskId): bool;
/**
* Unapproved hours by user and week (Monday to Sunday), oldest week first.
*
* @return list<ApprovalWeek>
*/
public function pendingWeeks(?int $userId = null): array;
/**
* Weeks with approved hours from the given Monday on, newest first,
* with the latest approval of each.
*
* @return list<ApprovalWeek>
*/
public function approvedWeeks(string $sinceMonday): array;
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* One user's hours of one week on the approval page: unapproved ones, or
* approved ones with the latest approval.
*/
final readonly class ApprovalWeek
{
/**
* @param string $monday Y-m-d
*/
public function __construct(
public int $userId,
public string $userName,
public string $monday,
public int $quarters,
public int $entryCount,
public ?WeekApproval $approval = null,
) {}
/**
* A stable key for lists, e.g. "12-2026-11-23".
*/
public function key(): string
{
return $this->userId.'-'.$this->monday;
}
}
@@ -11,5 +11,6 @@ final readonly class TimeEntrySummary
public string $workedOn,
public int $quarters,
public ?string $note,
public bool $isApproved = false,
) {}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* Who approved hours and when (Y-m-d H:i, the company's time zone).
*/
final readonly class WeekApproval
{
public function __construct(
public int $approvedBy,
public string $approverName,
public string $approvedAt,
) {}
}
@@ -13,10 +13,17 @@ final readonly class WeekRow
{
/**
* @param array<string, int> $quartersByDay Y-m-d => quarters of an hour (days without hours left out)
* @param list<string> $approvedDays Y-m-d of the days whose hours are approved
*/
public function __construct(
public BookableTask $task,
public array $quartersByDay,
public int $totalQuarters,
public array $approvedDays = [],
) {}
public function isApprovedOn(string $day): bool
{
return in_array($day, $this->approvedDays, true);
}
}
@@ -19,5 +19,17 @@ final readonly class WeekSheet
public array $rows,
public array $dayTotals,
public int $totalQuarters,
public int $unapprovedQuarters = 0,
public ?WeekApproval $lastApproval = null,
) {}
public function hasUnapprovedHours(): bool
{
return $this->unapprovedQuarters > 0;
}
public function hasApprovedHours(): bool
{
return $this->lastApproval !== null;
}
}
@@ -11,6 +11,7 @@ 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\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
@@ -32,6 +33,7 @@ final class AddTaskHours
* @throws InvalidWorkedHours
* @throws TaskNotBookable
* @throws TimeLocked
* @throws TimeApproved
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $taskId, string $day, string $hours, ?string $note = null): string
@@ -0,0 +1,49 @@
<?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\Users\Application\Contracts\Clock;
/**
* Approves a user's hours of one week (Monday to Sunday). Who may approve
* whose hours is checked by the caller: users their own, management anyone's.
*/
final class ApproveWeek
{
public function __construct(
private TimeEntryRepository $entries,
private Clock $clock,
private TransactionManager $transactions,
) {}
/**
* @param string $monday Y-m-d of the week's Monday.
* @return int How many entries were approved now.
*/
public function execute(int $userId, string $monday, int $approverId): int
{
$start = TimeBooking::day($monday);
$now = $this->clock->now();
return $this->transactions->run(function () use ($userId, $start, $approverId, $now): int {
$approved = 0;
foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
if ($entry->isApproved()) {
continue;
}
$entry->approve($approverId, $now);
$this->entries->save($entry);
$approved++;
}
return $approved;
});
}
}
@@ -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;
/**
* Cancels the approval of a user's week so the hours can be corrected.
* Only management may do this; the caller checks it.
*/
final class CancelWeekApproval
{
public function __construct(
private TimeEntryRepository $entries,
private TransactionManager $transactions,
) {}
/**
* @param string $monday Y-m-d of the week's Monday.
* @return int How many approvals were cancelled.
*/
public function execute(int $userId, string $monday): int
{
$start = TimeBooking::day($monday);
return $this->transactions->run(function () use ($userId, $start): int {
$cancelled = 0;
foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
if (! $entry->isApproved()) {
continue;
}
$entry->cancelApproval();
$this->entries->save($entry);
$cancelled++;
}
return $cancelled;
});
}
}
@@ -7,11 +7,12 @@ 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\TimeApproved;
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.
* Removes one of the user's own entries while the job is not locked and the entry is not approved.
*/
final class RemoveTimeEntry
{
@@ -24,11 +25,13 @@ final class RemoveTimeEntry
/**
* @throws TimeEntryNotFound
* @throws TimeLocked
* @throws TimeApproved
*/
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);
$entry->ensureNotApproved();
$this->booking->openTask($entry->taskId());
$this->entries->delete($entry);
});
@@ -11,6 +11,7 @@ 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\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
@@ -30,6 +31,7 @@ final class SetDayHours
* @throws InvalidWorkedHours
* @throws TaskNotBookable
* @throws TimeLocked
* @throws TimeApproved
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $taskId, string $day, string $hours): void
@@ -41,6 +43,8 @@ final class SetDayHours
$task = $this->booking->openTask($taskId);
$entry = $this->entries->findForDay($userId, $taskId, $date);
$entry?->ensureNotApproved();
if ($parsed === null) {
if ($entry !== null) {
$this->entries->delete($entry);
@@ -9,6 +9,7 @@ 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\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeEntryNotFound;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
@@ -28,6 +29,7 @@ final class UpdateTimeEntry
* @throws InvalidWorkedHours
* @throws TimeEntryNotFound
* @throws TimeLocked
* @throws TimeApproved
* @throws DailyHoursExceeded
*/
public function execute(int $userId, int $entryId, string $hours, ?string $note): void
@@ -36,6 +38,7 @@ final class UpdateTimeEntry
$this->transactions->run(function () use ($userId, $entryId, $parsed, $note): void {
$entry = $this->entries->findForUser($userId, $entryId) ?? throw new TimeEntryNotFound($entryId);
$entry->ensureNotApproved();
$this->booking->openTask($entry->taskId());
$this->booking->ensureDayFits($userId, $entry->workedOn(), $parsed, $entry->id());
@@ -18,6 +18,13 @@ interface TimeEntryRepository
public function save(TimeEntry $entry): TimeEntry;
/**
* The user's entries from $from to $to, both included.
*
* @return list<TimeEntry>
*/
public function forUserBetween(int $userId, DateTimeImmutable $from, DateTimeImmutable $to): array;
public function delete(TimeEntry $entry): void;
/**
@@ -4,12 +4,14 @@ declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Entities;
use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved;
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.
* Approved hours are locked until management cancels the approval.
*/
final class TimeEntry
{
@@ -22,6 +24,8 @@ final class TimeEntry
private DateTimeImmutable $workedOn,
private WorkedHours $hours,
private ?string $note,
private ?int $approvedBy = null,
private ?DateTimeImmutable $approvedAt = null,
) {}
public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self
@@ -29,13 +33,17 @@ final class TimeEntry
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
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null): self
{
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note);
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt);
}
/**
* @throws TimeApproved
*/
public function changeHours(WorkedHours $hours, ?string $note): void
{
$this->ensureNotApproved();
$this->hours = $hours;
$this->note = self::text($note);
}
@@ -45,6 +53,7 @@ final class TimeEntry
*/
public function addHours(WorkedHours $hours, ?string $note): void
{
$this->ensureNotApproved();
$this->hours = $this->hours->plus($hours);
$note = self::text($note);
@@ -53,6 +62,50 @@ final class TimeEntry
}
}
/**
* Approves the entry; an approved entry keeps its first approval.
*/
public function approve(int $approvedBy, DateTimeImmutable $approvedAt): void
{
if ($this->isApproved()) {
return;
}
$this->approvedBy = $approvedBy;
$this->approvedAt = $approvedAt;
}
public function cancelApproval(): void
{
$this->approvedBy = null;
$this->approvedAt = null;
}
public function isApproved(): bool
{
return $this->approvedAt !== null;
}
/**
* @throws TimeApproved
*/
public function ensureNotApproved(): void
{
if ($this->isApproved()) {
throw new TimeApproved;
}
}
public function approvedBy(): ?int
{
return $this->approvedBy;
}
public function approvedAt(): ?DateTimeImmutable
{
return $this->approvedAt;
}
public function id(): ?int
{
return $this->id;
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class TimeApproved extends DomainException
{
public function __construct()
{
parent::__construct('Approved hours are locked.');
}
}
@@ -19,9 +19,11 @@ use Illuminate\Database\Eloquent\Model;
* @property CarbonImmutable $worked_on
* @property string $hours
* @property string|null $note
* @property CarbonImmutable|null $approved_at
* @property int|null $approved_by
*/
#[Table('time_entries')]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note'])]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by'])]
#[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model
{
@@ -39,6 +41,8 @@ class TimeEntryModel extends Model
'customer_job_id' => 'integer',
'work_type_id' => 'integer',
'worked_on' => 'immutable_date',
'approved_at' => 'immutable_datetime',
'approved_by' => 'integer',
];
}
@@ -4,15 +4,22 @@ 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\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekApproval;
use App\Modules\TimeTracking\Application\DTOs\WeekRow;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
class EloquentTimeEntryQueries implements TimeEntryQueries
{
public function __construct(private TaskQueries $tasks) {}
public function __construct(
private TaskQueries $tasks,
private UserAccountQueries $users,
) {}
public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet
{
@@ -34,8 +41,13 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
)));
$byTask = [];
$approvedByTask = [];
foreach ($entries as $entry) {
$byTask[$entry->task_id][$entry->worked_on->toDateString()] = $entry->quarters();
if ($entry->approved_at !== null) {
$approvedByTask[$entry->task_id][] = $entry->worked_on->toDateString();
}
}
$rows = [];
@@ -48,10 +60,12 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
$dayTotals[$day] += $value;
}
$rows[] = new WeekRow($task, $quarters, array_sum($quarters));
$rows[] = new WeekRow($task, $quarters, array_sum($quarters), $approvedByTask[$task->taskId] ?? []);
}
return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals));
$unapproved = $entries->whereNull('approved_at')->sum(fn (TimeEntryModel $entry): int => $entry->quarters());
return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries));
}
public function entriesForTask(int $taskId, int $userId): array
@@ -61,7 +75,7 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
->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))
->map(fn (TimeEntryModel $model): TimeEntrySummary => new TimeEntrySummary($model->id, $model->worked_on->toDateString(), $model->quarters(), $model->note, $model->approved_at !== null))
->values()
->all();
}
@@ -70,4 +84,73 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
{
return TimeEntryModel::query()->where('task_id', $taskId)->exists();
}
public function pendingWeeks(?int $userId = null): array
{
$entries = TimeEntryModel::query()
->whereNull('approved_at')
->when($userId !== null, fn ($query) => $query->where('user_id', $userId))
->orderBy('worked_on')
->get();
return $this->byUserAndWeek($entries, withApproval: false, newestFirst: false);
}
public function approvedWeeks(string $sinceMonday): array
{
$entries = TimeEntryModel::query()
->whereNotNull('approved_at')
->where('worked_on', '>=', $sinceMonday)
->get();
return $this->byUserAndWeek($entries, withApproval: true, newestFirst: true);
}
/**
* @param Collection<int, TimeEntryModel> $entries
* @return list<ApprovalWeek>
*/
private function byUserAndWeek(Collection $entries, bool $withApproval, bool $newestFirst): array
{
$names = $this->users->namesByIds($entries->pluck('user_id')->unique()->values()->all());
$weeks = $entries
->groupBy(fn (TimeEntryModel $entry): string => $entry->user_id.'|'.$entry->worked_on->startOfWeek()->toDateString())
->map(function (Collection $group, string $key) use ($names, $withApproval): ApprovalWeek {
[$userId, $monday] = explode('|', $key);
return new ApprovalWeek(
(int) $userId,
$names[(int) $userId] ?? '',
$monday,
(int) $group->sum(fn (TimeEntryModel $entry): int => $entry->quarters()),
$group->count(),
$withApproval ? $this->latestApproval($group) : null,
);
})
->sortBy([
fn (ApprovalWeek $a, ApprovalWeek $b): int => $newestFirst ? $b->monday <=> $a->monday : $a->monday <=> $b->monday,
fn (ApprovalWeek $a, ApprovalWeek $b): int => $a->userName <=> $b->userName,
]);
return $weeks->values()->all();
}
/**
* @param Collection<int, TimeEntryModel> $entries
*/
private function latestApproval(Collection $entries): ?WeekApproval
{
/** @var TimeEntryModel|null $latest */
$latest = $entries->whereNotNull('approved_at')->sortByDesc('approved_at')->first();
if ($latest === null || $latest->approved_at === null || $latest->approved_by === null) {
return null;
}
return new WeekApproval(
$latest->approved_by,
$this->users->namesByIds([$latest->approved_by])[$latest->approved_by] ?? '',
$latest->approved_at->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
);
}
}
@@ -40,11 +40,25 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
'worked_on' => $entry->workedOn()->format('Y-m-d'),
'hours' => $entry->hours()->decimal(),
'note' => $entry->note(),
'approved_by' => $entry->approvedBy(),
'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'),
])->save();
return $this->toEntity($model->refresh());
}
public function forUserBetween(int $userId, DateTimeImmutable $from, DateTimeImmutable $to): array
{
return TimeEntryModel::query()
->where('user_id', $userId)
->whereBetween('worked_on', [$from->format('Y-m-d'), $to->format('Y-m-d')])
->orderBy('worked_on')
->get()
->map(fn (TimeEntryModel $model): TimeEntry => $this->toEntity($model))
->values()
->all();
}
public function delete(TimeEntry $entry): void
{
TimeEntryModel::query()->whereKey($entry->id())->delete();
@@ -70,6 +84,8 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
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,
$model->approved_by,
$model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at),
);
}
}
@@ -41,6 +41,14 @@ class TimeTrackingServiceProvider extends ServiceProvider
Gate::define('time.use', fn (User $user): bool => true);
// Users approve their own hours; management anyone's, including subcontractors' (spec 9).
Gate::define('time.approve', fn (User $user, int $ownerId): bool => $user->role->seesAllMoney()
|| ($user->role !== Role::Subcontractor && $user->id === $ownerId));
Gate::define('time.approve-others', fn (User $user): bool => $user->role->seesAllMoney());
Gate::define('time.cancel-approval', fn (User $user): bool => $user->role->seesAllMoney());
// 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,229 @@
<?php
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\UseCases\ApproveWeek;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* Management's view of hours to approve: unapproved hours by person and
* week, and recently approved weeks. Each week opens in the weekly view.
*/
new class extends Component
{
public string $personFilter = '';
public string $statusMessage = '';
public function mount(): void
{
$this->authorize('time.approve-others');
}
/**
* @return list<ApprovalWeek>
*/
#[Computed]
public function pending(): array
{
return app(TimeEntryQueries::class)->pendingWeeks($this->personFilter === '' ? null : (int) $this->personFilter);
}
/**
* @return list<ApprovalWeek>
*/
#[Computed]
public function approved(): array
{
$since = CarbonImmutable::instance(app(Clock::class)->today())->startOfWeek()->subWeeks(7)->toDateString();
$weeks = app(TimeEntryQueries::class)->approvedWeeks($since);
return $this->personFilter === ''
? $weeks
: array_values(array_filter($weeks, fn (ApprovalWeek $week): bool => $week->userId === (int) $this->personFilter));
}
/**
* @return list<UserOption>
*/
#[Computed]
public function people(): array
{
return app(UserAccountQueries::class)->activeUserOptions();
}
public function approve(int $userId, string $monday, ApproveWeek $approveWeek): void
{
$this->authorize('time.approve-others');
$week = collect($this->pending)->first(fn (ApprovalWeek $week): bool => $week->userId === $userId && $week->monday === $monday);
if ($week === null) {
return;
}
$approveWeek->execute($userId, $monday, (int) auth()->id());
unset($this->pending, $this->approved);
$this->statusMessage = __('time.approval.approved_for', ['name' => $week->userName, 'week' => $this->weekLabel($monday)]);
$this->js("document.getElementById('pending-heading')?.focus()");
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function pendingHeaders(): array
{
return [
['index' => 'person', 'label' => __('time.approvals.person'), 'sortable' => false],
['index' => 'week', 'label' => __('time.approvals.week'), 'sortable' => false],
['index' => 'hours', 'label' => __('time.approvals.hours'), 'sortable' => false, 'align' => 'right'],
['index' => 'actions', 'label' => __('time.approvals.actions'), 'sortable' => false],
];
}
/**
* @return list<array{index: string, label: string, sortable: bool, align?: string}>
*/
public function approvedHeaders(): array
{
return [
['index' => 'person', 'label' => __('time.approvals.person'), 'sortable' => false],
['index' => 'week', 'label' => __('time.approvals.week'), 'sortable' => false],
['index' => 'hours', 'label' => __('time.approvals.hours'), 'sortable' => false, 'align' => 'right'],
['index' => 'approver', 'label' => __('time.approvals.approver'), 'sortable' => false],
['index' => 'actions', 'label' => __('time.approvals.actions'), 'sortable' => false],
];
}
public function weekLabel(string $monday): string
{
$start = CarbonImmutable::parse($monday);
return __('time.week_heading', ['number' => $start->isoWeek(), 'from' => $start->format('j.n.'), 'to' => $start->addDays(6)->format('j.n.Y')]);
}
public function hours(int $quarters): string
{
return WorkedHours::formatQuarters($quarters);
}
public function weekUrl(ApprovalWeek $week): string
{
return route('time.week', ['kayttaja' => $week->userId, 'viikko' => $week->monday]);
}
public function render(): mixed
{
return $this->view()->title(__('time.approvals.title'));
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('time.approvals.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.approvals.intro') }}</p>
</div>
<div class="max-w-sm">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="personFilter" :label="__('time.approvals.person')" :aria-label="__('time.approvals.person')">
<option value="">{{ __('time.approvals.all_people') }}</option>
@foreach ($this->people as $person)
<option wire:key="person-{{ $person->id }}" value="{{ $person->id }}">{{ $person->name }}</option>
@endforeach
</x-select.native>
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm">{{ $statusMessage }}</p>
<section aria-labelledby="pending-heading" class="space-y-3">
<h2 id="pending-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('time.approvals.pending') }}</h2>
@if ($this->pending === [])
<p class="text-sm">{{ __('time.approvals.none_pending') }}</p>
@else
<x-table :headers="$this->pendingHeaders()" :rows="$this->pending">
@interact('column_person', $week)
<span class="font-medium">{{ $week->userName }}</span>
@endinteract
@interact('column_week', $week)
{{ $this->weekLabel($week->monday) }}
@endinteract
@interact('column_hours', $week)
{{ $this->hours($week->quarters) }}
@endinteract
@interact('column_actions', $week)
<div class="flex flex-wrap gap-2">
<x-button
wire:click="approve({{ $week->userId }}, '{{ $week->monday }}')"
sm
icon="check"
:text="__('time.approval.approve_week')"
:aria-label="__('time.approval.approve_week_of', ['name' => $week->userName, 'week' => $this->weekLabel($week->monday)])"
/>
<x-button
:href="$this->weekUrl($week)"
wire:navigate
subtle
color="black"
sm
:text="__('time.approvals.open_week')"
:aria-label="__('time.approvals.open_week_of', ['name' => $week->userName, 'week' => $this->weekLabel($week->monday)])"
/>
</div>
@endinteract
</x-table>
@endif
</section>
<section aria-labelledby="approved-heading" class="space-y-3">
<h2 id="approved-heading" class="text-xl font-semibold">{{ __('time.approvals.approved') }}</h2>
@if ($this->approved === [])
<p class="text-sm">{{ __('time.approvals.none_approved') }}</p>
@else
<x-table :headers="$this->approvedHeaders()" :rows="$this->approved">
@interact('column_person', $week)
<span class="font-medium">{{ $week->userName }}</span>
@endinteract
@interact('column_week', $week)
{{ $this->weekLabel($week->monday) }}
@endinteract
@interact('column_hours', $week)
{{ $this->hours($week->quarters) }}
@endinteract
@interact('column_approver', $week)
@if ($week->approval !== null)
{{ __('time.approvals.approver_value', ['name' => $week->approval->approverName, 'date' => \Carbon\CarbonImmutable::parse($week->approval->approvedAt)->format('j.n.Y H:i')]) }}
@endif
@endinteract
@interact('column_actions', $week)
<x-button
:href="$this->weekUrl($week)"
wire:navigate
subtle
color="black"
sm
:text="__('time.approvals.open_week')"
:aria-label="__('time.approvals.open_week_of', ['name' => $week->userName, 'week' => $this->weekLabel($week->monday)])"
/>
@endinteract
</x-table>
@endif
</section>
</div>
@@ -10,6 +10,7 @@ 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\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
@@ -104,7 +105,7 @@ new class extends Component
{
$entry = collect($this->entries)->firstWhere('id', $entryId);
if ($entry === null) {
if ($entry === null || $entry->isApproved) {
return;
}
@@ -151,7 +152,9 @@ new class extends Component
public function confirmRemoval(int $entryId): void
{
if (collect($this->entries)->firstWhere('id', $entryId) === null) {
$entry = collect($this->entries)->firstWhere('id', $entryId);
if ($entry === null || $entry->isApproved) {
return;
}
@@ -199,6 +202,7 @@ new class extends Component
$exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours',
$exception instanceof DailyHoursExceeded => 'time.errors.day_full',
$exception instanceof TimeLocked => 'time.errors.locked',
$exception instanceof TimeApproved => 'time.errors.approved',
default => 'time.errors.not_found',
});
}
@@ -266,7 +270,11 @@ new class extends Component
<p class="whitespace-pre-line text-zinc-700 dark:text-zinc-300">{{ $entry->note }}</p>
@endif
</div>
@unless ($task->isLocked())
@if ($entry->isApproved)
<span class="inline-flex items-center gap-1">
<x-icon name="check-circle" class="size-4" aria-hidden="true" /> {{ __('time.approval.cell_approved') }}
</span>
@elseif (! $task->isLocked())
<div class="flex flex-wrap gap-2">
<x-button
id="edit-entry-{{ $entry->id }}"
@@ -288,7 +296,7 @@ new class extends Component
:aria-label="__('time.task_page.remove_named', ['day' => $this->dayLabel($entry->workedOn)])"
/>
</div>
@endunless
@endif
</div>
@endif
</li>
@@ -5,12 +5,16 @@ 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\ApproveWeek;
use App\Modules\TimeTracking\Application\UseCases\CancelWeekApproval;
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\TimeApproved;
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\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
@@ -22,7 +26,8 @@ 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.
* day is shown at a time. Approved hours are locked. Management may open
* another user's week (?kayttaja=ID) to read, approve or cancel approval.
*/
new class extends Component
{
@@ -34,6 +39,19 @@ new class extends Component
#[Url(as: 'viikko', except: '')]
public string $week = '';
/**
* Another user's id from the URL, for management; '' is the signed-in user.
*/
#[Locked]
#[Url(as: 'kayttaja', except: '')]
public string $user = '';
#[Locked]
public int $viewedUserId = 0;
#[Locked]
public string $viewedUserName = '';
/**
* 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
@@ -77,6 +95,20 @@ new class extends Component
{
$this->authorize('time.use');
$this->viewedUserId = (int) auth()->id();
if ($this->user !== '' && (int) $this->user !== $this->viewedUserId) {
$this->authorize('time.approve-others');
$summary = ctype_digit($this->user) ? app(UserAccountQueries::class)->findSummary((int) $this->user) : null;
abort_if($summary === null, 404);
$this->viewedUserId = $summary->id;
$this->viewedUserName = $summary->name;
} else {
$this->user = '';
}
$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;
@@ -86,7 +118,56 @@ new class extends Component
#[Computed]
public function sheet(): WeekSheet
{
return app(TimeEntryQueries::class)->week((int) auth()->id(), $this->week, $this->extraTaskIds);
return app(TimeEntryQueries::class)->week($this->viewedUserId, $this->week, $this->extraTaskIds);
}
/**
* Whether management is looking at someone else's week: nothing can be typed then.
*/
public function isReadOnly(): bool
{
return $this->viewedUserId !== (int) auth()->id();
}
public function canApprove(): bool
{
return Gate::allows('time.approve', $this->viewedUserId);
}
public function approveWeek(ApproveWeek $approveWeek): void
{
$this->authorize('time.approve', $this->viewedUserId);
$count = $approveWeek->execute($this->viewedUserId, $this->week, (int) auth()->id());
unset($this->sheet);
$this->loadCells();
$this->rejected = [];
$this->resetErrorBag();
$this->errorMessage = '';
$this->statusMessage = $count === 0
? __('time.approval.nothing_to_approve')
: __('time.approval.approved', ['week' => $this->weekHeading()]);
}
public function confirmCancelApproval(): void
{
$this->authorize('time.cancel-approval');
$this->js("document.getElementById('cancel-approval-dialog').showModal()");
}
public function cancelApproval(CancelWeekApproval $cancelApproval): void
{
$this->authorize('time.cancel-approval');
$cancelApproval->execute($this->viewedUserId, $this->week);
unset($this->sheet);
$this->loadCells();
$this->statusMessage = __('time.approval.cancelled', ['week' => $this->weekHeading()]);
$this->js("document.getElementById('cancel-approval-dialog').close(); document.getElementById('approval-heading').focus()");
}
/**
@@ -115,7 +196,7 @@ new class extends Component
$row = collect($this->sheet->rows)->first(fn ($row): bool => $row->task->taskId === $taskId);
if ($row === null || ! in_array($day, $this->sheet->days, true)) {
if ($this->isReadOnly() || $row === null || ! in_array($day, $this->sheet->days, true)) {
return;
}
@@ -131,6 +212,7 @@ new class extends Component
$exception instanceof InvalidWorkedHours => 'time.errors.invalid_hours',
$exception instanceof DailyHoursExceeded => 'time.errors.day_full',
$exception instanceof TimeLocked => 'time.errors.locked',
$exception instanceof TimeApproved => 'time.errors.approved',
default => 'time.errors.not_found',
});
$this->addError("cells.{$taskId}.{$day}", $message);
@@ -155,7 +237,7 @@ new class extends Component
$task = app(TaskQueries::class)->bookableTask($taskId);
if ($task === null || $task->isLocked() || Gate::denies('time.book', $task->jobId)) {
if ($this->isReadOnly() || $task === null || $task->isLocked() || Gate::denies('time.book', $task->jobId)) {
return;
}
@@ -223,9 +305,14 @@ new class extends Component
return auth()->user()?->role === Role::Subcontractor;
}
public function heading(): string
{
return $this->isReadOnly() ? __('time.other_title', ['name' => $this->viewedUserName]) : __('time.title');
}
public function render(): mixed
{
return $this->view()->title(__('time.title'));
return $this->view()->title($this->heading());
}
private function loadCells(): void
@@ -257,8 +344,13 @@ new class extends Component
<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>
<h1 class="text-2xl font-semibold break-words">{{ $this->heading() }}</h1>
@if ($this->isReadOnly())
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.other_intro') }}</p>
<x-link :href="route('time.approvals')" navigate class="text-sm">{{ __('time.approval.back_to_list') }}</x-link>
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('time.intro') }}</p>
@endif
</div>
<div class="flex flex-wrap items-center justify-between gap-3">
@@ -303,7 +395,13 @@ new class extends Component
</th>
@foreach ($sheet->days as $day)
<td class="px-1 py-2 text-center">
@if ($row->task->isLocked())
@if ($row->isApprovedOn($day))
<span class="inline-flex items-center gap-1">
{{ $this->hours($row->quartersByDay[$day] ?? 0) }}
<x-icon name="check-circle" class="size-4" aria-hidden="true" />
<span class="sr-only">{{ __('time.approval.cell_approved') }}</span>
</span>
@elseif ($row->task->isLocked() || $this->isReadOnly())
{{ isset($row->quartersByDay[$day]) ? $this->hours($row->quartersByDay[$day]) : '' }}
@else
<input
@@ -366,12 +464,19 @@ new class extends Component
<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())
@if ($row->isApprovedOn($selectedDay))
<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
<x-icon name="check-circle" class="size-4" aria-hidden="true" /> {{ __('time.approval.cell_approved') }}
– {{ __('time.hours_suffix', ['hours' => $this->hours($row->quartersByDay[$selectedDay] ?? 0)]) }}
</p>
@elseif ($row->task->isLocked() || $this->isReadOnly())
<p class="mt-2 inline-flex items-center gap-1">
@if ($row->task->isLocked())
<x-icon name="lock-closed" class="size-4" aria-hidden="true" /> {{ __('time.locked') }}
@else
{{ $this->dayLabel($selectedDay) }}
@endif
– {{ __('time.hours_suffix', ['hours' => $this->hours($row->quartersByDay[$selectedDay] ?? 0)]) }}
</p>
@else
<label for="mcell-{{ $row->task->taskId }}-{{ $selectedDay }}" class="mt-2 block font-medium">
@@ -399,6 +504,50 @@ new class extends Component
<p class="text-sm font-semibold">{{ __('time.week_total', ['hours' => $this->hours($sheet->totalQuarters)]) }}</p>
@endif
<section aria-labelledby="approval-heading" class="space-y-3 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
<h2 id="approval-heading" tabindex="-1" class="text-lg font-semibold focus:outline-none">{{ __('time.approval.title') }}</h2>
@if ($sheet->hasUnapprovedHours())
<p class="text-sm">{{ __('time.approval.unapproved', ['hours' => $this->hours($sheet->unapprovedQuarters)]) }}</p>
@elseif ($sheet->totalQuarters === 0)
<p class="text-sm">{{ __('time.approval.no_hours') }}</p>
@endif
@if ($sheet->lastApproval !== null)
<p class="inline-flex items-center gap-1 text-sm">
<x-icon name="check-circle" class="size-4" aria-hidden="true" />
{{ __('time.approval.approved_by', ['date' => \Carbon\CarbonImmutable::parse($sheet->lastApproval->approvedAt)->format('j.n.Y H:i'), 'name' => $sheet->lastApproval->approverName]) }}
</p>
@endif
<div class="flex flex-wrap gap-2">
@if ($sheet->hasUnapprovedHours())
@if ($this->canApprove())
<x-button wire:click="approveWeek" icon="check" :text="__('time.approval.approve_week')" />
@else
<p class="text-sm">{{ __('time.approval.management_approves') }}</p>
@endif
@endif
@if ($sheet->hasApprovedHours())
@can('time.cancel-approval')
<x-button wire:click="confirmCancelApproval" subtle color="black" icon="arrow-uturn-left" :text="__('time.approval.cancel')" />
@endcan
@endif
</div>
</section>
@can('time.cancel-approval')
<x-confirm-dialog id="cancel-approval-dialog" :title="__('time.approval.cancel_title')">
<p>{{ __('time.approval.cancel_question', ['week' => $this->weekHeading()]) }}</p>
<x-slot:actions>
<x-button wire:click="cancelApproval" color="red" icon="arrow-uturn-left" :text="__('time.approval.cancel')" />
</x-slot:actions>
</x-confirm-dialog>
@endcan
@unless ($this->isReadOnly())
<section aria-labelledby="add-task-heading" class="space-y-2">
<h2 id="add-task-heading" class="sr-only">{{ __('time.add.search') }}</h2>
<x-input
@@ -432,4 +581,5 @@ new class extends Component
</ul>
@endif
</section>
@endunless
</div>
@@ -8,4 +8,5 @@ Route::middleware(['web', 'auth', 'can:time.use'])
->group(function () {
Route::livewire('/', 'time::week')->name('week');
Route::livewire('/tasks/{task}', 'time::task')->whereNumber('task')->name('task');
Route::livewire('/approvals', 'time::approvals')->middleware('can:time.approve-others')->name('approvals');
});
@@ -12,4 +12,9 @@ interface Clock
* The current day in the company's time zone.
*/
public function today(): DateTimeImmutable;
/**
* The current moment, e.g. when hours are approved.
*/
public function now(): DateTimeImmutable;
}
@@ -14,4 +14,9 @@ class SystemClock implements Clock
{
return Date::now($this->timezone)->startOfDay()->toDateTimeImmutable();
}
public function now(): DateTimeImmutable
{
return Date::now()->toDateTimeImmutable();
}
}