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

namespace App\Http\Controllers;

use Excel;
use App\InventoryTweak;
use App\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\OrderController;
use App\ProductAttribute;
use App\Attribute;
use App\Parameter;
use Illuminate\Support\Collection;
use DataTables;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Events\InventoryModification;
use App\InventoryMovementType;
use App\Http\Controllers\Exports\ListInventoryTweaksExport;


class InventoryTweakController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    private $util;

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

    public function index($storeType = 'main')
    {
        $events = InventoryMovementType::select(
            'id',
            'name'
        )
            ->orderBy('name', 'ASC')
            ->get();

        $products = Product::select(
            'products.id',
            'products.name',
            'inventory_tweaks.sku_attribute'
        )
            ->leftJoin('inventory_tweaks', 'inventory_tweaks.product_id', '=', 'products.id')
            ->get();

        return view("inventory_tweaks.list")
            ->with('events', $events)
            ->with('products', $products)
            ->with('storeType', $storeType);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function indexAdd($storeType = 'main')
    {
        $products = Product::where("active", true)
            ->where("store_type", $storeType)
            ->get();
        $inventory_movement_types = InventoryMovementType::all();

        return view("inventory_tweaks.create", compact("products", "inventory_movement_types", "storeType"));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();

            $product_attribute = ProductAttribute::where('product_id', $request->product_id)->where('value', $request->product_attribute_value)->first();

            if ($request->quantity < 0 && $product_attribute->available_units < abs($request->quantity)) {
                return response(array('r' => true, "type" => "error", 'm' => 'Error: ', "data" => null));
            } else {
                $o = new InventoryTweak;
                $o->user_id = Auth::user()->id;
                $o->product_id = $request->product_id;
                $o->inventory_movement_type_id = $request->inventory_movement_type_id;
                $o->sku_attribute = $request->product_attribute_sku;
                $o->value_attribute = $request->product_attribute_value;
                $o->quantity = $request->quantity;
                $o->description = $request->description;
                $o->save();

                // Modificar inventario
                $this->updateInventory($request->product_id, $request->product_attribute_id, $request->product_attribute_value, $request->quantity, $request);

                // Envío de notificaciones
                $parameters = Parameter::select('mailing_inventory')->first();
                if ($parameters->mailing_inventory) {
                    $product = Product::where("id", $request->product_id)->first();
                    $inventory_movement_type = InventoryMovementType::find($request->inventory_movement_type_id);
                    $attribute = Attribute::where('id', $product_attribute->attribute_id)->first();
                    $data_modification = array(
                        'product_id' => $request->product_id,
                        'product_name' => $product->name,
                        'product_plu' => $product->plu,
                        'product_attribute_sku' => $request->product_attribute_sku,
                        'product_attribute_value' => $request->product_attribute_value,
                        'product_attribute_name' => $attribute->name,
                        'inventory_movement_type' => $inventory_movement_type->name,
                        'quantity' => $request->quantity,
                        'description' => $request->description
                    );
                    event(new InventoryModification($data_modification));
                }

                DB::commit();
                return response(array("r" => true, "type" => "success", "title" => "", "m" => __('messages.created_successfully'), "data" => null));
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return array('r' => false, 'd' => null, 'm' => 'Error: ' . $e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function tableFilter($storeType = 'main', $events = null, $products = null, $from_date = null, $to_date = null)
    {
        DB::statement("SET sql_mode = ''");

        $obj = DB::table('inventory_tweaks')
            ->select(
                'inventory_tweaks.id',
                'products.name',
                'inventory_tweaks.user_id',
                'inventory_tweaks.inventory_movement_type_id',
                'inventory_tweaks.quantity',
                'inventory_tweaks.description',
                'inventory_tweaks.created_at',
                'users.first_name AS user_first_name',
                'users.last_name AS user_last_name',
                'users.document AS user_document',
                'inventory_movement_types.name AS movement_type_name',
                'inventory_tweaks.sku_attribute',
                'products.name AS product_name'
            )
            ->leftJoin('users', 'users.id', '=', 'inventory_tweaks.user_id')
            ->leftJoin('inventory_movement_types', 'inventory_movement_types.id', '=', 'inventory_tweaks.inventory_movement_type_id')
            ->leftJoin('products', 'products.id', '=', 'inventory_tweaks.product_id')
            ->where('products.store_type', $storeType);
        if ($products && $products != 'null') {
            $obj->whereIn('product_id', explode(',', $products));
        }

        if ($events && $events != 'null') {
            $obj->whereIn('inventory_tweaks.inventory_movement_type_id', explode(',', $events));
        }

        if ($from_date && $from_date != 'null') {
            $obj->whereDate('inventory_tweaks.created_at', '>=', $from_date);
        }

        if ($to_date && $to_date != 'null') {
            $obj->whereDate('inventory_tweaks.created_at', '<=', $to_date);
        }

        DB::statement("SET sql_mode = 'STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'");

        return DataTables::of($obj)
            ->editColumn('user_id', function ($obj) {
                return $obj->user_first_name . ' ' . $obj->user_last_name . ' - ' . $obj->user_document;
            })
            ->editColumn('inventory_movement_type_id', function ($obj) {
                return $obj->movement_type_name ?? "N/A";
            })
            ->editColumn('product_id', function ($obj) {
                return $obj->sku_attribute
                    ? $obj->product_name . " - " . $obj->sku_attribute
                    : $obj->product_name;
            })
            ->editColumn('created_at', function ($obj) {
                return \Carbon\Carbon::parse($obj->created_at)->format('Y-m-d h:i:s A');
            })
            ->make(true);
    }

    // Ajustes de inventario por el usuario
    public function updateInventory($product_id, $product_attribute_id, $value_attribute, $quantity, $request)
    {
        $orderController = new OrderController();
        $operacion = "sum";
        $quantity_sho = $quantity;
        if ($quantity < 0) {
            $quantity = abs($quantity);
            $operacion = "res";
        }

        $orderController->modifyQuantityProduct($product_id, $quantity, $operacion);

        if ($product_attribute_id) {
            $attributes = new Collection();
            $attr = array(["attribute_id" => $product_attribute_id, 'value' => $value_attribute]);

            $attributes = collect($attr)->map(function ($item) {
                return (object) $item;
            });

            $orderController->modifyQuantityProductAttributes($attributes, $quantity, $operacion, $product_id);

            $product_attribute = ProductAttribute::where('id', $request->product_attribute_real_id)->first();
            if ($product_attribute) {

                $parameters = Parameter::select('sync_shopify', 'sucursal_products')->find(1);
                if ($parameters && $parameters->sync_shopify) {
                    $sho = new ShopifyController();
                    $sho->updateInventoryLevel(
                        $product_attribute->reference_shopify_variation_id,
                        $quantity_sho,
                        'TI108',
                        'COP'
                    );
                }
            }
        }
    }

    public function attributesProduct($product_id)
    {
        return ProductAttribute::where('product_id', $product_id)->with('attribute')->get();
    }

    public function validateExport(Request $request)
    {
        if ($request['query']) {
            $results = $this->util->getGenericData($request["query"], $request["bindings"]);
            if (count($results) > 0) {
                $name = 'ReporteAjusteDeInventario' . time() . '.xlsx';
                Excel::store(new ListInventoryTweaksExport($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);
    }
}