Add Reports module with the hours by person report

Management's reports (spec 13) get their own module that reads the other
modules through ports. The first report sums hours by person in a period,
narrowed by service unit or customer, with breakdowns, a chart and CSV.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-25 08:39:19 +02:00
co-authored by Claude Sonnet 5.5
parent f906f9a43f
commit 64f1e7c54a
45 changed files with 1828 additions and 3 deletions
@@ -9,6 +9,7 @@ use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobBillingInfo;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\JobReportInfo;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
@@ -66,6 +67,14 @@ interface CustomerJobQueries
*/
public function billingInfoOf(array $ids): array;
/**
* Report details of the given jobs, keyed by id; unknown ids are left out.
*
* @param list<int> $ids
* @return array<int, JobReportInfo>
*/
public function reportInfoOf(array $ids): array;
/**
* The job's history, newest first.
*
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
/**
* A customer job as management's reports see it: whose it is, whether it
* is internal work, how it is billed and its service units.
*/
final readonly class JobReportInfo
{
/**
* @param list<int> $serviceUnitIds
*/
public function __construct(
public int $id,
public string $number,
public string $name,
public int $customerId,
public string $customerName,
public bool $isInternal,
public JobStatus $status,
public ?PaymentBasis $paymentBasis,
public ?int $quotedAmountCents,
public array $serviceUnitIds,
) {}
}
@@ -10,6 +10,7 @@ use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobBillingInfo;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\JobReportInfo;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
@@ -206,6 +207,43 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get());
}
public function reportInfoOf(array $ids): array
{
if ($ids === []) {
return [];
}
$result = [];
foreach (array_chunk(array_values(array_unique($ids)), 500) as $chunk) {
$models = CustomerJobModel::query()->whereIn('id', $chunk)->get();
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
$internalCustomerId = $this->customers->internalCustomerId();
$serviceUnitIds = [];
foreach (DB::table('customer_job_service_unit')->whereIn('customer_job_id', $chunk)->orderBy('service_unit_id')->get() as $row) {
$serviceUnitIds[(int) $row->customer_job_id][] = (int) $row->service_unit_id;
}
foreach ($models as $model) {
$result[$model->id] = new JobReportInfo(
$model->id,
$model->number,
$model->name,
$model->customer_id,
$customerNames[$model->customer_id] ?? '',
$model->customer_id === $internalCustomerId,
$model->status,
$model->payment_basis,
$model->quoted_amount_cents,
$serviceUnitIds[$model->id] ?? [],
);
}
}
return $result;
}
/**
* @param Collection<int, CustomerJobModel> $models
* @return array<int, JobBillingInfo>
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
use App\Modules\Reports\Application\DTOs\ReportWorkType;
/**
* Service units, work types and their prices, from the Catalog module.
*/
interface ReportCatalog
{
/**
* Every work type, inactive ones included.
*
* @return array<int, ReportWorkType>
*/
public function workTypes(): array;
/**
* Every service unit's name in catalog order, inactive ones included.
*
* @return array<int, string>
*/
public function serviceUnits(): array;
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
use App\Modules\Reports\Application\DTOs\HoursEntry;
use App\Modules\Reports\Application\DTOs\UnbilledEntry;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Recorded hours, from the TimeTracking module.
*/
interface ReportHours
{
/**
* Hours worked in the period by user, job and work type.
*
* @return list<HoursEntry>
*/
public function between(ReportPeriod $period): array;
/**
* Unbilled hours worked on or before the day (Y-m-d) by job and work type.
*
* @return list<UnbilledEntry>
*/
public function unbilledUntil(string $day): array;
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
use App\Modules\Reports\Application\DTOs\ReportJob;
/**
* Customer jobs, from the Jobs and Customers modules.
*/
interface ReportJobs
{
/**
* @param list<int> $ids
* @return array<int, ReportJob> Keyed by id; unknown ids are left out.
*/
public function infoOf(array $ids): array;
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
/**
* Users' names, from the Users module.
*/
interface ReportPeople
{
/**
* @param list<int> $ids
* @return array<int, string>
*/
public function namesByIds(array $ids): array;
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A part of a person's hours, e.g. one work type or one job, in quarter hours.
*/
final readonly class HoursBreakdown
{
public function __construct(
public string $label,
public int $quarters,
public ?int $jobId = null,
) {}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A user's hours on a job's work type in quarter hours: all, those waiting
* for approval and those billed.
*/
final readonly class HoursEntry
{
public function __construct(
public int $userId,
public int $jobId,
public int $workTypeId,
public int $quarters,
public int $unapprovedQuarters,
public int $billedQuarters,
) {}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* One row of the hours report: a person's hours on a job's work type, in
* quarter hours.
*/
final readonly class HoursLine
{
public function __construct(
public int $userId,
public string $userName,
public int $jobId,
public string $jobNumber,
public string $jobName,
public string $customerName,
public bool $isInternal,
public string $workTypeName,
public string $serviceUnitName,
public int $quarters,
public int $unapprovedQuarters,
public int $billedQuarters,
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* Hours by person: a row per person by name, their total, the rows behind
* them, and the customers and service units the hours can be narrowed to.
*/
final readonly class HoursReport
{
/**
* @param list<PersonHours> $people
* @param list<HoursLine> $lines
* @param array<int, string> $customers
* @param array<int, string> $serviceUnits
*/
public function __construct(
public array $people,
public PersonHours $total,
public array $lines,
public array $customers,
public array $serviceUnits,
) {}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A person's hours in the period in quarter hours: in all, on customers'
* and on internal jobs, waiting for approval and billed, broken down by
* work type and by job (most hours first).
*/
final readonly class PersonHours
{
/**
* @param list<HoursBreakdown> $byWorkType
* @param list<HoursBreakdown> $byJob
*/
public function __construct(
public int $userId,
public string $name,
public int $quarters,
public int $customerQuarters,
public int $internalQuarters,
public int $unapprovedQuarters,
public int $billedQuarters,
public array $byWorkType = [],
public array $byJob = [],
) {}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A customer job in a report. Status and payment basis are the Jobs
* module's keys (e.g. "done", "hourly"). A job bills its hours when its
* hours are priced by the hourly rates (hourly or price list work), and is
* billable when it is a customer's job that is billed at all.
*/
final readonly class ReportJob
{
/**
* @param list<int> $serviceUnitIds
*/
public function __construct(
public int $id,
public string $number,
public string $name,
public int $customerId,
public string $customerName,
public bool $isInternal,
public string $status,
public ?string $paymentBasis,
public bool $isBillable,
public bool $billsHours,
public ?int $quotedAmountCents,
public array $serviceUnitIds,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A work type with its service unit and hourly rate in cents (VAT 0).
*/
final readonly class ReportWorkType
{
public function __construct(
public int $id,
public string $name,
public int $serviceUnitId,
public string $serviceUnitName,
public ?int $rateCents,
) {}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A job's unbilled hours on a work type in quarter hours, with the first
* day worked (Y-m-d).
*/
final readonly class UnbilledEntry
{
public function __construct(
public int $jobId,
public int $workTypeId,
public int $approvedQuarters,
public int $unapprovedQuarters,
public string $oldestDay,
) {}
}
@@ -0,0 +1,157 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\UseCases;
use App\Modules\Reports\Application\Contracts\ReportCatalog;
use App\Modules\Reports\Application\Contracts\ReportHours;
use App\Modules\Reports\Application\Contracts\ReportJobs;
use App\Modules\Reports\Application\Contracts\ReportPeople;
use App\Modules\Reports\Application\DTOs\HoursBreakdown;
use App\Modules\Reports\Application\DTOs\HoursEntry;
use App\Modules\Reports\Application\DTOs\HoursLine;
use App\Modules\Reports\Application\DTOs\HoursReport;
use App\Modules\Reports\Application\DTOs\PersonHours;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Hours by person in a period (spec 13), optionally narrowed to the jobs
* of one service unit or one customer. Internal work is work on the
* internal customer's jobs.
*/
final readonly class HoursByPerson
{
public function __construct(
private ReportHours $hours,
private ReportJobs $jobs,
private ReportCatalog $catalog,
private ReportPeople $people,
) {}
public function execute(ReportPeriod $period, ?int $serviceUnitId = null, ?int $customerId = null): HoursReport
{
$entries = $this->hours->between($period);
$jobs = $this->jobs->infoOf(array_values(array_unique(array_map(fn (HoursEntry $entry): int => $entry->jobId, $entries))));
$workTypes = $this->catalog->workTypes();
$names = $this->people->namesByIds(array_values(array_unique(array_map(fn (HoursEntry $entry): int => $entry->userId, $entries))));
$customers = [];
$lines = [];
foreach ($entries as $entry) {
$job = $jobs[$entry->jobId] ?? null;
if ($job === null) {
continue;
}
$customers[$job->customerId] = $job->customerName;
if ($serviceUnitId !== null && ! in_array($serviceUnitId, $job->serviceUnitIds, true)) {
continue;
}
if ($customerId !== null && $job->customerId !== $customerId) {
continue;
}
$workType = $workTypes[$entry->workTypeId] ?? null;
$lines[] = new HoursLine(
$entry->userId,
$names[$entry->userId] ?? '',
$job->id,
$job->number,
$job->name,
$job->customerName,
$job->isInternal,
$workType->name ?? '',
$workType->serviceUnitName ?? '',
$entry->quarters,
$entry->unapprovedQuarters,
$entry->billedQuarters,
);
}
usort($lines, fn (HoursLine $a, HoursLine $b): int => [$a->userName, $a->userId, $a->jobNumber, $a->workTypeName] <=> [$b->userName, $b->userId, $b->jobNumber, $b->workTypeName]);
asort($customers, SORT_NATURAL | SORT_FLAG_CASE);
$byPerson = [];
foreach ($lines as $line) {
$byPerson[$line->userId][] = $line;
}
$people = array_map(fn (array $personLines): PersonHours => $this->person($personLines), array_values($byPerson));
return new HoursReport($people, $this->total($people), $lines, $customers, $this->catalog->serviceUnits());
}
/**
* @param non-empty-list<HoursLine> $lines
*/
private function person(array $lines): PersonHours
{
$byWorkType = [];
$byJob = [];
$jobLabels = [];
foreach ($lines as $line) {
$byWorkType[$line->workTypeName] = ($byWorkType[$line->workTypeName] ?? 0) + $line->quarters;
$byJob[$line->jobId] = ($byJob[$line->jobId] ?? 0) + $line->quarters;
$jobLabels[$line->jobId] = $line->jobNumber.' '.$line->jobName;
}
arsort($byWorkType);
arsort($byJob);
$workTypeRows = [];
foreach ($byWorkType as $label => $quarters) {
$workTypeRows[] = new HoursBreakdown((string) $label, $quarters);
}
$jobRows = [];
foreach ($byJob as $jobId => $quarters) {
$jobRows[] = new HoursBreakdown($jobLabels[$jobId], $quarters, $jobId);
}
return new PersonHours(
$lines[0]->userId,
$lines[0]->userName,
self::sum($lines, fn (HoursLine $line): int => $line->quarters),
self::sum($lines, fn (HoursLine $line): int => $line->isInternal ? 0 : $line->quarters),
self::sum($lines, fn (HoursLine $line): int => $line->isInternal ? $line->quarters : 0),
self::sum($lines, fn (HoursLine $line): int => $line->unapprovedQuarters),
self::sum($lines, fn (HoursLine $line): int => $line->billedQuarters),
$workTypeRows,
$jobRows,
);
}
/**
* @param list<PersonHours> $people
*/
private function total(array $people): PersonHours
{
return new PersonHours(
0,
'',
self::sum($people, fn (PersonHours $person): int => $person->quarters),
self::sum($people, fn (PersonHours $person): int => $person->customerQuarters),
self::sum($people, fn (PersonHours $person): int => $person->internalQuarters),
self::sum($people, fn (PersonHours $person): int => $person->unapprovedQuarters),
self::sum($people, fn (PersonHours $person): int => $person->billedQuarters),
);
}
/**
* @template T
*
* @param list<T> $items
* @param callable(T): int $value
*/
private static function sum(array $items, callable $value): int
{
return array_sum(array_map($value, $items));
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidReportPeriod extends DomainException
{
public function __construct()
{
parent::__construct('The report period is invalid.');
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Domain\ValueObjects;
use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod;
use DateTimeImmutable;
/**
* The days a report covers, first and last included (Y-m-d).
*/
final readonly class ReportPeriod
{
public string $from;
public string $to;
public function __construct(string $from, string $to)
{
$first = self::parse($from);
$last = self::parse($to);
if ($first === null || $last === null || $first > $last) {
throw new InvalidReportPeriod;
}
$this->from = $from;
$this->to = $to;
}
public static function month(DateTimeImmutable $day): self
{
return new self($day->format('Y-m-01'), $day->format('Y-m-t'));
}
public static function previousMonth(DateTimeImmutable $day): self
{
return self::month($day->modify('first day of previous month'));
}
public static function year(DateTimeImmutable $day): self
{
return new self($day->format('Y-01-01'), $day->format('Y-12-31'));
}
public static function previousYear(DateTimeImmutable $day): self
{
return self::year($day->modify('first day of january last year'));
}
/**
* The first month (Y-m), for data kept by month such as billing.
*/
public function fromMonth(): string
{
return substr($this->from, 0, 7);
}
public function toMonth(): string
{
return substr($this->to, 0, 7);
}
public function dayCount(): int
{
return (int) (new DateTimeImmutable($this->from))->diff(new DateTimeImmutable($this->to))->days + 1;
}
private static function parse(string $value): ?DateTimeImmutable
{
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) {
return null;
}
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
return $date !== false && $date->format('Y-m-d') === $value ? $date : null;
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Reports\Application\Contracts\ReportCatalog;
use App\Modules\Reports\Application\DTOs\ReportWorkType;
/**
* Service units, work types and prices for reports through the Catalog
* module's price list.
*/
class CatalogForReports implements ReportCatalog
{
public function __construct(private PriceListQueries $prices) {}
public function workTypes(): array
{
$workTypes = [];
foreach ($this->prices->hourlyRates() as $group) {
foreach ($group->rows as $row) {
$workTypes[$row->workTypeId] = new ReportWorkType($row->workTypeId, $row->name, $group->serviceUnitId, $group->serviceUnitName, $row->hourlyRateCents);
}
}
return $workTypes;
}
public function serviceUnits(): array
{
$units = [];
foreach ($this->prices->hourlyRates() as $group) {
$units[$group->serviceUnitId] = $group->serviceUnitName;
}
return $units;
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Reports\Application\Contracts\ReportHours;
use App\Modules\Reports\Application\DTOs\HoursEntry;
use App\Modules\Reports\Application\DTOs\UnbilledEntry;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\TimeTracking\Application\Contracts\TimeReportQueries;
use App\Modules\TimeTracking\Application\DTOs\ReportedHours;
use App\Modules\TimeTracking\Application\DTOs\UnbilledHours;
/**
* Hours for reports through the TimeTracking module.
*/
class HoursForReports implements ReportHours
{
public function __construct(private TimeReportQueries $queries) {}
public function between(ReportPeriod $period): array
{
return array_map(
fn (ReportedHours $hours): HoursEntry => new HoursEntry($hours->userId, $hours->jobId, $hours->workTypeId, $hours->quarters, $hours->unapprovedQuarters, $hours->billedQuarters),
$this->queries->hoursBetween($period->from, $period->to),
);
}
public function unbilledUntil(string $day): array
{
return array_map(
fn (UnbilledHours $hours): UnbilledEntry => new UnbilledEntry($hours->jobId, $hours->workTypeId, $hours->approvedQuarters, $hours->unapprovedQuarters, $hours->oldestDay),
$this->queries->unbilledUntil($day),
);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\JobReportInfo;
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
use App\Modules\Reports\Application\Contracts\ReportJobs;
use App\Modules\Reports\Application\DTOs\ReportJob;
/**
* Customer jobs for reports through the Jobs module. As in billing, a job
* without a payment basis is billed by its hours.
*/
class JobsForReports implements ReportJobs
{
public function __construct(private CustomerJobQueries $jobs) {}
public function infoOf(array $ids): array
{
return array_map(fn (JobReportInfo $job): ReportJob => new ReportJob(
$job->id,
$job->number,
$job->name,
$job->customerId,
$job->customerName,
$job->isInternal,
$job->status->value,
$job->paymentBasis?->value,
! $job->isInternal && $job->paymentBasis !== PaymentBasis::NotBillable,
! $job->isInternal && in_array($job->paymentBasis, [null, PaymentBasis::Hourly, PaymentBasis::PriceList], true),
$job->quotedAmountCents,
$job->serviceUnitIds,
), $this->jobs->reportInfoOf($ids));
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Reports\Application\Contracts\ReportPeople;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
/**
* Users' names for reports through the Users module.
*/
class PeopleForReports implements ReportPeople
{
public function __construct(private UserAccountQueries $users) {}
public function namesByIds(array $ids): array
{
return $ids === [] ? [] : $this->users->namesByIds($ids);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Modules\Reports\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Reports\Application\Contracts\ReportCatalog;
use App\Modules\Reports\Application\Contracts\ReportHours;
use App\Modules\Reports\Application\Contracts\ReportJobs;
use App\Modules\Reports\Application\Contracts\ReportPeople;
use App\Modules\Reports\Infrastructure\Adapters\CatalogForReports;
use App\Modules\Reports\Infrastructure\Adapters\HoursForReports;
use App\Modules\Reports\Infrastructure\Adapters\JobsForReports;
use App\Modules\Reports\Infrastructure\Adapters\PeopleForReports;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Reports module (management's reports, spec 13) into Laravel:
* the ports to the other modules, routes, the `reports::` Livewire
* namespace and the `reports.view` ability.
*/
class ReportsServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
ReportHours::class => HoursForReports::class,
ReportJobs::class => JobsForReports::class,
ReportCatalog::class => CatalogForReports::class,
ReportPeople::class => PeopleForReports::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('reports', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// Reports are for admin and management (spec 2.4).
Gate::define('reports.view', fn (User $user): bool => $user->role->seesAllMoney());
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Modules\Reports\Presentation\Csv;
use App\Modules\Reports\Application\UseCases\HoursByPerson;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Reports\Presentation\ReportFormat;
use Illuminate\Http\Request;
/**
* Hours by person as CSV: a row per person, job and work type.
*/
class HoursCsv implements ReportCsv
{
public function __construct(private HoursByPerson $report) {}
public function headers(): array
{
return array_values(__('reports.hours.csv'));
}
public function rows(ReportPeriod $period, Request $request): iterable
{
$report = $this->report->execute($period, self::id($request, 'yksikko'), self::id($request, 'asiakas'));
foreach ($report->lines as $line) {
yield [
$line->userName,
$line->jobNumber,
$line->jobName,
$line->customerName,
__($line->isInternal ? 'reports.yes' : 'reports.no'),
$line->serviceUnitName,
$line->workTypeName,
ReportFormat::csvHours($line->quarters),
ReportFormat::csvHours($line->unapprovedQuarters),
ReportFormat::csvHours($line->billedQuarters),
];
}
}
public static function id(Request $request, string $key): ?int
{
$value = $request->query($key);
return is_string($value) && ctype_digit($value) ? (int) $value : null;
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Modules\Reports\Presentation\Csv;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use Illuminate\Http\Request;
/**
* A report as CSV rows, with the filters of the report page read from the
* request's query string.
*/
interface ReportCsv
{
/**
* @return list<string>
*/
public function headers(): array;
/**
* @return iterable<list<string|int>>
*/
public function rows(ReportPeriod $period, Request $request): iterable;
}
@@ -0,0 +1,79 @@
<?php
namespace App\Modules\Reports\Presentation\Http\Controllers;
use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Reports\Presentation\Csv\HoursCsv;
use App\Modules\Reports\Presentation\Csv\ReportCsv;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Downloads a report as a CSV file for Excel, with the filters of its page
* (alku, loppu and the report's own): semicolons, a UTF-8 BOM, amounts in
* whole cents and hours with a decimal comma. Text that Excel would read
* as a formula gets a leading apostrophe, and the file is never cached.
*/
class DownloadReport
{
/** The reports that have a CSV, by their URL key. */
public const array REPORTS = ['hours'];
public function __invoke(string $report, Request $request): StreamedResponse
{
Gate::authorize('reports.view');
try {
$period = new ReportPeriod((string) $request->query('alku', ''), (string) $request->query('loppu', ''));
} catch (InvalidReportPeriod) {
abort(404);
}
$csv = $this->csv($report);
$rows = $csv->rows($period, $request);
$headers = $csv->headers();
return response()->streamDownload(function () use ($headers, $rows): void {
$out = fopen('php://output', 'w');
if ($out === false) {
return;
}
fwrite($out, "\u{FEFF}");
fputcsv($out, $headers, ';', '"', '');
foreach ($rows as $row) {
fputcsv($out, array_map(self::cell(...), $row), ';', '"', '');
}
fclose($out);
}, __('reports.csv_file', ['report' => __('reports.'.$report.'.file'), 'from' => $period->from, 'to' => $period->to]), [
'Content-Type' => 'text/csv; charset=UTF-8',
'Cache-Control' => 'no-store, private',
]);
}
/**
* Numbers are written as they are; text that starts like a formula gets
* a leading apostrophe.
*/
public static function cell(string|int $value): string
{
if (is_int($value)) {
return (string) $value;
}
return preg_match('/^[=+\-@\t\r\n]/', $value) === 1 ? "'".$value : $value;
}
private function csv(string $report): ReportCsv
{
return match ($report) {
'hours' => app(HoursCsv::class),
default => abort(404),
};
}
}
@@ -0,0 +1,128 @@
<?php
namespace App\Modules\Reports\Presentation\Livewire\Concerns;
use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Reports\Presentation\ReportFormat;
use App\Modules\Users\Application\Contracts\Clock;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
/**
* The period every report page covers, kept in the URL (alku, loppu), its
* quick choices and the shared number formats. Without a valid period in
* the URL a page starts with the current month.
*/
trait ReportPage
{
#[Url(as: 'alku', except: '')]
public string $from = '';
#[Url(as: 'loppu', except: '')]
public string $to = '';
protected function startPeriod(Clock $clock, string $default = 'this_month'): void
{
$this->authorize('reports.view');
if ($this->period() === null) {
$this->usePeriod($this->preset($default, $clock));
}
}
/**
* The period chosen, or null while the two days do not form one.
*/
#[Computed]
public function period(): ?ReportPeriod
{
try {
return new ReportPeriod($this->from, $this->to);
} catch (InvalidReportPeriod) {
return null;
}
}
public function updatedFrom(): void
{
$this->authorize('reports.view');
unset($this->period);
}
public function updatedTo(): void
{
$this->authorize('reports.view');
unset($this->period);
}
public function choosePeriod(string $preset, Clock $clock): void
{
$this->authorize('reports.view');
$this->usePeriod($this->preset($preset, $clock));
}
/**
* @return array<string, string> The quick choices by key.
*/
public function periodPresets(): array
{
return [
'this_month' => __('reports.period.this_month'),
'previous_month' => __('reports.period.previous_month'),
'this_year' => __('reports.period.this_year'),
'previous_year' => __('reports.period.previous_year'),
];
}
public function periodLabel(): string
{
$period = $this->period();
return $period === null ? '' : ReportFormat::period($period);
}
public function money(int $cents): string
{
return ReportFormat::money($cents);
}
public function hours(int $quarters): string
{
return ReportFormat::hours($quarters);
}
public function dateLabel(string $day): string
{
return ReportFormat::date($day);
}
/**
* The CSV of the report with the filters shown.
*
* @param array<string, string> $filters
*/
protected function csvUrl(string $report, array $filters = []): string
{
return route('reports.csv', array_filter(['report' => $report, 'alku' => $this->from, 'loppu' => $this->to, ...$filters], fn (string $value): bool => $value !== ''));
}
private function usePeriod(ReportPeriod $period): void
{
$this->from = $period->from;
$this->to = $period->to;
unset($this->period);
}
private function preset(string $preset, Clock $clock): ReportPeriod
{
$today = $clock->today();
return match ($preset) {
'previous_month' => ReportPeriod::previousMonth($today),
'this_year' => ReportPeriod::year($today),
'previous_year' => ReportPeriod::previousYear($today),
default => ReportPeriod::month($today),
};
}
}
@@ -0,0 +1,206 @@
<?php
use App\Modules\Reports\Application\DTOs\HoursReport;
use App\Modules\Reports\Application\UseCases\HoursByPerson;
use App\Modules\Reports\Presentation\Livewire\Concerns\ReportPage;
use App\Modules\Users\Application\Contracts\Clock;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* Hours by person (spec 13): everyone's hours in a period on customers'
* and internal jobs, waiting for approval and billed, with each person's
* hours by work type and by job. Narrowed by the jobs' service unit or
* customer.
*/
new class extends Component
{
use ReportPage;
#[Url(as: 'yksikko', except: '')]
public string $serviceUnit = '';
#[Url(as: 'asiakas', except: '')]
public string $customer = '';
public function mount(Clock $clock): void
{
$this->startPeriod($clock);
}
#[Computed]
public function report(): ?HoursReport
{
$period = $this->period();
if ($period === null) {
return null;
}
return app(HoursByPerson::class)->execute(
$period,
ctype_digit($this->serviceUnit) ? (int) $this->serviceUnit : null,
ctype_digit($this->customer) ? (int) $this->customer : null,
);
}
public function updated(): void
{
$this->authorize('reports.view');
unset($this->report);
}
public function csv(): string
{
return $this->csvUrl('hours', ['yksikko' => $this->serviceUnit, 'asiakas' => $this->customer]);
}
public function chartSummary(HoursReport $report): string
{
return implode(', ', array_map(
fn ($person): string => $person->name.' '.$this->hours($person->quarters).' h',
array_slice($report->people, 0, 15),
));
}
public function render(): mixed
{
return $this->view()->title(__('reports.hours.title'));
}
};
?>
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('reports.hours.title') }}</h1>
<x-reports.period-filter :presets="$this->periodPresets()" :valid="$this->period !== null" />
@php($report = $this->report)
@if ($report !== null)
<div class="grid max-w-2xl gap-4 sm:grid-cols-2">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="serviceUnit" :label="__('reports.filters.service_unit')" :aria-label="__('reports.filters.service_unit')">
<option value="">{{ __('reports.filters.all_service_units') }}</option>
@foreach ($report->serviceUnits as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model.live="customer" :label="__('reports.filters.customer')" :aria-label="__('reports.filters.customer')">
<option value="">{{ __('reports.filters.all_customers') }}</option>
@foreach ($report->customers as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</x-select.native>
</div>
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold" role="status" aria-live="polite">{{ $this->periodLabel() }}</h2>
<x-button :href="$this->csv()" subtle color="black" icon="arrow-down-tray" :text="__('reports.download_csv')" />
</div>
@if ($report->people === [])
<p>{{ __('reports.hours.none') }}</p>
@else
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('reports.hours.table', ['period' => $this->periodLabel()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('reports.hours.person') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.hours.total') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.hours.customer') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.hours.internal') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.hours.unapproved') }}</th>
<th scope="col" class="py-2 text-right">{{ __('reports.hours.billed') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->people as $person)
<tr wire:key="person-{{ $person->userId }}">
<th scope="row" class="py-2 pr-3 text-left font-normal">{{ $person->name }}</th>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($person->quarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($person->customerQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($person->internalQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($person->unapprovedQuarters) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->hours($person->billedQuarters) }}</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr class="border-t-2 border-zinc-400 font-semibold dark:border-zinc-500">
<th scope="row" class="py-2 pr-3 text-left">{{ __('reports.total') }}</th>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->quarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->customerQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->internalQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->unapprovedQuarters) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->hours($report->total->billedQuarters) }}</td>
</tr>
</tfoot>
</table>
</div>
<x-reports.chart
:title="__('reports.hours.chart')"
:summary="$this->chartSummary($report)"
:labels="array_map(fn ($person) => $person->name, $report->people)"
:values="array_map(fn ($person) => $person->quarters / 4, $report->people)"
:formatter="fn (float $value) => number_format($value, 0, ',', ' ').' h'"
/>
<section aria-labelledby="breakdown-heading" class="space-y-3">
<h2 id="breakdown-heading" class="text-xl font-semibold">{{ __('reports.hours.breakdown') }}</h2>
@foreach ($report->people as $person)
<details wire:key="details-{{ $person->userId }}" class="rounded-lg border border-zinc-300 p-3 dark:border-zinc-600">
<summary class="cursor-pointer font-medium focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600">
{{ __('reports.hours.person_summary', ['name' => $person->name, 'hours' => $this->hours($person->quarters)]) }}
</summary>
<div class="mt-3 grid gap-6 md:grid-cols-2">
<table class="w-full text-sm">
<caption class="mb-1 text-left font-semibold">{{ __('reports.hours.by_work_type') }}</caption>
<thead>
<tr class="text-left">
<th scope="col" class="py-1 pr-3">{{ __('reports.hours.work_type') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.hours.hours') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($person->byWorkType as $row)
<tr>
<th scope="row" class="py-1 pr-3 text-left font-normal">{{ $row->label }}</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->hours($row->quarters) }}</td>
</tr>
@endforeach
</tbody>
</table>
<table class="w-full text-sm">
<caption class="mb-1 text-left font-semibold">{{ __('reports.hours.by_job') }}</caption>
<thead>
<tr class="text-left">
<th scope="col" class="py-1 pr-3">{{ __('reports.hours.job') }}</th>
<th scope="col" class="py-1 text-right">{{ __('reports.hours.hours') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($person->byJob as $row)
<tr>
<th scope="row" class="py-1 pr-3 text-left font-normal">
<x-link :href="route('jobs.show', $row->jobId)" navigate>{{ $row->label }}</x-link>
</th>
<td class="py-1 text-right whitespace-nowrap">{{ $this->hours($row->quarters) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</details>
@endforeach
</section>
@endif
@endif
</div>
@@ -0,0 +1,54 @@
<?php
namespace App\Modules\Reports\Presentation;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
/**
* Finnish number, money and date formats of the reports, in both UI
* languages. Amounts may be negative (credits, losses), which Money does
* not hold, so the sign is added here.
*/
final class ReportFormat
{
public static function money(int $cents): string
{
return ($cents < 0 ? '-' : '').Money::fromCents(abs($cents))->format();
}
/**
* E.g. 6 quarters → "1,5".
*/
public static function hours(int $quarters): string
{
return rtrim(rtrim(number_format($quarters / 4, 2, ',', "\u{00A0}"), '0'), ',');
}
/**
* Hours for a CSV cell: a decimal comma and no thousands separator.
*/
public static function csvHours(int $quarters): string
{
return rtrim(rtrim(number_format($quarters / 4, 2, ',', ''), '0'), ',');
}
/**
* E.g. 0.256 → "25,6 %".
*/
public static function percent(float $ratio): string
{
return number_format($ratio * 100, 1, ',', "\u{00A0}")."\u{00A0}%";
}
public static function date(string $day): string
{
return (new DateTimeImmutable($day))->format('j.n.Y');
}
public static function period(ReportPeriod $period): string
{
return self::date($period->from).'–'.self::date($period->to);
}
}
@@ -0,0 +1,12 @@
<?php
use App\Modules\Reports\Presentation\Http\Controllers\DownloadReport;
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:reports.view'])
->prefix('reports')
->name('reports.')
->group(function () {
Route::livewire('/hours', 'reports::hours')->name('hours');
Route::get('/{report}/csv', DownloadReport::class)->whereIn('report', DownloadReport::REPORTS)->name('csv');
});
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ReportedHours;
use App\Modules\TimeTracking\Application\DTOs\UnbilledHours;
/**
* Hours summed for management's reports.
*/
interface TimeReportQueries
{
/**
* Hours worked from the first to the last day (Y-m-d, both included),
* summed by user, job and work type.
*
* @return list<ReportedHours>
*/
public function hoursBetween(string $from, string $to): array;
/**
* Hours not yet billed, worked on or before the day (Y-m-d), summed by
* job and work type.
*
* @return list<UnbilledHours>
*/
public function unbilledUntil(string $day): array;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A user's hours on a job's work type in a period, in quarter hours: all
* of them, those still waiting for approval and those already billed.
*/
final readonly class ReportedHours
{
public function __construct(
public int $userId,
public int $jobId,
public int $workTypeId,
public int $quarters,
public int $unapprovedQuarters,
public int $billedQuarters,
) {}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A job's unbilled hours on a work type in quarter hours, approved and
* waiting for approval, with the first day they were worked (Y-m-d).
*/
final readonly class UnbilledHours
{
public function __construct(
public int $jobId,
public int $workTypeId,
public int $approvedQuarters,
public int $unapprovedQuarters,
public string $oldestDay,
) {}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\TimeTracking\Application\Contracts\TimeReportQueries;
use App\Modules\TimeTracking\Application\DTOs\ReportedHours;
use App\Modules\TimeTracking\Application\DTOs\UnbilledHours;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
/**
* Sums hours in the database. Hours are kept in quarters (0,25 h), so four
* times their sum is a whole number.
*/
class EloquentTimeReportQueries implements TimeReportQueries
{
public function hoursBetween(string $from, string $to): array
{
return DB::table('time_entries')
->where('worked_on', '>=', $from)
->where('worked_on', '<', self::dayAfter($to))
->groupBy('user_id', 'customer_job_id', 'work_type_id')
->orderBy('user_id')
->select('user_id', 'customer_job_id', 'work_type_id')
->selectRaw('SUM(hours) * 4 as quarters')
->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN hours ELSE 0 END) * 4 as unapproved_quarters')
->selectRaw('SUM(CASE WHEN billing_export_id IS NULL THEN 0 ELSE hours END) * 4 as billed_quarters')
->get()
->map(fn (object $row): ReportedHours => new ReportedHours(
(int) $row->user_id,
(int) $row->customer_job_id,
(int) $row->work_type_id,
(int) round((float) $row->quarters),
(int) round((float) $row->unapproved_quarters),
(int) round((float) $row->billed_quarters),
))
->all();
}
public function unbilledUntil(string $day): array
{
return DB::table('time_entries')
->whereNull('billing_export_id')
->where('worked_on', '<', self::dayAfter($day))
->groupBy('customer_job_id', 'work_type_id')
->orderBy('customer_job_id')
->select('customer_job_id', 'work_type_id')
->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN 0 ELSE hours END) * 4 as approved_quarters')
->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN hours ELSE 0 END) * 4 as unapproved_quarters')
->selectRaw('MIN(worked_on) as oldest_day')
->get()
->map(fn (object $row): UnbilledHours => new UnbilledHours(
(int) $row->customer_job_id,
(int) $row->work_type_id,
(int) round((float) $row->approved_quarters),
(int) round((float) $row->unapproved_quarters),
substr((string) $row->oldest_day, 0, 10),
))
->all();
}
/**
* Days may be stored with a time, so a period ends before the next day.
*/
private static function dayAfter(string $day): string
{
return (new DateTimeImmutable($day))->modify('+1 day')->format('Y-m-d');
}
}
@@ -6,9 +6,11 @@ use App\Models\User;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
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\TimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryQueries;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeEntryRepository;
use App\Modules\TimeTracking\Infrastructure\Persistence\Repositories\EloquentTimeReportQueries;
use App\Modules\TimeTracking\Infrastructure\TaskUsageFromTimeEntries;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
@@ -26,6 +28,7 @@ class TimeTrackingServiceProvider extends ServiceProvider
public array $bindings = [
TimeEntryRepository::class => EloquentTimeEntryRepository::class,
TimeEntryQueries::class => EloquentTimeEntryQueries::class,
TimeReportQueries::class => EloquentTimeReportQueries::class,
TaskUsage::class => TaskUsageFromTimeEntries::class,
];