Files
Toiminnanohjaus/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php
T
petriandClaude Sonnet 5.5 568871c9dc Add the quick sales report
Quick sales of a period by cash day, product, seller and VAT rate, with
credits, open cash days flagged, a chart by day or month and CSV. VAT is
taken out of each day's total of a rate, as on the cash day balance.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-25 08:44:20 +02:00

82 lines
2.5 KiB
PHP

<?php
namespace App\Modules\Reports\Presentation\Http\Controllers;
use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod;
use App\Modules\Reports\Presentation\Csv\HoursCsv;
use App\Modules\Reports\Presentation\Csv\ReportCsv;
use App\Modules\Reports\Presentation\Csv\SalesCsv;
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
* 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', 'unbilled', 'sales'];
public function __invoke(string $report, Request $request): StreamedResponse
{
Gate::authorize('reports.view');
$csv = $this->csv($report);
try {
// Reading the file name checks the filters before anything is streamed.
$fileName = $csv->fileName($request).'.csv';
} catch (InvalidReportPeriod) {
abort(404);
}
return response()->streamDownload(function () use ($csv, $request): void {
$out = fopen('php://output', 'w');
if ($out === false) {
return;
}
fwrite($out, "\u{FEFF}");
fputcsv($out, $csv->headers(), ';', '"', '');
foreach ($csv->rows($request) as $row) {
fputcsv($out, array_map(self::cell(...), $row), ';', '"', '');
}
fclose($out);
}, $fileName, [
'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),
'unbilled' => app(UnbilledCsv::class),
'sales' => app(SalesCsv::class),
default => abort(404),
};
}
}