Files
2026-11-30 06:56:14 +02:00

65 lines
2.0 KiB
PHP

<?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\TimeTracking\Domain\Exceptions\BillingNotesMissing;
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.
*
* @throws BillingNotesMissing when an unapproved entry has no billing note
*/
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;
$entries = $this->entries->forUserBetween($userId, $start, $start->modify('+6 days'));
$missing = [];
foreach ($entries as $entry) {
if (! $entry->isApproved() && ! $entry->hasBillingNote()) {
$missing[] = (int) $entry->id();
}
}
if ($missing !== []) {
throw new BillingNotesMissing($missing);
}
foreach ($entries as $entry) {
if ($entry->isApproved()) {
continue;
}
$entry->approve($approverId, $now);
$this->entries->save($entry);
$approved++;
}
return $approved;
});
}
}