From a57b383e4df19acb0bb247af2e1dc06371edc583 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 08:41:43 +0200 Subject: [PATCH] Add the unbilled hours report Hours on customers' billable jobs that no billing material has taken, by job and work type up to a day, valued at the hourly rates for jobs billed by the hour, with a chart by service unit and CSV. Co-Authored-By: Claude Sonnet 5.5 --- .../Reports/Application/DTOs/UnbilledJob.php | 27 +++ .../Application/DTOs/UnbilledReport.php | 26 +++ .../Application/DTOs/UnbilledWorkType.php | 22 ++ .../UseCases/UnbilledHoursReport.php | 101 +++++++++ .../Reports/Presentation/Csv/CsvFilters.php | 52 +++++ .../Reports/Presentation/Csv/HoursCsv.php | 19 +- .../Reports/Presentation/Csv/ReportCsv.php | 15 +- .../Reports/Presentation/Csv/UnbilledCsv.php | 49 +++++ .../Http/Controllers/DownloadReport.php | 28 +-- .../Livewire/Concerns/FormatsReports.php | 31 +++ .../Livewire/Concerns/ReportPage.php | 19 +- .../Livewire/⚡unbilled.blade.php | 191 ++++++++++++++++++ .../Reports/Presentation/Routes/web.php | 1 + app/View/MainMenu.php | 1 + lang/en/reports.php | 38 +++- lang/fi/reports.php | 38 +++- .../Reports/UnbilledHoursReportTest.php | 84 ++++++++ 17 files changed, 697 insertions(+), 45 deletions(-) create mode 100644 app/Modules/Reports/Application/DTOs/UnbilledJob.php create mode 100644 app/Modules/Reports/Application/DTOs/UnbilledReport.php create mode 100644 app/Modules/Reports/Application/DTOs/UnbilledWorkType.php create mode 100644 app/Modules/Reports/Application/UseCases/UnbilledHoursReport.php create mode 100644 app/Modules/Reports/Presentation/Csv/CsvFilters.php create mode 100644 app/Modules/Reports/Presentation/Csv/UnbilledCsv.php create mode 100644 app/Modules/Reports/Presentation/Livewire/Concerns/FormatsReports.php create mode 100644 app/Modules/Reports/Presentation/Livewire/⚡unbilled.blade.php create mode 100644 tests/Feature/Modules/Reports/UnbilledHoursReportTest.php diff --git a/app/Modules/Reports/Application/DTOs/UnbilledJob.php b/app/Modules/Reports/Application/DTOs/UnbilledJob.php new file mode 100644 index 0000000..bff8944 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/UnbilledJob.php @@ -0,0 +1,27 @@ + $workTypes + */ + public function __construct( + public ReportJob $job, + public int $approvedQuarters, + public int $unapprovedQuarters, + public ?int $valueCents, + public bool $missingRate, + public string $oldestDay, + public array $workTypes, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/UnbilledReport.php b/app/Modules/Reports/Application/DTOs/UnbilledReport.php new file mode 100644 index 0000000..0ff8320 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/UnbilledReport.php @@ -0,0 +1,26 @@ + $jobs + * @param array $valueByServiceUnit + * @param array $serviceUnits + */ + public function __construct( + public array $jobs, + public int $approvedQuarters, + public int $unapprovedQuarters, + public int $valueCents, + public array $valueByServiceUnit, + public array $serviceUnits, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/UnbilledWorkType.php b/app/Modules/Reports/Application/DTOs/UnbilledWorkType.php new file mode 100644 index 0000000..3dfa3fb --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/UnbilledWorkType.php @@ -0,0 +1,22 @@ +hours->unbilledUntil($day); + $jobs = $this->jobs->infoOf(array_values(array_unique(array_map(fn (UnbilledEntry $entry): int => $entry->jobId, $entries)))); + $workTypes = $this->catalog->workTypes(); + + $byJob = []; + foreach ($entries as $entry) { + $job = $jobs[$entry->jobId] ?? null; + + if ($job === null || ! $job->isBillable) { + continue; + } + + if ($serviceUnitId !== null && ! in_array($serviceUnitId, $job->serviceUnitIds, true)) { + continue; + } + + $byJob[$job->id][] = $entry; + } + + $rows = []; + $valueByServiceUnit = []; + + foreach ($byJob as $jobId => $jobEntries) { + $job = $jobs[$jobId]; + $lines = []; + $missingRate = false; + + foreach ($jobEntries as $entry) { + $workType = $workTypes[$entry->workTypeId] ?? null; + $rate = $workType?->rateCents; + $value = null; + + if ($job->billsHours) { + if ($rate === null) { + $missingRate = true; + } else { + // Rounded half up to a cent, as on invoice lines. + $value = intdiv(($entry->approvedQuarters + $entry->unapprovedQuarters) * $rate * 2 + 4, 8); + $unit = $workType->serviceUnitName; + $valueByServiceUnit[$unit] = ($valueByServiceUnit[$unit] ?? 0) + $value; + } + } + + $lines[] = new UnbilledWorkType($workType->name ?? '', $workType->serviceUnitName ?? '', $entry->approvedQuarters, $entry->unapprovedQuarters, $rate, $value); + } + + $rows[] = new UnbilledJob( + $job, + array_sum(array_map(fn (UnbilledEntry $entry): int => $entry->approvedQuarters, $jobEntries)), + array_sum(array_map(fn (UnbilledEntry $entry): int => $entry->unapprovedQuarters, $jobEntries)), + $job->billsHours ? array_sum(array_map(fn (UnbilledWorkType $line): int => $line->valueCents ?? 0, $lines)) : null, + $missingRate, + min(array_map(fn (UnbilledEntry $entry): string => $entry->oldestDay, $jobEntries)), + $lines, + ); + } + + usort($rows, fn (UnbilledJob $a, UnbilledJob $b): int => [$a->oldestDay, $a->job->number] <=> [$b->oldestDay, $b->job->number]); + arsort($valueByServiceUnit); + + return new UnbilledReport( + $rows, + array_sum(array_map(fn (UnbilledJob $row): int => $row->approvedQuarters, $rows)), + array_sum(array_map(fn (UnbilledJob $row): int => $row->unapprovedQuarters, $rows)), + array_sum(array_map(fn (UnbilledJob $row): int => $row->valueCents ?? 0, $rows)), + $valueByServiceUnit, + $this->catalog->serviceUnits(), + ); + } +} diff --git a/app/Modules/Reports/Presentation/Csv/CsvFilters.php b/app/Modules/Reports/Presentation/Csv/CsvFilters.php new file mode 100644 index 0000000..897584e --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/CsvFilters.php @@ -0,0 +1,52 @@ +from; + } + + public static function id(Request $request, string $key): ?int + { + $value = self::text($request, $key); + + return ctype_digit($value) ? (int) $value : null; + } + + public static function flag(Request $request, string $key): bool + { + return self::text($request, $key) === '1'; + } + + private static function text(Request $request, string $key): string + { + $value = $request->query($key); + + return is_string($value) ? $value : ''; + } +} diff --git a/app/Modules/Reports/Presentation/Csv/HoursCsv.php b/app/Modules/Reports/Presentation/Csv/HoursCsv.php index 6272274..bf23e1f 100644 --- a/app/Modules/Reports/Presentation/Csv/HoursCsv.php +++ b/app/Modules/Reports/Presentation/Csv/HoursCsv.php @@ -3,7 +3,6 @@ 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; @@ -14,14 +13,21 @@ class HoursCsv implements ReportCsv { public function __construct(private HoursByPerson $report) {} + public function fileName(Request $request): string + { + $period = CsvFilters::period($request); + + return __('reports.hours.file').'-'.$period->from.'-'.$period->to; + } + public function headers(): array { return array_values(__('reports.hours.csv')); } - public function rows(ReportPeriod $period, Request $request): iterable + public function rows(Request $request): iterable { - $report = $this->report->execute($period, self::id($request, 'yksikko'), self::id($request, 'asiakas')); + $report = $this->report->execute(CsvFilters::period($request), CsvFilters::id($request, 'yksikko'), CsvFilters::id($request, 'asiakas')); foreach ($report->lines as $line) { yield [ @@ -38,11 +44,4 @@ class HoursCsv implements ReportCsv ]; } } - - 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 index 8b32afd..4bfa6ec 100644 --- a/app/Modules/Reports/Presentation/Csv/ReportCsv.php +++ b/app/Modules/Reports/Presentation/Csv/ReportCsv.php @@ -2,15 +2,22 @@ namespace App\Modules\Reports\Presentation\Csv; -use App\Modules\Reports\Domain\ValueObjects\ReportPeriod; +use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod; use Illuminate\Http\Request; /** * A report as CSV rows, with the filters of the report page read from the - * request's query string. + * request's query string (see CsvFilters). */ interface ReportCsv { + /** + * The file name without the extension, e.g. "tunnit-2026-11-01-2026-11-30". + * + * @throws InvalidReportPeriod + */ + public function fileName(Request $request): string; + /** * @return list */ @@ -18,6 +25,8 @@ interface ReportCsv /** * @return iterable> + * + * @throws InvalidReportPeriod */ - public function rows(ReportPeriod $period, Request $request): iterable; + public function rows(Request $request): iterable; } diff --git a/app/Modules/Reports/Presentation/Csv/UnbilledCsv.php b/app/Modules/Reports/Presentation/Csv/UnbilledCsv.php new file mode 100644 index 0000000..d6f4253 --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/UnbilledCsv.php @@ -0,0 +1,49 @@ +report->execute(CsvFilters::day($request, 'paiva'), CsvFilters::id($request, 'yksikko')); + + foreach ($report->jobs as $row) { + foreach ($row->workTypes as $line) { + yield [ + $row->job->number, + $row->job->name, + $row->job->customerName, + __('jobs.statuses.'.$row->job->status), + $row->job->paymentBasis === null ? '' : __('jobs.payment_bases.'.$row->job->paymentBasis), + $line->serviceUnitName, + $line->name, + ReportFormat::csvHours($line->approvedQuarters), + ReportFormat::csvHours($line->unapprovedQuarters), + $line->rateCents ?? '', + $line->valueCents ?? '', + $row->oldestDay, + ]; + } + } + } +} diff --git a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php index a735cf4..034d6b2 100644 --- a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php +++ b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php @@ -3,39 +3,38 @@ 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 App\Modules\Reports\Presentation\Csv\UnbilledCsv; 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. + * in the query string: 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 const array REPORTS = ['hours', 'unbilled']; public function __invoke(string $report, Request $request): StreamedResponse { Gate::authorize('reports.view'); + $csv = $this->csv($report); + try { - $period = new ReportPeriod((string) $request->query('alku', ''), (string) $request->query('loppu', '')); + // Reading the file name checks the filters before anything is streamed. + $fileName = $csv->fileName($request).'.csv'; } catch (InvalidReportPeriod) { abort(404); } - $csv = $this->csv($report); - $rows = $csv->rows($period, $request); - $headers = $csv->headers(); - - return response()->streamDownload(function () use ($headers, $rows): void { + return response()->streamDownload(function () use ($csv, $request): void { $out = fopen('php://output', 'w'); if ($out === false) { @@ -43,14 +42,14 @@ class DownloadReport } fwrite($out, "\u{FEFF}"); - fputcsv($out, $headers, ';', '"', ''); + fputcsv($out, $csv->headers(), ';', '"', ''); - foreach ($rows as $row) { + foreach ($csv->rows($request) as $row) { fputcsv($out, array_map(self::cell(...), $row), ';', '"', ''); } fclose($out); - }, __('reports.csv_file', ['report' => __('reports.'.$report.'.file'), 'from' => $period->from, 'to' => $period->to]), [ + }, $fileName, [ 'Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store, private', ]); @@ -73,6 +72,7 @@ class DownloadReport { return match ($report) { 'hours' => app(HoursCsv::class), + 'unbilled' => app(UnbilledCsv::class), default => abort(404), }; } diff --git a/app/Modules/Reports/Presentation/Livewire/Concerns/FormatsReports.php b/app/Modules/Reports/Presentation/Livewire/Concerns/FormatsReports.php new file mode 100644 index 0000000..1c3f30b --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/Concerns/FormatsReports.php @@ -0,0 +1,31 @@ +authorize('reports.view'); + + if (! $this->dayIsValid()) { + $this->day = $clock->today()->format('Y-m-d'); + } + } + + #[Computed] + public function report(): ?UnbilledReport + { + if (! $this->dayIsValid()) { + return null; + } + + return app(UnbilledHoursReport::class)->execute($this->day, ctype_digit($this->serviceUnit) ? (int) $this->serviceUnit : null); + } + + public function updated(): void + { + $this->authorize('reports.view'); + unset($this->report); + } + + public function dayIsValid(): bool + { + try { + new ReportPeriod($this->day, $this->day); + + return true; + } catch (InvalidReportPeriod) { + return false; + } + } + + public function csv(): string + { + return route('reports.csv', array_filter(['report' => 'unbilled', 'paiva' => $this->day, 'yksikko' => $this->serviceUnit])); + } + + public function valueText(UnbilledJob $row): string + { + if ($row->valueCents === null) { + return __('reports.unbilled.in_price'); + } + + return $this->money($row->valueCents).($row->missingRate ? ' '.__('reports.unbilled.missing_rate_short') : ''); + } + + public function render(): mixed + { + return $this->view()->title(__('reports.unbilled.title')); + } +}; +?> + +
+
+

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

+

{{ __('reports.unbilled.intro') }}

+
+ + @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 + + @endif +
+ + @if ($report === null) + + @else +
+

{{ __('reports.unbilled.until', ['day' => $this->dateLabel($day)]) }}

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

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

+ @else +
+ + + + + + + + + + + + + + @foreach ($report->jobs as $row) + + + + + + + + + @endforeach + + + + + + + + + +
{{ __('reports.unbilled.table', ['day' => $this->dateLabel($day)]) }}
{{ __('reports.unbilled.job') }}{{ __('reports.unbilled.status') }}{{ __('reports.unbilled.oldest') }}{{ __('reports.unbilled.approved') }}{{ __('reports.unbilled.unapproved') }}{{ __('reports.unbilled.value') }}
+ {{ $row->job->number }} {{ $row->job->name }} + {{ $row->job->customerName }} +
+ + {{ __('reports.unbilled.by_work_type', ['job' => $row->job->number]) }} + +
    + @foreach ($row->workTypes as $line) +
  • + {{ __('reports.unbilled.work_type_line', [ + 'name' => $line->name, + 'approved' => $this->hours($line->approvedQuarters), + 'unapproved' => $this->hours($line->unapprovedQuarters), + ]) }}@if ($line->valueCents !== null), {{ $this->money($line->valueCents) }}@elseif ($row->job->billsHours) ({{ __('reports.unbilled.missing_rate') }})@endif +
  • + @endforeach +
+
+
+ {{ __('jobs.statuses.'.$row->job->status) }} + @if ($row->job->paymentBasis !== null) + {{ __('jobs.payment_bases.'.$row->job->paymentBasis) }} + @endif + {{ $this->dateLabel($row->oldestDay) }}{{ $this->hours($row->approvedQuarters) }}{{ $this->hours($row->unapprovedQuarters) }}{{ $this->valueText($row) }}
{{ __('reports.total') }}{{ $this->hours($report->approvedQuarters) }}{{ $this->hours($report->unapprovedQuarters) }}{{ $this->money($report->valueCents) }}
+
+ + + @endif + @endif +
diff --git a/app/Modules/Reports/Presentation/Routes/web.php b/app/Modules/Reports/Presentation/Routes/web.php index b512f3e..ea61224 100644 --- a/app/Modules/Reports/Presentation/Routes/web.php +++ b/app/Modules/Reports/Presentation/Routes/web.php @@ -8,5 +8,6 @@ Route::middleware(['web', 'auth', 'can:reports.view']) ->name('reports.') ->group(function () { Route::livewire('/hours', 'reports::hours')->name('hours'); + Route::livewire('/unbilled', 'reports::unbilled')->name('unbilled'); Route::get('/{report}/csv', DownloadReport::class)->whereIn('report', DownloadReport::REPORTS)->name('csv'); }); diff --git a/app/View/MainMenu.php b/app/View/MainMenu.php index bb8b091..95fd5d1 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -98,6 +98,7 @@ final class MainMenu 'label' => 'layout.group_reports', 'items' => [ ['route' => 'reports.hours', 'pattern' => ['reports.hours'], 'label' => 'layout.report_hours', 'ability' => 'reports.view'], + ['route' => 'reports.unbilled', 'pattern' => ['reports.unbilled'], 'label' => 'layout.report_unbilled', 'ability' => 'reports.view'], ], ], 'maintenance' => [ diff --git a/lang/en/reports.php b/lang/en/reports.php index 7e24173..7f72d2a 100644 --- a/lang/en/reports.php +++ b/lang/en/reports.php @@ -5,7 +5,6 @@ return [ '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.', @@ -60,4 +59,41 @@ return [ 'billed' => 'Billed', ], ], + + 'unbilled' => [ + 'title' => 'Unbilled hours', + 'file' => 'unbilled-hours', + 'intro' => 'Hours on customers’ billable jobs that no billing material has billed yet, approved and not approved. The value is the hours times the work type’s hourly rate (VAT 0) on jobs billed by the hour; a fixed quote or monthly fee covers the hours of other jobs. Internal and not billable jobs are left out.', + 'day' => 'Worked on or before', + 'invalid_day' => 'Check the date.', + 'until' => 'Worked on or before :day', + 'none' => 'There are no unbilled hours.', + 'table' => 'Unbilled hours by customer job, worked on or before :day', + 'job' => 'Customer job', + 'status' => 'Status and payment basis', + 'oldest' => 'Oldest entry', + 'approved' => 'Approved', + 'unapproved' => 'Not approved', + 'value' => 'Value (VAT 0)', + 'in_price' => 'Included in the price', + 'missing_rate' => 'no hourly rate', + 'missing_rate_short' => '(partly no hourly rate)', + 'by_work_type' => 'By work type: :job', + 'work_type_line' => ':name: approved :approved h, not approved :unapproved h', + 'chart' => 'Value of unbilled hours by service unit', + 'csv' => [ + 'job_number' => 'Job number', + 'job' => 'Customer job', + 'customer' => 'Customer', + 'status' => 'Status', + 'payment_basis' => 'Payment basis', + 'service_unit' => 'Service unit', + 'work_type' => 'Work type', + 'approved' => 'Approved', + 'unapproved' => 'Not approved', + 'rate' => 'Hourly rate (cents)', + 'value' => 'Value (cents)', + 'oldest' => 'Oldest entry', + ], + ], ]; diff --git a/lang/fi/reports.php b/lang/fi/reports.php index 434b1a6..6e2f24c 100644 --- a/lang/fi/reports.php +++ b/lang/fi/reports.php @@ -5,7 +5,6 @@ return [ '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ää.', @@ -60,4 +59,41 @@ return [ 'billed' => 'Laskutettu', ], ], + + 'unbilled' => [ + 'title' => 'Laskuttamattomat tunnit', + 'file' => 'laskuttamattomat-tunnit', + 'intro' => 'Asiakkaiden laskutettavien töiden tunnit, joita mikään laskuaineisto ei ole vielä laskuttanut, hyväksytyt ja hyväksymättömät. Arvo on tunnit kertaa työtehtävän tuntihinta (ALV 0) töillä, jotka laskutetaan tunneittain; kiinteän tarjouksen ja kuukausihinnan tunnit sisältyvät hintaan. Sisäiset ja ei laskutettavat työt eivät ole mukana.', + 'day' => 'Tehty viimeistään', + 'invalid_day' => 'Tarkista päivämäärä.', + 'until' => 'Tehty viimeistään :day', + 'none' => 'Laskuttamattomia tunteja ei ole.', + 'table' => 'Laskuttamattomat tunnit asiakastöittäin, tehty viimeistään :day', + 'job' => 'Asiakastyö', + 'status' => 'Tila ja maksuperuste', + 'oldest' => 'Vanhin kirjaus', + 'approved' => 'Hyväksytty', + 'unapproved' => 'Hyväksymättä', + 'value' => 'Arvo (ALV 0)', + 'in_price' => 'Sisältyy hintaan', + 'missing_rate' => 'tuntihinta puuttuu', + 'missing_rate_short' => '(osalta tuntihinta puuttuu)', + 'by_work_type' => 'Työtehtävittäin: :job', + 'work_type_line' => ':name: hyväksytty :approved h, hyväksymättä :unapproved h', + 'chart' => 'Laskuttamattomien tuntien arvo palveluyksiköittäin', + 'csv' => [ + 'job_number' => 'Työn numero', + 'job' => 'Asiakastyö', + 'customer' => 'Asiakas', + 'status' => 'Tila', + 'payment_basis' => 'Maksuperuste', + 'service_unit' => 'Palveluyksikkö', + 'work_type' => 'Työtehtävä', + 'approved' => 'Hyväksytty', + 'unapproved' => 'Hyväksymättä', + 'rate' => 'Tuntihinta (snt)', + 'value' => 'Arvo (snt)', + 'oldest' => 'Vanhin kirjaus', + ], + ], ]; diff --git a/tests/Feature/Modules/Reports/UnbilledHoursReportTest.php b/tests/Feature/Modules/Reports/UnbilledHoursReportTest.php new file mode 100644 index 0000000..22621be --- /dev/null +++ b/tests/Feature/Modules/Reports/UnbilledHoursReportTest.php @@ -0,0 +1,84 @@ +actingAs(User::factory()->management()->create()); + $this->editing = WorkTypeModel::factory()->create(['name' => 'Editointi', 'hourly_rate_cents' => 8050]); + $this->unpriced = WorkTypeModel::factory()->create(['name' => 'Suunnittelu']); + $this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']); +}); + +function unbilledJob(array $attributes): CustomerJobModel +{ + return CustomerJobModel::factory()->create(array_merge(['customer_id' => test()->customer->id], $attributes)); +} + +function unbilledHours(CustomerJobModel $job, WorkTypeModel $workType, float $hours, string $day, bool $approved = true): TimeEntryModel +{ + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $workType->id]); + $factory = $approved ? TimeEntryModel::factory()->approved() : TimeEntryModel::factory(); + + return $factory->create(['task_id' => $task->id, 'hours' => $hours, 'worked_on' => $day]); +} + +it('values unbilled hours of jobs billed by the hour and leaves out billed, internal and not billable work', function () { + $hourly = unbilledJob(['name' => 'Tuntityö', 'payment_basis' => 'hourly']); + unbilledHours($hourly, $this->editing, 2.5, '2026-11-02'); + unbilledHours($hourly, $this->editing, 1, '2026-11-20', approved: false); + unbilledHours($hourly, $this->unpriced, 1, '2026-11-03'); + unbilledHours($hourly, $this->editing, 3, '2026-11-26'); + + $quote = unbilledJob(['name' => 'Tarjous', 'payment_basis' => 'fixed_quote']); + unbilledHours($quote, $this->editing, 4, '2026-10-01'); + + $billedExport = DB::table('billing_exports')->insertGetId(['status' => 'created', 'period' => '2026-10', 'created_by' => auth()->id(), 'created_at' => now(), 'updated_at' => now()]); + unbilledHours($hourly, $this->editing, 5, '2026-10-15')->update(['billing_export_id' => $billedExport]); + unbilledHours(unbilledJob(['payment_basis' => 'not_billable']), $this->editing, 6, '2026-11-02'); + unbilledHours(CustomerJobModel::factory()->create(['customer_id' => CustomerModel::query()->where('is_internal', true)->value('id')]), $this->editing, 7, '2026-11-02'); + + $report = Livewire::withQueryParams(['paiva' => '2026-11-25']) + ->test('reports::unbilled') + ->assertOk() + ->assertSee('Tuntityö') + ->assertSee(__('reports.unbilled.in_price')) + ->instance() + ->report(); + + expect($report->jobs)->toHaveCount(2) + ->and($report->jobs[0]->job->name)->toBe('Tarjous') + ->and($report->jobs[0]->valueCents)->toBeNull() + ->and($report->jobs[1]->approvedQuarters)->toBe(14) + ->and($report->jobs[1]->unapprovedQuarters)->toBe(4) + ->and($report->jobs[1]->valueCents)->toBe(28175) + ->and($report->jobs[1]->missingRate)->toBeTrue() + ->and($report->jobs[1]->oldestDay)->toBe('2026-11-02') + ->and($report->valueCents)->toBe(28175) + ->and($report->approvedQuarters)->toBe(30); +}); + +it('downloads the unbilled hours as CSV', function () { + unbilledHours(unbilledJob(['name' => 'Tuntityö', 'payment_basis' => 'hourly']), $this->editing, 2.5, '2026-11-02'); + + $response = $this->get(route('reports.csv', ['report' => 'unbilled', 'paiva' => '2026-11-25'])) + ->assertOk() + ->assertDownload('laskuttamattomat-tunnit-2026-11-25.csv'); + + $content = substr($response->streamedContent(), 3); + $lines = array_map(fn (string $line): array => str_getcsv($line, ';', '"', ''), array_values(array_filter(explode("\n", $content)))); + + expect($lines[0])->toBe(array_values(__('reports.unbilled.csv'))) + ->and(array_slice($lines[1], 1))->toBe(['Tuntityö', 'Asiakas Oy', 'Alustava', 'Tuntityö', $lines[1][5], 'Editointi', '2,5', '0', '8050', '20125', '2026-11-02']); + + $this->get(route('reports.csv', ['report' => 'unbilled', 'paiva' => '2026-02-30']))->assertNotFound(); +});