Files
Toiminnanohjaus/app/Modules/TimeTracking/Infrastructure/Persistence/Repositories/EloquentTimeEntryQueries.php
T
petriandClaude Opus 5.5 f4b58f6b1d Darken the dark canvas, add customer colours, the ongoing status and the board model
- Dark theme page background is #5a5e60; text on it is lifted to zinc-200 /
  primary-100 and TallStackUI's dark labels, hints and checkbox labels are
  lightened so everything stays at 4.5:1.
- Shared HexColor picks white or black text by the higher WCAG contrast; a
  native-dialog colour picker and a large work dialog component.
- Customers get a header colour (customers.header_color), set on the
  customer page.
- New job status Jatkuvat / Kausi (ongoing): open, never late, billed
  monthly like running jobs.
- Kanban model: board columns and views, urgent threshold, per-user board
  preferences (density, column colours and sort), card positions, tasks of
  continuing jobs pinned to the board, MoveBoardCard and board queries with
  logged hours from TimeTracking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 06:11:49 +02:00

215 lines
7.7 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 quartersByJobs(array $jobIds): array
{
return $this->quartersBy('customer_job_id', $jobIds);
}
public function quartersByTasks(array $taskIds): array
{
return $this->quartersBy('task_id', $taskIds);
}
/**
* @param list<int> $ids
* @return array<int, int>
*/
private function quartersBy(string $column, array $ids): array
{
if ($ids === []) {
return [];
}
return TimeEntryModel::query()
->whereIn($column, $ids)
->groupBy($column)
->selectRaw("{$column} as id, sum(hours) as total")
->pluck('total', 'id')
->map(fn ($total): int => (int) round(((float) $total) * 4))
->all();
}
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'),
);
}
}