diff --git a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php index d9a4e9e..ea8e48e 100644 --- a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php +++ b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php @@ -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 $ids + * @return array + */ + public function reportInfoOf(array $ids): array; + /** * The job's history, newest first. * diff --git a/app/Modules/Jobs/Application/DTOs/JobReportInfo.php b/app/Modules/Jobs/Application/DTOs/JobReportInfo.php new file mode 100644 index 0000000..8fac03d --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/JobReportInfo.php @@ -0,0 +1,31 @@ + $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, + ) {} +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php index fd47ce7..780b268 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php @@ -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 $models * @return array diff --git a/app/Modules/Reports/Application/Contracts/ReportCatalog.php b/app/Modules/Reports/Application/Contracts/ReportCatalog.php new file mode 100644 index 0000000..2bb0081 --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportCatalog.php @@ -0,0 +1,27 @@ + + */ + public function workTypes(): array; + + /** + * Every service unit's name in catalog order, inactive ones included. + * + * @return array + */ + public function serviceUnits(): array; +} diff --git a/app/Modules/Reports/Application/Contracts/ReportHours.php b/app/Modules/Reports/Application/Contracts/ReportHours.php new file mode 100644 index 0000000..20adfbc --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportHours.php @@ -0,0 +1,29 @@ + + */ + public function between(ReportPeriod $period): array; + + /** + * Unbilled hours worked on or before the day (Y-m-d) by job and work type. + * + * @return list + */ + public function unbilledUntil(string $day): array; +} diff --git a/app/Modules/Reports/Application/Contracts/ReportJobs.php b/app/Modules/Reports/Application/Contracts/ReportJobs.php new file mode 100644 index 0000000..357f247 --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportJobs.php @@ -0,0 +1,19 @@ + $ids + * @return array Keyed by id; unknown ids are left out. + */ + public function infoOf(array $ids): array; +} diff --git a/app/Modules/Reports/Application/Contracts/ReportPeople.php b/app/Modules/Reports/Application/Contracts/ReportPeople.php new file mode 100644 index 0000000..d0fb4e8 --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportPeople.php @@ -0,0 +1,17 @@ + $ids + * @return array + */ + public function namesByIds(array $ids): array; +} diff --git a/app/Modules/Reports/Application/DTOs/HoursBreakdown.php b/app/Modules/Reports/Application/DTOs/HoursBreakdown.php new file mode 100644 index 0000000..60e1a82 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/HoursBreakdown.php @@ -0,0 +1,17 @@ + $people + * @param list $lines + * @param array $customers + * @param array $serviceUnits + */ + public function __construct( + public array $people, + public PersonHours $total, + public array $lines, + public array $customers, + public array $serviceUnits, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/PersonHours.php b/app/Modules/Reports/Application/DTOs/PersonHours.php new file mode 100644 index 0000000..55243d4 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/PersonHours.php @@ -0,0 +1,29 @@ + $byWorkType + * @param list $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 = [], + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/ReportJob.php b/app/Modules/Reports/Application/DTOs/ReportJob.php new file mode 100644 index 0000000..b47736e --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/ReportJob.php @@ -0,0 +1,32 @@ + $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, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/ReportWorkType.php b/app/Modules/Reports/Application/DTOs/ReportWorkType.php new file mode 100644 index 0000000..7b61f36 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/ReportWorkType.php @@ -0,0 +1,19 @@ +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 $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 $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 $items + * @param callable(T): int $value + */ + private static function sum(array $items, callable $value): int + { + return array_sum(array_map($value, $items)); + } +} diff --git a/app/Modules/Reports/Domain/Exceptions/InvalidReportPeriod.php b/app/Modules/Reports/Domain/Exceptions/InvalidReportPeriod.php new file mode 100644 index 0000000..b0a4715 --- /dev/null +++ b/app/Modules/Reports/Domain/Exceptions/InvalidReportPeriod.php @@ -0,0 +1,15 @@ + $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; + } +} diff --git a/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php b/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php new file mode 100644 index 0000000..278736c --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php @@ -0,0 +1,40 @@ +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; + } +} diff --git a/app/Modules/Reports/Infrastructure/Adapters/HoursForReports.php b/app/Modules/Reports/Infrastructure/Adapters/HoursForReports.php new file mode 100644 index 0000000..838c828 --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/HoursForReports.php @@ -0,0 +1,35 @@ + 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), + ); + } +} diff --git a/app/Modules/Reports/Infrastructure/Adapters/JobsForReports.php b/app/Modules/Reports/Infrastructure/Adapters/JobsForReports.php new file mode 100644 index 0000000..c8789a2 --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/JobsForReports.php @@ -0,0 +1,36 @@ + 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)); + } +} diff --git a/app/Modules/Reports/Infrastructure/Adapters/PeopleForReports.php b/app/Modules/Reports/Infrastructure/Adapters/PeopleForReports.php new file mode 100644 index 0000000..c862275 --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/PeopleForReports.php @@ -0,0 +1,19 @@ +users->namesByIds($ids); + } +} diff --git a/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php new file mode 100644 index 0000000..03e84d5 --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php @@ -0,0 +1,48 @@ + + */ + 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()); + } +} diff --git a/app/Modules/Reports/Presentation/Csv/HoursCsv.php b/app/Modules/Reports/Presentation/Csv/HoursCsv.php new file mode 100644 index 0000000..6272274 --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/HoursCsv.php @@ -0,0 +1,48 @@ +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; + } +} diff --git a/app/Modules/Reports/Presentation/Csv/ReportCsv.php b/app/Modules/Reports/Presentation/Csv/ReportCsv.php new file mode 100644 index 0000000..8b32afd --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/ReportCsv.php @@ -0,0 +1,23 @@ + + */ + public function headers(): array; + + /** + * @return iterable> + */ + public function rows(ReportPeriod $period, Request $request): iterable; +} diff --git a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php new file mode 100644 index 0000000..a735cf4 --- /dev/null +++ b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php @@ -0,0 +1,79 @@ +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), + }; + } +} diff --git a/app/Modules/Reports/Presentation/Livewire/Concerns/ReportPage.php b/app/Modules/Reports/Presentation/Livewire/Concerns/ReportPage.php new file mode 100644 index 0000000..e89a0f8 --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/Concerns/ReportPage.php @@ -0,0 +1,128 @@ +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 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 $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), + }; + } +} diff --git a/app/Modules/Reports/Presentation/Livewire/⚡hours.blade.php b/app/Modules/Reports/Presentation/Livewire/⚡hours.blade.php new file mode 100644 index 0000000..0fd2048 --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/⚡hours.blade.php @@ -0,0 +1,206 @@ +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')); + } +}; +?> + +
+

{{ __('reports.hours.title') }}

+ + + + @php($report = $this->report) + + @if ($report !== null) +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($report->serviceUnits as $id => $name) + + @endforeach + + + + + @foreach ($report->customers as $id => $name) + + @endforeach + +
+ +
+

{{ $this->periodLabel() }}

+ +
+ + @if ($report->people === []) +

{{ __('reports.hours.none') }}

+ @else +
+ + + + + + + + + + + + + + @foreach ($report->people as $person) + + + + + + + + + @endforeach + + + + + + + + + + + +
{{ __('reports.hours.table', ['period' => $this->periodLabel()]) }}
{{ __('reports.hours.person') }}{{ __('reports.hours.total') }}{{ __('reports.hours.customer') }}{{ __('reports.hours.internal') }}{{ __('reports.hours.unapproved') }}{{ __('reports.hours.billed') }}
{{ $person->name }}{{ $this->hours($person->quarters) }}{{ $this->hours($person->customerQuarters) }}{{ $this->hours($person->internalQuarters) }}{{ $this->hours($person->unapprovedQuarters) }}{{ $this->hours($person->billedQuarters) }}
{{ __('reports.total') }}{{ $this->hours($report->total->quarters) }}{{ $this->hours($report->total->customerQuarters) }}{{ $this->hours($report->total->internalQuarters) }}{{ $this->hours($report->total->unapprovedQuarters) }}{{ $this->hours($report->total->billedQuarters) }}
+
+ + + +
+

{{ __('reports.hours.breakdown') }}

+ + @foreach ($report->people as $person) +
+ + {{ __('reports.hours.person_summary', ['name' => $person->name, 'hours' => $this->hours($person->quarters)]) }} + + +
+ + + + + + + + + + @foreach ($person->byWorkType as $row) + + + + + @endforeach + +
{{ __('reports.hours.by_work_type') }}
{{ __('reports.hours.work_type') }}{{ __('reports.hours.hours') }}
{{ $row->label }}{{ $this->hours($row->quarters) }}
+ + + + + + + + + + + @foreach ($person->byJob as $row) + + + + + @endforeach + +
{{ __('reports.hours.by_job') }}
{{ __('reports.hours.job') }}{{ __('reports.hours.hours') }}
+ {{ $row->label }} + {{ $this->hours($row->quarters) }}
+
+
+ @endforeach +
+ @endif + @endif +
diff --git a/app/Modules/Reports/Presentation/ReportFormat.php b/app/Modules/Reports/Presentation/ReportFormat.php new file mode 100644 index 0000000..101bc62 --- /dev/null +++ b/app/Modules/Reports/Presentation/ReportFormat.php @@ -0,0 +1,54 @@ +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); + } +} diff --git a/app/Modules/Reports/Presentation/Routes/web.php b/app/Modules/Reports/Presentation/Routes/web.php new file mode 100644 index 0000000..b512f3e --- /dev/null +++ b/app/Modules/Reports/Presentation/Routes/web.php @@ -0,0 +1,12 @@ +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'); + }); diff --git a/app/Modules/TimeTracking/Application/Contracts/TimeReportQueries.php b/app/Modules/TimeTracking/Application/Contracts/TimeReportQueries.php new file mode 100644 index 0000000..2cf55a5 --- /dev/null +++ b/app/Modules/TimeTracking/Application/Contracts/TimeReportQueries.php @@ -0,0 +1,30 @@ + + */ + 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 + */ + public function unbilledUntil(string $day): array; +} diff --git a/app/Modules/TimeTracking/Application/DTOs/ReportedHours.php b/app/Modules/TimeTracking/Application/DTOs/ReportedHours.php new file mode 100644 index 0000000..aae6ce4 --- /dev/null +++ b/app/Modules/TimeTracking/Application/DTOs/ReportedHours.php @@ -0,0 +1,21 @@ +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'); + } +} diff --git a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php index 8f3c377..e363c85 100644 --- a/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php +++ b/app/Modules/TimeTracking/Infrastructure/Providers/TimeTrackingServiceProvider.php @@ -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, ]; diff --git a/app/View/MainMenu.php b/app/View/MainMenu.php index ac38e4f..bb8b091 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -94,6 +94,12 @@ final class MainMenu ['route' => 'billing.index', 'pattern' => ['billing.*'], 'label' => 'layout.billing', 'ability' => 'billing.manage'], ], ], + 'reports' => [ + 'label' => 'layout.group_reports', + 'items' => [ + ['route' => 'reports.hours', 'pattern' => ['reports.hours'], 'label' => 'layout.report_hours', 'ability' => 'reports.view'], + ], + ], 'maintenance' => [ 'label' => 'layout.group_maintenance', 'items' => [ diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 0594142..e75f79a 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -6,6 +6,7 @@ use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; use App\Modules\Notifications\Infrastructure\Providers\NotificationsServiceProvider; +use App\Modules\Reports\Infrastructure\Providers\ReportsServiceProvider; use App\Modules\Sales\Infrastructure\Providers\SalesServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider; @@ -26,4 +27,5 @@ return [ SalesServiceProvider::class, BillingServiceProvider::class, NotificationsServiceProvider::class, + ReportsServiceProvider::class, ]; diff --git a/lang/en/layout.php b/lang/en/layout.php index cfd5ac2..fb32f89 100644 --- a/lang/en/layout.php +++ b/lang/en/layout.php @@ -26,7 +26,13 @@ return [ 'group_own' => 'My entries', 'group_sales' => 'Customers and sales', 'group_admin' => 'Administration', + 'group_reports' => 'Reports', 'group_maintenance' => 'Maintenance', + 'report_hours' => 'Hours by person', + 'report_unbilled' => 'Unbilled hours', + 'report_profitability' => 'Profitability', + 'report_sales' => 'Quick sales', + 'report_reimbursements' => 'Expense reimbursements', 'new_job' => 'New job', 'sales_list' => 'Quick sales and cash days', 'workflow_templates' => 'Workflow templates', diff --git a/lang/en/reports.php b/lang/en/reports.php new file mode 100644 index 0000000..7e24173 --- /dev/null +++ b/lang/en/reports.php @@ -0,0 +1,63 @@ + 'Total', + 'yes' => 'yes', + 'no' => 'no', + 'download_csv' => 'Download CSV', + 'csv_file' => ':report-:from-:to.csv', + 'chart_note' => 'The same figures are in the table.', + 'chart_empty' => 'There is nothing to show in the chart.', + + 'period' => [ + 'legend' => 'Period', + 'from' => 'From', + 'to' => 'To', + 'presets' => 'Quick choices', + 'this_month' => 'This month', + 'previous_month' => 'Previous month', + 'this_year' => 'This year', + 'previous_year' => 'Previous year', + 'invalid' => 'Check the period: give two dates, the first one not after the second.', + ], + + 'filters' => [ + 'service_unit' => 'Service unit', + 'all_service_units' => 'All service units', + 'customer' => 'Customer', + 'all_customers' => 'All customers', + ], + + 'hours' => [ + 'title' => 'Hours by person', + 'file' => 'hours', + 'none' => 'No hours were recorded in the period.', + 'table' => 'Hours by person :period', + 'person' => 'Person', + 'total' => 'Total hours', + 'customer' => 'Customer work', + 'internal' => 'Internal work', + 'unapproved' => 'Not approved', + 'billed' => 'Billed', + 'chart' => 'Hours by person', + 'breakdown' => 'Breakdown by person', + 'person_summary' => ':name, :hours h', + 'by_work_type' => 'By work type', + 'by_job' => 'By customer job', + 'work_type' => 'Work type', + 'job' => 'Customer job', + 'hours' => 'Hours', + 'csv' => [ + 'person' => 'Person', + 'job_number' => 'Job number', + 'job' => 'Customer job', + 'customer' => 'Customer', + 'internal' => 'Internal', + 'service_unit' => 'Service unit', + 'work_type' => 'Work type', + 'hours' => 'Hours', + 'unapproved' => 'Not approved', + 'billed' => 'Billed', + ], + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index e1ca17a..408b793 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -26,7 +26,13 @@ return [ 'group_own' => 'Oma kirjaus', 'group_sales' => 'Asiakkaat ja myynti', 'group_admin' => 'Hallinto', + 'group_reports' => 'Raportit', 'group_maintenance' => 'Ylläpito', + 'report_hours' => 'Tunnit henkilöittäin', + 'report_unbilled' => 'Laskuttamattomat tunnit', + 'report_profitability' => 'Kannattavuus', + 'report_sales' => 'Pikamyynnit', + 'report_reimbursements' => 'Kulukorvaukset', 'new_job' => 'Uusi työ', 'sales_list' => 'Pikamyynnit ja kassapäivät', 'workflow_templates' => 'Työnkulkupohjat', diff --git a/lang/fi/reports.php b/lang/fi/reports.php new file mode 100644 index 0000000..434b1a6 --- /dev/null +++ b/lang/fi/reports.php @@ -0,0 +1,63 @@ + 'Yhteensä', + 'yes' => 'kyllä', + 'no' => 'ei', + 'download_csv' => 'Lataa CSV', + 'csv_file' => ':report-:from-:to.csv', + 'chart_note' => 'Samat luvut ovat taulukossa.', + 'chart_empty' => 'Kaaviossa ei ole näytettävää.', + + 'period' => [ + 'legend' => 'Aikaväli', + 'from' => 'Alkaen', + 'to' => 'Päättyen', + 'presets' => 'Pikavalinnat', + 'this_month' => 'Tämä kuukausi', + 'previous_month' => 'Edellinen kuukausi', + 'this_year' => 'Tämä vuosi', + 'previous_year' => 'Edellinen vuosi', + 'invalid' => 'Tarkista aikaväli: anna kaksi päivämäärää, joista ensimmäinen ei ole jälkimmäisen jälkeen.', + ], + + 'filters' => [ + 'service_unit' => 'Palveluyksikkö', + 'all_service_units' => 'Kaikki palveluyksiköt', + 'customer' => 'Asiakas', + 'all_customers' => 'Kaikki asiakkaat', + ], + + 'hours' => [ + 'title' => 'Tunnit henkilöittäin', + 'file' => 'tunnit', + 'none' => 'Aikavälillä ei ole kirjattuja tunteja.', + 'table' => 'Tunnit henkilöittäin :period', + 'person' => 'Henkilö', + 'total' => 'Tunnit yhteensä', + 'customer' => 'Asiakastyö', + 'internal' => 'Sisäinen työ', + 'unapproved' => 'Hyväksymättä', + 'billed' => 'Laskutettu', + 'chart' => 'Tunnit henkilöittäin', + 'breakdown' => 'Erittely henkilöittäin', + 'person_summary' => ':name, :hours h', + 'by_work_type' => 'Työtehtävittäin', + 'by_job' => 'Asiakastöittäin', + 'work_type' => 'Työtehtävä', + 'job' => 'Asiakastyö', + 'hours' => 'Tunnit', + 'csv' => [ + 'person' => 'Henkilö', + 'job_number' => 'Työn numero', + 'job' => 'Asiakastyö', + 'customer' => 'Asiakas', + 'internal' => 'Sisäinen', + 'service_unit' => 'Palveluyksikkö', + 'work_type' => 'Työtehtävä', + 'hours' => 'Tunnit', + 'unapproved' => 'Hyväksymättä', + 'billed' => 'Laskutettu', + ], + ], +]; diff --git a/resources/views/components/reports/chart.blade.php b/resources/views/components/reports/chart.blade.php new file mode 100644 index 0000000..65bc562 --- /dev/null +++ b/resources/views/components/reports/chart.blade.php @@ -0,0 +1,30 @@ +{{-- + A bar chart of one series for a report, drawn by TallStackUI's server + side SVG chart. The chart is one image named by its title and summary; + the same figures are in the report's table, which the caption points to. + No legend or tooltip: their controls would sit inside the image. +--}} +@props(['title', 'summary', 'labels' => [], 'values' => [], 'formatter' => null]) + +
class('space-y-2') }}> +
+ {{ $title }} + {{ __('reports.chart_note') }} +
+ + @if ($values === [] || max(array_map('abs', $values)) == 0) +

{{ __('reports.chart_empty') }}

+ @else + + @endif +
diff --git a/resources/views/components/reports/period-filter.blade.php b/resources/views/components/reports/period-filter.blade.php new file mode 100644 index 0000000..4e0ba7f --- /dev/null +++ b/resources/views/components/reports/period-filter.blade.php @@ -0,0 +1,33 @@ +{{-- + A report's period: first and last day (Livewire properties `from` and + `to`, saved on change) and quick choices that call choosePeriod(key). + The page's ReportPage trait provides both. When the days do not form a + period, an alert says so and the report is not shown. +--}} +@props(['presets' => [], 'valid' => true]) + +
class('space-y-3') }}> + {{ __('reports.period.legend') }} + +
+
+ +
+
+ +
+
+ +
+ @foreach ($presets as $key => $label) + + @endforeach +
+ + @unless ($valid) + + @endunless +
diff --git a/tests/Feature/MainMenuTest.php b/tests/Feature/MainMenuTest.php index ce6b42c..c511f5f 100644 --- a/tests/Feature/MainMenuTest.php +++ b/tests/Feature/MainMenuTest.php @@ -30,11 +30,11 @@ it('gives an employee work, own entries and customers and sales but no managemen ->and(menuLabels($user))->toContain('Uusi työ', 'Pikamyynti', 'Hinnasto'); }); -it('gives management the admin and maintenance groups but not user or company settings', function () { +it('gives management the admin, reports and maintenance groups but not user or company settings', function () { $user = User::factory()->management()->create(); - expect(menuGroupKeys($user))->toBe(['work', 'own', 'sales', 'admin', 'maintenance']) - ->and(menuLabels($user))->toContain('Laskutus', 'Pohjatiedot', 'Työnkulkupohjat') + expect(menuGroupKeys($user))->toBe(['work', 'own', 'sales', 'admin', 'reports', 'maintenance']) + ->and(menuLabels($user))->toContain('Laskutus', 'Tunnit henkilöittäin', 'Pohjatiedot', 'Työnkulkupohjat') ->and(menuLabels($user))->not->toContain('Käyttäjät', 'Yritystiedot'); }); diff --git a/tests/Feature/Modules/Reports/HoursReportTest.php b/tests/Feature/Modules/Reports/HoursReportTest.php new file mode 100644 index 0000000..d5781ac --- /dev/null +++ b/tests/Feature/Modules/Reports/HoursReportTest.php @@ -0,0 +1,132 @@ +manager = User::factory()->management()->create(['name' => 'Maija Johto']); + $this->actingAs($this->manager); + $this->worker = User::factory()->employee()->create(['name' => 'Aino Tekijä']); + $this->editing = WorkTypeModel::factory()->create(['name' => 'Editointi']); + $this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']); + $this->customerTask = TaskModel::factory()->create([ + 'customer_job_id' => CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Video'])->id, + 'work_type_id' => $this->editing->id, + ]); + $internalId = CustomerModel::query()->where('is_internal', true)->value('id'); + $this->internalTask = TaskModel::factory()->create([ + 'customer_job_id' => CustomerJobModel::factory()->create(['customer_id' => $internalId, 'name' => 'Hallinto'])->id, + 'work_type_id' => $this->editing->id, + ]); +}); + +/** + * @return list> + */ +function hoursCsvRows(string $content): array +{ + $handle = fopen('php://memory', 'r+'); + fwrite($handle, $content); + rewind($handle); + $rows = []; + + while (($row = fgetcsv($handle, null, ';', '"', '')) !== false) { + $rows[] = $row; + } + + return $rows; +} + +it('sums hours by person on customer and internal work in the period', function () { + TimeEntryModel::factory()->approved()->create(['user_id' => $this->worker->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-11-02', 'hours' => 2.5]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-11-30', 'hours' => 1]); + TimeEntryModel::factory()->approved()->create(['user_id' => $this->worker->id, 'task_id' => $this->internalTask->id, 'worked_on' => '2026-11-10', 'hours' => 0.75]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-12-01', 'hours' => 8]); + TimeEntryModel::factory()->create(['user_id' => $this->manager->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-10-31', 'hours' => 8]); + + $report = Livewire::withQueryParams(['alku' => '2026-11-01', 'loppu' => '2026-11-30']) + ->test('reports::hours') + ->assertOk() + ->assertSee('Aino Tekijä') + ->assertDontSee('Maija Johto') + ->instance() + ->report(); + + expect($report->people)->toHaveCount(1) + ->and($report->people[0]->quarters)->toBe(17) + ->and($report->people[0]->customerQuarters)->toBe(14) + ->and($report->people[0]->internalQuarters)->toBe(3) + ->and($report->people[0]->unapprovedQuarters)->toBe(4) + ->and($report->people[0]->byWorkType[0]->label)->toBe('Editointi') + ->and($report->people[0]->byJob[0]->quarters)->toBe(14) + ->and($report->total->quarters)->toBe(17); +}); + +it('narrows the hours to a customer or a service unit', function () { + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-11-02', 'hours' => 2]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $this->internalTask->id, 'worked_on' => '2026-11-02', 'hours' => 1]); + $otherUnit = ServiceUnitModel::factory()->create(); + DB::table('customer_job_service_unit')->where('customer_job_id', $this->internalTask->customer_job_id)->update(['service_unit_id' => $otherUnit->id]); + + $page = Livewire::withQueryParams(['alku' => '2026-11-01', 'loppu' => '2026-11-30'])->test('reports::hours'); + + $page->set('customer', (string) $this->customer->id); + expect($page->instance()->report()->total->quarters)->toBe(8); + + $page->set('customer', '')->set('serviceUnit', (string) $otherUnit->id); + expect($page->instance()->report()->total->quarters)->toBe(4); +}); + +it('starts with the current month and says when the period is not valid', function () { + $this->travelTo('2026-11-25 12:00'); + + Livewire::test('reports::hours') + ->assertSet('from', '2026-11-01') + ->assertSet('to', '2026-11-30') + ->call('choosePeriod', 'previous_year') + ->assertSet('from', '2025-01-01') + ->assertSet('to', '2025-12-31') + ->set('from', '2026-01-02') + ->set('to', '2026-01-01') + ->assertSee(__('reports.period.invalid')); +}); + +it('downloads the hours as CSV', function () { + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $this->customerTask->id, 'worked_on' => '2026-11-02', 'hours' => 2.5]); + + $response = $this->get(route('reports.csv', ['report' => 'hours', 'alku' => '2026-11-01', 'loppu' => '2026-11-30'])) + ->assertOk() + ->assertDownload('tunnit-2026-11-01-2026-11-30.csv'); + + expect($response->headers->get('Cache-Control'))->toContain('no-store'); + + $rows = hoursCsvRows(substr($response->streamedContent(), 3)); + expect($rows[0])->toBe(array_values(__('reports.hours.csv'))) + ->and($rows)->toHaveCount(2) + ->and($rows[1][0])->toBe('Aino Tekijä') + ->and($rows[1][3])->toBe('Asiakas Oy') + ->and($rows[1][4])->toBe('ei') + ->and($rows[1][6])->toBe('Editointi') + ->and(array_slice($rows[1], 7))->toBe(['2,5', '2,5', '0']); +}); + +it('is only for admin and management', function () { + $this->actingAs(User::factory()->employee()->create()); + + $this->get(route('reports.hours'))->assertForbidden(); + $this->get(route('reports.csv', ['report' => 'hours', 'alku' => '2026-11-01', 'loppu' => '2026-11-30']))->assertForbidden(); + + $this->actingAs(User::factory()->admin()->create()); + $this->get(route('reports.hours'))->assertOk(); + $this->get(route('reports.csv', ['report' => 'hours', 'alku' => 'x', 'loppu' => '2026-11-30']))->assertNotFound(); +});