Files
admin-erahn/app/Exports/LaporanKeseluruhan/PelangganbaruAllExportExcel.php
T
2025-05-15 13:12:44 +08:00

94 lines
3.1 KiB
PHP

<?php
namespace App\Exports\LaporanKeseluruhan;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
class PelangganbaruAllExportExcel implements FromCollection, WithHeadings, WithMapping, WithEvents, WithCustomStartCell
{
protected $pelangganbaruData;
protected $total = 0;
protected $counter = 1;
protected $startDate;
protected $endDate;
public function __construct($pelangganbaruData, $startDate = null, $endDate = null)
{
$this->pelangganbaruData = $pelangganbaruData;
$this->startDate = $startDate;
$this->endDate = $endDate;
}
public function collection()
{
return collect($this->pelangganbaruData);
}
public function headings(): array
{
return [
'No.',
'Kod Caw',
'Nama Cawangan',
'Jumlah',
];
}
public function map($row): array
{
$jumlah = is_numeric($row['total_pelanggan_baru'] ?? null) ? (float) $row['total_pelanggan_baru'] : 0;
$this->total += $jumlah;
return [
$this->counter++,
$row['kodcaw'] ?? '',
$row['details_caw'] ?? '',
number_format($jumlah, 2),
];
}
public function startCell(): string
{
return 'A3'; // Mulakan heading di baris 3
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
// Tajuk laporan di A1:D1
$event->sheet->mergeCells('A1:D1');
$event->sheet->setCellValue('A1', 'LAPORAN PELANGGAN BARU');
$event->sheet->getStyle('A1')->getFont()->setSize(14)->setBold(true);
$event->sheet->getStyle('A1')->getAlignment()->setHorizontal('center');
// Tarikh di A2:D2
$tarikhMula = $this->startDate ? date('d/m/Y', strtotime($this->startDate)) : '-';
$tarikhTamat = $this->endDate ? date('d/m/Y', strtotime($this->endDate)) : '-';
$event->sheet->mergeCells('A2:D2');
$event->sheet->setCellValue('A2', "Tempoh: {$tarikhMula} hingga {$tarikhTamat}");
$event->sheet->getStyle('A2')->getFont()->setItalic(true);
$event->sheet->getStyle('A2')->getAlignment()->setHorizontal('center');
// Kira baris terakhir untuk jumlah keseluruhan
$lastRow = count($this->pelangganbaruData) + 3 + 1; // +1 untuk heading
$event->sheet->mergeCells("A{$lastRow}:C{$lastRow}");
$event->sheet->setCellValue("A{$lastRow}", 'Jumlah Keseluruhan');
$event->sheet->setCellValue("D{$lastRow}", number_format($this->total, 2));
$event->sheet->getStyle("A{$lastRow}:D{$lastRow}")->getFont()->setBold(true);
$event->sheet->getStyle("A{$lastRow}:D{$lastRow}")->getAlignment()->setHorizontal('right');
},
];
}
}