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