Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
7.6 kB
5
Indexable
Never
<?php

namespace App\Exports;

use App\Models\Expenditure;
use App\Models\FieldPlant;
use App\Models\Harvest;
use App\Models\Sale;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class KomoditiExport implements FromArray, WithStyles
{
    protected $data;
    public function __construct($request)
    {
        $query = Harvest::with(['plant', 'field']);

        if ($request['komoditi']) {
            $query->where('komoditi', $request['komoditi']);
        }

        if ($request['date'] != null) {
            $dateRange = explode(' to ', $request['date']);
            $startDate = $dateRange[0];
            if (isset($endDate[1])) {
                $endDate = $dateRange[1];
            } else {
                $endDate = $startDate;
            }

            $query->whereBetween('harvest_date', [$startDate, $endDate]);
        }

        return $this->data = $query->get();
    }

    public function array(): array
    {
        $exportData = [];
        $currentPlant = null;
        $currentField = null;
        $totalPanen = 0;

        $addedHeaders = [];
        $processedSales = [];
        $processedExpenditures = [];

        foreach ($this->data as $harvest) {
            $newPlant = $harvest->plant->name;
            $newField = $harvest->field->name;

            $headerKey = $newPlant . '|' . $newField;

            if (!isset($addedHeaders[$headerKey])) {
                if ($currentPlant !== null) {
                    $exportData[] = ['', '', '', '', '', '', '', '', '', '', '', ''];
                }

                $currentPlant = $newPlant;
                $currentField = $newField;
                $totalPanen = 0;

                $a = $harvest->field->luas ?? 0;

                $exportData[] = [
                    ['Nama tanaman', $currentPlant ?? 'Nama tanaman tidak ditemukan'],
                    ['Tanggal tanam', $harvest->plant->planting_date ?? 'Tanggal tanam tidak ditemukan'],
                    ['Lokasi lahan', $currentField ?? 'Lokasi lahan tidak ditemukan'],
                    ['Jumlah tanaman', $harvest->plant->qty ?? '0'],
                    ['Luasan lahan', $a, 'meter'],
                    [''],
                    ['Pendapatan dan pengeluaran', '', '', '', '', '', '', '', '', 'Panen'],
                    ['tanggal', 'keterangan', 'qty', 'satuan', 'harga satuan', 'debit', 'kredit', 'total', '', 'tanggal', 'qty', 'satuan', 'Total panen'],
                ];

                $addedHeaders[$headerKey] = true;
            }

            $financialData = [];
            $total = 0;

            $sales = Sale::with('buyer')->where('id_product', $harvest->plant->id)->get();

            foreach ($sales as $sale) {
                if (!isset($processedSales[$sale->id])) {
                    $debit = $sale->quantity_sale * $sale->unit_price;
                    $total += $debit;
                    $displayTotal = $total >= 0 ? (string)$total : '-' . (string)abs($total);

                    $financialData[] = [
                        'date' => $sale->date,
                        'data' => [
                            $sale->date,
                            'Penjualan ' . $sale->buyer->name,
                            $sale->quantity_sale,
                            $sale->unit,
                            $sale->unit_price,
                            $debit,
                            '',
                            $displayTotal,
                            '',
                            '',
                            '',
                            ''
                        ]
                    ];
                    $processedSales[$sale->id] = true;
                }
            }

            $expenditures = Expenditure::with('expenditureItems')
                ->where('id_field', $harvest->field->id)
                ->get();

            foreach ($expenditures as $expenditure) {
                foreach ($expenditure->expenditureItems as $item) {
                    if ($item->name === $harvest->plant->name && !isset($processedExpenditures[$expenditure->id])) {
                        $credit = $item->qty * $item->price;
                        $total -= $credit;
                        $displayTotal = $total >= 0 ? (string)$total : '-' . (string)abs($total);

                        $financialData[] = [
                            'date' => $expenditure->date,
                            'data' => [
                                $expenditure->date,
                                $expenditure->name,
                                $item->qty,
                                $item->unit,
                                $item->price,
                                '',
                                $credit,
                                $displayTotal,
                                '',
                                '',
                                '',
                                ''
                            ]
                        ];
                        $processedExpenditures[$expenditure->id] = true;
                    }
                }
            }

            usort($financialData, function ($a, $b) {
                return strtotime($a['date']) - strtotime($b['date']);
            });

            if (!empty($financialData)) {
                $lastIndex = count($financialData) - 2;
                $financialData[$lastIndex]['data'][9] = $harvest->harvest_date;
                $financialData[$lastIndex]['data'][10] = $harvest->quantity;
                $financialData[$lastIndex]['data'][11] = $harvest->unit;
                $financialData[$lastIndex]['data'][12] = $totalPanen + $harvest->quantity;
            } else {
                $financialData[] = [
                    'date' => $harvest->harvest_date,
                    'data' => [
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        '',
                        $harvest->harvest_date,
                        $harvest->quantity,
                        $harvest->unit,
                        $totalPanen + $harvest->quantity
                    ]
                ];
            }

            foreach ($financialData as $data) {
                $exportData[] = $data['data'];
            }

            $totalPanen += $harvest->quantity;
        }

        return $exportData;
    }


    public function styles(Worksheet $sheet)
    {
        $boldRows = [];
        $headerRowIndex = 8;

        foreach ($sheet->getRowIterator() as $row) {
            $cell = $sheet->getCell('A' . $row->getRowIndex());
            if ($cell->getValue() === 'Pendapatan dan pengeluaran') {
                $headerRowIndex = $row->getRowIndex();
                $boldRows[] = $headerRowIndex;
                $boldRows[] = $headerRowIndex + 1;
            }
        }

        foreach ($boldRows as $rowIndex) {
            $sheet->getStyle('A' . $rowIndex . ':L' . $rowIndex)
                ->getFont()
                ->setBold(true);
        }

        return [];
    }
}
Leave a Comment