TransactionExport.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Exports;
  3. use App\Models\Transaction;
  4. use App\Services\TransactionService;
  5. use Illuminate\Contracts\Support\Responsable;
  6. use Illuminate\Contracts\View\View;
  7. use Illuminate\Http\Request;
  8. use Maatwebsite\Excel\Concerns\Exportable;
  9. use Maatwebsite\Excel\Concerns\FromView;
  10. use Maatwebsite\Excel\Concerns\ShouldAutoSize;
  11. use Maatwebsite\Excel\Concerns\WithStyles;
  12. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  13. class TransactionExport implements ShouldAutoSize, Responsable, FromView, WithStyles
  14. {
  15. use Exportable;
  16. private $fileName = 'transaction-report.xls';
  17. public function __construct(private Request $request)
  18. {}
  19. public function view(): View
  20. {
  21. $transactions = Transaction::filter(request()->only('startDate', 'endDate', 'outlet'))
  22. ->get()
  23. ->groupBy('created_at')
  24. ->transform(fn($transactions) => [[
  25. 'date' => $transactions->first()->getRawOriginal('created_at'),
  26. 'createdAt' => $transactions->first()->created_at,
  27. 'totalTransaction' => $transactions->count(),
  28. 'totalPrice' => (new TransactionService)->totalPriceGroup($transactions),
  29. ]])
  30. ->flatten(1);
  31. return view('excel.transaction-report', compact('transactions'));
  32. }
  33. public function styles(Worksheet $sheet)
  34. {
  35. $lastRow = $sheet->getHighestDataRow();
  36. $lastSecondRow = $lastRow - 1;
  37. return [
  38. 1 => [
  39. 'font' => ['bold' => true, 'size' => 12],
  40. 'alignment' => ['vertical' => 'center', 'horizontal' => 'center'],
  41. ],
  42. 2 => [
  43. 'font' => ['bold' => true, 'size' => 12],
  44. 'alignment' => ['vertical' => 'center', 'horizontal' => 'center'],
  45. ],
  46. 4 => [
  47. 'font' => ['bold' => true],
  48. ],
  49. $lastRow => [
  50. 'font' => ['bold' => true, 'size' => 12],
  51. 'alignment' => ['horizontal' => 'left'],
  52. ],
  53. $lastSecondRow => [
  54. 'font' => ['bold' => true, 'size' => 12],
  55. 'alignment' => ['horizontal' => 'left'],
  56. ],
  57. ];
  58. }
  59. }