of($export, Gate::allows('customers.view-personal-identity-code')); } catch (BillingExportNotFound|ExportNotCreated) { abort(404); } $number = $exportViews->of($export)->number ?? abort(404); return response()->streamDownload(function () use ($rows): void { $out = fopen('php://output', 'w'); if ($out === false) { return; } fwrite($out, "\u{FEFF}"); fputcsv($out, array_values(__('billing.csv.columns')), ';', '"', ''); foreach ($rows as $row) { fputcsv($out, array_map(self::cell(...), $this->cells($row)), ';', '"', ''); } fclose($out); }, __('billing.csv.file', ['number' => $number]), [ 'Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store, private', ]); } /** * @return list */ private function cells(ExportRow $row): array { $customer = $row->customer; return [ (string) $row->invoiceNumber, $customer->name, __($customer->isConsumer ? 'billing.csv.consumer' : 'billing.csv.company'), (string) $customer->businessId, (string) $customer->personalIdentityCode, (string) $customer->billingUnitName, (string) $customer->billingAddress, (string) $customer->eInvoiceAddress, (string) $customer->eInvoiceOperator, (string) $row->reference, $row->jobNumber, $row->jobName, __('billing.kinds.'.$row->kind->value), $row->description, $row->recordedQuarters === null ? '' : self::hours($row->recordedQuarters), $row->quantityQuarters === null ? '1' : self::hours($row->quantityQuarters), __('billing.csv.units.'.match ($row->kind) { LineKind::Hours => 'hours', LineKind::MonthlyFee => 'month', default => 'piece', }), (string) $row->unitPriceCents, self::decimal($row->vatBasisPoints, 10), (string) $row->netCents, (string) $row->vatCents, (string) $row->grossCents(), ]; } /** * Guards against formula injection: a cell that Excel would read as a * formula gets a leading apostrophe. */ public static function cell(string $value): string { return preg_match('/^[=+\-@\t\r\n]/', $value) === 1 ? "'".$value : $value; } private static function hours(int $quarters): string { return self::decimal($quarters * 25, 100); } /** * E.g. 2550 / 10 → "255", 1000 / 100 → "10", 250 / 100 → "2,5". */ private static function decimal(int $value, int $divisor): string { $text = number_format($value / $divisor, 2, ',', ''); return rtrim(rtrim($text, '0'), ','); } }