Kanban / timesheet update

This commit is contained in:
2026-11-30 06:56:14 +02:00
parent 6332ff0fa9
commit a4dbe8ce09
46 changed files with 8091 additions and 331 deletions
@@ -6,7 +6,9 @@ namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\DTOs\MonthSummary;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\TimesheetWeek;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
interface TimeEntryQueries
@@ -19,6 +21,19 @@ interface TimeEntryQueries
*/
public function week(int $userId, string $monday, array $extraTaskIds = []): WeekSheet;
/**
* The time sheet of a week: scheduled and pinned tasks with their
* entries, grouped by customer and job (docs/ui-timesheet.md 4).
*
* @param string $monday Y-m-d
*/
public function timesheet(int $userId, string $monday): TimesheetWeek;
/**
* The user's hours in a month (Y-m), billable against internal.
*/
public function monthSummary(int $userId, string $month): MonthSummary;
/**
* The user's entries on a task, newest day first.
*
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* An unapproved entry of the week without a billing note.
*/
final readonly class MissingBillingNote
{
public function __construct(
public int $taskId,
public string $day,
public int $quarters,
public string $customerName,
public string $jobNumber,
public string $taskTitle,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A user's hours in a month: in all, billable or within a fixed price, and
* internal (not billable), by each entry's laskutusperuste.
*/
final readonly class MonthSummary
{
public function __construct(
public string $month,
public int $totalQuarters,
public int $billableQuarters,
public int $internalQuarters,
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
/**
* The user's entry on one task and day of the time sheet.
*/
final readonly class TimesheetCell
{
public function __construct(
public int $quarters,
public ?string $billingNote,
public ?string $internalComment,
public ?EntryBillingModel $billingModel,
public bool $approved,
) {}
public function hasBillingNote(): bool
{
return $this->billingNote !== null && trim($this->billingNote) !== '';
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A customer on the time sheet (level 1), in its own colour, with its jobs.
*/
final readonly class TimesheetCustomerGroup
{
/**
* @param list<TimesheetJobGroup> $jobs
*/
public function __construct(
public int $customerId,
public string $name,
public ?string $headerColor,
public array $jobs,
) {}
public function taskCount(): int
{
return array_sum(array_map(fn (TimesheetJobGroup $job): int => count($job->rows), $this->jobs));
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
/**
* A customer job on the time sheet (level 2) with its task rows.
*/
final readonly class TimesheetJobGroup
{
/**
* @param list<TimesheetTaskRow> $rows
*/
public function __construct(
public int $jobId,
public string $number,
public string $name,
public JobStatus $status,
public ?string $paymentBasis,
public int $accumulatedQuarters,
public array $rows,
) {}
public function billingModel(): EntryBillingModel
{
return EntryBillingModel::forPaymentBasis($this->paymentBasis);
}
public function isContinuing(): bool
{
return $this->status === JobStatus::Ongoing;
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
/**
* A task row of the time sheet (level 3): its entries by day.
*/
final readonly class TimesheetTaskRow
{
/**
* @param array<string, TimesheetCell> $cells by Y-m-d
*/
public function __construct(
public BookableTask $task,
public array $cells,
public int $totalQuarters,
public bool $pinned,
) {}
public function cell(string $day): ?TimesheetCell
{
return $this->cells[$day] ?? null;
}
/**
* The laskutusperuste new entries get: from the job's payment basis.
*/
public function defaultBillingModel(): EntryBillingModel
{
return EntryBillingModel::forPaymentBasis($this->task->paymentBasis);
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* One user's time sheet for a week (docs/ui-timesheet.md 4): the
* "Aikataulutettu" part (tasks scheduled for the week and tasks with hours
* that are not pinned) and the "Lukitut työt" part (pinned tasks that can
* still take hours, or have hours this week), both grouped customer A–Ö →
* job → task.
*/
final readonly class TimesheetWeek
{
/**
* @param list<string> $days Y-m-d, Monday to Sunday
* @param list<TimesheetCustomerGroup> $scheduled
* @param list<TimesheetCustomerGroup> $pinned
* @param array<string, int> $dayTotals
* @param list<MissingBillingNote> $missingNotes
*/
public function __construct(
public array $days,
public array $scheduled,
public array $pinned,
public array $dayTotals,
public int $totalQuarters,
public int $unapprovedQuarters,
public ?WeekApproval $lastApproval,
public array $missingNotes,
) {}
public function isApproved(): bool
{
return $this->totalQuarters > 0 && $this->unapprovedQuarters === 0;
}
/**
* @return list<TimesheetTaskRow>
*/
public function rows(): array
{
$rows = [];
foreach ([...$this->scheduled, ...$this->pinned] as $customer) {
foreach ($customer->jobs as $job) {
foreach ($job->rows as $row) {
$rows[] = $row;
}
}
}
return $rows;
}
public function row(int $taskId): ?TimesheetTaskRow
{
foreach ($this->rows() as $row) {
if ($row->task->taskId === $taskId) {
return $row;
}
}
return null;
}
public function scheduledTaskCount(): int
{
return array_sum(array_map(fn (TimesheetCustomerGroup $customer): int => $customer->taskCount(), $this->scheduled));
}
public function pinnedTaskCount(): int
{
return array_sum(array_map(fn (TimesheetCustomerGroup $customer): int => $customer->taskCount(), $this->pinned));
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Services;
use App\Modules\TimeTracking\Application\DTOs\TimesheetCustomerGroup;
use App\Modules\TimeTracking\Application\DTOs\TimesheetJobGroup;
use App\Modules\TimeTracking\Application\DTOs\TimesheetTaskRow;
use Collator;
/**
* Splits a week's task rows into the time sheet's two parts and groups each
* customer A–Ö (Finnish order) → job by number → task by title
* (docs/ui-timesheet.md 4):
*
* - "Lukitut työt": pinned tasks that can still take hours, or have hours
* this week; a pin of a done or invoiced job or task thus lapses on later
* weeks but stays on the weeks with hours;
* - "Aikataulutettu": tasks scheduled for the week or with hours this week
* that are not in the pinned part.
*/
final class TimesheetLayout
{
/**
* @param list<TimesheetTaskRow> $rows every candidate row, pinned or not
* @param list<int> $scheduledTaskIds
* @param array<int, int> $accumulatedQuarters by job id
* @return array{scheduled: list<TimesheetCustomerGroup>, pinned: list<TimesheetCustomerGroup>}
*/
public function arrange(array $rows, array $scheduledTaskIds, array $accumulatedQuarters): array
{
$scheduled = [];
$pinned = [];
foreach ($rows as $row) {
$open = ! $row->task->isLocked() && $row->task->taskStatus->value !== 'done';
if ($row->pinned && ($open || $row->totalQuarters > 0)) {
$pinned[] = $row;
} elseif ($row->totalQuarters > 0 || ($open && in_array($row->task->taskId, $scheduledTaskIds, true))) {
$scheduled[] = $row;
}
}
return [
'scheduled' => $this->grouped($scheduled, $accumulatedQuarters),
'pinned' => $this->grouped($pinned, $accumulatedQuarters),
];
}
/**
* @param list<TimesheetTaskRow> $rows
* @param array<int, int> $accumulatedQuarters
* @return list<TimesheetCustomerGroup>
*/
private function grouped(array $rows, array $accumulatedQuarters): array
{
$collator = class_exists(Collator::class) ? new Collator('fi_FI') : null;
$compare = fn (string $a, string $b): int => $collator?->compare($a, $b) ?: strcmp(mb_strtolower($a), mb_strtolower($b));
usort($rows, fn (TimesheetTaskRow $a, TimesheetTaskRow $b): int => $compare($a->task->customerName, $b->task->customerName)
?: ($a->task->customerId <=> $b->task->customerId)
?: strnatcmp($a->task->jobNumber, $b->task->jobNumber)
?: $compare($a->task->taskTitle, $b->task->taskTitle)
?: ($a->task->taskId <=> $b->task->taskId));
$customers = [];
foreach ($rows as $row) {
$customers[$row->task->customerId]['name'] = $row->task->customerName;
$customers[$row->task->customerId]['color'] = $row->task->customerHeaderColor;
$customers[$row->task->customerId]['jobs'][$row->task->jobId][] = $row;
}
$groups = [];
foreach ($customers as $customerId => $customer) {
$jobs = [];
foreach ($customer['jobs'] as $jobId => $jobRows) {
$task = $jobRows[0]->task;
$jobs[] = new TimesheetJobGroup($jobId, $task->jobNumber, $task->jobName, $task->jobStatus, $task->paymentBasis, $accumulatedQuarters[$jobId] ?? 0, $jobRows);
}
$groups[] = new TimesheetCustomerGroup($customerId, $customer['name'], $customer['color'], $jobs);
}
return $groups;
}
}
@@ -7,6 +7,7 @@ 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;
/**
@@ -24,6 +25,8 @@ final class ApproveWeek
/**
* @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
{
@@ -32,8 +35,20 @@ final class ApproveWeek
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 ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
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;
}
@@ -0,0 +1,40 @@
<?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\Enums\EntryBillingModel;
use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved;
use App\Modules\TimeTracking\Domain\Exceptions\TimeEntryNotFound;
/**
* "Muokkaa kirjausta" on the time sheet: the laskutusperuste, billing note
* and internal comment of the user's entry on a task and day.
*/
final class DescribeTimeEntry
{
public function __construct(
private TimeEntryRepository $entries,
private TransactionManager $transactions,
) {}
/**
* @throws TimeEntryNotFound
* @throws TimeApproved
*/
public function execute(int $userId, int $taskId, string $day, ?EntryBillingModel $billingModel, ?string $billingNote, ?string $internalComment): void
{
$date = TimeBooking::day($day);
$this->transactions->run(function () use ($userId, $taskId, $date, $billingModel, $billingNote, $internalComment): void {
$entry = $this->entries->findForDay($userId, $taskId, $date) ?? throw new TimeEntryNotFound(0);
$entry->describe($billingModel, $billingNote, $internalComment);
$this->entries->save($entry);
});
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository;
use App\Modules\TimeTracking\Domain\Exceptions\TaskNotBookable;
use App\Modules\TimeTracking\Domain\Exceptions\TimeLocked;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Pins tasks to the "Lukitut työt" part of a user's time sheet (★), or
* unpins them. Only tasks that can take hours (open task of an unlocked
* job) can be pinned; unpinning always works.
*/
final class PinTimesheetTasks
{
public function __construct(
private PinnedTaskRepository $pins,
private TaskQueries $tasks,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @param list<int> $taskIds
*
* @throws TaskNotBookable
* @throws TimeLocked
*/
public function pin(int $userId, array $taskIds): void
{
$now = $this->clock->now();
$this->transactions->run(function () use ($userId, $taskIds, $now): void {
foreach ($taskIds as $taskId) {
$task = $this->tasks->bookableTask($taskId) ?? throw new TaskNotBookable($taskId);
if ($task->isLocked()) {
throw new TimeLocked;
}
$this->pins->pin($userId, $taskId, $now);
}
});
}
public function unpin(int $userId, int $taskId): void
{
$this->transactions->run(fn () => $this->pins->unpin($userId, $taskId));
}
/**
* "Poista kaikki kiinnitykset".
*/
public function unpinAll(int $userId): int
{
return $this->transactions->run(fn (): int => $this->pins->unpinAll($userId));
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Contracts;
use DateTimeImmutable;
/**
* Tasks each user has pinned to the "Lukitut työt" part of their time sheet.
*/
interface PinnedTaskRepository
{
public function pin(int $userId, int $taskId, DateTimeImmutable $at): void;
public function unpin(int $userId, int $taskId): void;
/**
* @return int how many pins were removed
*/
public function unpinAll(int $userId): int;
/**
* @return list<int>
*/
public function pinnedTaskIds(int $userId): array;
}
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Entities;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
use App\Modules\TimeTracking\Domain\Exceptions\TimeApproved;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use DateTimeImmutable;
@@ -28,6 +29,8 @@ final class TimeEntry
private ?int $approvedBy = null,
private ?DateTimeImmutable $approvedAt = null,
private ?int $billingExportId = null,
private ?EntryBillingModel $billingModel = null,
private ?string $internalComment = null,
) {}
public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self
@@ -35,9 +38,39 @@ 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, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null): 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, ?int $billingExportId = null, ?EntryBillingModel $billingModel = null, ?string $internalComment = null): self
{
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId);
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId, $billingModel, $internalComment);
}
/**
* The entry's laskutusperuste, billing note (shown to the customer or in
* fixed-price follow-up, required before the week is approved) and
* internal comment. A null billing model follows the job.
*
* @throws TimeApproved
*/
public function describe(?EntryBillingModel $billingModel, ?string $billingNote, ?string $internalComment): void
{
$this->ensureNotApproved();
$this->billingModel = $billingModel;
$this->note = self::text($billingNote);
$this->internalComment = self::text($internalComment);
}
public function hasBillingNote(): bool
{
return $this->note !== null;
}
public function billingModel(): ?EntryBillingModel
{
return $this->billingModel;
}
public function internalComment(): ?string
{
return $this->internalComment;
}
/**
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Enums;
/**
* Laskutusperuste of a time entry (docs/ui-timesheet.md 5.2): within a
* fixed price (K), billed by the hour (€) or not billable (•). It is
* tracking only: billing still follows the job's payment basis.
*/
enum EntryBillingModel: string
{
case Fixed = 'fixed';
case Hourly = 'hourly';
case NonBillable = 'non_billable';
/**
* The default of an entry, from its job's payment basis (a Jobs
* PaymentBasis value).
*/
public static function forPaymentBasis(?string $paymentBasis): self
{
return match ($paymentBasis) {
'fixed_quote', 'price_list', 'monthly_fee' => self::Fixed,
'not_billable' => self::NonBillable,
default => self::Hourly,
};
}
public function symbol(): string
{
return match ($this) {
self::Fixed => 'K',
self::Hourly => '€',
self::NonBillable => '•',
};
}
/**
* Billed or within a fixed price, against internal work.
*/
public function isBillable(): bool
{
return $this !== self::NonBillable;
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A week cannot be approved while any of its entries lacks a billing note
* (docs/ui-timesheet.md 6).
*/
final class BillingNotesMissing extends DomainException
{
/**
* @param list<int> $entryIds
*/
public function __construct(public readonly array $entryIds)
{
parent::__construct(count($entryIds).' time entries have no billing note.');
}
}
@@ -51,6 +51,47 @@ final readonly class WorkedHours
return new self((int) round($quarters));
}
/**
* Parses what the time sheet's cell accepts (docs/ui-timesheet.md 5.1):
* "1:30" (hours and minutes), "1,5" or "1.5" (hours), a whole number up
* to 24 as hours ("2") and above it as minutes ("90"). Null for an empty
* value or zero. Always whole quarter hours.
*
* @throws InvalidWorkedHours
*/
public static function parseFlexible(string $value): ?self
{
$value = trim($value);
if ($value === '' || preg_match('/^0+([:.,]0+)?$/', $value) === 1) {
return null;
}
if (preg_match('/^(\d{1,2}):([0-5]\d)$/', $value, $matches) === 1) {
$minutes = (int) $matches[1] * 60 + (int) $matches[2];
} elseif (preg_match('/^\d+$/', $value) === 1 && (int) $value > 24) {
$minutes = (int) $value;
} else {
return self::parse($value);
}
if ($minutes % 15 !== 0) {
throw new InvalidWorkedHours;
}
return new self(intdiv($minutes, 15));
}
/**
* Hours and minutes, "1:30" or "0:00".
*/
public static function formatClock(int $quarters): string
{
$minutes = $quarters * 15;
return intdiv($minutes, 60).':'.str_pad((string) ($minutes % 60), 2, '0', STR_PAD_LEFT);
}
public static function fromDecimal(float $hours): self
{
return new self((int) round($hours * 4));
@@ -22,9 +22,11 @@ use Illuminate\Database\Eloquent\Model;
* @property CarbonImmutable|null $approved_at
* @property int|null $approved_by
* @property int|null $billing_export_id
* @property string|null $billing_model EntryBillingModel value; null follows the job
* @property string|null $internal_comment
*/
#[Table('time_entries')]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id'])]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id', 'billing_model', 'internal_comment'])]
#[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model
{
@@ -0,0 +1,39 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
class EloquentPinnedTaskRepository implements PinnedTaskRepository
{
public function pin(int $userId, int $taskId, DateTimeImmutable $at): void
{
DB::table('time_pinned_tasks')->insertOrIgnore([
'user_id' => $userId,
'task_id' => $taskId,
'pinned_at' => $at->format('Y-m-d H:i:s'),
]);
}
public function unpin(int $userId, int $taskId): void
{
DB::table('time_pinned_tasks')->where('user_id', $userId)->where('task_id', $taskId)->delete();
}
public function unpinAll(int $userId): int
{
return DB::table('time_pinned_tasks')->where('user_id', $userId)->delete();
}
public function pinnedTaskIds(int $userId): array
{
return DB::table('time_pinned_tasks')
->where('user_id', $userId)
->orderBy('pinned_at')
->pluck('task_id')
->map(fn ($id): int => (int) $id)
->all();
}
}
@@ -6,10 +6,18 @@ 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;
@@ -20,8 +28,103 @@ 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();
@@ -4,6 +4,7 @@ namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Domain\Entities\TimeEntry;
use App\Modules\TimeTracking\Domain\Enums\EntryBillingModel;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
use DateTimeImmutable;
@@ -40,6 +41,8 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
'worked_on' => $entry->workedOn()->format('Y-m-d'),
'hours' => $entry->hours()->decimal(),
'note' => $entry->note(),
'billing_model' => $entry->billingModel()?->value,
'internal_comment' => $entry->internalComment(),
'approved_by' => $entry->approvedBy(),
'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'),
'billing_export_id' => $entry->billingExportId(),
@@ -102,6 +105,8 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
$model->approved_by,
$model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at),
$model->billing_export_id,
$model->billing_model === null ? null : EntryBillingModel::tryFrom($model->billing_model),
$model->internal_comment,
);
}
}
@@ -8,8 +8,10 @@ use App\Modules\Jobs\Application\Contracts\LoggedJobHours;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\Contracts\TimeReportQueries;
use App\Modules\TimeTracking\Domain\Contracts\PinnedTaskRepository;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\LoggedHoursFromTimeEntries;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentPinnedTaskRepository;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryQueries;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeReportQueries;
@@ -29,6 +31,7 @@ class TimeTrackingServiceProvider extends ServiceProvider
*/
public array $bindings = [
TimeEntryRepository::class => EloquentTimeEntryRepository::class,
PinnedTaskRepository::class => EloquentPinnedTaskRepository::class,
TimeEntryQueries::class => EloquentTimeEntryQueries::class,
TimeReportQueries::class => EloquentTimeReportQueries::class,
TaskUsage::class => TaskUsageFromTimeEntries::class,
@@ -3,6 +3,7 @@
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\Exceptions\BillingNotesMissing;
use App\Modules\TimeTracking\Domain\ValueObjects\WorkedHours;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
@@ -68,7 +69,14 @@ new class extends Component
return;
}
$approveWeek->execute($userId, $monday, (int) auth()->id());
try {
$approveWeek->execute($userId, $monday, (int) auth()->id());
} catch (BillingNotesMissing $exception) {
$this->statusMessage = __('time.approvals.notes_missing', ['name' => $week->userName, 'week' => $this->weekLabel($monday), 'count' => count($exception->entryIds)]);
return;
}
unset($this->pending, $this->approved);
$this->statusMessage = __('time.approval.approved_for', ['name' => $week->userName, 'week' => $this->weekLabel($monday)]);
File diff suppressed because it is too large Load Diff