Files
Toiminnanohjaus/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php
T
petriandClaude Opus 5.5 97bd23bed5 Add the billing material with drafts, combined invoices and billed marks
Management builds the monthly billing material (laskuaineisto) as a
draft: done jobs are added as invoices of their own, combined when the
customer, billing unit and reference allow it, and their billable hours
are set per work type. Creating the material checks the jobs again,
marks the approved hours and billable expenses billed, forms invoice
lines with price and VAT snapshots and moves the jobs to "Lasku luotu".
Fixed price jobs bill their quoted amount once. Billed hours keep their
approval and billed expenses can no longer change. The Fennoa export
and monthly fee lines come later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 13:08:24 +02:00

186 lines
7.0 KiB
PHP

<?php
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\JobBillingHours;
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,
private UserAccountQueries $users,
) {}
public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet
{
$start = CarbonImmutable::parse($monday)->startOfWeek();
$days = [];
for ($i = 0; $i < 7; $i++) {
$days[] = $start->addDays($i)->toDateString();
}
$entries = TimeEntryModel::query()
->where('user_id', $userId)
->whereBetween('worked_on', [$days[0], $days[6]])
->get();
$taskIds = array_values(array_unique(array_merge(
$this->tasks->assignedOpenTaskIds($userId),
$entries->pluck('task_id')->map(fn ($id): int => (int) $id)->all(),
$extraTaskIds,
)));
$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 = [];
$dayTotals = array_fill_keys($days, 0);
foreach ($this->tasks->bookableTasks($taskIds) as $task) {
$quarters = $byTask[$task->taskId] ?? [];
foreach ($quarters as $day => $value) {
$dayTotals[$day] += $value;
}
$rows[] = new WeekRow($task, $quarters, array_sum($quarters), $approvedByTask[$task->taskId] ?? []);
}
$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 billingHours(array $jobIds): array
{
$approved = array_fill_keys($jobIds, []);
$unapproved = array_fill_keys($jobIds, 0);
if ($jobIds !== []) {
$entries = TimeEntryModel::query()
->whereIn('customer_job_id', $jobIds)
->whereNull('billing_export_id')
->get(['customer_job_id', 'work_type_id', 'hours', 'approved_at']);
foreach ($entries as $entry) {
if ($entry->approved_at === null) {
$unapproved[$entry->customer_job_id] += $entry->quarters();
} else {
$approved[$entry->customer_job_id][$entry->work_type_id] = ($approved[$entry->customer_job_id][$entry->work_type_id] ?? 0) + $entry->quarters();
}
}
}
$result = [];
foreach ($jobIds as $jobId) {
$result[$jobId] = new JobBillingHours($jobId, $approved[$jobId], $unapproved[$jobId]);
}
return $result;
}
public function entriesForTask(int $taskId, int $userId): array
{
return TimeEntryModel::query()
->where('task_id', $taskId)
->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, $model->approved_at !== null))
->values()
->all();
}
public function hasEntries(int $taskId): bool
{
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'),
);
}
}