Jump to content

Modulo Aliexpress Oficial Cambios en la API - Ya no recupera los pedidos


led22

Recommended Posts

Buenas tardes,

 

Recientemente aliexpress ha realizado un cambio en su API de conexión con un nuevo método (antes utilizaba el método AliexpressTradeSellerOrderlistGetRequest y ahora utiliza AliexpressSolutionOrderGetRequest) y esto ha ocasionado que los que tenemos la versión instalada del modulo 1.0.23 o anteriores (cuando era gratuito), nos quedemos sin poder importar pedidos en nuestra tienda prestashop. Esto nos obliga a coger el nuevo modulo para poder continuar trabajando.

 

He revisado los cambios en la API y he tratado de hacer la modificación pero no soy capaz, intento modificar el código yo a mano pero me esta dando varias excepciones.

https://api.alidayu.com/docs/api.htm?apiId=42270

 

Alguien se ha encontrado en mi misma situación y ha podido implementarlo y seguir trabajando con esta versión?

Si pudieran echar un vistazo por favor.

 

El código original es el siguiente:

AliexpressTradeSellerOrderlistGetRequest.php

<?php

/**
 * TOP API: aliexpress.trade.seller.orderlist.get request
 *
 * @author auto create
 * @since 1.0, 2019.08.01
 */
class AliexpressTradeSellerOrderlistGetRequest
{
    /**
     * 入参
     **/
    private $paramAeopOrderQuery;

    private $apiParas = array();

    public function setParamAeopOrderQuery($paramAeopOrderQuery)
    {
        $this->paramAeopOrderQuery = $paramAeopOrderQuery;
        $this->apiParas["param_aeop_order_query"] = $paramAeopOrderQuery;
    }

    public function getParamAeopOrderQuery()
    {
        return $this->paramAeopOrderQuery;
    }

    public function getApiMethodName()
    {
        return "aliexpress.trade.seller.orderlist.get";
    }

    public function getApiParas()
    {
        return $this->apiParas;
    }

    public function check()
    {

    }

    public function putOtherTextParam($key, $value)
    {
        $this->apiParas[$key] = $value;
        $this->$key = $value;
    }
}

AliexpressOrderSyncronizer.php

<?php
/**
 *  Please read the terms of the CLUF license attached to this module(cf "licences" folder)
 *
 * @author    Línea Gráfica E.C.E. S.L.
 * @copyright Lineagrafica.es - Línea Gráfica E.C.E. S.L. all rights reserved.
 * @license   https://www.lineagrafica.es/licenses/license_en.pdf
 *            https://www.lineagrafica.es/licenses/license_es.pdf
 *            https://www.lineagrafica.es/licenses/license_fr.pdf
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

include_once(dirname(__FILE__).'/AliexpressApiv2.php');
include_once(dirname(__FILE__).'/AliexpressCarrier.php');
include_once(dirname(__FILE__).'/AliexpressCarrierRelation.php');
include_once(dirname(__FILE__).'/AliexpressException.php');
include_once(dirname(__FILE__).'/AliexpressFileLogger.php');
include_once(dirname(__FILE__).'/AliexpressNotification.php');
include_once(dirname(__FILE__).'/AliexpressOrder.php');
include_once(dirname(__FILE__).'/AliexpressPayment.php');
include_once(dirname(__FILE__).'/AliexpressShippingTemplate.php');
include_once(dirname(__FILE__).'/AliexpressTools.php');
include_once(dirname(__FILE__).'/AliexpressUser.php');

class AliexpressOrderSyncronizer
{
    protected static $ordersProcessed = 0;
    protected static $ordersUpdated = 0;
    protected static $context;
    protected static $module;

    const DEFAULT_PAGE_SIZE = 50;
    private static $synclogger; // Variable privada para loguear toda la sincronizacion
    public static $aliexpress_order_status = array(
        AliexpressConfiguration::AE_ORDER_STATUS_PLACE_ORDER_SUCCESS       => 'PLACE_ORDER_SUCCESS',
        AliexpressConfiguration::AE_ORDER_STATUS_IN_CANCEL                 => 'IN_CANCEL',
        AliexpressConfiguration::AE_ORDER_STATUS_WAIT_SELLER_SEND_GOODS    => 'WAIT_SELLER_SEND_GOODS',
        AliexpressConfiguration::AE_ORDER_STATUS_SELLER_PART_SEND_GOODS    => 'SELLER_PART_SEND_GOODS',
        AliexpressConfiguration::AE_ORDER_STATUS_WAIT_BUYER_ACCEPT_GOODS   => 'WAIT_BUYER_ACCEPT_GOODS',
        AliexpressConfiguration::AE_ORDER_STATUS_IN_ISSUE                  => 'IN_ISSUE',
        AliexpressConfiguration::AE_ORDER_STATUS_IN_FROZEN                 => 'IN_FROZEN',
        AliexpressConfiguration::AE_ORDER_STATUS_WAIT_SELLER_EXAMINE_MONEY => 'WAIT_SELLER_EXAMINE_MONEY',
        AliexpressConfiguration::AE_ORDER_STATUS_RISK_CONTROL              => 'RISK_CONTROL',
        AliexpressConfiguration::AE_ORDER_STATUS_FINISH                    => 'FINISH',
    );

    public static function getProcessedOrders()
    {
        return self::$ordersProcessed;
    }

    public static function getUpdatedOrders()
    {
        return self::$ordersUpdated;
    }

    /**
     * Establece el contexto para que sea la importación utilice el contexto,
     * es necesario en las funciones importOrder,
     * createUser y createAddress, luego en realidad es encesario en principio para la importación de pedidos
     *
     * @param null $context
     */
    public static function setContext($context = null)
    {
        if (is_null($context)) {
            self::$context = Context::getContext();
        } else {
            self::$context = $context;
        }
    }

    public static function setModule($module = null)
    {
        if (is_null($module)) {
            $module = Module::getInstanceByName(AliexpressConfiguration::MODULE_NAME);
        }

        self::$module = $module;
    }

    /**
     *
     */
    public static function sync()
    {
        if (Tools::getValue('force_products')) {
            self::forceProducts();
        }
        $response              = array();
        $contador_de_seguridad = 0;

        self::$synclogger = new AliexpressFileLogger('ORDERS_SYNC');
        self::$synclogger->open();

        $max_intentos      = 5;
        $contador_intentos = 0;
        $processed_items   = 0;
        $total_items       = 0;
        $page              = 1;
        $now               = new DateTime();

        if (!Tools::getValue('last_cron')) {
            $last_cron =
                AliexpressConfiguration::get('ALIEXPRESS_ORDER_CRON_DATETIME') > '0000-00-00 00:00:00' &&
                preg_match(
                    '/[0-9]{4}-[0-9]{2}-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}/',
                    AliexpressConfiguration::get('ALIEXPRESS_ORDER_CRON_DATETIME')
                )
                    ? AliexpressConfiguration::get('ALIEXPRESS_ORDER_CRON_DATETIME')
                    : '0000-00-00 00:00:00';
            if ($last_cron != '0000-00-00 00:00:00') {
                $date = new DateTime($last_cron);
                $date->sub(new DateInterval('P5D'));
                $last_cron = $date->format('Y-m-d H:i:s');
                $last_cron = AliexpressTools::getDateTimeFromAEDateTime($last_cron);
                $last_upd  = $last_cron;
            }
        } else {
            $last_cron = Tools::getValue('last_cron');
            $last_upd = $last_cron;
        }

        if (empty($last_cron)) {
            $last_cron = '0000-00-00 00:00:00';
        }

        if (empty($last_upd)) {
            $last_upd = '0000-00-00 00:00:00';
        }

        $page_size = AliexpressConfiguration::get('ALIEXPRESS_ORDER_PAGE_SIZE', self::DEFAULT_PAGE_SIZE);

        self::$synclogger->addLine(
            array(
                'VALORES INICIALES' => array(
                    'MAX INTENTOS'      => $max_intentos,
                    'CONTADOR INTENTOS' => $contador_intentos,
                    'TOTAL ITEMS'       => $total_items,
                    'PAGE'              => $page,
                    'PAGE SIZE'         => $page_size,
                    'LAST CRON'         => $last_cron,
                    'NOW'               => $now->format('Y-m-d H:i:s'),
                )
            )
        );

        do {
            try {
                self::$synclogger->addLine(
                    array(
                        'LLAMADA' => array(
                            'LAST CRON' => $last_cron,
                            'NOW'       => $now->format('Y-m-d H:i:s'),
                            'PAGE'      => $page,
                            'PAGE SIZE' => $page_size,
                        )
                    )
                );

                $result = self::getOrdersFromAE($last_cron, $last_upd, $now->format('Y-m-d H:i:s'), $page, $page_size);

                self::$synclogger->addLine(
                    array(
                        'RESULTADO' => $result
                    )
                );

                self::$ordersUpdated =0;

                if (isset($result->result) && isset($result->result->total_count)) {
                    $total_items = $result->result->total_count;
                    $processed_items += $total_items;
                }

                self::$synclogger->addLine(
                    array(
                        'TOTAL ITEMS TO PROCESS' => $total_items
                    )
                );

                try {
                    if ($total_items > 0 && !empty($result->result->target_list->aeop_order_item_dto)) {
                        $orderList             = array_reverse($result->result->target_list->aeop_order_item_dto);
                        if (Tools::getValue('debug')) {
                            echo '<pre>';
                            print_r($orderList);
                            echo '</pre>';
                            die();
                        }
                        self::$ordersProcessed = 0;
                        foreach ($orderList as $ae_order) {
                            try {
                                $ae_order = self::syncAliexpressOrderSave($ae_order);
                                self::$synclogger->addLine(
                                    array(
                                        'AE_ORDER_ID (SI ES 0 ES QUENO EXISTE):' => $ae_order->id
                                    )
                                );
                                if (Validate::isLoadedObject($ae_order)) {
                                    if (empty($ae_order->reference)) {
                                        self::$synclogger->addLine('ACCION: IMPORTAR A PRESTASHOP');
                                        self::syncAliexpressOrderImportToPS($ae_order);
                                    } else {
                                        self::$synclogger->addLine('ACCION: ACTUALIZAR');
                                        self::syncAliexpressOrderUpdate($ae_order);
                                    }
                                } else {
                                }
                            } catch (Exception $e) {
                                $excepcion = array(
                                    'code' => $e->getCode(),
                                    'message' => $e->getMessage(),
                                );
                                $response['errors'][] = $excepcion;
                                self::$synclogger->addLine(
                                    array(
                                        'excepción' => $excepcion
                                    )
                                );
                            }
                        }
                    }
                    AliexpressConfiguration::updateValue('ALIEXPRESS_ORDER_CRON_DATETIME', date('Y-m-d H:i:s'));
                } catch (AliexpressException $e) {
                    // future function
                }
            } catch (AliexpressException $e) {
                $contador_intentos++;
            }

            $page++;
            $contador_de_seguridad++;
        } while (($total_items > 0 || $total_items < $page_size)
        && $contador_intentos < $max_intentos
        && $contador_de_seguridad < 10
        );

        $response['processed_items'] = $processed_items;

        self::$synclogger->close();
        return $response;
    }

    /**
     * Sincroniza un pedido Aliexpress a partir de los datos de un Pedido Aliexpress (En definitva guarda los datos)
     *
     * @param $order aeop_order_item_dto
     */
    public static function syncAliexpressOrderSave($ae_order)
    {
        $ae_order_info                     = self::getOrderInfoFromAE($ae_order->order_id);
        $aliexpress_order                  = AliexpressOrder::getInstanceByAliexpressId($ae_order->order_id);

        $aliexpress_order->ae_id           = $ae_order_info->target->id;
        $aliexpress_order->ae_order_status = $ae_order->order_status;
        $aliexpress_order->info            = serialize($ae_order);
        $aliexpress_order->extended_info   = serialize($ae_order_info);

        $aliexpress_order->save();

        return AliexpressOrder::getInstanceByAliexpressId($ae_order->order_id); // Es para forzar a que se cargue
    }

    /**
     * Sincroniza un pedido Aliexpress a partir de los datos de un Pedido Aliexpress (En definitva guarda los datos)
     *
     * @param $order aeop_order_item_dto
     */
    public static function syncAliexpressOrderSaveFromInfoData($ae_id)
    {
        $ae_order_info                     = self::getOrderInfoFromAE($ae_id);
        $aliexpress_order                  = AliexpressOrder::getInstanceByAliexpressId($ae_id);

        if (Validate::isLoadedObject($aliexpress_order)) {
            $aliexpress_order->ae_id           = $ae_id;
            $aliexpress_order->ae_order_status = $ae_order_info->target->order_status;
            $aliexpress_order->save();

            $ps_orders = Order::getByReference($aliexpress_order->reference);

            $id_order_state = Configuration::get('AEOS_'.$ae_order_info->target->order_status);

            if ($ps_orders->count() > 0) {
                $orders_aux = $ps_orders->getAll();
                $ps_order   = $orders_aux[0];


                if ($ps_order->current_state != $id_order_state) {
                    $ps_order->current_state = $id_order_state;
                    $ps_order->save();
                    $ps_order->setCurrentState($id_order_state);
                }
            }
        }
    }

    public static function forceProducts()
    {
        $sql =
            'SELECT o.`id_order`, ao.`info`, ao.`extended_info` FROM `'._DB_PREFIX_.'orders` o '.
            'JOIN `'._DB_PREFIX_.'aliexpress_order` ao ON ao.`reference` = o.`reference` '.
            'WHERE o.`id_order` NOT IN(SELECT DISTINCT `id_order` FROM `'._DB_PREFIX_.'order_detail`) '.
            'AND `payment` = "Aliexpress Payment"';
        if ($rows = Db::getInstance()->executeS($sql)) {
            foreach ($rows as $row) {
                $order =  new Order((int)$row['id_order']);
                $cart  = new Cart($order->id_cart);
                if (!$cart->getProducts()) {
                    $info = unserialize($row['info']);
                    $extended_info = unserialize($row['extended_info']);
                    $id_order_state = Configuration::get('AEOS_'.$info->order_status);
                    $productos_aliexpress = self::cartProducts($cart, $info, $extended_info);
                    self::addOrderDetails($order, $cart, $productos_aliexpress, $order->id_address_delivery);
                    self::updateOrderData($order, $productos_aliexpress, $order->id_carrier, $id_order_state);
                }
            }
        }
    }

    /**
     * Actualiza un pedido Aliexpress
     */
    public static function syncAliexpressOrderUpdate($ae_order)
    {
        if (Tools::getValue('force_products')) {
            $orders   = Order::getByReference($ae_order->reference)->getResults();
            $order    = current($orders);
            $cart     = new Cart($order->id_cart);
            if (!$cart->getProducts()) {
                $info = unserialize($ae_order->info);
                $extended_info = unserialize($ae_order->extended_info);
                $id_order_state = Configuration::get('AEOS_'.$info->order_status);
                $productos_aliexpress = self::cartProducts($cart, $info, $extended_info);
                self::addOrderDetails($order, $cart, $productos_aliexpress, $order->id_address_delivery);
                self::updateOrderData($order, $productos_aliexpress, $order->id_carrier, $id_order_state);
            }
        }
        if (Tools::getValue('force_address')) {
            $sql =
                'SELECT o.`id_order`, o.`id_customer` FROM `'._DB_PREFIX_.'orders` o '.
                'JOIN `'._DB_PREFIX_.'aliexpress_order` ao ON ao.`reference` = o.`reference`'.
                'WHERE o.`id_customer` > 0 AND o.`id_address_delivery` = 0 AND ao.`ae_id` = '.(int)$ae_order->ae_id;
            if ($order = Db::getInstance()->getRow($sql)) {
                $order_info = unserialize($ae_order->extended_info);
                $ae_user_id = $order_info->target->buyerloginid;
                if ($id_address = self::createAddress($order_info, $order['id_customer'], $ae_user_id)) {
                    $sql =
                        'UPDATE `'._DB_PREFIX_.'orders` SET `id_address_delivery` = '.(int)$id_address.', '.
                        '`id_address_invoice` = '.(int)$id_address.' WHERE `id_order` = '.(int)$order['id_order'];
                    Db::getInstance()->execute($sql);
                } else {
                    throw new AliexpressException(
                        AliexpressException::ORDER_SYNC_PROVINCE_NOT_FOUND,
                        ' '.$order_info->target->id.': '.
                        $order_info->target->receipt_address->country.' / '.
                        $order_info->target->receipt_address->province
                    );
                }
            }
        }
        if (Tools::getValue('force_customer')) {
            $extended_info = unserialize($ae_order->extended_info);
            $customer = self::createUser($extended_info, $extended_info->target->buyerloginid);
            $orders   = Order::getByReference($ae_order->reference)->getResults();
            $order    = current($orders);
            if ($customer->id != $order->id_customer) {
                $order->id_customer = $customer->id;
                $order->save();
            }
        }
        if (Tools::getValue('force_states')) {
            $extended_info = unserialize($ae_order->extended_info);
            $sql =
                'SELECT o.`id_address_delivery` FROM `'._DB_PREFIX_.'orders` o '.
                'JOIN `'._DB_PREFIX_.'address` a '.
                'ON o.`id_address_delivery` = a.`id_address` '.
                'WHERE a.`id_state` = 0 AND o.`reference` ="'.$ae_order->reference.'"';
            if ($id_address_delivery = Db::getInstance()->getValue($sql)) {
                $address = new Address($id_address_delivery);
                $id_state = State::getIdByName($extended_info->target->receipt_address->province);
                if ($id_state > 0 && 1 > (int)$address->id_state) {
                    $address->id_state = $id_state;
                    $address->save();
                }
            }
        }
        $ae_order->updateStatus(self::$synclogger);
        self::$ordersUpdated++;
    }

    /**
     * Importa un pedido en Prestashop desde el peido Aliexpress guardado en la base de datos
     */
    public static function syncAliexpressOrderImportToPS($ae_order)
    {
        self::importOrder($ae_order->id);
    }

    /**
     * Este método importará los pedidos existentes en la base de datos a Prestashop y los relacionará
     */
    public static function import()
    {
        $aliexpressOrders = AliexpressOrder::getAll(true);

        foreach ($aliexpressOrders as $order) {
            self::importOrder($order['id_aliexpress_order']);
        }
    }

    public static function importOrder($id_aliexpress_order)
    {
        $id_shop    = (int)AliexpressConfiguration::get('ALIEXPRESS_ID_SHOP', 0);
        $synclogger = new AliexpressFileLogger('ORDERS_IMPORT_TO_PS');
        $response   = array();
        $synclogger->open();

        AliexpressValidator::setContext(self::$context);
        AliexpressValidator::setModule(self::$module);
        AliexpressValidator::validateAliexpressOrder($id_aliexpress_order);

        $aliexpressOrder = new AliexpressOrder((int)$id_aliexpress_order);

        $synclogger->addLine(
            array(
                'id_aliexpress_order' => $id_aliexpress_order,
                'object' => $aliexpressOrder->id,
            )
        );

        if (Validate::isLoadedObject($aliexpressOrder) && empty($aliexpressOrder->reference)) {
            $order_info = unserialize($aliexpressOrder->info);

            if (count($order_info->product_list->aeop_order_product_dto) > 1) {
                $id_carrier      = 0;
                foreach ($order_info->product_list->aeop_order_product_dto as $delivery_info) {
                    $service_name       = $delivery_info->logistics_type;
                    $categoryRelation   = AliexpressCarrierRelation::getInstanceByServiceName(
                        $service_name,
                        false,
                        $id_shop
                    );
                    $id_carrier = $categoryRelation->id_carrier;
                    if (!$id_carrier) {
                        throw new AliexpressException(
                            self::$module
                                ->l('One of Aliexpress logistic services is not matched with a Prestashop Carrier')
                        );
                    }
                }
            } else {
                $delivery_info    = $order_info->product_list->aeop_order_product_dto[0];
                $service_name     = $delivery_info->logistics_type;
                $categoryRelation = AliexpressCarrierRelation::getInstanceByServiceName($service_name, false, $id_shop);
                $id_carrier       = $categoryRelation->id_carrier;
                if ($id_carrier == 0) {
                    throw new AliexpressException(
                        self::$module->l('One of Aliexpress logistic services is not matched with a Prestashop Carrier')
                    );
                }
            }
            $delivery_option = $id_carrier.",";

            $synclogger->addLine(
                array(
                    'DELIVERY OPTION' => $delivery_option,
                )
            );

            $ae_order_info = unserialize($aliexpressOrder->extended_info);
            $ae_user_id    = $ae_order_info->target->buyerloginid;

            try {
                $customer  = self::createUser($ae_order_info, $ae_user_id);
            } catch (Exception $e) {
                $excepcion = array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage(),
                );
                $response['errors'][] = $excepcion;
            }

            if (!Validate::isLoadedObject($customer)) {
                throw new Exception(
                    '[ '.$order_info->order_id.' ] '.self::$module->l(' error creating user'),
                    AliexpressException::ORDER_SYNC_USER_NOT_CREATED
                );
            }

            try {
                $address_id = self::createAddress($ae_order_info, $customer->id, $ae_user_id);
                if (empty($address_id)) {
                    $response['errors'][] = array(
                        'error' => ' '.$ae_order_info->target->id.': '.
                            $ae_order_info->target->receipt_address->country.' / '.
                            $ae_order_info->target->receipt_address->province
                    );
                    return false;
                }
            } catch (Exception $e) {
                $excepcion = array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage(),
                );
                $response['errors'][] = $excepcion;
            }

            $id_currency   = Currency::getIdByIsoCode($order_info->pay_amount->currency_code);
            $cart          = self::createCart($customer->id, $address_id, $id_currency, $id_carrier, $delivery_option);
            $productos_aliexpress = self::cartProducts($cart, $order_info, $ae_order_info);

            $synclogger->addLine(
                array(
                    'CART' => $cart->id,
                )
            );

            self::$context->cart = $cart;
            $payment       = new AliexpressPayment('aliexpress_payment', self::$context);
            $payment->setContext(self::$context);
            $payment->setContextCart($cart);

            $id_order_state = Configuration::get('AEOS_'.$order_info->order_status);

            try {
                $ps_order = self::createOrder(
                    $order_info,
                    $cart,
                    $productos_aliexpress,
                    $customer,
                    $address_id,
                    $address_id,
                    $id_order_state
                );
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }

            if (Validate::isLoadedObject($ps_order)) {
                self::addOrderDetails($ps_order, $cart, $productos_aliexpress, $address_id);
                // Joining PS order with AE order
                $aliexpressOrder->reference = $ps_order->reference;

                $synclogger->addLine(
                    array(
                        'REFERENCIA OBTENIDA' => $aliexpressOrder->reference,
                    )
                );

                $result = $aliexpressOrder->save();
                if (!$result) {
                    throw new AliexpressException(AliexpressException::ORDER_SYNC_AE_ORDER_NOT_CREATED);
                }

                $notification = AliexpressNotification::getInstanceByData(
                    AliexpressNotification::TYPE_ORDER_PENDING_TRACKNUMBER,
                    $aliexpressOrder->id
                );

                if ((
                        $order_info->order_status == AliexpressConfiguration::AE_ORDER_STATUS_WAIT_SELLER_SEND_GOODS ||
                        $order_info->order_status == AliexpressConfiguration::AE_ORDER_STATUS_SELLER_PART_SEND_GOODS
                    ) && !AliexpressNotification::exists(
                        AliexpressNotification::TYPE_ORDER_PENDING_TRACKNUMBER,
                        !$notification->id
                    )
                ) {
                    AliexpressNotification::addNotification(
                        self::$module->l('Pending update tracking number'),
                        sprintf(
                            self::$module->l(
                                'The order ID: %1$s from Aliexpress is waiting to update tracking information number.'
                            ),
                            $order_info->order_id
                        ),
                        AliexpressNotification::TYPE_ORDER_PENDING_TRACKNUMBER,
                        $ps_order->id
                    );
                }

                $result = self::updateOrderData(
                    $ps_order,
                    $productos_aliexpress,
                    $id_carrier,
                    $id_order_state
                );
                if (!$result) {
                    throw new AliexpressException(AliexpressException::ORDER_SYNC_ORDER_NOT_UPDATED);
                }

                $ps_order->setCurrentState($id_order_state);

                self::$ordersProcessed++;
            } else {
                throw new AliexpressException(AliexpressException::ORDER_SYNC_ORDER_NOT_CREATED);
            }
            $currency  = new Currency($cart->id_currency);
            $orderStatus = new OrderState((int)$id_order_state);
            if (
                Validate::isLoadedObject($ps_order) &&
                Validate::isLoadedObject($cart) &&
                Validate::isLoadedObject($customer) &&
                Validate::isLoadedObject($currency) &&
                Validate::isLoadedObject($orderStatus)
            ) {
                Hook::exec('actionValidateOrder', array(
                    'cart' => $cart,
                    'order' => $ps_order,
                    'customer' => $customer,
                    'currency' => $currency,
                    'orderStatus' => $orderStatus
                ));
            }
        }
        $synclogger->close();
    }

    /**
     * Obtiene un usuario a partir de la identidad de Aiexpress, si no existe se crea
     *
     * @param $ae_order_info
     * @param $ae_user_id
     * @return Customer
     * @throws AliexpressException
     * @throws PrestaShopException
     */
    protected static function createUser($ae_order_info, $ae_user_id)
    {
        $id_shop              = AliexpressConfiguration::getShopId();
        $customer             = AliexpressUser::getCustomerInstanceByAliExpressId($ae_user_id);
        $shop_domain          = ShopUrl::getMainShopDomain($id_shop);
        $password             = $ae_user_id.'.aliexpress';
        $email                = $password.'@'.$shop_domain;

        if (!Validate::isLoadedObject($customer)) {
            $first_name = AliexpressValidator::isName($ae_order_info->target->buyer_info->first_name)
                ? $ae_order_info->target->buyer_info->first_name
                : self::normalizeName($ae_order_info->target->buyer_info->first_name);
            $last_name  = AliexpressValidator::isName($ae_order_info->target->buyer_info->last_name)
                ? $ae_order_info->target->buyer_info->last_name
                : self::normalizeName($ae_order_info->target->buyer_info->last_name);
            $customer = new Customer();
            $customer->getByEmail($email);
            $customer->active     = 1;
            $customer->firstname  = $first_name;
            $customer->lastname   = $last_name;
            $customer->email      = $email;
            $customer->passwd     = Tools::encrypt($password);
            $customer->newsletter = false;
            $customer->id_shop    = $id_shop;
            $customer->save();
            if (!Validate::isLoadedObject($customer)) {
                return null;
            } else {
                $ae_customer = new AliexpressUser();
                $ae_customer->ae_id = $ae_user_id;
                $ae_customer->id_customer = $customer->id;
                $ae_customer->save();
                if (!Validate::isLoadedObject($ae_customer)) {
                    return null;
                }
            }
        }
        return $customer;
    }

    /**
     * Crea una Dirección a partir de la información del peidido
     *
     * @param $ae_order_info
     * @param $customer_id
     * @param $ae_user_id
     * @throws AliexpressException
     * @throws PrestaShopException
     */
    protected static function createAddress($ae_order_info, $customer_id, $ae_user_id)
    {
        $alias =  md5($ae_user_id.'-'.$ae_order_info->target->id);
        $query = new DbQuery();
        $query->select('id_address');
        $query->from('address');
        $query->where('alias = \''.pSQL($alias).'\'');
        $query->where('id_customer = '.(int)$customer_id);
        $query->where('deleted = 0');

        $id_address = (int)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
        $address    = new Address((int)$id_address);
        if (Validate::isLoadedObject($address)) {
            return $address->id;
        } else {
            $id_country = Country::getByIso($ae_order_info->target->receipt_address->country);
            if (!$id_country) {
                throw new AliexpressException(AliexpressException::ORDER_SYNC_COUNTRY_NOT_FOUND);
            }
            $id_state = !empty($ae_order_info->target->receipt_address->province)
                ? State::getIdByName($ae_order_info->target->receipt_address->province)
                : 0;
            if (empty($id_state)) {
                if (Country::containsStates($id_country)) {
                    $id_state = self::getIdStateByName(
                        $id_country,
                        $ae_order_info->target->receipt_address->province
                    );
                    if (empty($id_state)) {
                        return false;
                    }
                }
            }
            if (empty($ae_order_info->target->receipt_address->contact_person)) {
                $first_name = AliexpressValidator::isName($ae_order_info->target->buyer_info->first_name)
                    ? $ae_order_info->target->buyer_info->first_name
                    : self::normalizeName($ae_order_info->target->buyer_info->first_name);
                $last_name = AliexpressValidator::isName($ae_order_info->target->buyer_info->last_name)
                    ? $ae_order_info->target->buyer_info->last_name
                    : self::normalizeName($ae_order_info->target->buyer_info->last_name);
            } else {
                $name_parts = preg_split('/\s+/', trim($ae_order_info->target->receipt_address->contact_person));
                if (sizeof($name_parts) > 1) {
                    $first_name = array_shift($name_parts);
                    $last_name = implode(' ', $name_parts);
                } else {
                    $first_name = $ae_order_info->target->receipt_address->contact_person;
                    $last_name = self::$module->l('receiver');
                }
                $first_name = AliexpressValidator::isName($first_name)
                    ? $first_name
                    : self::normalizeName($first_name);
                $last_name = AliexpressValidator::isName($last_name)
                    ? $last_name
                    : self::normalizeName($last_name);
            }
            $address1 = AliexpressValidator::isAddress($ae_order_info->target->receipt_address->detail_address)
                ? $ae_order_info->target->receipt_address->detail_address
                : self::normalizeAddress($ae_order_info->target->receipt_address->detail_address);
            $address2 = empty($ae_order_info->target->receipt_address->address2)
                ? ''
                : (AliexpressValidator::isAddress($ae_order_info->target->receipt_address->address2)
                    ? $ae_order_info->target->receipt_address->address2
                    : self::normalizeAddress($ae_order_info->target->receipt_address->address2)
                );
            $address->id_customer = (int)$customer_id;
            $address->id_country  = (int)$id_country;
            $address->id_state    = (int)$id_state;
            $address->alias       = $alias;
            $address->firstname   = $first_name;
            $address->lastname    = $last_name;
            $address->postcode    = $ae_order_info->target->receipt_address->zip;
            $address->city        = $ae_order_info->target->receipt_address->city;
            $address->address1    = $address1;
            $address->address2    = $address2;
            $address->phone       = empty($ae_order_info->target->receipt_address->phone_number)
                ? (empty($ae_order_info->target->receipt_address->mobile_no)
                    ? null
                    : $ae_order_info->target->receipt_address->mobile_no
                )
                : $ae_order_info->target->receipt_address->phone_number;
            $address->phone_mobile= empty($ae_order_info->target->receipt_address->mobile_no)
                ? null
                : $ae_order_info->target->receipt_address->mobile_no;

            $address_format = AddressFormat::getOrderedAddressFields($id_country);
            foreach ($address_format as $field) {
                $parts = preg_split('/\s+/', $field);
                foreach ($parts as $name) {
                    if (!preg_match('/[:]/', $name)) {
                        $value = empty($address->$name) ? null : $address->$name;
                        $valid = $address->validateField($name, $value);
                        if ($valid !== true && empty($address->$name)) {
                            $address->$name = self::$module->l('empty');
                        }
                    }
                }
            }

            try {
                $result = $address->save();
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }

            if (!$result || !Validate::isLoadedObject($address)) {
                return null;
            } else {
                return $address->id;
            }
        }
    }

    /**
     * Crea un carrito vacío para insertar los productos del pedido de Aliexpress
     *
     * @throws AliexpressException
     * @throws PrestaShopException
     */
    protected static function createCart($customer_id, $address_id, $id_currency, $id_carrier, $delivery_option = null)
    {
        $shop                      = new Shop((int)AliexpressConfiguration::getShopId());
        $cart                      = new Cart();
        $cart->id_currency         = $id_currency; //new Currency($id_currency);
        $cart->id_lang             = self::$context->language->id;
        $cart->id_customer         = $customer_id;
        $cart->id_shop             = $shop->id;
        $cart->id_shop_group       = $shop->id_shop_group;
        $cart->id_address_delivery = $address_id;
        $cart->id_address_invoice  = $address_id;
        $cart->id_carrier          = $id_carrier;
        $cart->delivery_option     = serialize($delivery_option);
        $result = $cart->save();

        if (!$result) {
            return null;
        }

        return $cart;
    }

    protected static function createOrder(
        $order_info,
        $cart,
        $productos_aliexpress,
        $customer,
        $id_address_delivery,
        $id_address_invoice,
        $id_order_state
    ) {
        $carrier = new Carrier($cart->id_carrier);
        $ae_order  = new AliexpressOrder((int)$order_info->order_id);
        if (Validate::isLoadedObject($ae_order)) {
            $order = Order::getByReference($ae_order->reference);
        }
        if (empty($order) || !Validate::isLoadedObject($order)) {
            $order = new Order();
        }
        $currency  = new Currency($cart->id_currency);

        $useTaxes = true;
        $carrier_tax_rate = $carrier
            ->getTaxesRate(new Address((int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
        $date_add = empty($order_info->gmt_pay_time)
            ? AliexpressTools::getDateTimeFromAEDateTime($order_info->gmt_create)
            : AliexpressTools::getDateTimeFromAEDateTime($order_info->gmt_pay_time);

        $order->id_address_delivery      = (int)$id_address_delivery;
        $order->id_address_invoice       = (int)$id_address_invoice;
        $order->id_cart                  = (int)$cart->id;
        $order->id_currency              = (int)$cart->id_currency;
        $order->id_lang                  = (int)$cart->id_lang;
        $order->id_customer              = (int)$cart->id_customer;
        $order->id_carrier               = (int)$cart->id_carrier;
        $order->secure_key               = pSQL($customer->secure_key);
        $order->payment                  = pSQL($customer->secure_key);
        $order->conversion_rate          = ($currency->conversion_rate ? $currency->conversion_rate : 1);
        $order->recyclable               = (bool)Configuration::get('PS_RECYCLABLE_PACK');
        $order->gift                     = (bool)$cart->gift;
        $order->gift_message             = $cart->gift_message;
        $order->module                   = 'aliexpress_payment';
        $order->payment                  = 'Aliexpress Payment';
        $order->shipping_number          = '';
        $order->total_discounts          = (float)abs(
            self::getOrderTotals($cart, $productos_aliexpress, $order_info, false, 2)
        );
        $order->total_discounts_tax_incl = (float)abs(
            self::getOrderTotals($cart, $productos_aliexpress, $order_info, true, 2)
        );

        $order->total_paid               = (float)self::getOrderTotals(
            $cart,
            $productos_aliexpress,
            $order_info,
            $useTaxes,
            3
        );
        $order->total_paid_real          = (float)self::getOrderTotals(
            $cart,
            $productos_aliexpress,
            $order_info,
            $useTaxes,
            3
        );
        $order->total_products           = (float)self::getOrderTotals(
            $cart,
            $productos_aliexpress,
            $order_info,
            false,
            1
        );
        $order->total_products_wt        = (float)self::getOrderTotals(
            $cart,
            $productos_aliexpress,
            $order_info,
            $useTaxes,
            1
        );
        $order->total_shipping           = (float)self::getOrderTotals(
            $cart,
            $productos_aliexpress,
            $order_info,
            $useTaxes,
            5
        );

        $order->carrier_tax_rate         = $carrier_tax_rate;
        $order->total_wrapping           = (float)abs(
            self::getOrderTotals($cart, $productos_aliexpress, $order_info, false, 6)
        );

        $order->total_wrapping_tax_incl  = 0;
        $order->total_wrapping_tax_excl  = 0;

        $order->delivery_number          = 0;
        $order->invoice_date             = AliexpressConfiguration::NULL_DATE;
        $order->delivery_date            = AliexpressConfiguration::NULL_DATE;
        $order->valid                    = 1;
        $order->round_mode               = Configuration::get('PS_PRICE_ROUND_MODE');
        $order->round_type               = Configuration::get('PS_ROUND_TYPE');
        $order->payment                  = 'Aliexpress Payment';


        if (version_compare(_PS_VERSION_, '1.5', '>=')) {
            if (empty($order->reference)) {
                $order->reference = Order::generateReference();
            }
            $order->total_paid_tax_excl     =
                (float)self::getOrderTotals($cart, $productos_aliexpress, $order_info, false, 3);
            $order->total_paid_tax_incl     =
                (float)self::getOrderTotals($cart, $productos_aliexpress, $order_info, true, 3);
            $order->total_shipping_tax_excl =
                (float)self::getOrderTotals($cart, $productos_aliexpress, $order_info, false, 5);
            $order->total_shipping_tax_incl =
                (float)self::getOrderTotals($cart, $productos_aliexpress, $order_info, true, 5);
            $order->total_paid_real         = 0;
            $order->current_state           = (int)$id_order_state;

            $order->id_shop_group = (int)$cart->id_shop_group;
            $order->id_shop       = (int)$cart->id_shop;
        } else {
            $order->id_shop = 1;
        }

        if ($date_add) {
            $order->date_add = $date_add;
            $order->date_upd = date('Y-m-d H:i:s');
            $autodate = false;
        } else {
            $autodate = true;
        }
        if (!Validate::isLoadedObject($order)) {
            $order->add($autodate);
        } else {
            $order->save();
        }

        return $order;
    }

    /**
     * Establece el transportista de un pedido
     *
     * @param $id_order
     * @param $id_carrier
     * @param $id_order_invoice
     * @param $weight
     * @param $shipping_cost_tax_excl
     * @param $shipping_cost_tax_incl
     * @param string $tracking_number
     * @return mixed
     */
    public static function setCarrier(
        $id_order,
        $id_carrier,
        $id_order_invoice,
        $weight,
        $shipping_cost_tax_excl,
        $shipping_cost_tax_incl,
        $tracking_number = ''
    ) {
        $query = new DbQuery();
        $query->select('id_order_carrier');
        $query->from('order_carrier');
        $query->where('`id_order` = '.(int)$id_order);

        $id_order_carrier                     = (int)Db::getInstance()->getValue($query);
        $orderCarrier                         = new OrderCarrier($id_order_carrier);
        $orderCarrier->id_order               = (int)$id_order;
        $orderCarrier->id_carrier             = (int)$id_carrier;
        $orderCarrier->id_order_invoice       = $id_order_invoice;
        $orderCarrier->weight                 = $weight;
        $orderCarrier->shipping_cost_tax_excl = $shipping_cost_tax_excl;
        $orderCarrier->shipping_cost_tax_incl = $shipping_cost_tax_incl;
        $orderCarrier->tracking_number        = $tracking_number;
        return $orderCarrier->save();
    }

    public static function getOrdersFromAE(
        $oldest_date = null,
        $oldest_date_upd = null,
        $newest_date = null,
        $page = 1,
        $pageSize = null,
        $orderStatus = null
    ) {
        if (is_null($pageSize)) {
            $pageSize = self::DEFAULT_PAGE_SIZE;
        }

        $final_orders_status = array();
        if (!is_null($orderStatus)) {
            if (is_string($orderStatus) && in_array($orderStatus, array_values(self::$aliexpress_order_status))) {
                $final_orders_status = array_values(self::$aliexpress_order_status);
            } elseif (is_array($orderStatus)) {
                foreach ($orderStatus as $status) {
                    if (in_array($status, array_values(self::$aliexpress_order_status))) {
                        $final_orders_status[] = $status;
                    }
                }
            }
        } else {
            $final_orders_status = array_values(self::$aliexpress_order_status);
        }

        $req                       = new AliexpressTradeSellerOrderlistGetRequest;
        $param1                    = new AeopOrderQuery;

        if (!is_null($newest_date) && !empty($oldest_date) && is_string($oldest_date) && trim($oldest_date) != '') {
            $param1->create_date_start     = $oldest_date;
            $param1->modified_date_start   = $oldest_date_upd;
        } else {
            $param1->create_date_start     = "0000-00-00 00:00:00";
            $param1->modified_date_start   = "0000-00-00 00:00:00";
        }

        if (!is_null($newest_date) && !empty($newest_date) && is_string($newest_date) && trim($newest_date) != '') {
            $param1->modified_date_end   = $newest_date;
            $param1->create_date_end     = $newest_date;
        } else {
            $param1->modified_date_end = date("Y-m-d H:i:s");
            $param1->create_date_end   = date("Y-m-d H:i:s");
        };

        if (count($final_orders_status) > 1) {
            $param1->order_status_list = '["'.implode('", "', $final_orders_status).'"]';
            $param1->order_status_list = $final_orders_status;
        } else {
            $param1->order_status = $final_orders_status[0];
        }

        $param1->current_page      = $page;
        $param1->page_size         = $pageSize;

        $param1->create_date_end = "0000-00-00 00:00:00";
        $param1->modified_date_end = "0000-00-00 00:00:00";

        $req->setParamAeopOrderQuery(json_encode($param1));
        $result = AliexpressApiv2::callAPI($req);
        return $result;
    }

    public static function getOrderInfoFromAE($ae_id)
    {
        $req                       = new AliexpressTradeNewRedefiningFindorderbyidRequest;
        $param1                    = new AeopTpSingleOrderQuery;
        $param1->order_id          = $ae_id;

        $req->setParam1(json_encode($param1));
        $result = AliexpressApiv2::callAPI($req);

        return $result;
    }

    /**
     * Este método devuelve al combinación del producto comprado en Aliexpress
     *
     * @param $id_product
     * @param $skuInfo
     * @return int
     */
    public static function getProductAttributeFromSKUInfo($id_product, $skuInfo)
    {
        $sku_info = json_decode($skuInfo);
        foreach ($sku_info as $sku) {
            $sku_id    = $sku['pId'];

            $product = new Product((int)$id_product);
            if (Validate::isLoadedObject($product)) {
                $categoryRelation = AliexpressCategoryRelation::getAECategryIdByPSCategoryId(
                    $product->id_category_default
                );
                if (Validate::isLoadedObject($categoryRelation)) {
                    $skuRelation = AliexpressSKURelation::getInstanceByIdSku($categoryRelation->id, $sku_id);
                    if (Validate::isLoadedObject($skuRelation)) {
                        if ($skuRelation->type == AliexpressSKURelation::TYPE_FORCED) {
                        }
                        if ($skuRelation->type == AliexpressSKURelation::TYPE_ATTRIBUTE_GROUP) {
                        }
                        if ($skuRelation->type == AliexpressSKURelation::TYPE_ATTRIBUTE_GROUP) {
                        }
                    }
                }
            }
        }
    }

    /**
     * Total Cart amount
     *
     * 1 - products amount
     * 2 - discounts amount
     * 3 - products + discounts amount
     * 4 - products + discounts amount but not shipping
     * 5 - shipping amount
     * 6 - wrapping amount
     * 7 - products amount without shipping
     *
     * @param object $cart Cart object initialized
     * @param array $productos_aliexpress list of products imported from Aliexpress
     * @param array $order_info Aliexpress order information
     * @param boolean $tax_included With or without taxes
     * @param integer $type Total type
     *
     * @return float Order total
     */

    public static function getOrderTotals($cart, $productos_aliexpress, $order_info, $tax_included = true, $type = 3)
    {
        $type = (int)$type;
        if (!in_array($type, array(1, 2, 3, 4, 5, 6, 7, 8))) {
            echo Tools::displayError('Type is not specified');
            return (false);
        }

        $total_tax_incl = (float)$order_info->pay_amount->amount;

        $taxCalculationMethod = self::setTaxCalculationMethod($cart->id_customer);

        $total_price_tax_incl = $total_price_tax_excl = 0;
        $carrier = new Carrier($cart->id_carrier);
        $carrier_tax_rate = $carrier
            ->getTaxesRate(new Address((int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));

        $products = $cart->getProducts();
        foreach ($products as $product) {
            $product_tax_rate = self::getTaxRate($product, $taxCalculationMethod);

            $unit_price =
                (float)$productos_aliexpress[$product['id_product'].'-'.$product['id_product_attribute']]['price'];

            $unit_price_tax_excl = Tools::ps_round($unit_price / ((100 + $product_tax_rate) / 100), 2);
            $unit_price_tax_incl = (float)$unit_price;

            $total_price_tax_incl+= ($unit_price_tax_incl * (int)$product['cart_quantity']);
            $total_price_tax_excl+= ($unit_price_tax_excl * (int)$product['cart_quantity']);
        }

        $total_shipping_tax_incl = $total_tax_incl - $total_price_tax_incl;

        $total_shipping_tax_excl = (float)Tools::ps_round(
            $total_shipping_tax_incl / ((100 + $carrier_tax_rate) / 100),
            2
        );
        $total_shipping_tax_incl = (float)Tools::ps_round($total_shipping_tax_incl, 2);

        switch ($type) {
            case 1:
            case 8:
                $amount = $tax_included
                    ? $total_price_tax_incl
                    : $total_price_tax_excl;
                break;
            case 2:
                return 0;
            case 3:
                $amount = $tax_included
                    ? ($total_price_tax_incl + $total_shipping_tax_incl)
                    : ($total_price_tax_excl + $total_shipping_tax_excl);
                break;
            case 4:
                $amount = $tax_included
                    ? $total_price_tax_incl
                    : $total_price_tax_excl;
                break;
            case 5:
                $amount = $tax_included
                    ? $total_shipping_tax_incl > 0 ? $total_shipping_tax_incl : 0
                    : $total_shipping_tax_excl > 0 ? $total_shipping_tax_excl : 0;
                break;
            case 6:
                $amount = 0;
                break;
            case 7:
                $amount = $tax_included
                    ? $total_price_tax_incl
                    : $total_price_tax_excl;
                break;
            default:
                $amount = 0;
        }

        return Tools::ps_round($amount, 2);
    }

    private static function setTaxCalculationMethod($id_customer)
    {
        if ($id_customer) {
            $customer = new Customer((int)($id_customer));
            return !Group::getPriceDisplayMethod((int)($customer->id_default_group));
        } else {
            return !Group::getDefaultPriceDisplayMethod();
        }
    }

    private static function getCarrierTaxRate($id_carrier, $calculation_method, $id_address_delivery)
    {
        if ($calculation_method && $id_address_delivery && method_exists('Tax', 'getCarrierTaxRate')) {
            return (float)Tax::getCarrierTaxRate($id_carrier, (int)$id_address_delivery);
        }
        return 0;
    }

    private static function getTaxRate($product, $calculation_method)
    {
        if ($calculation_method) {
            if (method_exists('Tax', 'getProductTaxRate')) {
                return (float)Tax::getProductTaxRate(
                    (int)$product['id_product'],
                    (int)$product['id_address_delivery']
                );
            } elseif (version_compare(_PS_VERSION_, '1.4.0.3', '<=') && method_exists('Tax', 'getApplicableTax')) {
                return (float)Tax::getApplicableTax(
                    (int)$product['id_tax'],
                    $product['tax_rate'],
                    (int)$product['id_address_delivery']
                );
            }
        }
        return 0;
    }

    private static function updateOrderData($ps_order, $productos_aliexpress, $id_carrier, $id_order_state)
    {
        $ps_order_details  = $ps_order->getOrderDetailList();
        $products_total    = 0;
        $total_shipping    = 0;
        $products_weight   = 0;
        $products_total_wt = 0;
        $total_shipping_wt = 0;
        $productos_aliexpress = empty($productos_aliexpress) ? array() : $productos_aliexpress;
        foreach ($ps_order_details as $detail) {
            $ae_price    = $productos_aliexpress[$detail['product_id'].'-'.$detail['product_attribute_id']]['price'];
            $ae_quantity = $productos_aliexpress[$detail['product_id'].'-'.$detail['product_attribute_id']]['quantity'];
            $ae_shipping = $productos_aliexpress[$detail['product_id'].'-'.$detail['product_attribute_id']]['shipping'];
            $taxCalculator = OrderDetail::getTaxCalculatorStatic($detail['id_order_detail']);
            $products_weight   += $detail['product_weight']*$ae_quantity;
            $products_total    += $taxCalculator->removeTaxes($ae_price*$ae_quantity);
            $products_total_wt += $ae_price*$ae_quantity;
            $total_shipping_wt += $ae_shipping;
            if ($ps_order->carrier_tax_rate > 0) {
                $ae_shipping_tax_excl = $ae_shipping / ($ps_order->carrier_tax_rate / 100);
                $ae_shipping_tax_excl = (float)Tools::ps_round($ae_shipping_tax_excl, 2);
            } else {
                $ae_shipping_tax_excl = $ae_shipping;
            }

            $order_detail_array = array(
                'product_price'                 => $taxCalculator->removeTaxes($ae_price),
                'original_product_price'        => $taxCalculator->removeTaxes($ae_price),
                'unit_price_tax_incl'           => $ae_price,
                'unit_price_tax_excl'           => $taxCalculator->removeTaxes($ae_price),
                'total_price_tax_incl'          => $ae_price*$ae_quantity,
                'total_price_tax_excl'          => $taxCalculator->removeTaxes($ae_price*$ae_quantity),
                'total_shipping_price_tax_incl' => $ae_shipping,
                'total_shipping_price_tax_excl' => $ae_shipping_tax_excl,
            );

            $result = Db::getInstance()->update(
                'order_detail',
                $order_detail_array,
                'id_order_detail = '.(int)$detail['id_order_detail']
            );

            if (!$result) {
                throw new AliexpressException(AliexpressException::ORDER_SYNC_ORDER_DETAIL_NOT_UPDATED);
            }
        }

        $ps_order_total_shipping_tax_excl = $total_shipping_wt;
        if ($ps_order->carrier_tax_rate > 0) {
            $ps_order_total_shipping_tax_excl = $ps_order_total_shipping_tax_excl / ($ps_order->carrier_tax_rate / 100);
            $ps_order_total_shipping_tax_excl = (float)Tools::ps_round($ps_order_total_shipping_tax_excl, 2);
        }
        $order_array = array(
            'id_carrier'              => $id_carrier,
            'total_paid'              => $total_shipping + $products_total,
            'total_paid_tax_incl'     => $total_shipping + $products_total,
            'total_paid_tax_excl'     => $ae_price,
            'total_paid_real'         => $total_shipping + $products_total,
            'total_products'          => $products_total,
            'total_products_wt'       => $products_total_wt,
            'total_shipping'          => $total_shipping_wt,
            'total_shipping_tax_incl' => $total_shipping_wt,
            'total_shipping_tax_excl' => $ps_order_total_shipping_tax_excl,
            'current_state'           => $id_order_state,
        );
        $sql = 'SELECT 1 FROM `'._DB_PREFIX_.'order_carrier` WHERE `id_order` = '.(int)$ps_order->id;
        if (!Db::getInstance()->getValue($sql)) {
            self::setCarrier(
                $ps_order->id,
                $id_carrier,
                0,
                $products_weight,
                $total_shipping_wt,
                $ps_order_total_shipping_tax_excl
            );
        }
        return Db::getInstance()->update('orders', $order_array, 'id_order = '.$ps_order->id);
    }


    private static function addOrderDetails($order, $cart, $productos_aliexpress, $address_id)
    {
        $id_warehouse = 1;

        if (!$products = $cart->getProducts()) {
            echo Tools::displayError('Unable to get products from cart.');
            return false;
        }

        foreach ($products as $product) {
            $id_product = (int)$product['id_product'];
            $id_product_attribute = $product['id_product_attribute']
                ? (int)$product['id_product_attribute']
                : null;

            if (version_compare(_PS_VERSION_, '1.5.0.3', '<')) {
                $product_quantity = (int)Product::getQuantity($id_product, $id_product_attribute);
                $quantity_in_stock = 0 > ($product_quantity - (int)$product['cart_quantity'])
                    ? $product_quantity
                    : (int)$product['cart_quantity'];
                Product::updateQuantity($product);
            }

            $product['stock_quantity']-= $product['cart_quantity'];
            if (0 > (int)$product['stock_quantity']) {
                $product['stock_quantity'] = 0;
            }

            $order_state = new OrderState((int)$order->current_state);
            $update_stocks = $order_state->paid ? true : false;

            if (version_compare(_PS_VERSION_, '1.5.0.3', '<=') && $update_stocks) {
                @Hook::updateQuantity($product, $order);
            } else {
                $product_quantity = Product::getRealQuantity(
                    $id_product,
                    $id_product_attribute,
                    $id_warehouse,
                    $order->id_shop
                );
                $quantity_in_stock = ($product_quantity - $product['cart_quantity']);

                if ($update_stocks) {
                    StockAvailable::updateQuantity(
                        $id_product,
                        $id_product_attribute,
                        ($product['cart_quantity'] * -1),
                        $order->id_shop
                    );
                }
            }

            $product['id_tax'] = $product['rate'] = 0;
            $product['tax'] = null;

            if (!Tax::excludeTaxeOption()) {
                $tax_rate = (float)Tax::getProductTaxRate($product['id_product'], $address_id);
                $taxes = Tax::getTaxes($order->id_lang);
                foreach ($taxes as $tax) {
                    if ((float)$tax['rate'] == (float)$tax_rate) {
                        $product['id_tax'] = $tax['id_tax'];
                        $product['tax'] = $tax['name'];
                        $product['rate'] = $tax_rate;
                    }
                }
            }
            $quantity = (int)$product['cart_quantity'];

            $unit_price           =
                (float)$productos_aliexpress[$product['id_product'].'-'.$product['id_product_attribute']]['price'];
            $unit_price_tax_incl  = (float)$unit_price;
            $unit_price_tax_excl  = (float)Tools::ps_round($unit_price_tax_incl / (1 + ($product['rate'] / 100)), 2);
            $total_price_tax_incl = (float)Tools::ps_round($unit_price_tax_incl, 2) * $quantity;
            $total_price_tax_excl = (float)Tools::ps_round($unit_price_tax_excl, 2) * $quantity;

            $taxes = (float)Tools::ps_round($total_price_tax_incl - $total_price_tax_excl, 2);

            $product_name = $product['name'] . (
                (isset($product['attributes']) && $product['attributes'] != null)
                    ? ' - ' . $product['attributes']
                    : ''
                );

            $order_detail = new OrderDetail;
            $order_detail->id_order = (int)$order->id;
            $order_detail->product_name = $product_name;
            $order_detail->product_id = $id_product;
            $order_detail->product_attribute_id = $id_product_attribute;
            $order_detail->product_quantity = (int)$product['cart_quantity'];
            $order_detail->product_quantity_in_stock = (int)$quantity_in_stock;
            $order_detail->product_price = (float)$unit_price_tax_excl;
            $order_detail->product_ean13 = $product['ean13']
                ? trim($product['ean13'])
                : null;
            $order_detail->product_upc = $product['upc']
                ? trim($product['upc'])
                : null;
            $order_detail->product_reference = trim($product['reference']);
            $order_detail->product_supplier_reference = $product['supplier_reference']
                ? $product['supplier_reference']
                : null;
            $order_detail->product_weight = (float)Tools::ps_round(
                $product['id_product_attribute']
                    ? $product['weight_attribute']
                    : $product['weight'],
                2
            );

            $order_detail->tax_name = Tools::substr($product['tax'], 0, 16); // is deprecated
            $order_detail->tax_rate = (float)$product['rate'];
            $order_detail->ecotax = $product['ecotax'];

            // Needed for 1.4
            $order_detail->download_deadline = AliexpressConfiguration::NULL_DATE;

            // Needed for 1.5 and highter
            $order_detail->total_price_tax_incl = (float)$total_price_tax_incl;
            $order_detail->total_price_tax_excl = (float)$total_price_tax_excl;
            $order_detail->unit_price_tax_incl = (float)$unit_price_tax_incl;
            $order_detail->unit_price_tax_excl = (float)$unit_price_tax_excl;

            // shop and warehouse
            $order_detail->id_shop = (int)$order->id_shop;
            $order_detail->id_warehouse = (int)$id_warehouse;

            $order_detail->add();

            if (!Validate::isLoadedObject($order_detail)) {
                Tools::displayError('Failed to create order detail');
                echo Db::getInstance()->getMsgError();
                return false;
            }

            $id_order_detail = $order_detail->id;
            $tax_query =
                'INSERT INTO `' . _DB_PREFIX_ . 'order_detail_tax` '.
                '(id_order_detail, id_tax, unit_amount, total_amount) VALUES ' .
                sprintf(
                    '(%d, %d, %f, %f) ;',
                    pSQL($id_order_detail),
                    pSQL($product['id_tax']),
                    pSQL($total_price_tax_excl),
                    (float)Tools::ps_round(($total_price_tax_incl - $total_price_tax_excl), 2)
                );

            if (!Db::getInstance()->Execute($tax_query)) {
                echo nl2br(print_r($tax_query, true));
                Tools::displayError('Failed to add tax details.');
                return false;
            }
        }
        $sql = 'SELECT 1 FROM `'._DB_PREFIX_.'order_carrier` WHERE `id_order` = '.(int)$order->id;
        if ($order->id_carrier && !Db::getInstance()->getValue($sql)) {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int)$order->id;
            $order_carrier->id_carrier = $order->id_carrier;
            $order_carrier->weight = (float)$order->getTotalWeight();
            $order_carrier->shipping_cost_tax_excl = $order->total_shipping_tax_excl;
            $order_carrier->shipping_cost_tax_incl = $order->total_shipping_tax_incl;
            $order_carrier->add();
        }
    }

    public static function syncTracking()
    {
        $response = array();
        $response['shipping_total'] = $response['shipping_updated'] = 0;
        if (1 > (int)AliexpressOrder::checkPendingTrackingNumber()) {
            return $response;
        }
        $contador_de_seguridad = 0;
        $max_intentos          = 5;
        $contador_intentos     = 0;
        $ids                   = array();
        do {
            try {
                $query =
                    'SELECT DISTINCT ao.`ae_id`,o.`id_order`,o.`reference`,o.`shipping_number`,o.`id_carrier`,'.
                    'IFNULL(c2.`url`, c.`url`) AS `url` '.
                    'FROM `' . _DB_PREFIX_ . 'orders` o ' .
                    'JOIN `' . _DB_PREFIX_ . 'carrier` c ON c.`id_carrier` = o.`id_carrier` '.
                    'LEFT JOIN `' . _DB_PREFIX_ . 'carrier` c2 '.
                    'ON c.`id_reference` = c2.`id_reference` AND c2.`deleted` = 0 '.
                    'JOIN `' . _DB_PREFIX_ . 'aliexpress_order` ao ' .
                    'ON ao.`reference` = o.`reference` AND ao.`ae_order_status` IN ("' .
                    AliexpressConfiguration::AE_ORDER_STATUS_WAIT_SELLER_SEND_GOODS . '","' .
                    AliexpressConfiguration::AE_ORDER_STATUS_SELLER_PART_SEND_GOODS .
                    '") WHERE (o.`shipping_number` != "" AND o.`shipping_number` IS NOT NULL) '.
                    'GROUP BY o.`id_order`';
                $query2 =
                    'SELECT DISTINCT ao.`ae_id`,o.`id_order`,o.`reference`,'.
                    'oc.`tracking_number` AS `shipping_number`,oc.`id_carrier`,IFNULL(c2.`url`, c.`url`) AS `url` '.
                    'FROM `' . _DB_PREFIX_ . 'order_carrier` oc ' .
                    'JOIN `' . _DB_PREFIX_ . 'carrier` c ON c.`id_carrier` = oc.`id_carrier` '.
                    'LEFT JOIN `' . _DB_PREFIX_ . 'carrier` c2 '.
                    'ON c.`id_reference` = c2.`id_reference` AND c2.`deleted` = 0 '.
                    'JOIN `' . _DB_PREFIX_ . 'orders` o ON o.`id_order` = oc.`id_order` ' .
                    'JOIN `' . _DB_PREFIX_ . 'aliexpress_order` ao ' .
                    'ON ao.`reference` = o.`reference` AND ao.`ae_order_status` IN ("' .
                    AliexpressConfiguration::AE_ORDER_STATUS_WAIT_SELLER_SEND_GOODS . '","' .
                    AliexpressConfiguration::AE_ORDER_STATUS_SELLER_PART_SEND_GOODS .
                    '") WHERE (oc.`tracking_number` != "" AND oc.`tracking_number` IS NOT NULL) '.
                    'GROUP BY o.`id_order`';
                $query = '('.$query.') UNION ('.$query2.')';
                if ($rows = Db::getInstance()->ExecuteS($query)) {
                    $response['shipping_total'] = count($rows);
                    foreach ($rows as $row) {
                        if (!in_array($row['id_order'], $ids)) {
                            $ids[] = $row['id_order'];
                            $order = AliexpressOrder::getInstanceByOrderReference($row['reference']);
                            if (Validate::isLoadedObject($order)) {
                                $shipping_number = $row['shipping_number'];
                                if (!empty($row['url'])) {
                                    $result = $order->uploadTrackingInfo($shipping_number, $row['url']);
                                    if ($result->result_success) {
                                        $notification = AliexpressNotification::getInstanceByData(
                                            AliexpressNotification::TYPE_ORDER_PENDING_TRACKNUMBER,
                                            $row['id_order']
                                        );
                                        if (ValidateCore::isLoadedObject($notification)) {
                                            $notification->processed = true;
                                            $notification->save();
                                        }
                                        $response['shipping_updated']++;
                                    } else {
                                        if ($result->result_error_code == '-320') {
                                            $response['errors'][] = array(
                                                'code' => $result->result_error_code,
                                                'message' =>
                                                    '[ PS: ' . $row['reference'] . ' - AE: ' . $row['ae_id'] . '] ' .
                                                    self::$module->l('AliExpress order changed in seller panel') . ' ' .
                                                    'ERROR DESCRIPTION: ' . $result->result_error_desc

                                            );
                                        } else if ($result->result_error_code == '-314') {
                                            $response['errors'][] = array(
                                                'code' => $result->result_error_code,
                                                'message' =>
                                                    '[ PS: ' . $row['reference'] . ' - AE: ' . $row['ae_id'] . '] ' .
                                                    self::$module->l('AliExpress order not ready to be shipped').' '.
                                                    'ERROR DESCRIPTION: '.$result->result_error_desc

                                            );
                                        } else {
                                            $response['errors'][] = array(
                                                'message' =>
                                                    '[ PS: ' . $row['reference'] . ' - AE: ' . $row['ae_id'] . '] ' .
                                                    self::$module->l('AliExpress order tracking number update error')
                                            );
                                        }
                                    }
                                } else {
                                    $response['errors'][] = array(
                                        'message' => '[ PS: '.$row['reference'].' - AE: '.$row['ae_id'].'] '.
                                            self::$module->l('Carrier do not have tracking url')
                                    );
                                }
                                $order->updateStatus();
                            }
                        }
                    }
                }
            } catch (Exception $e) {
                $contador_intentos++;
                $excepcion = array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage(),
                );
                $response['errors'][] = $excepcion;
                self::$synclogger->addLine(
                    array(
                        'excepción' => $excepcion
                    )
                );
            }
            $contador_de_seguridad++;
        } while ($contador_intentos < $max_intentos
        && $contador_de_seguridad < 10
        );
        return $response;
    }

    public static function getIdStateByName($id_country, $name)
    {
        if (empty($id_country)) {
            return null;
        }
        $id_state = Db::getInstance()->getValue(
            'SELECT `id_state` FROM `'._DB_PREFIX_.'aliexpress_state` '.
            'WHERE UPPER(`name`) = "'.pSQL(Tools::strtoupper($name)).'" AND `id_country` = "'.(int)$id_country.'"'
        );
        if ($id_state) {
            return (int)$id_state;
        }
        Db::getInstance()->execute(
            'INSERT IGNORE INTO `'._DB_PREFIX_.'aliexpress_state` (`id_country`,`name`) '.
            'VALUES ('.(int)$id_country.',"'.pSQL($name).'")'
        );
        return null;
    }

    public static function normalizeName($string)
    {
        $regex  = method_exists('Validate', 'isCustomerName')
            ? '/[!^0-9!<>,;?=+()\/\\@#"°*`{}_^$%:¤\[\]|\.。]|[!\.。]/'
            : '/[!^0-9!<>,;?=+()@#"°{}_$%:]/';
        $string = str_replace('receiber', '', Tools::stripslashes($string));
        $string = preg_replace($regex, ' ', Tools::stripslashes($string));
        $string = Tools::substr($string, 0, 32);
        return AliexpressTools::cleanNonAsciiCharactersInString($string);
    }

    public static function normalizeAddress($string)
    {
        $string = preg_replace('/[_]/', '-', Tools::stripslashes($string));
        $string = preg_replace('/[!^!<>?=+@{}_$%]/', ' ', $string);
        $string = Tools::substr($string, 0, 128);
        return AliexpressTools::cleanNonAsciiCharactersInString($string);
    }

    public static function cartProducts($cart, $order_info = array(), $ae_order_info = array())
    {
        $response = array();
        $productos_aliexpress = array();
        foreach ($order_info->product_list->aeop_order_product_dto as $ae_product) {
            $product = AliexpressProduct::getProductInstanceByAliexpressId($ae_product->product_id);
            if (!Validate::isLoadedObject($product)) {
                if ($id_product = AliexpressImportedProduct::searchPSProdct($ae_product->sku_code)) {
                    $product = AliexpressProduct::getInstanceByIdProduct($id_product);
                }
            }
            if (Validate::isLoadedObject($product)) {
                $product_attribute = 0;
                if (is_array($ae_product->sku_code)) {
                    $product_attribute = (int)AliexpressProduct::getProductAttributeBySkuValueId(
                        $ae_product->product_id,
                        $ae_product->sku_code
                    );
                }

                if (empty($product_attribute)) {
                    $product_attribute = (int)AliexpressProduct::getProductAttributeBySkuCode(
                        $ae_product->product_id,
                        $ae_product->sku_code
                    );
                    if (empty($product_attribute)) {
                        foreach ($ae_order_info->target->child_order_list->aeop_tp_child_order_dto as $ae_product_2) {
                            if ($ae_product->product_id == $ae_product_2->id) {
                                // Doble validación en caso de que no se reciba correctamente el sku_code
                                $sku_arr = json_decode($ae_product_2->product_attributes, true);
                                if (!empty($sku_arr['sku']) && is_array($sku_arr['sku'])) {
                                    $product_attribute = (int)AliexpressProduct::getProductAttributeBySkuValueId(
                                        $ae_product->product_id,
                                        $sku_arr['sku']
                                    );
                                }
                            }
                        }
                    }
                }

                $productos_aliexpress[$product->id . '-' . $product_attribute]['price']
                    = $ae_product->product_unit_price->amount;
                $productos_aliexpress[$product->id . '-' . $product_attribute]['quantity']
                    = $ae_product->product_count;
                $productos_aliexpress[$product->id . '-' . $product_attribute]['shipping']
                    = $ae_product->logistics_amount->amount;

                if (Validate::isLoadedObject($product)) {
                    $qty = StockAvailable::getQuantityAvailableByProduct($product->id, $product_attribute);
                    if ($qty > 0) {
                        try {
                            $result = $cart->updateQty(
                                $ae_product->product_count,
                                $product->id,
                                $product_attribute
                            );
                            if (!$result) {
                                $message =
                                    ' Can\'t update product [ ' . $product->id . ' - ' . $ae_product->sku_code . ' ] ' .
                                    'revise that is active and have stock. Aliexpress order: '.
                                    (int)$order_info->order_id;
                                throw new AliexpressException(
                                    AliexpressException::ORDER_SYNC_CART_DETAIL_NOT_CREATED,
                                    $message
                                );
                            }
                        } catch (Exception $e) {
                            $excepcion = array(
                                'code' => $e->getCode(),
                                'message' => $e->getMessage(),
                            );
                            $response['errors'][] = $excepcion;
                        }
                    } else {
                        $response['errors'][] = array(
                            'message' => ' ['.$ae_product->product_id.' - '.$ae_product->sku_code.'] '.
                                self::$module->l('Product out of stock')
                        );
                    }
                } else {
                    $response['errors'][] = array(
                        'message' => ' ['.$ae_product->product_id.' - '.$ae_product->sku_code.'] '.
                            self::$module->l('Aliexpress product does not exists')
                    );
                }
            } else {
                throw new Exception(
                    '[ '.$order_info->order_id.' ] '.self::$module->l('Aliexpress product does not exists'),
                    AliexpressException::ORDER_SYNC_CART_DETAIL_AEPRODUCT_NOT_EXISTS
                );
            }
        }
        return $productos_aliexpress;
    }
}

Muchas gracias.

 

Un saludo.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...