diff --git a/CLAUDE.md b/CLAUDE.md index fcbcdfb..f02feff 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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` (`::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`, `time.use`, `time.book`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). 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`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). 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`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`. - Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. diff --git a/app/Modules/Jobs/Domain/Enums/JobStatus.php b/app/Modules/Jobs/Domain/Enums/JobStatus.php index 28b3098..31cf56a 100644 --- a/app/Modules/Jobs/Domain/Enums/JobStatus.php +++ b/app/Modules/Jobs/Domain/Enums/JobStatus.php @@ -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. * diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index e1cc220..d9b1103 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -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); diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php index efbddbc..a0e71f6 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php @@ -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) { diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php index f9a118f..d5ac277 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php @@ -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'); } diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 08c4dc2..42e6996 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -452,6 +452,9 @@ new class extends Component 'old' => $this->historyValue($change->field, $change->oldValue), 'new' => $this->historyValue($change->field, $change->newValue), ]) }} + @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))) + {{ __('jobs.history.unlocked') }} + @endif @endif {{ __('jobs.history.by', ['user' => $change->userName, 'time' => CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i')]) }} diff --git a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php index db2abc9..db4b326 100644 --- a/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php +++ b/app/Modules/TimeTracking/Application/Contracts/TimeEntryQueries.php @@ -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 + */ + 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 + */ + public function approvedWeeks(string $sinceMonday): array; } diff --git a/app/Modules/TimeTracking/Application/DTOs/ApprovalWeek.php b/app/Modules/TimeTracking/Application/DTOs/ApprovalWeek.php new file mode 100644 index 0000000..dd7427e --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/ApprovalWeek.php @@ -0,0 +1,32 @@ +userId.'-'.$this->monday; + } +} diff --git a/app/Modules/TimeTracking/Application/DTOs/TimeEntrySummary.php b/app/Modules/TimeTracking/Application/DTOs/TimeEntrySummary.php index 7302ef1..cef36c4 100644 --- a/app/Modules/TimeTracking/Application/DTOs/TimeEntrySummary.php +++ b/app/Modules/TimeTracking/Application/DTOs/TimeEntrySummary.php @@ -11,5 +11,6 @@ final readonly class TimeEntrySummary public string $workedOn, public int $quarters, public ?string $note, + public bool $isApproved = false, ) {} } diff --git a/app/Modules/TimeTracking/Application/DTOs/WeekApproval.php b/app/Modules/TimeTracking/Application/DTOs/WeekApproval.php new file mode 100644 index 0000000..dfbf1af --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/WeekApproval.php @@ -0,0 +1,17 @@ + $quartersByDay Y-m-d => quarters of an hour (days without hours left out) + * @param list $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); + } } diff --git a/app/Modules/TimeTracking/Application/DTOs/WeekSheet.php b/app/Modules/TimeTracking/Application/DTOs/WeekSheet.php index 95208dd..2b1ae00 100644 --- a/app/Modules/TimeTracking/Application/DTOs/WeekSheet.php +++ b/app/Modules/TimeTracking/Application/DTOs/WeekSheet.php @@ -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; + } } diff --git a/app/Modules/TimeTracking/Application/UseCases/AddTaskHours.php b/app/Modules/TimeTracking/Application/UseCases/AddTaskHours.php index 4c01ac5..f3490af 100644 --- a/app/Modules/TimeTracking/Application/UseCases/AddTaskHours.php +++ b/app/Modules/TimeTracking/Application/UseCases/AddTaskHours.php @@ -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 diff --git a/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php b/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php new file mode 100644 index 0000000..a0f7887 --- /dev/null +++ b/app/Modules/TimeTracking/Application/UseCases/ApproveWeek.php @@ -0,0 +1,49 @@ +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; + }); + } +} diff --git a/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php b/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php new file mode 100644 index 0000000..4803bd7 --- /dev/null +++ b/app/Modules/TimeTracking/Application/UseCases/CancelWeekApproval.php @@ -0,0 +1,46 @@ +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; + }); + } +} diff --git a/app/Modules/TimeTracking/Application/UseCases/RemoveTimeEntry.php b/app/Modules/TimeTracking/Application/UseCases/RemoveTimeEntry.php index 6dad5c3..3e3cf97 100644 --- a/app/Modules/TimeTracking/Application/UseCases/RemoveTimeEntry.php +++ b/app/Modules/TimeTracking/Application/UseCases/RemoveTimeEntry.php @@ -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); }); diff --git a/app/Modules/TimeTracking/Application/UseCases/SetDayHours.php b/app/Modules/TimeTracking/Application/UseCases/SetDayHours.php index 1f45edd..56594b2 100644 --- a/app/Modules/TimeTracking/Application/UseCases/SetDayHours.php +++ b/app/Modules/TimeTracking/Application/UseCases/SetDayHours.php @@ -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); diff --git a/app/Modules/TimeTracking/Application/UseCases/UpdateTimeEntry.php b/app/Modules/TimeTracking/Application/UseCases/UpdateTimeEntry.php index 113de83..5ad7286 100644 --- a/app/Modules/TimeTracking/Application/UseCases/UpdateTimeEntry.php +++ b/app/Modules/TimeTracking/Application/UseCases/UpdateTimeEntry.php @@ -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()); diff --git a/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php b/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php index a5f9284..226c890 100644 --- a/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php +++ b/app/Modules/TimeTracking/Domain/Contracts/TimeEntryRepository.php @@ -18,6 +18,13 @@ interface TimeEntryRepository public function save(TimeEntry $entry): TimeEntry; + /** + * The user's entries from $from to $to, both included. + * + * @return list + */ + public function forUserBetween(int $userId, DateTimeImmutable $from, DateTimeImmutable $to): array; + public function delete(TimeEntry $entry): void; /** diff --git a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php index 1e7b9c5..78d6cec 100644 --- a/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php +++ b/app/Modules/TimeTracking/Domain/Entities/TimeEntry.php @@ -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; diff --git a/app/Modules/TimeTracking/Domain/Exceptions/TimeApproved.php b/app/Modules/TimeTracking/Domain/Exceptions/TimeApproved.php new file mode 100644 index 0000000..2dbbaa3 --- /dev/null +++ b/app/Modules/TimeTracking/Domain/Exceptions/TimeApproved.php @@ -0,0 +1,15 @@ + 'integer', 'work_type_id' => 'integer', 'worked_on' => 'immutable_date', + 'approved_at' => 'immutable_datetime', + 'approved_by' => 'integer', ]; } diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php index 3e90bc0..fd9a2b0 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php @@ -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 $entries + * @return list + */ + 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 $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'), + ); + } } diff --git a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php index df20afc..f7d5274 100644 --- a/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php +++ b/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryRepository.php @@ -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), ); } } diff --git a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php index 0104f06..8f3c377 100644 --- a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php +++ b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php @@ -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)); diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php new file mode 100644 index 0000000..4818918 --- /dev/null +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡approvals.blade.php @@ -0,0 +1,229 @@ +authorize('time.approve-others'); + } + + /** + * @return list + */ + #[Computed] + public function pending(): array + { + return app(TimeEntryQueries::class)->pendingWeeks($this->personFilter === '' ? null : (int) $this->personFilter); + } + + /** + * @return list + */ + #[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 + */ + #[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 + */ + 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 + */ + 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')); + } +}; +?> + +
+
+

{{ __('time.approvals.title') }}

+

{{ __('time.approvals.intro') }}

+
+ +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->people as $person) + + @endforeach + +
+ +

{{ $statusMessage }}

+ +
+

{{ __('time.approvals.pending') }}

+ + @if ($this->pending === []) +

{{ __('time.approvals.none_pending') }}

+ @else + + @interact('column_person', $week) + {{ $week->userName }} + @endinteract + + @interact('column_week', $week) + {{ $this->weekLabel($week->monday) }} + @endinteract + + @interact('column_hours', $week) + {{ $this->hours($week->quarters) }} + @endinteract + + @interact('column_actions', $week) +
+ + +
+ @endinteract +
+ @endif +
+ +
+

{{ __('time.approvals.approved') }}

+ + @if ($this->approved === []) +

{{ __('time.approvals.none_approved') }}

+ @else + + @interact('column_person', $week) + {{ $week->userName }} + @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) + + @endinteract + + @endif +
+
diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡task.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡task.blade.php index e56b977..7852b26 100644 --- a/app/Modules/TimeTracking/Presentation/Livewire/⚡task.blade.php +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡task.blade.php @@ -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

{{ $entry->note }}

@endif - @unless ($task->isLocked()) + @if ($entry->isApproved) + + + @elseif (! $task->isLocked())
- @endunless + @endif @endif diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php index ebbb447..449b5a7 100644 --- a/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡week.blade.php @@ -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
-

{{ __('time.title') }}

-

{{ __('time.intro') }}

+

{{ $this->heading() }}

+ @if ($this->isReadOnly()) +

{{ __('time.other_intro') }}

+ {{ __('time.approval.back_to_list') }} + @else +

{{ __('time.intro') }}

+ @endif
@@ -303,7 +395,13 @@ new class extends Component @foreach ($sheet->days as $day) - @if ($row->task->isLocked()) + @if ($row->isApprovedOn($day)) + + {{ $this->hours($row->quartersByDay[$day] ?? 0) }} + + @elseif ($row->task->isLocked() || $this->isReadOnly()) {{ isset($row->quartersByDay[$day]) ? $this->hours($row->quartersByDay[$day]) : '' }} @else {{ $row->task->label() }} {{ $row->task->workTypeName }} - @if ($row->task->isLocked()) + @if ($row->isApprovedOn($selectedDay))

-

+ @elseif ($row->task->isLocked() || $this->isReadOnly()) +

+ @if ($row->task->isLocked()) +

@else
diff --git a/app/Modules/TimeTracking/Presentation/Routes/web.php b/app/Modules/TimeTracking/Presentation/Routes/web.php index e182e0c..27e1e00 100644 --- a/app/Modules/TimeTracking/Presentation/Routes/web.php +++ b/app/Modules/TimeTracking/Presentation/Routes/web.php @@ -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'); }); diff --git a/app/Modules/Users/Application/Contracts/Clock.php b/app/Modules/Users/Application/Contracts/Clock.php index 0353c9b..d5f4fa1 100644 --- a/app/Modules/Users/Application/Contracts/Clock.php +++ b/app/Modules/Users/Application/Contracts/Clock.php @@ -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; } diff --git a/app/Modules/Users/Infrastructure/SystemClock.php b/app/Modules/Users/Infrastructure/SystemClock.php index 5366fe8..3afaa67 100644 --- a/app/Modules/Users/Infrastructure/SystemClock.php +++ b/app/Modules/Users/Infrastructure/SystemClock.php @@ -14,4 +14,9 @@ class SystemClock implements Clock { return Date::now($this->timezone)->startOfDay()->toDateTimeImmutable(); } + + public function now(): DateTimeImmutable + { + return Date::now()->toDateTimeImmutable(); + } } diff --git a/database/factories/TimeEntryFactory.php b/database/factories/TimeEntryFactory.php index d199972..8663365 100644 --- a/database/factories/TimeEntryFactory.php +++ b/database/factories/TimeEntryFactory.php @@ -28,4 +28,12 @@ class TimeEntryFactory extends Factory 'hours' => 2, ]; } + + public function approved(?User $by = null): static + { + return $this->state(fn (array $attributes): array => [ + 'approved_at' => now(), + 'approved_by' => $by->id ?? $attributes['user_id'], + ]); + } } diff --git a/database/migrations/2026_11_24_061516_add_approval_to_time_entries_table.php b/database/migrations/2026_11_24_061516_add_approval_to_time_entries_table.php new file mode 100644 index 0000000..e21014f --- /dev/null +++ b/database/migrations/2026_11_24_061516_add_approval_to_time_entries_table.php @@ -0,0 +1,30 @@ +timestamp('approved_at')->nullable()->after('note'); + $table->foreignId('approved_by')->nullable()->after('approved_at')->constrained('users')->restrictOnDelete(); + + $table->index('approved_at'); + }); + } + + public function down(): void + { + Schema::table('time_entries', function (Blueprint $table) { + $table->dropIndex(['approved_at']); + $table->dropConstrainedForeignId('approved_by'); + $table->dropColumn('approved_at'); + }); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index ea97cad..97edede 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -156,7 +156,7 @@ Tilat ovat asiakastöiden Kanban-taulun sarakkeet tässä järjestyksessä: - Tila etenee yleensä järjestyksessä, mutta minkä tahansa tilan voi valita *(K21)*. - "Valmis"-tilaan asti tilan saa vaihtaa kuka tahansa, jolla on muokkausoikeus. "Lasku luotu" ja "Laskutettu" asetetaan laskun tekemisen yhteydessä (laskuttaja tai johto). -- Kun työ on **valmis**, sen tunnit ja kulut lukitaan *(K21)*. Lukituksen voi avata johto (ks. avoimet kysymykset). +- Kun työ on **valmis**, sen tunnit ja kulut lukitaan *(K21)*. Lukituksen voi avata vain johto siirtämällä työn takaisin aiempaan tilaan; muutoshistoriassa siirto näkyy merkinnällä "lukitus avattu" *(valmis)*. - **Arkistoitu** työ ei näy Kanban-taululla, mutta löytyy haulla ja listasta. - Tehtäviä voi luoda tarjouspyyntö-tilasta alkaen (eli alustavan jälkeen) *(K36)*. @@ -256,7 +256,9 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä - 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)*. - **Hyväksyntä**: työntekijä ja harjoittelija hyväksyvät omat tuntinsa itse (esim. viikkonäkymästä "Hyväksy viikko"). Johto voi hyväksyä kenen tahansa tunnit ja hyväksyy alihankkijoiden tunnit. Hyväksyjä ja aika tallennetaan. - **Johdon tarkistus**: johto tarkistaa hyväksytyt tunnit laskutuksen yhteydessä ja kirjaa niiden perusteella laskulle laskutettavan kokonaistuntimäärän (luku 12). Kirjattuja tunteja ei muuteta. -- Hyväksytyt tunnit ja valmiin työn tunnit ovat lukittuja. +- Hyväksytyt tunnit ja valmiin työn tunnit ovat lukittuja. Hyväksytyn viikon päiville voi kirjata uusia tunteja muille tehtäville; ne on hyväksyttävä erikseen. +- Hyväksynnän voi perua vain johto (esim. virheen korjaamiseksi); sen jälkeen tunteja voi muuttaa ja ne hyväksytään uudelleen. +- Johdolla on Tuntien hyväksyntä -sivu (hyväksymättömät tunnit henkilöittäin ja viikoittain, viimeisten 8 viikon hyväksytyt), ja johto voi avata kenen tahansa viikkonäkymän lukutilassa hyväksyäkseen tai perukseen sen *(valmis)*. ## 10. Kulut *(K42–K45)* @@ -357,7 +359,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` (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)* +- `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`, `approved_by` *(V2, olemassa)*, `billing_export_id` *(V2)* **Expenses** *(V2)* - `expenses` *(olemassa)*: `customer_job_id`, `user_id` (kenen kulu), `recorded_by`, `category` (`materials`/`mileage`/`other`), `paid_by` (`company`/`employee`), `spent_on`, `description`, `cost_cents` (hankintahinta), `kilometers` (decimal 7,1), `destination`, `purpose`, `is_billable`, `markup_basis_points`, `billed_amount_cents` (laskutettava summa, null jos ei laskuteta); `billing_export_id` lisätään laskutuksen osassa @@ -458,9 +460,14 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t - Valikon "Kulut" (`/expenses`) näyttää omat kulut kuukausittain summineen. - Hinnastoon lisättiin kulujen oletuskate. +### 17.4 Tuntien hyväksyntä ja lukitus *(valmis)* +- Viikkonäkymässä "Hyväksy viikko" hyväksyy käyttäjän viikon hyväksymättömät tunnit (työntekijä, harjoittelija, johto omansa). Hyväksytyt solut näytetään tekstinä ja merkinnällä "hyväksytty"; alihankkijalle kerrotaan, että johto hyväksyy tunnit. +- Johdon Tuntien hyväksyntä -sivu (`/time/approvals`, valikossa "Hyväksyntä") ja toisen käyttäjän viikkonäkymä lukutilassa (`/time?kayttaja=ID`), jossa hyväksyntä ja sen peruminen (vahvistus dialogissa). +- Valmiin työn siirto takaisin aiempaan tilaan vain johdolle (Kanban ja työn lomake). + ## 18. Avoimet kysymykset -1. **Lukitus**: voiko johto avata valmiin työn tunti- ja kululukituksen, jos jotain unohtui? (Ehdotus: kyllä, ja avaus kirjataan muutoshistoriaan.) +1. ~~**Lukitus**~~: ratkaistu – vain johto avaa valmiin työn lukituksen siirtämällä työn aiempaan tilaan, ja avaus näkyy muutoshistoriassa (5.3). 2. **Alihankkijayritys**: onko yrityksellä useita käyttäjätunnuksia, ja tarvitaanko yritys omana tietonaan (nimi, Y-tunnus)? 3. **Pikamyynnin raportointi**: siirtyvätkö pikamyynnit Fennoaan, vai kirjataanko ne kassan kautta muualla? 4. **Fennoan tuontimuoto**: tarvitaan esimerkki Fennoan laskujen tuontitiedostosta. diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 1f06a53..82e82c7 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -68,6 +68,7 @@ return [ 'moved' => 'Työ :job siirretty tilaan :status.', 'not_moved' => 'Työtä ei siirretty. Päivitä sivu ja yritä uudelleen.', 'billing_not_allowed' => 'Työtä :job ei siirretty: tilan :status voi asettaa vain johto tai työn laskuttaja.', + 'unlock_not_allowed' => 'Työtä :job ei siirretty tilaan :status: valmiin työn tunnit ja kulut on lukittu, ja lukituksen voi avata vain johto.', ], 'quick' => [ @@ -178,6 +179,7 @@ return [ 'history' => [ 'empty' => 'Ei muutoksia.', + 'unlocked' => '(lukitus avattu)', 'created' => ':user loi työn :number.', 'changed' => ':field: :old → :new', 'by' => ':user, :time', diff --git a/lang/fi/layout.php b/lang/fi/layout.php index f84d0cb..7b6caa3 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -8,6 +8,7 @@ return [ 'quick_intake' => 'Pikavastaanotto', 'board' => 'Kanban', 'time' => 'Tuntikirjaus', + 'approvals' => 'Hyväksyntä', 'expenses' => 'Kulut', 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', diff --git a/lang/fi/time.php b/lang/fi/time.php index 540a993..9a3f175 100644 --- a/lang/fi/time.php +++ b/lang/fi/time.php @@ -2,6 +2,8 @@ return [ 'title' => 'Tuntikirjaus', + 'other_title' => 'Tuntikirjaus: :name', + 'other_intro' => 'Katselet toisen käyttäjän tunteja. Voit hyväksyä viikon tai perua sen hyväksynnän, mutta et muuttaa tunteja.', 'week_heading' => 'Viikko :number: :from–:to', 'previous_week' => 'Edellinen viikko', 'this_week' => 'Tämä viikko', @@ -62,5 +64,43 @@ return [ '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.', + 'approved' => 'Tunnit on hyväksytty, joten niitä ei voi muuttaa. Pyydä johtoa perumaan hyväksyntä.', + ], + + 'approval' => [ + 'title' => 'Viikon hyväksyntä', + 'unapproved' => 'Hyväksymättä :hours h.', + 'no_hours' => 'Viikolla ei ole tunteja.', + 'approved_by' => 'Hyväksytty :date (:name).', + 'approve_week' => 'Hyväksy viikko', + 'approve_week_of' => 'Hyväksy viikko: :name, :week', + 'approved' => ':week hyväksytty. Hyväksytyt tunnit on lukittu.', + 'approved_for' => ':name: :week hyväksytty.', + 'nothing_to_approve' => 'Viikolla ei ole hyväksymättömiä tunteja.', + 'management_approves' => 'Johto hyväksyy tuntisi.', + 'cancel' => 'Peru hyväksyntä', + 'cancel_title' => 'Perutaanko hyväksyntä?', + 'cancel_question' => 'Perutaanko viikon :week hyväksyntä? Tunteja voi sen jälkeen muuttaa, ja ne on hyväksyttävä uudelleen.', + 'cancelled' => ':week: hyväksyntä peruttu.', + 'cell_approved' => 'hyväksytty', + 'back_to_list' => 'Takaisin tuntien hyväksyntään', + ], + + 'approvals' => [ + 'title' => 'Tuntien hyväksyntä', + 'intro' => 'Työntekijät ja harjoittelijat hyväksyvät omat tuntinsa; johto hyväksyy alihankkijoiden tunnit ja voi hyväksyä kenen tahansa. Hyväksyntä lukitsee tunnit. Hyväksynnän voi perua viikon sivulla.', + 'pending' => 'Hyväksymättä', + 'approved' => 'Hyväksytyt (8 viikkoa)', + 'none_pending' => 'Kaikki tunnit on hyväksytty.', + 'none_approved' => 'Ei hyväksyttyjä tunteja.', + 'person' => 'Henkilö', + 'all_people' => 'Kaikki', + 'week' => 'Viikko', + 'hours' => 'Tunnit', + 'approver' => 'Hyväksyjä', + 'actions' => 'Toiminnot', + 'open_week' => 'Avaa viikko', + 'open_week_of' => 'Avaa viikko: :name, :week', + 'approver_value' => ':name, :date', ], ]; diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 85b616b..3e3939b 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -59,7 +59,7 @@ @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')]) + @include('partials.nav-item', ['route' => 'time.week', 'pattern' => ['time.week', 'time.task'], 'label' => __('layout.time')]) @include('partials.nav-item', ['route' => 'expenses.mine', 'pattern' => 'expenses.*', 'label' => __('layout.expenses')]) @@ -67,6 +67,10 @@ @include('partials.nav-item', ['route' => 'jobs.quick', 'pattern' => 'jobs.quick', 'label' => __('layout.quick_intake')]) @endcan + @can('time.approve-others') + @include('partials.nav-item', ['route' => 'time.approvals', 'pattern' => 'time.approvals', 'label' => __('layout.approvals')]) + @endcan + @can('customers.use') @include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')]) @endcan diff --git a/tests/Browser/TimeTrackingAccessibilityTest.php b/tests/Browser/TimeTrackingAccessibilityTest.php index 40a5803..3084fe1 100644 --- a/tests/Browser/TimeTrackingAccessibilityTest.php +++ b/tests/Browser/TimeTrackingAccessibilityTest.php @@ -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(); +}); diff --git a/tests/Fakes/FakeClock.php b/tests/Fakes/FakeClock.php index 463b5a2..4f85b87 100644 --- a/tests/Fakes/FakeClock.php +++ b/tests/Fakes/FakeClock.php @@ -13,4 +13,9 @@ class FakeClock implements Clock { return $this->today; } + + public function now(): DateTimeImmutable + { + return $this->today->setTime(12, 0); + } } diff --git a/tests/Fakes/InMemoryTimeEntryRepository.php b/tests/Fakes/InMemoryTimeEntryRepository.php index 70b0645..cf7a228 100644 --- a/tests/Fakes/InMemoryTimeEntryRepository.php +++ b/tests/Fakes/InMemoryTimeEntryRepository.php @@ -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()]); diff --git a/tests/Feature/Modules/TimeTracking/ApprovalTest.php b/tests/Feature/Modules/TimeTracking/ApprovalTest.php new file mode 100644 index 0000000..3c8213b --- /dev/null +++ b/tests/Feature/Modules/TimeTracking/ApprovalTest.php @@ -0,0 +1,126 @@ +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')); +}); diff --git a/tests/Unit/Modules/TimeTracking/ApprovalTest.php b/tests/Unit/Modules/TimeTracking/ApprovalTest.php new file mode 100644 index 0000000..88b34ef --- /dev/null +++ b/tests/Unit/Modules/TimeTracking/ApprovalTest.php @@ -0,0 +1,78 @@ +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'); +});