318 lines
12 KiB
PHP
318 lines
12 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\MissingBillingNote;
|
|
use App\Modules\TimeTracking\Application\DTOs\MonthSummary;
|
|
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
|
|
use App\Modules\TimeTracking\Application\DTOs\TimesheetCell;
|
|
use App\Modules\TimeTracking\Application\DTOs\TimesheetTaskRow;
|
|
use App\Modules\TimeTracking\Application\DTOs\TimesheetWeek;
|
|
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\Application\Services\TimesheetLayout;
|
|
use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository;
|
|
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
|
|
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,
|
|
private PinnedTaskRepository $pins,
|
|
private TimesheetLayout $layout,
|
|
) {}
|
|
|
|
public function timesheet(int $userId, string $monday): TimesheetWeek
|
|
{
|
|
$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();
|
|
$pinnedIds = $this->pins->pinnedTaskIds($userId);
|
|
$scheduledIds = $this->tasks->scheduledTaskIdsFor($userId, $days[0], $days[6]);
|
|
$taskIds = array_values(array_unique(array_merge(
|
|
$pinnedIds,
|
|
$scheduledIds,
|
|
$entries->pluck('task_id')->map(fn ($id): int => (int) $id)->all(),
|
|
)));
|
|
|
|
$cells = [];
|
|
foreach ($entries as $entry) {
|
|
$cells[$entry->task_id][$entry->worked_on->toDateString()] = new TimesheetCell(
|
|
$entry->quarters(),
|
|
$entry->note,
|
|
$entry->internal_comment,
|
|
$entry->billing_model === null ? null : EntryBillingModel::tryFrom($entry->billing_model),
|
|
$entry->approved_at !== null,
|
|
);
|
|
}
|
|
|
|
$rows = [];
|
|
$dayTotals = array_fill_keys($days, 0);
|
|
$missing = [];
|
|
|
|
foreach ($this->tasks->bookableTasks($taskIds) as $task) {
|
|
$taskCells = $cells[$task->taskId] ?? [];
|
|
$total = 0;
|
|
|
|
foreach ($taskCells as $day => $cell) {
|
|
$dayTotals[$day] += $cell->quarters;
|
|
$total += $cell->quarters;
|
|
|
|
if (! $cell->approved && ! $cell->hasBillingNote()) {
|
|
$missing[] = new MissingBillingNote($task->taskId, $day, $cell->quarters, $task->customerName, $task->jobNumber, $task->taskTitle);
|
|
}
|
|
}
|
|
|
|
$rows[] = new TimesheetTaskRow($task, $taskCells, $total, in_array($task->taskId, $pinnedIds, true));
|
|
}
|
|
|
|
usort($missing, fn (MissingBillingNote $a, MissingBillingNote $b): int => [$a->day, $a->jobNumber] <=> [$b->day, $b->jobNumber]);
|
|
|
|
$sections = $this->layout->arrange(
|
|
$rows,
|
|
$scheduledIds,
|
|
$this->quartersByJobs(array_values(array_unique(array_map(fn (TimesheetTaskRow $row): int => $row->task->jobId, $rows)))),
|
|
);
|
|
$unapproved = $entries->whereNull('approved_at')->sum(fn (TimeEntryModel $entry): int => $entry->quarters());
|
|
|
|
return new TimesheetWeek($days, $sections['scheduled'], $sections['pinned'], $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries), $missing);
|
|
}
|
|
|
|
public function monthSummary(int $userId, string $month): MonthSummary
|
|
{
|
|
$start = CarbonImmutable::createFromFormat('!Y-m', $month) ?: CarbonImmutable::now()->startOfMonth();
|
|
$entries = TimeEntryModel::query()
|
|
->where('user_id', $userId)
|
|
->whereBetween('worked_on', [$start->toDateString(), $start->endOfMonth()->toDateString()])
|
|
->get();
|
|
$paymentBases = [];
|
|
|
|
foreach ($this->tasks->bookableTasks($entries->pluck('task_id')->map(fn ($id): int => (int) $id)->unique()->values()->all()) as $task) {
|
|
$paymentBases[$task->taskId] = $task->paymentBasis;
|
|
}
|
|
|
|
$billable = 0;
|
|
$internal = 0;
|
|
|
|
foreach ($entries as $entry) {
|
|
$model = ($entry->billing_model === null ? null : EntryBillingModel::tryFrom($entry->billing_model))
|
|
?? EntryBillingModel::forPaymentBasis($paymentBases[$entry->task_id] ?? null);
|
|
|
|
if ($model->isBillable()) {
|
|
$billable += $entry->quarters();
|
|
} else {
|
|
$internal += $entry->quarters();
|
|
}
|
|
}
|
|
|
|
return new MonthSummary($start->format('Y-m'), $billable + $internal, $billable, $internal);
|
|
}
|
|
|
|
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'),
|
|
);
|
|
}
|
|
}
|