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
@@ -76,3 +76,38 @@ it('records hours from the task page', function () {
->assertSee('kirjaus on nyt 3,5 h.')
->assertNoAccessibilityIssues(level: 2);
});
it('has no accessibility issues on the approval pages', function (string $page, string $device, string $colorScheme) {
TimeEntryModel::query()->update(['approved_at' => now(), 'approved_by' => $this->user->id]);
$other = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
TimeEntryModel::factory()->create(['task_id' => TaskModel::factory()->assignedTo([$other->id])->create()->id, 'user_id' => $other->id, 'worked_on' => $this->monday]);
$this->actingAs(User::factory()->management()->create());
$url = $page === 'approvals' ? route('time.approvals') : route('time.week', ['kayttaja' => $this->user->id]);
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee($page === 'approvals' ? 'Kaisa Kollega' : 'hyväksytty')
->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['approvals', 'week of another user'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('approves the own week with the keyboard and shows the cells as approved', function () {
visit(route('time.week'))
->assertSee('Hyväksymättä 1,5 h.')
->keys('#approval-heading + p + div button', 'Enter')
->assertSee('Hyväksytyt tunnit on lukittu.')
->assertSee('hyväksytty')
->assertNoAccessibilityIssues(level: 2);
expect(TimeEntryModel::query()->sole()->approved_at)->not->toBeNull();
});
+5
View File
@@ -13,4 +13,9 @@ class FakeClock implements Clock
{
return $this->today;
}
public function now(): DateTimeImmutable
{
return $this->today->setTime(12, 0);
}
}
+10 -1
View File
@@ -34,11 +34,20 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository
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());
$this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt());
return clone $this->entries[$id];
}
public function forUserBetween(int $userId, DateTimeImmutable $from, DateTimeImmutable $to): array
{
$found = array_filter($this->entries, fn (TimeEntry $entry): bool => $entry->userId() === $userId
&& $entry->workedOn()->format('Y-m-d') >= $from->format('Y-m-d')
&& $entry->workedOn()->format('Y-m-d') <= $to->format('Y-m-d'));
return array_values(array_map(fn (TimeEntry $entry): TimeEntry => clone $entry, $found));
}
public function delete(TimeEntry $entry): void
{
unset($this->entries[$entry->id()]);
@@ -0,0 +1,126 @@
<?php
use App\Models\User;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->employee()->create(['name' => 'Eero Työntekijä']);
$this->task = TaskModel::factory()->assignedTo([$this->employee->id])->create(['title' => 'Mainoskuvat']);
$this->monday = now()->startOfWeek()->toDateString();
$this->entry = TimeEntryModel::factory()->create(['task_id' => $this->task->id, 'user_id' => $this->employee->id, 'worked_on' => $this->monday, 'hours' => 3]);
});
it('decides who may approve whose hours', function () {
$management = User::factory()->management()->create();
$subcontractor = User::factory()->subcontractor()->create();
expect(Gate::forUser($this->employee)->allows('time.approve', $this->employee->id))->toBeTrue()
->and(Gate::forUser($this->employee)->allows('time.approve', $management->id))->toBeFalse()
->and(Gate::forUser($subcontractor)->allows('time.approve', $subcontractor->id))->toBeFalse()
->and(Gate::forUser($management)->allows('time.approve', $subcontractor->id))->toBeTrue()
->and(Gate::forUser($this->employee)->allows('time.cancel-approval'))->toBeFalse();
});
it('approves the own week in the weekly view, which locks its cells', function () {
$this->actingAs($this->employee);
Livewire::test('time::week')
->assertSee('Hyväksymättä 3 h.')
->call('approveWeek')
->assertSet('statusMessage', fn (string $message) => str_contains($message, 'hyväksytty. Hyväksytyt tunnit on lukittu.'))
->assertDontSee('id="cell-'.$this->task->id.'-'.$this->monday.'"', false)
->assertDontSee(__('time.approval.cancel'))
->call('saveCell', $this->task->id, $this->monday, '5');
$entry = $this->entry->refresh();
expect($entry->approved_by)->toBe($this->employee->id)
->and($entry->approved_at)->not->toBeNull()
->and((float) $entry->hours)->toBe(3.0);
});
it('does not let a subcontractor approve own hours', function () {
$subcontractor = User::factory()->subcontractor()->create();
$job = CustomerJobModel::factory()->withMembers([$subcontractor->id])->create(['status' => JobStatus::Order]);
$task = TaskModel::factory()->assignedTo([$subcontractor->id])->create(['customer_job_id' => $job->id]);
TimeEntryModel::factory()->create(['task_id' => $task->id, 'user_id' => $subcontractor->id, 'worked_on' => $this->monday]);
$this->actingAs($subcontractor);
Livewire::test('time::week')
->assertSee(__('time.approval.management_approves'))
->call('approveWeek')
->assertForbidden();
});
it('lets management open, approve and cancel another user\'s week read-only', function () {
$this->actingAs(User::factory()->management()->create(['name' => 'Johtaja']));
$this->get(route('time.week', ['kayttaja' => $this->employee->id]))
->assertOk()
->assertSee('Tuntikirjaus: Eero Työntekijä')
->assertDontSee('id="cell-', false)
->assertDontSee('id="task-search"', false);
Livewire::withQueryParams(['kayttaja' => (string) $this->employee->id])
->test('time::week')
->call('saveCell', $this->task->id, $this->monday, '5')
->call('approveWeek')
->assertSee('Johtaja')
->call('cancelApproval')
->assertSet('statusMessage', fn (string $message) => str_ends_with($message, 'hyväksyntä peruttu.'));
expect((float) $this->entry->refresh()->hours)->toBe(3.0)
->and($this->entry->approved_at)->toBeNull();
});
it('keeps employees out of other users\' weeks and the approval page', function () {
$this->actingAs(User::factory()->employee()->create());
$this->get(route('time.week', ['kayttaja' => $this->employee->id]))->assertForbidden();
$this->get(route('time.approvals'))->assertForbidden();
});
it('lists unapproved and approved weeks for management and approves from the list', function () {
$colleague = User::factory()->employee()->create(['name' => 'Kaisa Kollega']);
TimeEntryModel::factory()->approved()->create(['task_id' => TaskModel::factory()->assignedTo([$colleague->id])->create()->id, 'user_id' => $colleague->id, 'worked_on' => $this->monday, 'hours' => 1.5]);
$this->actingAs(User::factory()->management()->create());
Livewire::test('time::approvals')
->assertSeeInOrder(['Hyväksymättä', 'Eero Työntekijä', 'Hyväksytyt', 'Kaisa Kollega'])
->call('approve', $this->employee->id, $this->monday)
->assertSet('statusMessage', fn (string $message) => str_starts_with($message, 'Eero Työntekijä:'))
->assertSee(__('time.approvals.none_pending'));
expect($this->entry->refresh()->approved_at)->not->toBeNull();
});
it('lets only management move a done job back, which opens its lock', function () {
$job = CustomerJobModel::factory()->create(['status' => JobStatus::Done]);
$this->actingAs($this->employee);
Livewire::test('jobs::board')
->set('mine', false)
->call('moveJob', $job->id, 'in_production')
->assertSet('statusMessage', fn (string $message) => str_contains($message, 'lukituksen voi avata vain johto'));
expect($job->refresh()->status)->toBe(JobStatus::Done);
$this->actingAs(User::factory()->management()->create());
Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $job->id, 'in_production');
expect($job->refresh()->status)->toBe(JobStatus::InProduction);
$this->get(route('jobs.show', $job->id))->assertSee(__('jobs.history.unlocked'));
});
@@ -0,0 +1,78 @@
<?php
use App\Modules\TimeTracking\Application\Services\TimeBooking;
use App\Modules\TimeTracking\Application\UseCases\AddTaskHours;
use App\Modules\TimeTracking\Application\UseCases\ApproveWeek;
use App\Modules\TimeTracking\Application\UseCases\CancelWeekApproval;
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\Exceptions\TimeApproved;
use Tests\Fakes\FakeClock;
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->approveWeek = new ApproveWeek($this->entries, new FakeClock(new DateTimeImmutable('2026-11-30')), $transactions);
$this->cancelApproval = new CancelWeekApproval($this->entries, $transactions);
$this->tasks->addTask(1);
$this->tasks->addTask(2);
// Week 48: Monday 23.11.2026.
$this->setDayHours->execute(10, 1, '2026-11-23', '4');
$this->setDayHours->execute(10, 1, '2026-11-29', '2');
$this->setDayHours->execute(10, 1, '2026-11-30', '3');
$this->setDayHours->execute(11, 1, '2026-11-23', '5');
});
it('approves the user\'s unapproved hours of the week only', function () {
expect($this->approveWeek->execute(10, '2026-11-23', approverId: 99))->toBe(2);
$approved = array_filter($this->entries->entries, fn ($entry) => $entry->isApproved());
expect(array_map(fn ($entry) => [$entry->userId(), $entry->workedOn()->format('Y-m-d'), $entry->approvedBy()], array_values($approved)))->toBe([
[10, '2026-11-23', 99],
[10, '2026-11-29', 99],
])->and($this->approveWeek->execute(10, '2026-11-23', 99))->toBe(0);
});
it('locks approved hours against every change', function (Closure $change) {
$this->approveWeek->execute(10, '2026-11-23', 10);
expect(fn () => $change->call($this))->toThrow(TimeApproved::class);
})->with([
'week cell' => [fn () => $this->setDayHours->execute(10, 1, '2026-11-23', '5')],
'emptied cell' => [fn () => $this->setDayHours->execute(10, 1, '2026-11-23', '')],
'task page' => [fn () => $this->addTaskHours->execute(10, 1, '2026-11-23', '1')],
'edit' => [fn () => $this->updateEntry->execute(10, 1, '1', null)],
'remove' => [fn () => $this->removeEntry->execute(10, 1)],
]);
it('lets new hours be added to an approved week on another task', function () {
$this->approveWeek->execute(10, '2026-11-23', 10);
$this->setDayHours->execute(10, 2, '2026-11-23', '1');
expect($this->entries->findForDay(10, 2, new DateTimeImmutable('2026-11-23'))?->isApproved())->toBeFalse();
});
it('cancels the approval of a week so the hours can be changed again', function () {
$this->approveWeek->execute(10, '2026-11-23', 99);
expect($this->cancelApproval->execute(10, '2026-11-23'))->toBe(2);
$this->setDayHours->execute(10, 1, '2026-11-23', '5');
expect($this->entries->findForDay(10, 1, new DateTimeImmutable('2026-11-23'))?->hours()->format())->toBe('5');
});