您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ExportService.php 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\ExportableReport;
  4. use App\Models\Company;
  5. use Barryvdh\DomPDF\Facade\Pdf;
  6. use Illuminate\Support\Carbon;
  7. use Symfony\Component\HttpFoundation\StreamedResponse;
  8. class ExportService
  9. {
  10. public function exportToCsv(Company $company, ExportableReport $report, string $startDate, string $endDate): StreamedResponse
  11. {
  12. $formattedStartDate = Carbon::parse($startDate)->format('Y-m-d');
  13. $formattedEndDate = Carbon::parse($endDate)->format('Y-m-d');
  14. $timestamp = Carbon::now()->format('Y-m-d-H_i');
  15. $filename = $company->name . ' ' . $report->getTitle() . ' ' . $formattedStartDate . ' to ' . $formattedEndDate . ' ' . $timestamp . '.csv';
  16. $headers = [
  17. 'Content-Type' => 'text/csv',
  18. 'Content-Disposition' => 'attachment; filename="' . $filename . '"',
  19. ];
  20. $callback = function () use ($report, $company, $formattedStartDate, $formattedEndDate) {
  21. $file = fopen('php://output', 'wb');
  22. fputcsv($file, [$report->getTitle()]);
  23. fputcsv($file, [$company->name]);
  24. fputcsv($file, ['Date Range: ' . $formattedStartDate . ' to ' . $formattedEndDate]);
  25. fputcsv($file, []);
  26. fputcsv($file, $report->getHeaders());
  27. foreach ($report->getCategories() as $category) {
  28. fputcsv($file, $category->header);
  29. foreach ($category->data as $accountRow) {
  30. fputcsv($file, $accountRow);
  31. }
  32. fputcsv($file, $category->summary);
  33. fputcsv($file, []); // Empty row for spacing
  34. }
  35. fputcsv($file, $report->getOverallTotals());
  36. fclose($file);
  37. };
  38. return response()->streamDownload($callback, $filename, $headers);
  39. }
  40. public function exportToPdf(Company $company, ExportableReport $report, string $startDate, string $endDate): StreamedResponse
  41. {
  42. $formattedStartDate = Carbon::parse($startDate)->format('Y-m-d');
  43. $formattedEndDate = Carbon::parse($endDate)->format('Y-m-d');
  44. $timestamp = Carbon::now()->format('Y-m-d-H_i');
  45. $filename = $company->name . ' ' . $report->getTitle() . ' ' . $formattedStartDate . ' to ' . $formattedEndDate . ' ' . $timestamp . '.pdf';
  46. $pdf = Pdf::loadView('components.company.reports.report-pdf', [
  47. 'company' => $company,
  48. 'report' => $report,
  49. 'startDate' => Carbon::parse($startDate)->format('M d, Y'),
  50. 'endDate' => Carbon::parse($endDate)->format('M d, Y'),
  51. ])->setPaper('letter');
  52. return response()->streamDownload(function () use ($pdf) {
  53. echo $pdf->stream();
  54. }, $filename);
  55. }
  56. }