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/qas.sports-crowd.com/app/Http/Controllers/CollectionInvoiceController.php
<?php

namespace App\Http\Controllers;

use App\AcademyPurchase;
use DB;
use \Excel;
use DataTables;
use App\CollectionInvoice;
use App\CollectionInvoicesDetailTransaction;
use App\Core\Payment\PaymentServicesEnum;
use App\GatewayPayment;
use App\Http\Controllers\Exports\CollectionInvoicesExport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class CollectionInvoiceController extends Controller
{
    private $__VALID_PAYMENT = 'invoice';
    private $util;

    public function __construct()
    {
        $this->util = new UtilController();
    }

    public function index()
    {
        return view('collection_invoices.list');
    }

    public function indexAdd()
    {
        $gatewayPayments = GatewayPayment::select('id', 'name')->where([['active', true], ['valid_payments', $this->__VALID_PAYMENT]])->get();
        return view('collection_invoices.create', compact('gatewayPayments'))->with('types', collect(PaymentServicesEnum::ALLOWED_VALUES)->where('value', '!=', 'invoice'));
    }

    public function indexEdit($id)
    {
        $object = CollectionInvoice::findOrFail($id);
        $gatewayPayments = GatewayPayment::select('id', 'name')->where([['active', true], ['valid_payments', $this->__VALID_PAYMENT]])->get();
        return view('collection_invoices.edit', compact('object', 'gatewayPayments'))->with('types', collect(PaymentServicesEnum::ALLOWED_VALUES)->where('value', '!=', 'invoice'));
    }

    public function indexDetail($id)
    {
        $invoice = CollectionInvoice::findOrFail($id);
        return view('collection_invoices.detail')->with('invoice', $invoice);
    }

    public function tableFilter()
    {
        $obj = CollectionInvoice::select('collection_invoices.*')->with('gateway_payment', 'user')->orderBy('created_at', 'DESC')->get();
        foreach ($obj as $invoice) {
            $data = CollectionInvoicesDetailTransaction::select(DB::raw('MAX(created_at) AS lastPaymentDate'))->where('invoice_id', $invoice->id)->first();
            $invoice->lastPaymentDate = $data->lastPaymentDate ?? '';
            $transactions = CollectionInvoicesDetailTransaction::where('invoice_id', $invoice->id)->count();
            $invoice->transactions = $transactions;
        }

        return DataTables::of($obj)
            ->addColumn('actions', function ($obj) {
                $actions = '';
                if (in_array(Auth::user()->rol->id, [$this->__SUPERADMIN_ROL])) {
                    $actions .= '
                        <i class="fa fa-pencil iconMini" onClick="clickEdit(' . $obj->id . ')" data-id="' . $obj->id . '" title="Editar"></i>
                        <i class="fa fa-trash iconMini" onClick="clickDelete(' . $obj->id . ')" data-id="' . $obj->id . '" title="Eliminar"></i>
                    ';
                }
                if ($obj->transactions) {
                    $actions .= '
                        <i class="fa fa-list iconMini" onClick="clickDetail(' . $obj->id . ')" data-id="' . $obj->id . '" title="Transacciones"></i>
                    ';
                }
                return $actions;
            })
            ->editColumn('active', function ($obj) {
                if ($obj->active == 0) {
                    return '<div class="switch"><label><div class="checkbox checbox-switch switch-success"> <label> ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" /> <span></span>' . __('messages.yes') . ' </label></div> </label> </div>';
                } else {
                    return '<div class="switch"><label> <div class="checkbox checbox-switch switch-success"> <label>   ' . __('messages.no') . ' <input type="checkbox" onChange="chk(' . $obj->id . ')" data-id="' . $obj->id . '" id="Checkactive' . $obj->id . '" name="Checkactivo" checked="" />
                        <span></span> ' . __('messages.yes') . ' </label> </div>  </label> </div>';
                }
            })
            ->editColumn('image', function ($obj) {
                if (!$obj->image) {
                    return $this->util->generateEmptyImageColumn();
                } else {
                    return $this->util->generateImageColumn(config('filesystems.disks.s3.url') . '/collection_invoice/' . $obj->image, 'Factura - ' . $obj->name, 'factura' . $obj->id);
                }
            })
            ->editColumn('created_at', function ($obj) {
                return $obj->created_at ? \Carbon\Carbon::parse($obj->created_at)->format('Y-m-d h:i:s A') : '';
            })
            ->editColumn('lastPaymentDate', function ($obj) {
                return $obj->lastPaymentDate ? \Carbon\Carbon::parse($obj->lastPaymentDate)->format('Y-m-d h:i:s A') : '';
            })
            ->editColumn('deposit_of', function ($obj) {
                $deposit_of = [];
                if ($obj->deposit_of) {
                    foreach (explode(',', $obj->deposit_of) as $item) {
                        $object = collect(PaymentServicesEnum::ALLOWED_VALUES)->where('value', $item)->first();
                        if ($object)
                            $deposit_of[] = $object['name'];
                    }
                }
                return implode(',', $deposit_of);
            })
            ->rawColumns(['actions', 'active', 'image'])
            ->make(true);
    }

    public function store(Request $request)
    {
        try {
            if (!CollectionInvoice::where('name', $request->input('name'))->first()) {
                $data = $request->all();
                if ($data['payment'] > $data['total']) {
                    return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating') . ', "Abono actual no puede ser mayor a Total factura"', "data" => null));
                }
                $data['debt'] = ($data['total'] - $data['payment']);
                $data['user_id'] = Auth::user()->id;
                if ($model = CollectionInvoice::create($data)) {
                    $this->registerLog(Auth::user()->id, 'Crear factura', json_encode($data), "Create", $this->getModule($request));
                    return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.created_successfully'), "data" => $model->id));
                } else {
                    return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating'), "data" => null));
                }
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('tag')]), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function update(Request $request, $id)
    {
        try {
            $request['id'] = $id;
            if (CollectionInvoice::where([['id', '!=', $id], ['name', $request->input('name')]])->first()) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.already_exists', ['name' => $request->input('name')]), "data" => null));
            }
            $data = $request->all();
            if ($data['payment'] > $data['total']) {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_creating') . ', "Abono actual no puede ser mayor a Total factura"', "data" => null));
            }
            $data['debt'] = ($data['total'] - $data['payment']);
            if (CollectionInvoice::where('id', $id)->update($data)) {
                $this->registerLog(Auth::user()->id, 'Editar factura', json_encode($data), "Update", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => $id));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => null));
            }
        } catch (\Exception $e) {
            return response(
                array(
                    "r" => false,
                    "type" => "error",
                    "title" => "Oops...",
                    "m" => __($e->getMessage()),
                    "data" => null
                )
            );
        }
    }

    public function saveImage(Request $request)
    {
        try {
            $extension = $request->file('image')->getClientOriginalExtension();
            $filenametostore = $request->id . '.' . $extension;

            Storage::disk('s3')->put(config('s3.collection_invoice') . $filenametostore, fopen($request->file('image'), 'r+'), 'public');

            $object = CollectionInvoice::find($request->id);
            $object->image = $filenametostore;
            $object->update();

            return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.updated_successfully'), "data" => null));
        } catch (\Throwable $th) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_updating'), "data" => $th->getMessage()));
        }
    }

    public function destroy(Request $request, $id)
    {
        try {
            $invoice = CollectionInvoice::find($id);
            if (CollectionInvoice::where('id', $id)->delete()) {
                $this->registerLog(Auth::user()->id, 'Eliminó factura', json_encode($invoice), "Delete", $this->getModule($request));
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.deleted_successfully'), "data" => null));
            } else {
                return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.error_removing'), "data" => null));
            }
        } catch (\Illuminate\Database\QueryException $e) {
            return response(array("r" => false, "type" => "error", "title" => "Oops...", "m" => __('messages.delete_relation_data'), "data" => null));
        }
    }

    public function activate(Request $request)
    {
        try {
            $id = $request['id'];
            $state = $request['state'];

            $invoice = CollectionInvoice::find($id);
            $invoice->active = $state;
            $invoice->update();

            $this->registerLog(Auth::user()->id, 'Activar/Desactivar factura', json_encode($invoice), "Update", $this->getModule($request));
            return array('r' => true, 'd' => null, 'm' => __('messages.updated_successfully'));
        } catch (\Throwable $th) {
            return array('r' => false, 'd' => null, 'm' => __('messages.error_updating'));
        }
    }

    public function tableFilterDetail($id)
    {
        DB::statement("SET sql_mode = ''");
        $obj = $obj = DB::table('collection_invoices_detail_transactions')
            ->select(
                'collection_invoices_detail_transactions.id',
                'reference',
                'transaction_id',
                'origin',
                'collection_invoices_detail_transactions.total',
                'collection_invoices_detail_transactions.created_at',
                'gateway.name AS gateway.name',
                'invoice.name AS invoice.name'
            )
            ->leftjoin('gateway_payments AS gateway', 'gateway.id', '=', 'collection_invoices_detail_transactions.gateway_id')
            ->leftjoin('collection_invoices AS invoice', 'invoice.id', '=', 'collection_invoices_detail_transactions.invoice_id')
            ->where('invoice_id', $id)
            ->groupBy('collection_invoices_detail_transactions.id')
            ->orderBy('collection_invoices_detail_transactions.created_at', 'DESC');

        \DB::enableQueryLog();
        $dataTable = DataTables::of($obj)
            ->editColumn('created_at', function ($obj) {
                return $obj->created_at ? \Carbon\Carbon::parse($obj->created_at)->format('Y-m-d h:i:s A') : '';
            });

        $response = $dataTable->make(true);
        $data = $response->getData();
        $data = json_decode(json_encode($data), true);
        $queries = \DB::getQueryLog();
        $data['queries'] = $queries;
        return $data;
    }

    public function validateExport(Request $request)
    {
        if ($request['query']) {
            $results = $this->util->getGenericData($request["query"], $request["bindings"]);
            if (count($results) > 0) {
                $name = 'ReporteTransaccionesCuentadeCobro' . time() . '.xlsx';
                Excel::store(new CollectionInvoicesExport($results), $name, 'public');
                return response()->json(['success' => true, 'message' => 'Validación OK', 'data' => $name]);
            }
        }
        return response()->json(['success' => false, 'message' => 'No existen datos a exportar']);
    }

    public function export($name)
    {
        return $this->util->export($name);
    }

    public function validateAvailableCollectionInvoice($type)
    {
        $invoices = CollectionInvoice::with('gateway_payment')->where('active', true)->whereIn('deposit_of', ['all', $type])->get();
        if (count($invoices)) {
            foreach ($invoices as $invoice) {
                if ($invoice->debt > ROUND(($invoice->total * $invoice->percentage) / 100)) {
                    if ($invoice->gateway_payment) {
                        return array($invoice->gateway_payment);
                    }
                    return GatewayPayment::select('id', 'name', 'image')->where([['active', true], ['valid_payments', $this->__VALID_PAYMENT]])->get();
                }
            }
        }
        return false;
    }

    public function validateCreditCollectionInvoice($gatewayPaymentsId, $paymentReference, $paymentTransactionId, $origin, $total = null)
    {
        if (CollectionInvoicesDetailTransaction::where('gateway_id', $gatewayPaymentsId)
            ->where(function ($query) use ($paymentReference, $paymentTransactionId) {
                $query->where('reference', $paymentReference)->orWhere('transaction_id', $paymentTransactionId);
            })->first()
        ) {
            return;
        }

        if (GatewayPayment::select('id', 'name')->where([['id', $gatewayPaymentsId], ['valid_payments', $this->__VALID_PAYMENT]])->first()) {
            $invoices = CollectionInvoice::where('active', true)
                ->where(function ($query) use ($gatewayPaymentsId) {
                    $query->where('collection_invoices.gateway_payment_id', $gatewayPaymentsId)->orWhereNull('collection_invoices.gateway_payment_id');
                })->get();
            if (!count($invoices)) {
                $invoices = CollectionInvoice::orderBy('updated_at', 'DESC')->limit(1)->get();
            }

            // Validar total transferencia
            if (!$total) {
                switch ($origin) {
                    case str_contains($origin, 'Academy'):
                        $purchase = AcademyPurchase::select('academy_purchases.price')
                            ->leftjoin('payment_transactions', 'payment_transactions.id', '=', 'academy_purchases.payment_transaction_id')
                            ->where('payment_transactions.reference', $paymentReference)->orWhere('payment_transactions.gateway_transaction_id', $paymentTransactionId)
                            ->first();
                        if ($purchase)
                            $total = $purchase->price;
                        break;
                    default:
                        break;
                }
            }

            // Cuentas de cobro activas
            foreach ($invoices as $key => $invoice) {
                if ($invoice->debt > ROUND(($invoice->total * $invoice->percentage) / 100) || (($key + 1) == count($invoices))) {
                    $detail = new CollectionInvoicesDetailTransaction();
                    $detail->reference = $paymentReference;
                    $detail->transaction_id = $paymentTransactionId;
                    $detail->origin = $origin;
                    $detail->total = $total;
                    $detail->gateway_id = $gatewayPaymentsId;
                    $detail->invoice_id = $invoice->id;
                    $detail->save();

                    $invoice->debt -= $total;
                    $invoice->payment += $total;
                    if ($invoice->debt < ROUND(($invoice->total * $invoice->percentage) / 100)) {
                        $invoice->active = false;
                    }
                    $invoice->update();
                    break;
                } else {
                    $invoice->active = false;
                    $invoice->update();
                }
            }
        }
    }
}