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/WoocommerceController.php
<?php

namespace App\Http\Controllers;

use App\Product;
use Carbon\Carbon;
use App\Category;
use App\Parameter;
use App\Attribute;
use App\Subcategories;
use App\ProductAttribute;
use App\IntegrationProvider;
use Illuminate\Http\Request;
use Automattic\WooCommerce\Client;
use App\Http\Controllers\UserController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\AddressController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\AttributeController;

class WoocommerceController extends Controller
{
    private $validSync = false;
    private $woocommerce;
    private $last_load_date;
    private $integration;
    private $parameters;

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

    public function initApiRest()
    {
        $this->parameters = Parameter::select('sync_woocommerce','sucursal_products')->find(1);
        if($this->parameters && $this->parameters->sync_woocommerce){
            $this->integration = IntegrationProvider::where([['ecommerce_type_id', 2],['active', true]])->first();
            if($this->integration){
                $this->validSync = true;
                $this->last_load_date = $this->integration->last_load_date;
                $this->woocommerce = new Client(
                    $this->integration->endpoint,
                    $this->integration->key_public,
                    $this->integration->key_private,
                    [
                        'version' => 'wc/v3',
                    ]
                );
            }
        }
    }

    public function searchForId($id, $array) {
        foreach ($array as $key => $val) {
            if ($val->key === $id) {
                return $key;
            }
        }
        return null;
    }

    public function syncOrders()
    {
        try {
            if($this->validSync){
                $request_params = new Request([]);
                $date = Carbon::parse($this->last_load_date)->toIso8601String();
                $orders = $this->woocommerce->get('orders', $parameters = ['per_page' => 100, 'after' => $date]);
                $document = null;
                $city_id = null;
                $user_id = "";
                $address_id = 0;
                foreach ($orders as $key => $order) {
                    if($order->status == "completed"){
                        $customers = $this->woocommerce->get('customers/'.$order->customer_id);
                        $controllerOrder = new OrderController($request_params);
                        $controllerAddress = new AddressController();
                        $controllerUser = new UserController($request_params);

                        $index = $this->searchForId('billing_document', $customers->meta_data);
                        $city_id = $controllerAddress->searchCityByName($order->shipping->city);

                        if($index){
                            $document = $customers->meta_data[$index]->value;
                        }

                        $user = $controllerUser->searchUser($document,$customers->email,$customers->first_name,$customers->last_name,$order->billing->phone);
                        if($user){
                            $user_id = $user->id;
                            $address = $controllerAddress->searchAddressByAddress($order->shipping->address_1,$user_id);
                            if($address){
                                $address_id = $address;
                            }
                        }

                        $products = [];
                        $subtotal = 0;
                        foreach ($order->line_items as $key => $product) {
                            $current_product = Product::where('reference_woocommerce_product_id', $product->product_id)->first();
                            if($current_product){
                                $valuesAttributes = [];
                                $product_atribute = ProductAttribute::where([['product_id', $current_product->id],['value', $product->meta_data[0]->value]])->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->quantity,
                                        'sku'               => $product_atribute->sku,
                                        'stowage_pattern'   => null,
                                        'value'             => $product->meta_data[0]->value,
                                        'weight'            => null,
                                        'width'             => null,
                                        'created_at'        => null,
                                        'updated_at'        => null,
                                    );
                                    $valuesAttributes[] = $arrayAttribute;
                                }
                                $newProduct = array(
                                    'quantity'                      => $product->quantity,
                                    'max_units_per_order'           => $current_product->max_units_per_order,
                                    'price'                         => $product->subtotal,
                                    'priceTotal'                    => $product->total,
                                    '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;
                            }
                            $subtotal = $subtotal + $product->total;
                        }

                        $data = array('data' => array(
                            'first_name'        => $customers->first_name,
                            'last_name'         => $customers->last_name,
                            'document'          => $document,
                            'phone'             => $order->billing->phone,
                            'email'             => $customers->email,
                            'order_reference'   => $order->number,
                            'sucursal'          => null,
                            'products'          => $products,
                            'confirmOrder'      => array(
                                'observations'      => $order->customer_note,
                                'effectivePayment'  => 0,
                                'cellphone'         => $order->billing->phone,
                                'wayPay'            => 5,
                                'address'           => $address_id,
                                'address_new'       => array(
                                    'direction' => $order->shipping->address_1,
                                    'district'  => '',
                                    'instru'    => $order->shipping->address_2,
                                    'lat'       => '',
                                    'lng'       => '',
                                ),
                            ),
                            'dCampana'          => null,
                            'dReferred'         => null,
                            'dCoupone'          => null,
                            'subtotal'          => $subtotal,
                            'discount'          => $order->discount_total,
                            'priceDomicile'     => $order->shipping_total,
                            'total'             => $order->total,
                            'productsNotFound'  => null,
                            'order_type_id'     => 5,
                            'client_id'         => $user_id,
                            'city_id'           => $city_id,
                            'delivery_man_id'   => null,
                        ));
                        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());
        }
    }

    // Categorias
    public function createCategory($data)
    {
        try{
            if($this->validSync){
                $category = $this->woocommerce->post('products/categories', $data);
                return $category->id;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateCategory($id,$data)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->woocommerce->put('products/categories/'.$id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteCategory($id)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->woocommerce->delete('products/categories/'.$id, ['force' => true]);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    // Atributos
    public function createAttribute($data)
    {
        try{
            if($this->validSync){
                $attribute = $this->woocommerce->post('products/attributes', $data);
                return $attribute->id;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateAttribute($id,$data)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->woocommerce->put('products/attributes/'.$id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteAttribute($id)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->woocommerce->delete('products/attributes/'.$id, ['force' => true]);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    // Attribute terms
    public function createAttributeTerm($attribute_id,$data)
    {
        try{
            if($this->validSync && $attribute_id && $attribute_id != ""){
                $attributeTerm = $this->woocommerce->post('products/attributes/'.$attribute_id.'/terms', $data);
                return $attributeTerm->id;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateAttributeTerm($attribute_term_id,$attribute_id,$data)
    {
        try{
            if($this->validSync && $attribute_term_id && $attribute_term_id != "" && $attribute_id && $attribute_id != ""){
                $this->woocommerce->put('products/attributes/'.$attribute_id.'/terms/'.$attribute_term_id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteAttributeTerm($attribute_term_id,$attribute_id)
    {
        try{
            if($this->validSync && $attribute_term_id && $attribute_term_id != "" && $attribute_id && $attribute_id != ""){
                $this->woocommerce->delete('products/attributes/'.$attribute_id.'/terms/'.$attribute_term_id, ['force' => true]);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    // produtcs
    public function createProduct($data)
    {
        try{
            if($this->validSync){
                $product = $this->woocommerce->post('products', $data);
                return $product->id;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateProduct($id,$data)
    {
        try{
            if($this->validSync && $id && $id != ""){
                $this->woocommerce->put('products/'.$id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

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

    // products Variation
    public function createProductVariation($product_id,$data)
    {
        try{
            if($this->validSync && $product_id && $product_id != ""){
                $variation = $this->woocommerce->post('products/'.$product_id.'/variations', $data);
                return $variation->id;
            }
            return null;
        } catch (\Exception $e) {
            return null;
        }
    }

    public function updateProductVariation($product_id,$variation_id,$data)
    {
        try{
            if($this->validSync && $product_id && $product_id != "" && $variation_id && $variation_id != ""){
                $this->woocommerce->put('products/'.$product_id.'/variations/'.$variation_id, $data);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

    public function deleteProductVariation($product_id,$variation_id)
    {
        try{
            if($this->validSync && $product_id && $product_id != "" && $variation_id && $variation_id != ""){
                $this->woocommerce->delete('products/'.$product_id.'/variations/'.$variation_id, ['force' => true]);
            }
        } catch (\Exception $e) {
            return null;
        }
    }

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

    public function syncProducts()
    {
        try {
            if($this->validSync){
                $request_params = $this->newRequest([]);
                $products = $this->woocommerce->get('products', $parameters = ['per_page' => 100]);
                $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->name)->first();
                        // si existe actualizamos si no creamos
                        if($current_product){
                            $current_product->reference_woocommerce_product_id = $product->id;
                            foreach ($product->attributes as $attribute) {
                                $search_attribute = Attribute::where('name', $attribute->name)->first();
                                if($search_attribute){
                                    $search_attribute->reference_woocommerce_attribute_id = $attribute->id;
                                    $search_attribute->update();
                                }
                            }
                            foreach ($product->categories as $item_category) {
                                $search_category = Category::where('name', $item_category->name)->first();
                                if($search_category){
                                    $search_category->reference_woocommerce_category_id = $item_category->id;
                                    $search_category->update();

                                    $search_subcategory = Subcategories::where([['category_id', $search_category->id],['name', $item_category->name]])->first();
                                    if($search_subcategory){
                                        $search_subcategory->reference_woocommerce_category_id = $item_category->id;
                                        $search_subcategory->update();
                                    }
                                }
                            }
                            foreach ($product->variations as $variant) {
                                $search_variant = $this->woocommerce->get('products/'.$product->id.'/variations/'.$variant);
                                if(count($search_variant->attributes)){
                                    $current_product_attribute = ProductAttribute::select('id','reference_shopify_id','reference_shopify_variation_id')
                                                                                    ->where('product_id', $current_product->id)
                                                                                    ->where('value', $search_variant->attributes[0]->option)
                                                                                    ->first();
                                    if($current_product_attribute){
                                        $current_product_attribute->reference_woocommerce_variation_id = $search_variant->id;
                                        $current_product_attribute->update();
                                    }
                                }
                            }
                            $current_product->update();
                        }else{
                            $sucursal_id = $this->parameters->sucursal_products ? Auth::user()->userInfo->sucursal_id : null;
                            $brand_id = null;

                            $sub_categories = [];
                            if(count($product->categories)){
                                foreach ($product->categories as $subcategory) {
                                    $data_category = [
                                        'name'        => $subcategory->name,
                                        'sucursal_id' => $sucursal_id,
                                        'priority'    => 1,
                                        'reference_woocommerce_category_id' => $subcategory->id,
                                    ];
                                    $c_category = $category->create($this->newRequest($data_category),false);
                                    if($c_category){
                                        $sub_categories[] = $c_category["s"];
                                    }
                                }
                            }

                            $available_units = $product->stock_quantity != null ? $product->stock_quantity : 0;
                            if(count($product->variations)){
                                foreach ($product->variations as $variant) {
                                    $search_variant = $this->woocommerce->get('products/'.$product->id.'/variations/'.$variant);
                                    if($search_variant){
                                        $available_units = $available_units + $search_variant->stock_quantity;
                                    }
                                }
                            }

                            $price = 0;
                            if($product->price != null || $product->price != ''){
                                $price = $product->price;
                            }
                            $plu = $product->slug;
                            if($product->sku != null || $product->sku != ''){
                                $plu = $product->sku;
                            }

                            $product_id = null;
                            $data_product = [
                                'name' => $product->name,
                                'plu' => $plu,
                                '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' => $sub_categories,
                                'reference_woocommerce_product_id' => $product->id,
                            ];
                            $cproduct = $product_controller->create($this->newRequest($data_product),false);
                            if($cproduct){
                                $product_id = $cproduct["d"]["id"];
                            }

                            foreach ($product->attributes as $attribute) {
                                $name_attribute = "Tallas checkbox único";
                                foreach ($attribute->options as $option) {
                                    $current_sku = null;
                                    $current_available_units = 0;
                                    $current_variation_id = 0;
                                    foreach ($product->variations as $variant) {
                                        $search_variant = $this->woocommerce->get('products/'.$product->id.'/variations/'.$variant);
                                        if($search_variant){
                                            foreach ($search_variant->attributes as $search) {
                                                if($option == $search->option){
                                                    $current_sku = $search_variant->sku;
                                                    $current_available_units = $search_variant->stock_quantity;
                                                    $current_variation_id = $search_variant->id;
                                                    $name_attribute = $search->name;
                                                    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,
                                        "reference_woocommerce_attribute_id" => $attribute->id,
                                    ];
                                    $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" => $option,
                                        "price_additional" => 0,
                                        "sku" => $current_sku,
                                        "available_units" => $current_available_units,
                                        "pmi" => 0,
                                        "packaging" => 0,
                                        "weight" => 0,
                                        "ean" => 0,
                                        "width" => 0,
                                        "length" => 0,
                                        "high" => 0,
                                        "observation" => 0,
                                        "main_position" => 0,
                                        "stowage_pattern" => 0,
                                        "reference_woocommerce_variation_id" => $current_variation_id,
                                    ];
                                    $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) {
            dd($th->getMessage());
            return response(array('r' => false, 'm' => 'Hubo un error, intenta más tarde', 'd' => $th->getMessage()));
        }
    }

    public function getCurrent()
    {
        if($this->validSync){
            // dd($this->woocommerce->get('products/27954/variations/27955'));
            // dd($this->woocommerce->get(`products/attributes/5/terms`));
            $items = $this->woocommerce->get('products', $parameters = ['per_page' => 100]);
            // foreach ($items as $key => $item) {
            //     if($item->id == 29376){
            //     }
            // }
            dd($items[65]);
            // $this->syncProducts();
        }else{
            dd("activa la sincronización");
        }
    }
}