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/agile-selling-wpb/app/Http/Controllers/ShopifyController.php
<?php

namespace App\Http\Controllers;

use App\Product;
use App\Parameter;
use Carbon\Carbon;
use App\ProductAttribute;
use Slince\Shopify\Client;
use Illuminate\Http\Request;
use App\IntegrationProvider;
use Illuminate\Support\Facades\Auth;
use Slince\Shopify\PrivateAppCredential;
use App\Http\Controllers\UserController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\BrandsController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\AddressController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\AttributeController;

class ShopifyController extends Controller
{
    private $validSync = false;
    private $shopify;
    private $last_load_date;
    private $integration;
    private $parameters;

    public function __construct(){
        $this->initApiRest();
    }

    public function initApiRest()
    {
        $this->parameters = Parameter::select('sync_shopify','sucursal_products')->find(1);
        if($this->parameters && $this->parameters->sync_shopify){
            $this->integration = IntegrationProvider::where([['ecommerce_type_id', 3],['active', true]])->first();
            if($this->integration){
                $this->validSync = true;
                $this->last_load_date = $this->integration->last_load_date;
                $credential = new PrivateAppCredential($this->integration->key_public,$this->integration->password,$this->integration->key_private);
                $this->shopify = new Client(
                    $credential,
                    $this->integration->endpoint,
                    [
                        'metaCacheDir'  => './tmp',
                        'apiVersion'      => '2021-04',
                    ],
                );
            }
        }
    }

    // produtcs
    public function createProduct($data)
    {
        try{
            if($this->validSync){
                $product = $this->shopify->getProductManager()->create($data);
                return $product->getId();
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateProduct($id,$data)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->shopify->getProductManager()->update($id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function addImageProduct($id,$data)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->shopify->getProductImageManager()->create($id,$data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteProduct($id)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->shopify->delete('products/'.$id);
            }
        } catch (\Exception $e) {
            return null;
        }
    }


    // Variant
    public function createVariant($product_id,$data)
    {
        try{
            if($this->validSync && $product_id && $product_id != ""){
                $variant = $this->shopify->getProductVariantManager()->create($product_id,$data);
                return $variant;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateVariant($variant_id,$data)
    {
        try{
            if($this->validSync && $variant_id && $variant_id != ""){
                $this->shopify->getProductVariantManager()->update($variant_id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteVariant($variant_id,$product_id)
    {
        try{
            if($this->validSync && $variant_id && $variant_id != "" && $product_id && $product_id != ""){
                $this->shopify->getProductVariantManager()->remove($product_id,$variant_id);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateInventoryLevel($inventory_item_id,$quantity_adjustment)
    {
        try{
            if($this->validSync && $inventory_item_id && $inventory_item_id != "" && $quantity_adjustment != "0"){
                $inventory_location = $this->shopify->getLocationManager()->findAll();
                $data = [
                    "location_id" => $inventory_location[0]->getId(),
                    "inventory_item_id" => $inventory_item_id,
                    "available_adjustment" => $quantity_adjustment,
                ];
                $this->shopify->getInventoryLevelManager()->adjust($data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function syncOrders()
    {
        try {
            if($this->validSync){
                $request_params = new Request([]);
                $date = Carbon::parse($this->last_load_date)->toIso8601String();
                $orders = $this->shopify->getOrderManager()->findAll(['updated_at_min' => $date, 'limit' => 250]);
                $document = null;
                $city_id = null;
                $user_id = "";
                $address_id = 0;
                foreach ($orders as $key => $order) {
                    if($order->getFinancialStatus() == "authorized" || $order->getFinancialStatus() == "paid"){
                        $customer = $order->getCustomer();
                        $controllerOrder = new OrderController($request_params);
                        $controllerAddress = new AddressController();
                        $controllerUser = new UserController($request_params);

                        $city_id = $controllerAddress->searchCityByName($order->getBillingAddress()->getCity());
                        $user = $controllerUser->searchUser($document,$customer->getEmail(),$customer->getFirstName(),$customer->getLastName(),$order->getPhone());
                        if($user){
                            $user_id = $user->id;
                            $address = $controllerAddress->searchAddressByAddress($order->getBillingAddress()->getAddress1(),$user_id);
                            if($address){
                                $address_id = $address;
                            }
                        }

                        $products = [];
                        foreach ($order->getLineItems() as $key => $product) {
                            $current_product = Product::where('reference_shopify_id', $product->getProductId())->first();
                            if($current_product){
                                $valuesAttributes = [];
                                $product_atribute = ProductAttribute::where([['product_id', $current_product->id],['reference_shopify_id', $product->getVariantId()]])->with('attribute')->first();
                                if($product_atribute){
                                    $arrayAttribute = array(
                                        'attribute'         => $product_atribute->attribute->toArray(),
                                        'attribute_id'      => $product_atribute->attribute->id,
                                        'available_units'   => $product_atribute->available_units,
                                        'dispatched_units'  => $product_atribute->dispatched_units,
                                        'ean'               => $product_atribute->ean,
                                        'high'              => $product_atribute->high,
                                        'id'                => $product_atribute->id,
                                        'length'            => $product_atribute->length,
                                        'main_position'     => $product_atribute->main_position,
                                        'observation'       => $product_atribute->observation,
                                        'packaging'         => $product_atribute->packaging,
                                        'pmi'               => $product_atribute->pmi,
                                        'price_additional'  => $product_atribute->price_additional,
                                        'product_id'        => $product_atribute->product_id,
                                        'quantity'          => $product->getQuantity(),
                                        'sku'               => $product_atribute->sku,
                                        'stowage_pattern'   => null,
                                        'value'             => $product->getVariantTitle(),
                                        'weight'            => null,
                                        'width'             => null,
                                        'created_at'        => null,
                                        'updated_at'        => null,
                                    );
                                    $valuesAttributes[] = $arrayAttribute;
                                }
                                $newProduct = array(
                                    'quantity'                      => $product->getQuantity(),
                                    'max_units_per_order'           => $current_product->max_units_per_order,
                                    'price'                         => $product->getPrice(),
                                    'priceTotal'                    => $product->getPrice(),
                                    'id'                            => $current_product->id,
                                    'plu'                           => $current_product->plu,
                                    'name'                          => $current_product->name,
                                    'priceAfterDiscount'            => null,
                                    'priceAfterFlash'               => null,
                                    'percentage_discount'           => null,
                                    'start_discount'                => null,
                                    'limit_discount'                => null,
                                    'limit_hour_discount'           => null,
                                    'flash_price'                   => null,
                                    'start_flash_discount'          => null,
                                    'limit_flash_discount'          => null,
                                    'limit_hour_flash_discount'     => null,
                                    'product_attributes_selected'   => $valuesAttributes
                                );
                                $products[] = $newProduct;
                            }
                        }

                        $priceDomicile = $order->getShippingLines();
                        if(count($priceDomicile)){
                            $priceDomicile = $priceDomicile[0]->getPrice();
                        }

                        $data = array('data' => array(
                            'first_name'        => $customer->getFirstName(),
                            'last_name'         => $customer->getLastName(),
                            'document'          => $document,
                            'phone'             => $order->getBillingAddress()->getPhone(),
                            'email'             => $customer->getEmail(),
                            'order_reference'   => $order->getOrderNumber(),
                            'sucursal'          => null,
                            'products'          => $products,
                            'confirmOrder'      => array(
                                'observations'      => "",
                                'effectivePayment'  => 0,
                                'cellphone'         => $order->getBillingAddress()->getPhone(),
                                'wayPay'            => 5,
                                'address'           => $address_id,
                                'address_new'       => array(
                                    'direction' => $order->getBillingAddress()->getAddress1(),
                                    'district'  => '',
                                    'instru'    => $order->getBillingAddress()->getAddress2(),
                                    'lat'       => '',
                                    'lng'       => '',
                                ),
                            ),
                            'dCampana'          => null,
                            'dReferred'         => null,
                            'dCoupone'          => null,
                            'subtotal'          => $order->getSubtotalPrice(),
                            'discount'          => $order->getTotalDiscounts(),
                            'priceDomicile'     => $priceDomicile,
                            'total'             => $order->getTotalPrice(),
                            'productsNotFound'  => null,
                            'order_type_id'     => 5,
                            'client_id'         => $user_id,
                            'city_id'           => $city_id,
                            'delivery_man_id'   => null,
                            'job_sync'          => true,
                        ));
                        if(count($products)){
                            $request = new Request($data);
                            $result = $controllerOrder->create($request);
                        }
                    }
                }
                $this->integration->last_load_date = Carbon::now();
                $this->integration->update();
            }
        } catch (\Throwable $th) {
            dd($th->getMessage());
        }
    }

    public function newRequest($data)
    {
        return new Request($data);
    }

    public function syncProducts()
    {
        try {
            if($this->validSync){
                $request_params = $this->newRequest([]);
                $products = $this->shopify->getProductManager()->findAll(['status' => 'active', 'limit' => 250]);
                $brand = new BrandsController($request_params);
                $category = new CategoryController($request_params);
                $product_controller = new ProductController($request_params);
                $productAttribute_controller = new ProductAttributeController($request_params);
                $attribute_controller = new AttributeController($request_params);
                if(count($products)){
                    foreach ($products as $product) {
                        $current_product = Product::where('name', $product->getTitle())->first();
                        // si existe actualizamos si no creamos
                        if($current_product){
                            $current_product->reference_shopify_id = $product->getId();
                            foreach ($product->getVariants() as $variant) {
                                $current_product_attribute = ProductAttribute::select('id','reference_shopify_id','reference_shopify_variation_id')
                                ->where('product_id', $current_product->id)
                                ->where('value', $variant->getTitle())
                                ->first();
                                if($current_product_attribute){
                                    $current_product_attribute->reference_shopify_id = $variant->getId();
                                    $current_product_attribute->reference_shopify_variation_id = $variant->getInventoryItemId();
                                    $current_product_attribute->update();
                                }
                            }
                            $current_product->update();
                        }else{
                            $default_sucursal_id = 2;
                            if(Auth::user()){
                                $default_sucursal_id = Auth::user()->userInfo->sucursal_id;
                            }
                            $sucursal_id = $this->parameters->sucursal_products ? $default_sucursal_id : null;
                            $brand_id = null;
                            $c_brand = $brand->create($this->newRequest(['name' => $product->getVendor()]));
                            if($c_brand){
                                $brand_id = $c_brand["d"]["id"];
                            }

                            $subcategory_id = null;
                            $data_category = [
                                'name'        => $product->getProductType(),
                                'sucursal_id' => $sucursal_id,
                                'priority'    => 1,
                            ];
                            $c_category = $category->create($this->newRequest($data_category),false);
                            if($c_category){
                                $subcategory_id = $c_category["s"];
                            }

                            $price = 0;
                            $available_units = 0;
                            foreach ($product->getVariants() as $variant) {
                                $price = $variant->getPrice();
                                $available_units = $available_units + $variant->getInventoryQuantity();
                            }

                            $product_id = null;
                            $data_product = [
                                'name' => $product->getTitle(),
                                'plu' => $product->getHandle(),
                                'bar_code' => null,
                                'price' => $price,
                                'available_units' => $available_units,
                                'max_units_per_order' => 100,
                                'percentage_discount' => null,
                                'start_discount' => null,
                                'limit_discount' => null,
                                'limit_hour_discount' => null,
                                'flash_price' => null,
                                'start_flash_discount' => null,
                                'limit_flash_discount' => null,
                                'limit_hour_flash_discount' => null,
                                'brand_id' => $brand_id,
                                'order' => 1,
                                'chkAgeProduct' => false,
                                'sucursal_id' => $sucursal_id,
                                'sub_categories' => [$subcategory_id],
                                'reference_shopify_id' => $product->getId(),
                            ];
                            $cproduct = $product_controller->create($this->newRequest($data_product),false);
                            if($cproduct){
                                $product_id = $cproduct["d"]["id"];
                            }
                            foreach ($product->getVariants() as $variant) {
                                $name_attribute = "Tallas checkbox único";
                                foreach ($product->getOptions() as $options) {
                                    foreach ($options->getValues() as $option) {
                                        if($option == $variant->getTitle()){
                                            $name_attribute = $options->getName();
                                            break;
                                        }
                                    }
                                }

                                $attribute_id = null;
                                $data_attribute = [
                                    "name" => $name_attribute,
                                    "display_name" => $name_attribute,
                                    "is_more_one" => false,
                                    "required" => true,
                                    "attribute_type_id" => 2,
                                    "active" => true,
                                ];
                                $catrribute = $attribute_controller->store($this->newRequest($data_attribute),false);
                                if($catrribute){
                                    $attribute_id = $catrribute["d"];
                                }

                                $data_productAttribute = [
                                    "product_id" => $product_id,
                                    "attribute_id" => $attribute_id,
                                    "value" => $variant->getTitle(),
                                    "price_additional" => 0,
                                    "sku" => $variant->getSku(),
                                    "available_units" => $variant->getInventoryQuantity(),
                                    "pmi" => 0,
                                    "packaging" => 0,
                                    "weight" => 0,
                                    "ean" => 0,
                                    "width" => 0,
                                    "length" => 0,
                                    "high" => 0,
                                    "observation" => 0,
                                    "main_position" => 0,
                                    "stowage_pattern" => 0,
                                    "reference_shopify_variation_id" => $variant->getInventoryItemId(),
                                    "reference_shopify_id" => $variant->getId(),
                                ];
                                $productAttribute_controller->store($this->newRequest($data_productAttribute),$product_id,false);
                            }
                        }
                    }
                }
                return response(array('r' => true, 'm' => 'Catálogo sincronizado exitosamente', 'd' => null));
            }
        } catch (\Throwable $th) {
            return response(array('r' => false, 'm' => 'Hubo un error, intenta más tarde', 'd' => $th->getMessage()));
        }
    }

    public function getCurrent()
    {
        if($this->validSync){
            // $items = $this->shopify->getOrderManager()->findAll(['updated_at_min' => '2021-05-10T00:00:00-5:00', 'limit' => 250]);
            // $items = $this->shopify->getProductManager()->findAll(['status' => 'active', 'limit' => 250]);
            // dd($items);
            $this->syncOrders();
            // $this->syncProducts();
        }else{
            dd("activa la sincronización");
        }
    }
}