HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/comfama.sports-crowd.com/app/Http/Controllers/Exports/ReportOrders.php
<?php

namespace App\Http\Controllers\Exports;

use App\Order;
use App\Transfer;
use App\Parameter;
use App\Sucursal;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;

class ReportOrders implements FromCollection, WithHeadings, WithEvents
{

    // set the headings
    public function headings(): array
    {
        $parameter = Parameter::select('name_delivery_man')->first();

        return [
            'No. pedido',
            'Tipo pedido',
            'Pedido',
            'Estado',
            'Sucursal',
            'Sucursal transferencia',
            'Sucursal origen (Traslado)',
            'Sucursal usuario',
            'Forma de pago',
            'Estado de pago',
            'Express productos',
            'PLU',
            'Nombre producto',
            'Atributo',
            'Precio Unitario',
            'Cantidad',
            'Subtotal',
            'Domicilio',
            'Valor total',
            'Costo real',
            'Ciudad usuario',
            'Cedula / documento',
            'Cliente',
            'Correo',
            'Ciudad',
            'Telefono',
            'Dirección',
            'Punto de venta',
            'Indicaciones',
            $parameter->name_delivery_man . ' Nombre',
            $parameter->name_delivery_man . ' Documento',
            $parameter->name_delivery_man . ' Empresa',
            'Fecha de solicitud',
            'Fecha aceptado',
            'Fecha de recogida',
            'Tiempo de atención',
            'Fecha entrega',
            'Tiempo entrega',
            'Fecha finalización mensajero',
            'Fecha finalización cliente',
            'Fecha finalización admin',
            'Cantidad de transferencias',
            'Tiempo total transferencias (Min)',
            'Tiempo total pedido (Min)',
        ];
    }

    // freeze the first row with headings
    public function registerEvents(): array
    {
        return [];
    }

    public $request;

    public function collection()
    {
        list($day, $month, $year) = explode('/', $this->request->from_date);
        $from = $year . '-' . $month . '-' . $day;

        list($day, $month, $year) = explode('/', $this->request->to_date);
        $to = $year . '-' . $month . '-' . $day;

        $sucursals = Sucursal::all();
        $orders = Order::whereBetween('orders.creation_date', [$from . " 00:00:00", $to . " 23:59:59"])
            ->leftJoin('transfers', function ($join) {
                $join->on('orders.id', '=', 'transfers.order_id');
            })
            ->select('orders.*', 'transfers.id as tid', 'transfers.sucursal_id as stid', 'transfers.description as descriptionT')
            ->with('client', 'admin', 'deliveryMan', 'sucursal', 'orderState', 'paymentType', 'address', 'point_sale', 'orderProducts')
            ->get();

        $idOrderBefore = 0;
        $countRow = 2;
        $data = [];
        foreach ($orders as $index => $order) {

            $quantityTransfer = 0;
            $totalTimeTransfer = 0;
            $transfers = Transfer::where('order_id', $order->id)->orderBy('collected_date', 'desc')->get();
            //tiempo de atencion
            if ($order->creation_date != null && $order->collected_date != null) {
                $to_time = strtotime($order->creation_date);
                $from_time = strtotime($order->collected_date);
                $timeA = round(abs($to_time - $from_time) / 60, 2);
            } else {
                $timeA = "NA";
            }
            //tiempo de entrega
            if ($order->collected_date != null && $order->deliver_date != null) {
                $to_time = strtotime($order->collected_date);
                $from_time = strtotime($order->deliver_date);
                $timeE = round(abs($to_time - $from_time) / 60, 2);
            } else {
                $timeE = "NA";
            }
            //tiempo total
            if ($order->creation_date != null && $order->deliver_date != null) {
                $to_time = strtotime($order->creation_date);
                $from_time = strtotime($order->deliver_date);
                $timeT = round(abs($to_time - $from_time) / 60, 2);
                // Transferencias, calculo de tiempo total de todas las transferencias
                if (count($transfers) > 0) {
                    $quantityTransfer = count($transfers);
                    $to_time = strtotime($order->deliver_date);
                    $from_time = strtotime($transfers[0]->deliver_date);
                    $totalTimeTransfer = round(abs($to_time - $from_time) / 60, 2);
                    $timeT = $timeT + $totalTimeTransfer;
                }
            } else {
                $quantityTransfer = count($transfers);
                $totalTimeTransfer = "NA";
                $timeT = "NA";
            }
            if ($order->current_sucursal_id) {
                //$order->current_sucursal_id = $order->currentSucursal->name;
            } else {
                $order->current_sucursal_id = "NA";
            }
            if ($order->order_type_id != null) {
                $order->order_type_id = $order->orderType->name;
            } else {
                $order->order_type_id = 'NA';
            }
            if ($order->sales_channel_id != null) {
                $order->sales_channel_id = $order->channel->name;
            } else {
                $order->sales_channel_id = 'NA';
            }
            if ($order->line_businesses_id != null) {
                $order->line_businesses_id = $order->line->name;
            } else {
                $order->line_businesses_id = 'NA';
            }
            if ($order->delivery_man_id != null) {
                $order->delivery_man_id = $order->deliveryMan->first_name . ' ' . $order->deliveryMan->last_name;
                $documentDeliveryMan = $order->deliveryMan->document;
                $companyDeliveryMan = isset($order->deliveryMan->userInfo->company->name) ? $order->deliveryMan->userInfo->company->name : 'NA';
            } else {
                $order->delivery_man_id = 'NA';
                $documentDeliveryMan = 'NA';
                $companyDeliveryMan = 'NA';
            }
            if ($order->address_id != null) {
                $order->address_id = $order->address->direction;
            } else {
                if ($order->point_sale_id) {
                    $order->address_id = $order->point_sale->name;
                } else {
                    $order->address_id = "NA";
                }
            }
            if ($order->sucursal_id != null) {
                $order->sucursal_id = $order->sucursal->name;
                $city_sucursal = $order->sucursal->city->name;
            } else {
                $order->sucursal_id = "NA";
                $city_sucursal = "NA";
            }
            if ($order->sucursal_origin_id != null) {
                $order->sucursal_origin_id = $order->sucursalOrigin->name;
            } else if ($order->order_type_id != "Ventas" || $order->order_type_id != "Convenios" || $order->order_type_id != "Diligencia") {
                $order->sucursal_origin_id = "NA";
            } else {
                $order->sucursal_origin_id = " ";
            }
            if ($order->gw_state) {
                if ($order->gw_state == 'CONFIRMED') {
                    $order->gw_state = "Confirmado";
                } elseif ($order->gw_state == 'PENDING') {
                    $order->gw_state = "Pendiente";
                } elseif ($order->gw_state == 'REJECTED') {
                    $order->gw_state = "Rechazada";
                } elseif ($order->gw_state == 'ERROR') {
                    $order->gw_state = "Error";
                }
            }
            $name_state = $order->orderState->name;
            $stateTransfer = " ";
            $transfer = "0";
            $descriptionTranser = "0";
            if ($idOrderBefore == $order->id) {
                if ($name_state == "Entregado") {
                    $stateTransfer = $name_state;
                }
                if ($order->stid != null) {
                    foreach ($sucursals as $key => $value) {
                        if ($value->id == $order->stid) {
                            $transfer = $value->name;
                        }
                    }
                    $descriptionTranser = $order->descriptionT;
                    $data[$countRow] = [
                        $order->code, "transfer", $stateTransfer,
                        $order->sucursal_id,
                        $transfer,
                        " ", " ",
                        str_replace("\n", " ", $descriptionTranser),
                    ];
                }
            } else {
                foreach ($order->orderProducts as $product) {
                    $attribute = "";
                    if (isset($product->orderProductAttributes) && count($product->orderProductAttributes)) {
                        $attribute = $product->orderProductAttributes[0]->attribute->display_name . ": " . $product->orderProductAttributes[0]->value;
                    }

                    $data[$countRow] = [
                        $order->code,
                        $order->order_type_id,
                        $order->is_change,
                        $name_state,
                        $order->sucursal_id,
                        " ",
                        $order->sucursal_origin_id,
                        $order->current_sucursal_id,
                        $order->paymentType->name,
                        $order->gw_state,
                        str_replace("\n", " ", $order->express_products),
                        $product->product->plu ?? '',
                        $product->product->name ?? '',
                        $attribute,
                        $product->price,
                        $product->quantity,
                        ($product->price * $product->quantity),
                        $order->cost_delivery,
                        $order->total_price,
                        $order->cost_real,
                        $order->address && $order->address->city ? $order->address->city->name : '',
                        $order->client->document,
                        $order->client->first_name . ' ' . $order->client->last_name,
                        $order->client->email,
                        $city_sucursal,
                        $order->client->phone,
                        $order->address_id,
                        $order->point_sale_id,
                        str_replace("\n", " ", $order->indications),
                        $order->delivery_man_id,
                        $documentDeliveryMan,
                        $companyDeliveryMan,
                        $order->creation_date,
                        $order->accepted_date,
                        $order->collected_date,
                        $timeA,
                        $order->deliver_date,
                        $timeE,
                        $order->finished_delivery_man_date,
                        $order->finished_client_date,
                        $order->finished_admin_date,
                        $quantityTransfer,
                        $totalTimeTransfer,
                        $timeT,
                    ];
                    if ($order->stid != null) {
                        $countRow = $countRow + 1;
                        foreach ($sucursals as $key => $value) {
                            if ($value->id == $order->stid) {
                                $transfer = $value->name;
                            }
                        }
                        if ($name_state == "Entregado") {
                            $stateTransfer = $name_state;
                        }
                        $descriptionTranser = $order->descriptionT;
                        $data[$countRow] = [
                            $order->code, "Transferencia", $stateTransfer,
                            $order->sucursal_id,
                            $transfer,
                            " ", " ",
                            str_replace("\n", " ", $descriptionTranser),
                        ];
                    }
                    $countRow = $countRow + 1;
                }
            }
            $idOrderBefore = $order->id;
        }
        return collect($data);
    }
}