Replace the demo home page with a dashboard

Everyone sees their open tasks on an agenda, their open jobs, this
week's hours and quick links. Admin and management also get a lazily
loaded management panel: things to do, the month so far against the
previous month, jobs and late work, and everyone's workload.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-25 09:20:02 +02:00
co-authored by Claude Sonnet 5.5
parent d4251d00d7
commit 487a7d34ba
46 changed files with 2032 additions and 62 deletions
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts;
/**
* What the management panel needs from Billing, Sales, Users and the
* holiday calendar. Days are Y-m-d.
*/
interface DashboardAdmin
{
/**
* The billing material draft being prepared, if there is one.
*/
public function openDraftId(): ?int;
/**
* Days before the day with quick sales whose cash day is not closed.
*
* @return list<string>
*/
public function unclosedCashDaysBefore(string $day): array;
/**
* Active users who do the work, subcontractors left out, by name.
*
* @return array<int, string>
*/
public function staff(): array;
/**
* Public holidays in use and company days off between the days.
*
* @return list<string>
*/
public function holidaysBetween(string $from, string $to): array;
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts;
use App\Modules\Dashboard\Application\DTOs\PeriodFigures;
/**
* Key figures from the Reports module.
*/
interface DashboardFigures
{
/**
* Figures of the days from the first to the last (Y-m-d).
*/
public function between(string $from, string $to): PeriodFigures;
/**
* The value (VAT 0, cents) of the hours not billed yet, worked on or
* before the day.
*/
public function unbilledValueCents(string $day): int;
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts;
use App\Modules\Dashboard\Application\DTOs\PendingApproval;
use App\Modules\Dashboard\Application\DTOs\WeekHours;
/**
* Recorded hours, from the TimeTracking module.
*/
interface DashboardTime
{
/**
* The user's hours in the week starting on the Monday (Y-m-d).
*/
public function week(int $userId, string $monday): WeekHours;
/**
* Everyone's hours waiting for approval, by person (by name).
*
* @return list<PendingApproval>
*/
public function pendingApprovals(): array;
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\Contracts;
use App\Modules\Dashboard\Application\DTOs\WorkJob;
use App\Modules\Dashboard\Application\DTOs\WorkTask;
/**
* Jobs, tasks and their bookings, from the Jobs module. Days are Y-m-d;
* lateness is decided by the Dashboard, so isLate is false here.
*/
interface DashboardWork
{
/**
* @return list<WorkTask>
*/
public function openTasksOf(int $userId): array;
/**
* @return list<WorkJob>
*/
public function openJobsOf(int $userId): array;
/**
* @return array<string, int> Kanban status key => jobs.
*/
public function jobCountsByStatus(): array;
public function overdueJobCount(string $today): int;
public function overdueTaskCount(string $today): int;
/**
* @return list<WorkTask>
*/
public function oldestOverdueTasks(string $today, int $limit): array;
/**
* The daily maximum a person's tasks may book, in minutes.
*/
public function dailyCapacityMinutes(): int;
/**
* Minutes the open tasks book per person in the days.
*
* @param list<int> $userIds
* @return array<int, int>
*/
public function bookedMinutes(array $userIds, string $from, string $to): array;
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* The management panel of the home page on a day:
*
* - to do: hours waiting for approval by person, done jobs waiting for
* billing, the open billing draft, unclosed cash days and the value of
* unbilled hours;
* - this month so far against the same days of the previous month;
* - the jobs by status, late jobs and late tasks (the oldest of them);
* - everyone's workload this week and next (Mondays given).
*/
final readonly class ManagementOverview
{
/**
* @param list<PendingApproval> $pendingApprovals
* @param list<string> $unclosedCashDays
* @param array<string, int> $jobCounts
* @param list<WorkTask> $oldestOverdueTasks
* @param list<PersonLoad> $workloads
*/
public function __construct(
public array $pendingApprovals,
public int $doneJobCount,
public ?int $draftExportId,
public array $unclosedCashDays,
public int $unbilledValueCents,
public string $monthFrom,
public string $monthTo,
public string $previousFrom,
public string $previousTo,
public PeriodFigures $month,
public PeriodFigures $previousMonth,
public array $jobCounts,
public int $overdueJobCount,
public int $overdueTaskCount,
public array $oldestOverdueTasks,
public string $thisMonday,
public string $nextMonday,
public array $workloads,
) {}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* A person's hours waiting for approval, in quarter hours, over some weeks.
*/
final readonly class PendingApproval
{
public function __construct(
public int $userId,
public string $name,
public int $quarters,
public int $weekCount,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* Key figures of a period: hours on customers' and internal jobs (quarter
* hours), billed by the created billing materials of its months (work and
* expenses, VAT 0), the margin (null without an internal hourly cost) and
* quick sales (with VAT). Cents.
*/
final readonly class PeriodFigures
{
public function __construct(
public int $customerQuarters,
public int $internalQuarters,
public int $billedCents,
public ?int $marginCents,
public int $salesCents,
) {}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
use App\Modules\Dashboard\Domain\ValueObjects\Workload;
/**
* A person's workload this week and next week.
*/
final readonly class PersonLoad
{
public function __construct(
public int $userId,
public string $name,
public Workload $thisWeek,
public Workload $nextWeek,
) {}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* What the home page shows everyone: their open tasks on an agenda (late,
* today or tomorrow, later this week, and how many later), their first
* open jobs and how many there are, and their hours this week.
*/
final readonly class PersonalOverview
{
/**
* @param list<WorkTask> $overdue
* @param list<WorkTask> $soon
* @param list<WorkTask> $thisWeek
* @param list<WorkJob> $jobs
*/
public function __construct(
public array $overdue,
public array $soon,
public array $thisWeek,
public int $laterCount,
public array $jobs,
public int $jobCount,
public WeekHours $week,
) {}
public function hasTasks(): bool
{
return $this->overdue !== [] || $this->soon !== [] || $this->thisWeek !== [] || $this->laterCount > 0;
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* A user's hours in a week, in quarter hours: each day (Y-m-d, Monday to
* Sunday), the total and those waiting for approval.
*/
final readonly class WeekHours
{
/**
* @param array<string, int> $days
*/
public function __construct(
public string $monday,
public array $days,
public int $totalQuarters,
public int $unapprovedQuarters,
) {}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* An open customer job on the home page. Status and priority are the Jobs
* module's keys; the due date is Y-m-d.
*/
final readonly class WorkJob
{
public function __construct(
public int $id,
public string $number,
public string $name,
public string $customerName,
public string $status,
public string $priority,
public ?string $dueOn,
public bool $isLate = false,
) {}
public function late(): self
{
return new self($this->id, $this->number, $this->name, $this->customerName, $this->status, $this->priority, $this->dueOn, true);
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\DTOs;
/**
* An open task on the home page. The status is the Jobs module's task
* status key; days are Y-m-d.
*/
final readonly class WorkTask
{
public function __construct(
public int $taskId,
public int $jobId,
public string $jobNumber,
public string $jobName,
public string $title,
public string $status,
public ?string $dueOn,
public ?string $plannedFrom,
public ?string $plannedTo,
public ?string $assigneeName,
public bool $isLate = false,
) {}
public function late(): self
{
return new self($this->taskId, $this->jobId, $this->jobNumber, $this->jobName, $this->title, $this->status, $this->dueOn, $this->plannedFrom, $this->plannedTo, $this->assigneeName, true);
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\UseCases;
use App\Modules\Dashboard\Application\Contracts\DashboardAdmin;
use App\Modules\Dashboard\Application\Contracts\DashboardFigures;
use App\Modules\Dashboard\Application\Contracts\DashboardTime;
use App\Modules\Dashboard\Application\Contracts\DashboardWork;
use App\Modules\Dashboard\Application\DTOs\ManagementOverview;
use App\Modules\Dashboard\Application\DTOs\PersonLoad;
use App\Modules\Dashboard\Application\DTOs\WorkTask;
use App\Modules\Dashboard\Domain\ValueObjects\Workload;
use DateTimeImmutable;
/**
* The management panel of the home page for admin and management on a day.
* The month so far is compared with the same days of the previous month
* (to its end when it is shorter).
*/
final readonly class ManagementOverviewQuery
{
public const int OVERDUE_TASK_LIMIT = 5;
public function __construct(
private DashboardWork $work,
private DashboardTime $time,
private DashboardAdmin $admin,
private DashboardFigures $figures,
) {}
public function execute(DateTimeImmutable $today): ManagementOverview
{
$day = $today->format('Y-m-d');
$monthFrom = $today->format('Y-m-01');
$previousStart = $today->modify('first day of previous month');
$previousFrom = $previousStart->format('Y-m-d');
$previousTo = $previousStart->format('Y-m-').sprintf('%02d', min((int) $today->format('j'), (int) $previousStart->format('t')));
$jobCounts = $this->work->jobCountsByStatus();
$thisMonday = $today->modify('monday this week');
$nextMonday = $thisMonday->modify('+7 days');
return new ManagementOverview(
$this->time->pendingApprovals(),
$jobCounts['done'] ?? 0,
$this->admin->openDraftId(),
$this->admin->unclosedCashDaysBefore($day),
$this->figures->unbilledValueCents($day),
$monthFrom,
$day,
$previousFrom,
$previousTo,
$this->figures->between($monthFrom, $day),
$this->figures->between($previousFrom, $previousTo),
$jobCounts,
$this->work->overdueJobCount($day),
$this->work->overdueTaskCount($day),
array_map(fn (WorkTask $task): WorkTask => $task->late(), $this->work->oldestOverdueTasks($day, self::OVERDUE_TASK_LIMIT)),
$thisMonday->format('Y-m-d'),
$nextMonday->format('Y-m-d'),
$this->workloads($thisMonday, $nextMonday),
);
}
/**
* @return list<PersonLoad>
*/
private function workloads(DateTimeImmutable $thisMonday, DateTimeImmutable $nextMonday): array
{
$staff = $this->admin->staff();
$daily = $this->work->dailyCapacityMinutes();
$weeks = [];
foreach ([$thisMonday, $nextMonday] as $monday) {
$from = $monday->format('Y-m-d');
$to = $monday->modify('+6 days')->format('Y-m-d');
$weeks[] = [
'booked' => $this->work->bookedMinutes(array_keys($staff), $from, $to),
'days' => Workload::workingDays($from, $to, $this->admin->holidaysBetween($from, $to)),
];
}
$result = [];
foreach ($staff as $userId => $name) {
$result[] = new PersonLoad(
$userId,
$name,
Workload::of($weeks[0]['booked'][$userId] ?? 0, $daily, $weeks[0]['days']),
Workload::of($weeks[1]['booked'][$userId] ?? 0, $daily, $weeks[1]['days']),
);
}
return $result;
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Application\UseCases;
use App\Modules\Dashboard\Application\Contracts\DashboardTime;
use App\Modules\Dashboard\Application\Contracts\DashboardWork;
use App\Modules\Dashboard\Application\DTOs\PersonalOverview;
use App\Modules\Dashboard\Application\DTOs\WorkJob;
use App\Modules\Dashboard\Domain\Enums\AgendaBucket;
use DateTimeImmutable;
/**
* The user's own part of the home page on a day: open tasks they are the
* assignee or a member of, their open jobs (5.6) and this week's hours.
*/
final readonly class PersonalOverviewQuery
{
public const int JOB_LIMIT = 10;
public function __construct(
private DashboardWork $work,
private DashboardTime $time,
) {}
public function execute(int $userId, DateTimeImmutable $today): PersonalOverview
{
$day = $today->format('Y-m-d');
$tomorrow = $today->modify('+1 day')->format('Y-m-d');
$monday = $today->modify('monday this week');
$sunday = $monday->modify('+6 days')->format('Y-m-d');
$buckets = ['overdue' => [], 'soon' => [], 'this_week' => [], 'later' => []];
foreach ($this->work->openTasksOf($userId) as $task) {
$bucket = AgendaBucket::of($task->dueOn, $task->plannedFrom, $day, $tomorrow, $sunday);
$buckets[$bucket->value][] = $bucket === AgendaBucket::Overdue ? $task->late() : $task;
}
$jobs = array_map(
fn (WorkJob $job): WorkJob => $job->dueOn !== null && $job->dueOn < $day ? $job->late() : $job,
$this->work->openJobsOf($userId),
);
return new PersonalOverview(
$buckets['overdue'],
$buckets['soon'],
$buckets['this_week'],
count($buckets['later']),
array_slice($jobs, 0, self::JOB_LIMIT),
count($jobs),
$this->time->week($userId, $monday->format('Y-m-d')),
);
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Domain\Enums;
/**
* Where an open task falls on the home page's agenda: late (due before
* today), today or tomorrow (due, starting or under way by tomorrow), later
* this week, or later still.
*/
enum AgendaBucket: string
{
case Overdue = 'overdue';
case Soon = 'soon';
case ThisWeek = 'this_week';
case Later = 'later';
/**
* Days are Y-m-d. A task with no dates is "later".
*/
public static function of(?string $dueOn, ?string $plannedFrom, string $today, string $tomorrow, string $weekEnd): self
{
if ($dueOn !== null && $dueOn < $today) {
return self::Overdue;
}
$nearest = min(array_filter([$dueOn, $plannedFrom]) ?: ['9999-12-31']);
return match (true) {
$nearest <= $tomorrow => self::Soon,
$nearest <= $weekEnd => self::ThisWeek,
default => self::Later,
};
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Domain\ValueObjects;
/**
* How a figure changed from the comparison period: the ratio of the
* difference to the earlier value, or null when there was nothing to
* compare with (the earlier value was zero).
*/
final readonly class Change
{
public function __construct(
public int $current,
public int $previous,
) {}
public function ratio(): ?float
{
return $this->previous === 0 ? null : ($this->current - $this->previous) / abs($this->previous);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Modules\Dashboard\Domain\ValueObjects;
/**
* A person's booked work in a week against what they can do in it: the
* daily maximum on each working day (weekends, public holidays and company
* days off excluded). Minutes.
*/
final readonly class Workload
{
public function __construct(
public int $bookedMinutes,
public int $capacityMinutes,
) {}
public static function of(int $bookedMinutes, int $dailyCapacityMinutes, int $workingDays): self
{
return new self($bookedMinutes, $dailyCapacityMinutes * $workingDays);
}
/**
* Booked work as a share of the capacity, null without working days.
*/
public function ratio(): ?float
{
return $this->capacityMinutes === 0 ? null : $this->bookedMinutes / $this->capacityMinutes;
}
public function isOverloaded(): bool
{
return $this->bookedMinutes > $this->capacityMinutes;
}
/**
* Weekdays (Monday to Friday) between the days (Y-m-d, both included)
* that are not among the holidays.
*
* @param list<string> $holidays
*/
public static function workingDays(string $from, string $to, array $holidays): int
{
$days = 0;
for ($day = new \DateTimeImmutable($from); $day->format('Y-m-d') <= $to; $day = $day->modify('+1 day')) {
if ((int) $day->format('N') <= 5 && ! in_array($day->format('Y-m-d'), $holidays, true)) {
$days++;
}
}
return $days;
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Dashboard\Application\Contracts\DashboardAdmin;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
/**
* Billing drafts, cash days, people and holidays for the management panel
* through the Billing, Sales, Users and Shared modules.
*/
class AdminForDashboard implements DashboardAdmin
{
public function __construct(
private BillingQueries $billing,
private QuickSaleQueries $sales,
private UserAccountQueries $users,
private HolidayCalendar $holidays,
) {}
public function openDraftId(): ?int
{
foreach ($this->billing->exports() as $export) {
if ($export->status === ExportStatus::Draft) {
return $export->id;
}
}
return null;
}
public function unclosedCashDaysBefore(string $day): array
{
return $this->sales->unclosedDaysBefore($day);
}
public function staff(): array
{
$staff = [];
foreach ($this->users->activeUserOptions() as $user) {
if ($user->role !== Role::Subcontractor) {
$staff[$user->id] = $user->name;
}
}
return $staff;
}
public function holidaysBetween(string $from, string $to): array
{
return $this->holidays->activeDatesBetween($from, $to);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Dashboard\Application\Contracts\DashboardFigures;
use App\Modules\Dashboard\Application\DTOs\PeriodFigures;
use App\Modules\Reports\Application\UseCases\HoursByPerson;
use App\Modules\Reports\Application\UseCases\ProfitabilityByJob;
use App\Modules\Reports\Application\UseCases\QuickSalesReport;
use App\Modules\Reports\Application\UseCases\UnbilledHoursReport;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Key figures through the Reports module's reports, so the panel shows the
* same numbers as the reports.
*/
class FiguresForDashboard implements DashboardFigures
{
public function __construct(
private HoursByPerson $hours,
private ProfitabilityByJob $profitability,
private QuickSalesReport $sales,
private UnbilledHoursReport $unbilled,
) {}
public function between(string $from, string $to): PeriodFigures
{
$period = new ReportPeriod($from, $to);
$hours = $this->hours->execute($period)->total;
$profit = $this->profitability->execute($period)->total;
return new PeriodFigures(
$hours->customerQuarters,
$hours->internalQuarters,
$profit->revenueCents(),
$profit->marginCents(),
$this->sales->execute($period)->totalCents(),
);
}
public function unbilledValueCents(string $day): int
{
return $this->unbilled->execute($day)->valueCents;
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Dashboard\Application\Contracts\DashboardTime;
use App\Modules\Dashboard\Application\DTOs\PendingApproval;
use App\Modules\Dashboard\Application\DTOs\WeekHours;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
/**
* Hours for the home page through the TimeTracking module.
*/
class TimeForDashboard implements DashboardTime
{
public function __construct(private TimeEntryQueries $entries) {}
public function week(int $userId, string $monday): WeekHours
{
$sheet = $this->entries->week($userId, $monday);
return new WeekHours($monday, $sheet->dayTotals, $sheet->totalQuarters, $sheet->unapprovedQuarters);
}
public function pendingApprovals(): array
{
$people = [];
foreach ($this->entries->pendingWeeks() as $week) {
$current = $people[$week->userId] ?? new PendingApproval($week->userId, $week->userName, 0, 0);
$people[$week->userId] = new PendingApproval($week->userId, $week->userName, $current->quarters + $week->quarters, $current->weekCount + 1);
}
$people = array_values($people);
usort($people, fn (PendingApproval $a, PendingApproval $b): int => strnatcasecmp($a->name, $b->name));
return $people;
}
}
@@ -0,0 +1,88 @@
<?php
namespace App\Modules\Dashboard\Infrastructure\Adapters;
use App\Modules\Dashboard\Application\Contracts\DashboardWork;
use App\Modules\Dashboard\Application\DTOs\WorkJob;
use App\Modules\Dashboard\Application\DTOs\WorkTask;
use App\Modules\Jobs\Application\Contracts\JobOverviewQueries;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\OpenTask;
use App\Modules\Jobs\Application\Services\TaskPlanner;
/**
* Jobs, tasks and bookings for the home page through the Jobs module.
*/
class WorkForDashboard implements DashboardWork
{
public function __construct(
private JobOverviewQueries $overview,
private TaskCalendarQueries $calendar,
private TaskPlanner $planner,
) {}
public function openTasksOf(int $userId): array
{
return array_map(self::task(...), $this->overview->openTasksOf($userId));
}
public function openJobsOf(int $userId): array
{
return array_map(fn (CustomerJobSummary $job): WorkJob => new WorkJob(
$job->id,
$job->number,
$job->name,
$job->customerName,
$job->status->value,
$job->priority->value,
$job->dueOn,
), $this->overview->openJobsOf($userId));
}
public function jobCountsByStatus(): array
{
return $this->overview->jobCountsByStatus();
}
public function overdueJobCount(string $today): int
{
return $this->overview->overdueJobCount($today);
}
public function overdueTaskCount(string $today): int
{
return $this->overview->overdueTaskCount($today);
}
public function oldestOverdueTasks(string $today, int $limit): array
{
return array_map(self::task(...), $this->overview->oldestOverdueTasks($today, $limit));
}
public function dailyCapacityMinutes(): int
{
return $this->planner->capacityMinutes();
}
public function bookedMinutes(array $userIds, string $from, string $to): array
{
return array_map(fn (array $days): int => array_sum($days), $this->calendar->openMinutesByUser($userIds, $from, $to));
}
private static function task(OpenTask $task): WorkTask
{
return new WorkTask(
$task->taskId,
$task->jobId,
$task->jobNumber,
$task->jobName,
$task->title,
$task->status->value,
$task->dueOn,
$task->plannedFrom,
$task->plannedTo,
$task->assigneeName,
);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Modules\Dashboard\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Dashboard\Application\Contracts\DashboardAdmin;
use App\Modules\Dashboard\Application\Contracts\DashboardFigures;
use App\Modules\Dashboard\Application\Contracts\DashboardTime;
use App\Modules\Dashboard\Application\Contracts\DashboardWork;
use App\Modules\Dashboard\Infrastructure\Adapters\AdminForDashboard;
use App\Modules\Dashboard\Infrastructure\Adapters\FiguresForDashboard;
use App\Modules\Dashboard\Infrastructure\Adapters\TimeForDashboard;
use App\Modules\Dashboard\Infrastructure\Adapters\WorkForDashboard;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Dashboard module (the home page) into Laravel: the ports to
* the other modules, the home route, the `dashboard::` Livewire namespace
* and the `dashboard.management` ability.
*/
class DashboardServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
DashboardWork::class => WorkForDashboard::class,
DashboardTime::class => TimeForDashboard::class,
DashboardAdmin::class => AdminForDashboard::class,
DashboardFigures::class => FiguresForDashboard::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('dashboard', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// The management panel of the home page: admin and management.
Gate::define('dashboard.management', fn (User $user): bool => $user->role->seesAllMoney());
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Modules\Dashboard\Presentation\Livewire\Concerns;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
/**
* Finnish number, money and date formats of the home page, in both UI
* languages. Amounts may be negative (a loss), which Money does not hold.
*/
trait FormatsDashboard
{
public function money(int $cents): string
{
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
}
/**
* E.g. 6 quarters → "1,5".
*/
public function hours(int $quarters): string
{
return rtrim(rtrim(number_format($quarters / 4, 2, ',', "\u{00A0}"), '0'), ',');
}
/**
* E.g. 0.125 → "12,5 %".
*/
public function percent(float $ratio): string
{
return number_format($ratio * 100, 1, ',', "\u{00A0}")."\u{00A0}%";
}
public function dateLabel(string $day): string
{
return (new DateTimeImmutable($day))->format('j.n.Y');
}
}
@@ -0,0 +1,195 @@
<?php
use App\Modules\Dashboard\Application\DTOs\PersonalOverview;
use App\Modules\Dashboard\Application\UseCases\PersonalOverviewQuery;
use App\Modules\Dashboard\Presentation\Livewire\Concerns\FormatsDashboard;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* The home page: the user's open tasks on an agenda, their open jobs,
* this week's hours and quick links; admin and management also get the
* management panel, loaded lazily.
*/
new class extends Component
{
use FormatsDashboard;
#[Computed]
public function overview(): PersonalOverview
{
return app(PersonalOverviewQuery::class)->execute((int) auth()->id(), app(Clock::class)->today());
}
/**
* @return list<array{route: string, label: string, icon: string}>
*/
public function quickLinks(): array
{
$links = [
['route' => 'jobs.quick', 'label' => __('dashboard.links.quick_intake'), 'icon' => 'bolt', 'ability' => 'jobs.manage'],
['route' => 'jobs.create', 'label' => __('dashboard.links.new_job'), 'icon' => 'plus', 'ability' => 'jobs.manage'],
['route' => 'time.week', 'label' => __('dashboard.links.time'), 'icon' => 'clock', 'ability' => 'time.use'],
['route' => 'sales.sell', 'label' => __('dashboard.links.quick_sale'), 'icon' => 'shopping-cart', 'ability' => 'sales.use'],
['route' => 'jobs.calendar', 'label' => __('dashboard.links.calendar'), 'icon' => 'calendar-days', 'ability' => 'jobs.view'],
];
return array_values(array_map(
fn (array $link): array => ['route' => $link['route'], 'label' => $link['label'], 'icon' => $link['icon']],
array_filter($links, fn (array $link): bool => Gate::allows($link['ability'])),
));
}
public function dayName(string $day): string
{
return __('time.days')[(int) (new DateTimeImmutable($day))->format('N') - 1];
}
public function render(): mixed
{
return $this->view()->title(__('dashboard.title'));
}
};
?>
<div class="mx-auto max-w-7xl space-y-8 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('dashboard.greeting', ['name' => auth()->user()->name]) }}</h1>
@php($overview = $this->overview)
<nav aria-label="{{ __('dashboard.links.title') }}">
<ul class="flex flex-wrap gap-2">
@foreach ($this->quickLinks() as $link)
<li><x-button :href="route($link['route'])" wire:navigate :icon="$link['icon']" :text="$link['label']" /></li>
@endforeach
</ul>
</nav>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="tasks-heading" class="space-y-4 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="tasks-heading" class="text-xl font-semibold">{{ __('dashboard.tasks.title') }}</h2>
@if (! $overview->hasTasks())
<p class="text-sm">{{ __('dashboard.tasks.none') }}</p>
@endif
@foreach (['overdue' => $overview->overdue, 'soon' => $overview->soon, 'this_week' => $overview->thisWeek] as $group => $tasks)
@if ($tasks !== [])
<div class="space-y-2">
<h3 class="flex items-center gap-2 font-semibold">
@if ($group === 'overdue')
<x-icon name="exclamation-triangle" class="size-5 text-red-700 dark:text-red-400" aria-hidden="true" />
@endif
{{ __('dashboard.tasks.groups.'.$group, ['count' => count($tasks)]) }}
</h3>
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($tasks as $task)
<li wire:key="task-{{ $task->taskId }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="flex flex-wrap gap-x-3 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.tasks.statuses.'.$task->status) }}</span>
@if ($task->dueOn !== null)
<span>{{ __('dashboard.tasks.due', ['date' => $this->dateLabel($task->dueOn)]) }}</span>
@endif
@if ($task->plannedFrom !== null)
<span>{{ __('dashboard.tasks.starts', ['date' => $this->dateLabel($task->plannedFrom)]) }}</span>
@endif
@if ($task->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif
</span>
</li>
@endforeach
</ul>
</div>
@endif
@endforeach
@if ($overview->laterCount > 0)
<p class="text-sm">{{ trans_choice('dashboard.tasks.later', $overview->laterCount, ['count' => $overview->laterCount]) }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.tasks.to_calendar') }}</x-link></p>
@endif
</section>
<div class="space-y-6">
<section aria-labelledby="week-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="week-heading" class="text-xl font-semibold">{{ __('dashboard.week.title') }}</h2>
<table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.week.caption', ['from' => $this->dateLabel($overview->week->monday)]) }}</caption>
<thead>
<tr>
@foreach (array_keys($overview->week->days) as $day)
<th scope="col" class="py-1 text-center font-medium">
{{ $this->dayName($day) }}
<span class="block text-xs font-normal text-zinc-600 dark:text-zinc-300">{{ (new DateTimeImmutable($day))->format('j.n.') }}</span>
</th>
@endforeach
</tr>
</thead>
<tbody>
<tr>
@foreach ($overview->week->days as $quarters)
<td class="py-1 text-center">{{ $this->hours($quarters) }}</td>
@endforeach
</tr>
</tbody>
</table>
<p class="text-sm">
{{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }}
@if ($overview->week->unapprovedQuarters > 0)
<span class="inline-flex items-center gap-1">
<x-icon name="exclamation-circle" class="size-4" aria-hidden="true" />
{{ __('dashboard.week.unapproved', ['hours' => $this->hours($overview->week->unapprovedQuarters)]) }}
</span>
@endif
</p>
<p class="text-sm"><x-link :href="route('time.week')" navigate>{{ __('dashboard.week.open') }}</x-link></p>
</section>
<section aria-labelledby="jobs-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="jobs-heading" class="text-xl font-semibold">{{ __('dashboard.jobs.title') }}</h2>
@if ($overview->jobs === [])
<p class="text-sm">{{ __('dashboard.jobs.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobs as $job)
<li wire:key="job-{{ $job->id }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $job->id)" navigate class="font-medium">{{ $job->number }} {{ $job->name }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $job->customerName }}</span>
<span class="flex flex-wrap items-center gap-x-3 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.statuses.'.$job->status) }}</span>
<x-jobs.priority :priority="\App\Modules\Jobs\Domain\Enums\Priority::from($job->priority)" />
@if ($job->dueOn !== null)
<span>{{ __('dashboard.jobs.due', ['date' => $this->dateLabel($job->dueOn)]) }}</span>
@endif
@if ($job->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif
</span>
</li>
@endforeach
</ul>
@endif
<p class="text-sm">
<x-link :href="route('jobs.index')" navigate>{{ trans_choice('dashboard.jobs.all', $overview->jobCount, ['count' => $overview->jobCount]) }}</x-link>
</p>
</section>
</div>
</div>
@can('dashboard.management')
{{-- Loaded right after the page, not only when scrolled to. --}}
<livewire:dashboard::management lazy="on-load" />
@endcan
</div>
@@ -0,0 +1,244 @@
<?php
use App\Modules\Dashboard\Application\DTOs\ManagementOverview;
use App\Modules\Dashboard\Application\UseCases\ManagementOverviewQuery;
use App\Modules\Dashboard\Domain\ValueObjects\Change;
use App\Modules\Dashboard\Domain\ValueObjects\Workload;
use App\Modules\Dashboard\Presentation\Livewire\Concerns\FormatsDashboard;
use App\Modules\Users\Application\Contracts\Clock;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* The management panel of the home page (admin and management): what
* needs doing, this month's key figures against the same days of the
* previous month, the jobs and late work, and everyone's workload. Loaded
* lazily after the rest of the home page.
*/
new class extends Component
{
use FormatsDashboard;
public function mount(): void
{
$this->authorize('dashboard.management');
}
#[Computed]
public function overview(): ManagementOverview
{
return app(ManagementOverviewQuery::class)->execute(app(Clock::class)->today());
}
public function placeholder(): string
{
return '<section class="rounded-lg border border-zinc-300 p-4 dark:border-zinc-600"><p role="status" class="text-sm">'.e(__('dashboard.management.loading')).'</p></section>';
}
/**
* E.g. "+12,5 % edelliseen", or "ei vertailukohtaa" when the earlier value was zero.
*/
public function change(int $current, int $previous): string
{
$ratio = (new Change($current, $previous))->ratio();
if ($ratio === null) {
return __('dashboard.management.no_comparison');
}
return __('dashboard.management.change', ['change' => ($ratio > 0 ? '+' : ($ratio < 0 ? '−' : '±')).$this->percent(abs($ratio))]);
}
public function load(Workload $load): string
{
$ratio = $load->ratio();
return $ratio === null ? '–' : $this->percent($ratio);
}
public function render(): mixed
{
return $this->view();
}
};
?>
<section aria-labelledby="management-heading" class="space-y-6">
@php($overview = $this->overview)
<h2 id="management-heading" class="text-xl font-semibold">{{ __('dashboard.management.title') }}</h2>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="todo-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="todo-heading" class="text-lg font-semibold">{{ __('dashboard.todo.title') }}</h3>
<ul class="space-y-2 text-sm">
@can('time.approve-others')
<li>
<x-link :href="route('time.approvals')" navigate>
{{ trans_choice('dashboard.todo.approvals', count($overview->pendingApprovals), ['count' => count($overview->pendingApprovals)]) }}
</x-link>
@if ($overview->pendingApprovals !== [])
<ul class="mt-1 ml-4 list-disc">
@foreach ($overview->pendingApprovals as $pending)
<li>{{ __('dashboard.todo.approval_line', ['name' => $pending->name, 'hours' => $this->hours($pending->quarters), 'weeks' => $pending->weekCount]) }}</li>
@endforeach
</ul>
@endif
</li>
@endcan
@can('billing.manage')
<li>
<x-link :href="route('billing.index')" navigate>{{ trans_choice('dashboard.todo.done_jobs', $overview->doneJobCount, ['count' => $overview->doneJobCount]) }}</x-link>
</li>
@if ($overview->draftExportId !== null)
<li><x-link :href="route('billing.export', $overview->draftExportId)" navigate>{{ __('dashboard.todo.draft') }}</x-link></li>
@endif
@endcan
@can('sales.close-day')
@if ($overview->unclosedCashDays !== [])
<li>
<x-link :href="route('sales.index', ['paiva' => $overview->unclosedCashDays[0]])" navigate>
{{ trans_choice('dashboard.todo.cash_days', count($overview->unclosedCashDays), ['count' => count($overview->unclosedCashDays), 'first' => $this->dateLabel($overview->unclosedCashDays[0])]) }}
</x-link>
</li>
@endif
@endcan
@can('reports.view')
<li>
<x-link :href="route('reports.unbilled')" navigate>{{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }}</x-link>
</li>
@endcan
</ul>
</section>
@can('reports.view')
<section aria-labelledby="month-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="month-heading" class="text-lg font-semibold">{{ __('dashboard.month.title') }}</h3>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
{{ __('dashboard.month.period', [
'from' => $this->dateLabel($overview->monthFrom), 'to' => $this->dateLabel($overview->monthTo),
'previous_from' => $this->dateLabel($overview->previousFrom), 'previous_to' => $this->dateLabel($overview->previousTo),
]) }}
</p>
@php($month = $overview->month)
@php($previous = $overview->previousMonth)
<dl class="grid gap-3 sm:grid-cols-2">
@foreach ([
['label' => 'customer_hours', 'value' => $this->hours($month->customerQuarters).' h', 'current' => $month->customerQuarters, 'previous' => $previous->customerQuarters, 'route' => 'reports.hours'],
['label' => 'internal_hours', 'value' => $this->hours($month->internalQuarters).' h', 'current' => $month->internalQuarters, 'previous' => $previous->internalQuarters, 'route' => 'reports.hours'],
['label' => 'billed', 'value' => $this->money($month->billedCents), 'current' => $month->billedCents, 'previous' => $previous->billedCents, 'route' => 'reports.profitability'],
['label' => 'margin', 'value' => $month->marginCents === null ? __('dashboard.month.no_cost') : $this->money($month->marginCents), 'current' => $month->marginCents, 'previous' => $previous->marginCents, 'route' => 'reports.profitability'],
['label' => 'sales', 'value' => $this->money($month->salesCents), 'current' => $month->salesCents, 'previous' => $previous->salesCents, 'route' => 'reports.sales'],
] as $figure)
<div class="rounded border border-zinc-200 p-3 dark:border-zinc-700">
<dt class="text-sm">
<x-link :href="route($figure['route'])" navigate>{{ __('dashboard.month.'.$figure['label']) }}</x-link>
</dt>
<dd class="text-lg font-semibold">{{ $figure['value'] }}</dd>
@if ($figure['current'] !== null && $figure['previous'] !== null)
<dd class="text-sm text-zinc-700 dark:text-zinc-200">{{ $this->change($figure['current'], $figure['previous']) }}</dd>
@endif
</div>
@endforeach
</dl>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('dashboard.month.billing_note') }}</p>
</section>
@endcan
</div>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="jobs-overview-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="jobs-overview-heading" class="text-lg font-semibold">{{ __('dashboard.stock.title') }}</h3>
<table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.stock.caption') }}</caption>
<thead class="sr-only">
<tr>
<th scope="col">{{ __('dashboard.stock.status') }}</th>
<th scope="col">{{ __('dashboard.stock.count') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobCounts as $status => $count)
<tr wire:key="status-{{ $status }}">
<th scope="row" class="py-1 text-left font-normal">
<x-link :href="route('jobs.index', ['status' => $status, 'mine' => 0])" navigate>{{ __('jobs.statuses.'.$status) }}</x-link>
</th>
<td class="py-1 text-right">{{ $count }}</td>
</tr>
@endforeach
</tbody>
</table>
<p class="flex items-center gap-2 text-sm">
@if ($overview->overdueJobCount > 0)
<x-icon name="exclamation-triangle" class="size-5 text-red-700 dark:text-red-400" aria-hidden="true" />
@endif
{{ trans_choice('dashboard.stock.overdue_jobs', $overview->overdueJobCount, ['count' => $overview->overdueJobCount]) }}
</p>
<p class="flex items-center gap-2 text-sm">
@if ($overview->overdueTaskCount > 0)
<x-icon name="exclamation-triangle" class="size-5 text-red-700 dark:text-red-400" aria-hidden="true" />
@endif
{{ trans_choice('dashboard.stock.overdue_tasks', $overview->overdueTaskCount, ['count' => $overview->overdueTaskCount]) }}
</p>
@if ($overview->oldestOverdueTasks !== [])
<h4 class="font-semibold">{{ __('dashboard.stock.oldest_overdue') }}</h4>
<ul class="divide-y divide-zinc-200 text-sm dark:divide-zinc-700">
@foreach ($overview->oldestOverdueTasks as $task)
<li wire:key="late-{{ $task->taskId }}" class="py-2">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">
{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->assigneeName ?? __('dashboard.stock.no_assignee') }}
· {{ __('dashboard.tasks.due', ['date' => $this->dateLabel((string) $task->dueOn)]) }}
</span>
</li>
@endforeach
</ul>
@endif
</section>
<section aria-labelledby="load-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="load-heading" class="text-lg font-semibold">{{ __('dashboard.load.title') }}</h3>
@if ($overview->workloads === [])
<p class="text-sm">{{ __('dashboard.load.none') }}</p>
@else
<div class="overflow-x-auto rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600" tabindex="0" role="region" aria-label="{{ __('dashboard.load.caption') }}">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.load.caption') }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left align-bottom dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('dashboard.load.person') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('dashboard.load.week', ['from' => $this->dateLabel($overview->thisMonday)]) }}</th>
<th scope="col" class="py-2 text-right">{{ __('dashboard.load.week', ['from' => $this->dateLabel($overview->nextMonday)]) }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->workloads as $person)
<tr wire:key="load-{{ $person->userId }}">
<th scope="row" class="py-2 pr-3 text-left font-normal">{{ $person->name }}</th>
@foreach ([$person->thisWeek, $person->nextWeek] as $index => $load)
<td class="py-2 text-right {{ $index === 0 ? 'pr-3' : '' }}">
{{ __('dashboard.load.value', ['booked' => $this->hours(intdiv($load->bookedMinutes, 15)), 'capacity' => $this->hours(intdiv($load->capacityMinutes, 15)), 'ratio' => $this->load($load)]) }}
@if ($load->isOverloaded())
<span class="flex items-center justify-end gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('dashboard.load.overloaded') }}
</span>
@endif
</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
</div>
<p class="text-sm">{{ __('dashboard.load.note') }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.load.to_calendar') }}</x-link></p>
@endif
</section>
</div>
</section>
@@ -0,0 +1,7 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth'])->group(function () {
Route::livewire('/', 'dashboard::home')->name('home');
});
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\OpenTask;
/**
* Jobs and tasks summed up for the home page. Days are Y-m-d. Tasks of the
* quick sale jobs are left out: they only hold quick sale hours.
*/
interface JobOverviewQueries
{
/**
* Open tasks the user is the assignee or a member of, by due date (none
* last), then planned start.
*
* @return list<OpenTask>
*/
public function openTasksOf(int $userId): array;
/**
* The user's own jobs (5.6) that are still open (before done), by due
* date (none last), then newest first.
*
* @return list<CustomerJobSummary>
*/
public function openJobsOf(int $userId): array;
/**
* Jobs by Kanban status key (archived left out), every status included.
*
* @return array<string, int>
*/
public function jobCountsByStatus(): array;
/**
* Open jobs (before done) whose due date is before the day.
*/
public function overdueJobCount(string $today): int;
/**
* Open tasks whose due date is before the day.
*/
public function overdueTaskCount(string $today): int;
/**
* The open tasks that have been late the longest.
*
* @return list<OpenTask>
*/
public function oldestOverdueTasks(string $today, int $limit): array;
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task that is not done, on a job that is not archived, with its dates
* (Y-m-d) and its assignee.
*/
final readonly class OpenTask
{
public function __construct(
public int $taskId,
public int $jobId,
public string $jobNumber,
public string $jobName,
public string $title,
public TaskStatus $status,
public ?string $dueOn,
public ?string $plannedFrom,
public ?string $plannedTo,
public ?int $assigneeUserId,
public ?string $assigneeName,
) {}
}
@@ -46,6 +46,22 @@ enum JobStatus: string
return in_array($this, [self::Done, self::Invoiced, self::Billed, self::Archived], true);
}
/**
* Work still to be done: a job past its due date in such a status is late.
*/
public function isOpen(): bool
{
return ! $this->locksTime();
}
/**
* @return list<self>
*/
public static function openStatuses(): array
{
return array_values(array_filter(self::cases(), fn (self $status): bool => $status->isOpen()));
}
/**
* Whether moving from this status to $to opens the lock on hours and expenses.
*/
@@ -0,0 +1,137 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\JobOverviewQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\OpenTask;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
/**
* Assignee names come from the Users module, never from its table.
*/
class EloquentJobOverviewQueries implements JobOverviewQueries
{
public function __construct(
private UserAccountQueries $users,
private CustomerJobQueries $jobs,
) {}
public function openTasksOf(int $userId): array
{
$query = $this->openTasks()
->where(fn (Builder $query) => $query
->where('tasks.assignee_user_id', $userId)
->orWhereIn('tasks.id', DB::table('task_members')->select('task_id')->where('user_id', $userId)))
->orderByRaw('tasks.due_on IS NULL')
->orderBy('tasks.due_on')
->orderByRaw('tasks.planned_from IS NULL')
->orderBy('tasks.planned_from')
->orderBy('tasks.id');
return $this->toOpenTasks($query);
}
public function openJobsOf(int $userId): array
{
$query = DB::table('customer_jobs')
->whereIn('status', array_map(fn (JobStatus $status): string => $status->value, JobStatus::openStatuses()))
->whereNull('quick_sale_year');
JobInvolvement::restrict($query, $userId);
$ids = $query->orderByRaw('due_on IS NULL')->orderBy('due_on')->orderByDesc('id')
->pluck('id')->map(fn ($id): int => (int) $id)->all();
$summaries = $this->jobs->summariesByIds($ids);
return array_values(array_filter(array_map(fn (int $id): ?CustomerJobSummary => $summaries[$id] ?? null, $ids)));
}
public function jobCountsByStatus(): array
{
$counts = DB::table('customer_jobs')
->where('status', '!=', JobStatus::Archived->value)
->groupBy('status')
->selectRaw('status, COUNT(*) as job_count')
->pluck('job_count', 'status');
$result = [];
foreach (JobStatus::kanbanStatuses() as $status) {
$result[$status->value] = (int) ($counts[$status->value] ?? 0);
}
return $result;
}
public function overdueJobCount(string $today): int
{
return DB::table('customer_jobs')
->whereIn('status', array_map(fn (JobStatus $status): string => $status->value, JobStatus::openStatuses()))
->whereNull('quick_sale_year')
->whereNotNull('due_on')
->where('due_on', '<', $today)
->count();
}
public function overdueTaskCount(string $today): int
{
return $this->overdueTasks($today)->count();
}
public function oldestOverdueTasks(string $today, int $limit): array
{
return $this->toOpenTasks($this->overdueTasks($today)->orderBy('tasks.due_on')->orderBy('tasks.id')->limit($limit));
}
private function overdueTasks(string $today): Builder
{
return $this->openTasks()->whereNotNull('tasks.due_on')->where('tasks.due_on', '<', $today);
}
private function openTasks(): Builder
{
return DB::table('tasks')
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->where('tasks.status', '!=', TaskStatus::Done->value)
->where('customer_jobs.status', '!=', JobStatus::Archived->value)
->whereNull('customer_jobs.quick_sale_year');
}
/**
* @return list<OpenTask>
*/
private function toOpenTasks(Builder $query): array
{
$rows = $query->get([
'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.status', 'tasks.due_on', 'tasks.planned_from', 'tasks.planned_to', 'tasks.assignee_user_id',
'customer_jobs.number', 'customer_jobs.name',
]);
$assigneeIds = $rows->pluck('assignee_user_id')->filter()->map(fn ($id): int => (int) $id)->unique()->values()->all();
$names = $assigneeIds === [] ? [] : $this->users->namesByIds($assigneeIds);
return $rows->map(fn (object $row): OpenTask => new OpenTask(
(int) $row->id,
(int) $row->customer_job_id,
(string) $row->number,
(string) $row->name,
(string) $row->title,
TaskStatus::from((string) $row->status),
self::day($row->due_on),
self::day($row->planned_from),
self::day($row->planned_to),
$row->assignee_user_id === null ? null : (int) $row->assignee_user_id,
$row->assignee_user_id === null ? null : ($names[(int) $row->assignee_user_id] ?? null),
))->values()->all();
}
private static function day(mixed $value): ?string
{
return $value === null ? null : substr((string) $value, 0, 10);
}
}
@@ -7,6 +7,7 @@ use App\Modules\Customers\Application\Contracts\CustomerReferences;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\ChecklistQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\JobOverviewQueries;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\Contracts\TaskCommentQueries;
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
@@ -30,6 +31,7 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistIt
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentJobOverviewQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBookingRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCommentQueries;
@@ -62,6 +64,7 @@ class JobsServiceProvider extends ServiceProvider
TaskQueries::class => EloquentTaskQueries::class,
TaskBookingRepository::class => EloquentTaskBookingRepository::class,
TaskCalendarQueries::class => EloquentTaskCalendarQueries::class,
JobOverviewQueries::class => EloquentJobOverviewQueries::class,
ChecklistItemRepository::class => EloquentChecklistItemRepository::class,
ChecklistQueries::class => EloquentChecklistQueries::class,
TaskCommentRepository::class => EloquentTaskCommentRepository::class,