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]>
80 lines
2.5 KiB
PHP
80 lines
2.5 KiB
PHP
<?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),
|
|
};
|
|
}
|
|
}
|