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
@@ -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');
});