From 9d40ea19529036cd112219d27dc4c79753ebe259 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Mon, 14 Aug 2017 11:47:22 +0300 Subject: [PATCH 01/11] multi module for api v4, v5 --- retailcrm/config_ru.xml | 13 + retailcrm/job/sync.php | 694 +++++++++++++++++++++++++++++++++++++++- retailcrm/retailcrm.php | 6 +- 3 files changed, 708 insertions(+), 5 deletions(-) create mode 100644 retailcrm/config_ru.xml diff --git a/retailcrm/config_ru.xml b/retailcrm/config_ru.xml new file mode 100644 index 0000000..d684978 --- /dev/null +++ b/retailcrm/config_ru.xml @@ -0,0 +1,13 @@ + + + retailcrm + + + + + + + 1 + 1 + + \ No newline at end of file diff --git a/retailcrm/job/sync.php b/retailcrm/job/sync.php index 1ce1dd1..6f72a0c 100644 --- a/retailcrm/job/sync.php +++ b/retailcrm/job/sync.php @@ -27,5 +27,695 @@ if (!empty($apiUrl) && !empty($apiKey)) { exit(); } -RetailcrmHistory::customersHistory(); -RetailcrmHistory::ordersHistory(); +$lastSync = Configuration::get('RETAILCRM_LAST_SYNC'); +$references = new RetailcrmReferences($api); +$startFrom = ($lastSync === false) + ? date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))) + : $lastSync +; + +$customerFix = array(); +$orderFix = array(); +$startDate = new DateTime($startFrom); +$history = $api->ordersHistory(array( + 'startDate' => $startDate->format('Y-m-d H:i:s') +)); + +if ($history->isSuccessful() && count($history->history) > 0) { + $statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true))); + $deliveries = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true))); + $payments = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true))); + $deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true); + $paymentDefault = json_decode(Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT'), true); + $orders = RetailcrmHistoryHelper::assemblyOrder($history->history); + + foreach ($orders as $order_history) { + if (isset($order_history['deleted']) && $order_history['deleted'] == true) { + continue; + } + + if (!array_key_exists('externalId', $order_history)) { + $responce = $api->ordersGet($order_history['id'], 'id'); + + if ($responce->isSuccessful()) { + $order = $responce['order']; + } else { + continue; + } + + $delivery = $order['delivery']['code']; + + if (array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') { + $deliveryType = $deliveries[$delivery]; + } + + if ($apiVersion != 5) { + $payment = $order['paymentType']; + } else { + if (isset($order['payments']) && count($order['payments']) == 1) { + $paymentCRM = end($order['payments']); + $payment = $paymentCRM['type']; + } elseif (isset($order['payments']) && count($order['payments']) > 1) { + foreach ($order['payments'] as $paymentCRM) { + if ($payment['status'] != 'paid') { + $payment = $paymentCRM['type']; + } + } + } + } + + if (array_key_exists($payment, $payments) && $payments[$payment] != '') { + if (Module::getInstanceByName($payments[$payment])) { + $paymentType = Module::getModuleName($payments[$payment]); + } else { + $paymentType = $payments[$payment]; + } + $paymentId = $payments[$payment]; + } + + $state = $order['status']; + + if (array_key_exists($state, $statuses) && $statuses[$state] != '') { + $orderStatus = $statuses[$state]; + } + if (!isset($paymentId) || !$paymentId) { + $paymentId = $paymentDefault; + } + + if (!$paymentType) { + if ($paymentDefault) { + if (Module::getInstanceByName($paymentDefault)) { + $paymentType = Module::getModuleName($paymentDefault); + } else { + $paymentType = $paymentDefault; + } + } else { + error_log( + 'orderHistory: set default payment(error in order where id = '.$order['id'].')', + 3, + _PS_ROOT_DIR_ . '/retailcrm.log' + ); + + continue; + } + } + + if (!$deliveryType) { + if ($deliveryDefault) { + $deliveryType = $deliveryDefault; + } else { + error_log( + 'orderHistory: set default delivery(error in order where id = '.$order['id'].')', + 3, + _PS_ROOT_DIR_ . '/retailcrm.log' + ); + continue; + } + } + + $customer = new Customer(); + if (!empty($order['customer']['email'])) { + $customer->getByEmail($order['customer']['email'], null, false); + } + + if (!array_key_exists('externalId', $order['customer'])) { + if (!$customer->id) { + $customer->firstname = $order['customer']['firstName']; + $customer->lastname = !empty($order['customer']['lastName']) ? $order['customer']['lastName'] : '-'; + $customer->email = Validate::isEmail($order['customer']['email']) ? + $order['customer']['email'] : + md5($order['customer']['firstName']) . '@retailcrm.ru'; + $customer->passwd = Tools::substr(str_shuffle(Tools::strtolower(sha1(rand() . time()))), 0, 5); + + $customer->add(); + } + + array_push( + $customerFix, + array( + 'id' => $order['customer']['id'], + 'externalId' => $customer->id + ) + ); + } + + $address = new Address(); + $address->id_customer = $customer->id; + $address->id_country = $default_country; + $address->lastname = $customer->lastname; + $address->firstname = $customer->firstname; + $address->alias = 'default'; + $address->postcode = $order['delivery']['address']['index']; + $address->city = !empty($order['delivery']['address']['city']) ? + $order['delivery']['address']['city'] : '-'; + $address->address1 = !empty($order['delivery']['address']['text']) ? + $order['delivery']['address']['text'] : '-'; + $address->phone = $order['phone']; + $address->add(); + + $cart = new Cart(); + $cart->id_currency = $default_currency; + $cart->id_lang = $default_lang; + $cart->id_customer = $customer->id; + $cart->id_address_delivery = (int) $address->id; + $cart->id_address_invoice = (int) $address->id; + $cart->id_carrier = (int) $deliveryType; + + $cart->add(); + + $products = array(); + + if (!empty($order['items'])) { + foreach ($order['items'] as $item) { + $productId = explode('#', $item['offer']['externalId']); + + $product = array(); + $product['id_product'] = (int) $productId[0]; + $product['id_product_attribute'] = !empty($productId[1]) ? $productId[1] : 0; + $product['quantity'] = $item['quantity']; + $product['id_address_delivery'] = (int) $address->id; + $products[] = $product; + } + } + + $cart->setWsCartRows($products); + $cart->update(); + + /* + * Create order + */ + $newOrder = new Order(); + $shops = Shop::getShops(); + $newOrder->id_shop = Context::getContext()->shop->id; + $newOrder->id_shop_group = (int)$shops[Context::getContext()->shop->id]['id_shop_group']; + $newOrder->reference = $newOrder->generateReference(); + $newOrder->id_address_delivery = (int) $address->id; + $newOrder->id_address_invoice = (int) $address->id; + $newOrder->id_cart = (int) $cart->id; + $newOrder->id_currency = $default_currency; + $newOrder->id_lang = $default_lang; + $newOrder->id_customer = (int) $customer->id; + if (isset($deliveryType)) { + $newOrder->id_carrier = (int) $deliveryType; + } + if (isset($paymentType)) { + $newOrder->payment = $paymentType; + $newOrder->module = $paymentId; + } + $newOrder->total_paid = $order['summ'] + $order['delivery']['cost']; + $newOrder->total_paid_tax_incl = $order['summ'] + $order['delivery']['cost']; + $newOrder->total_paid_tax_excl = $order['summ'] + $order['delivery']['cost']; + $newOrder->total_paid_real = $order['summ'] + $order['delivery']['cost']; + $newOrder->total_products = $order['summ']; + $newOrder->total_products_wt = $order['summ']; + $newOrder->total_shipping = $order['delivery']['cost']; + $newOrder->total_shipping_tax_incl = $order['delivery']['cost']; + $newOrder->total_shipping_tax_excl = $order['delivery']['cost']; + $newOrder->conversion_rate = 1.000000; + if (isset($orderStatus)) { + $newOrder->current_state = (int) $orderStatus; + } + if (!empty($order['delivery']['date'])) { + $newOrder->delivery_date = $order['delivery']['date']; + } + $newOrder->date_add = $order['createdAt']; + $newOrder->date_upd = $order['createdAt']; + $newOrder->invoice_date = $order['createdAt']; + $newOrder->valid = 1; + $newOrder->secure_key = md5(time()); + + if (isset($order['discount'])) { + $newOrder->total_discounts = $order['discount']; + } + + $product_list = array(); + + foreach ($order['items'] as $item) { + $product = new Product((int) $item['offer']['externalId'], false, $default_lang); + $product_id = $item['offer']['externalId']; + $product_attribute_id = 0; + if (strpos($item['offer']['externalId'], '#') !== false) { + $product_id = explode('#', $item['offer']['externalId']); + $product_attribute_id = $product_id[1]; + $product_id = $product_id[0]; + } + + if ($product_attribute_id != 0) { + $productName = htmlspecialchars( + strip_tags(Product::getProductName($product_id, $product_attribute_id)) + ); + + $combinationPrice = Combination::getPrice($product_attribute_id); + $productPrice = $combinationPrice > 0 ? $product->getPrice()+ $combinationPrice : $product->getPrice(); + } else { + $productName = htmlspecialchars(strip_tags($product->name)); + $productPrice = $product->getPrice(); + } + + $product_list[] = array( + 'product' => $product, + 'product_attribute_id' => $product_attribute_id, + 'product_price' => $product->price, + 'product_price_inc_tax' => $productPrice, + 'product_name' => $productName, + 'quantity' => $item['quantity'] + ); + + if (isset($item['discountTotal']) && $apiVersion == 5) { + $newOrder->total_discounts += $item['discountTotal'] * $item['quantity']; + } + } + + $newOrder->add(false, false); + + foreach ($order['payments'] as $pay) { + if (!isset($pay['externalId']) && $pay['status'] == 'paid') { + $ptype = $payment['type']; + $ptypes = $references->getSystemPaymentModules(); + if ($payments[$ptype] != null) { + foreach ($ptypes as $pay) { + if ($pay['code'] == $payments[$ptype]) { + $payType = $pay['name']; + } + } + $paymentType = Module::getModuleName($payments[$ptype]); + Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` + (`payment_method`, `order_reference` , `amount`, `date_add`) + VALUES + (\'' . $payType . '\', + \'' . $newOrder->reference . '\', + \'' . $payment['amount'] . '\', + \'' . $payment['paidAt'] . '\')'); + } + } + } + + $carrier = new OrderCarrierCore(); + $carrier->id_order = $newOrder->id; + $carrier->id_carrier = $deliveryType; + $carrier->shipping_cost_tax_excl = $order['delivery']['cost']; + $carrier->shipping_cost_tax_incl = $order['delivery']['cost']; + $carrier->date_add = $order['delivery']['date']; + $carrier->add(false, false); + + /* + * collect order ids for single fix request + */ + array_push($orderFix, array('id' => $order['id'], 'externalId' => $newOrder->id)); + + /* + * Create order details + */ + $query = 'INSERT `'._DB_PREFIX_.'order_detail` + ( + `id_order`, `id_order_invoice`, `id_shop`, `product_id`, `product_attribute_id`, + `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, + `product_reference`, `total_price_tax_excl`, `total_price_tax_incl`, + `unit_price_tax_excl`, `unit_price_tax_incl`, `original_product_price` + ) + + VALUES'; + + $context = new Context(); + foreach ($product_list as $product) { + $query .= '(' + .(int) $newOrder->id.', + 0, + '. Context::getContext()->shop->id.', + '.(int) $product['product']->id.', + '.$product['product_attribute_id'].', + '.implode('', array('\'', $product['product_name'], '\'')).', + '.(int) $product['quantity'].', + '.(int) $product['quantity'].', + '.$product['product_price'].', + '.implode('', array('\'', $product['product']->reference, '\'')).', + '.$product['product_price'].', + '.$product['product_price_inc_tax'].', + '.$product['product_price'].', + '.$product['product_price_inc_tax'].', + '.$product['product_price'].' + ),'; + } + + Db::getInstance()->execute(rtrim($query, ',')); + + if (!empty($customerFix)) { + $api->customersFixExternalIds($customerFix); + } + if (!empty($orderFix)) { + $api->ordersFixExternalIds($orderFix); + } + } else { + $order = $order_history; + $orderToUpdate = new Order((int) $order['externalId']); + + /* + * check delivery type + */ + if (!empty($order['delivery']['code'])) { + $dtype = $order['delivery']['code']; + $dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null; + + if ($deliveries[$dtype] != null) { + if ($deliveries[$dtype] != $orderToUpdate->id_carrier or $dcost != null) { + if ($dtype != null) { + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` + SET + `id_carrier` = \'' . $deliveries[$dtype] . '\' + WHERE + `id_order` = ' . (int)$order['externalId']); + } + + $updateCarrierFields = array(); + if ($dtype != null) { + $updateCarrierFields[] = '`id_carrier` = \'' . $deliveries[$dtype] . '\' '; + } + if ($dcost != null) { + $updateCarrierFields[] = '`shipping_cost_tax_incl` = \'' . $dcost . '\' '; + $updateCarrierFields[] = '`shipping_cost_tax_excl` = \'' . $dcost . '\' '; + } + $updateCarrierFields = implode(', ', $updateCarrierFields); + + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_carrier` + SET + '.$updateCarrierFields.' + WHERE + `id_order` = \'' . $orderToUpdate->id . '\''); + } + } + } + + /* + * check payment type + */ + + if (!empty($order['paymentType']) && $apiVersion != 5) { + $ptype = $order['paymentType']; + + if ($payments[$ptype] != null) { + $paymentType = Module::getModuleName($payments[$ptype]); + if ($payments[$ptype] != $orderToUpdate->payment) { + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` + SET + `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' + WHERE + `id_order` = ' . (int)$order['externalId']); + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_payment` + SET + `payment_method` = \'' . $payments[$ptype] . '\' + WHERE + `order_reference` = \'' . $orderToUpdate->reference . '\''); + } + } + } elseif (!empty($order['payments']) && $apiVersion == 5) { + if ($order['payments']) { + foreach ($order['payments'] as $payment) { + if (!isset($payment['externalId']) && $payment['status'] == 'paid') { + $ptype = $payment['type']; + $ptypes = $references->getSystemPaymentModules(); + if ($payments[$ptype] != null) { + foreach ($ptypes as $pay) { + if ($pay['code'] == $payments[$ptype]) { + $payType = $pay['name']; + } + } + $paymentType = Module::getModuleName($payments[$ptype]); + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` + SET + `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' + WHERE + `id_order` = ' . (int)$order['externalId']); + + Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` + (`payment_method`, `order_reference` , `amount`, `date_add`) + VALUES + (\'' . $payType . '\', + \'' . $orderToUpdate->reference . '\', + \'' . $payment['amount'] . '\', + \'' . $payment['paidAt'] . '\')'); + } + } + } + } + } elseif (!empty($order['payments']) && $apiVersion == 5) { + if ($order['payments']) { + foreach ($order['payments'] as $payment) { + if (!isset($payment['externalId']) && $payment['status'] == 'paid') { + $ptype = $payment['type']; + $ptypes = $references->getSystemPaymentModules(); + if ($payments[$ptype] != null) { + foreach ($ptypes as $pay) { + if ($pay['code'] == $payments[$ptype]) { + $payType = $pay['name']; + } + } + $paymentType = Module::getModuleName($payments[$ptype]); + + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` + SET + `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' + WHERE + `id_order` = ' . (int)$order['externalId']); + + Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` + (`payment_method`, `order_reference` , `amount`, `date_add`) + VALUES + (\'' . $payType . '\', + \'' . $orderToUpdate->reference . '\', + \'' . $payment['amount'] . '\', + \'' . $payment['paidAt'] . '\')'); + } + } + } + } + } + + /* + * Clean deleted items + */ + foreach ($order['items'] as $key => $item) { + if (isset($item['delete']) && $item['delete'] == true) { + if (strpos($item['offer']['externalId'], '#') !== false) { + $itemId = explode('#', $item['offer']['externalId']); + $product_id = $itemId[0]; + $product_attribute_id = $itemId[1]; + } else { + $product_id = $item['offer']['externalId']; + $product_attribute_id = 0; + } + + Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail` + WHERE + `id_order` = '. $orderToUpdate->id .' + AND + `product_id` = '.$product_id. ' AND `product_attribute_id` = '.$product_attribute_id); + + unset($order['items'][$key]); + $ItemDiscount = true; + } + } + + /* + * Check items quantity and discount + */ + foreach ($orderToUpdate->getProductsDetail() as $orderItem) { + foreach ($order['items'] as $key => $item) { + if (strpos($item['offer']['externalId'], '#') !== false) { + $itemId = explode('#', $item['offer']['externalId']); + $product_id = $itemId[0]; + $product_attribute_id = $itemId[1]; + } else { + $product_id = $item['offer']['externalId']; + $product_attribute_id = 0; + } + + if ($product_id == $orderItem['product_id'] && + $product_attribute_id == $orderItem['product_attribute_id']) { + // discount + if (isset($item['discount']) || + isset($item['discountPercent']) || + isset($item['discountTotal'])) { + + $product = new Product((int) $product_id, false, $default_lang); + $tax = new TaxCore($product->id_tax_rules_group); + + if ($product_attribute_id != 0) { + $prodPrice = Combination::getPrice($product_attribute_id); + $prodPrice = $prodPrice > 0 ? $prodPrice : $product->price; + } else { + $prodPrice = $product->price; + } + + $prodPrice = $prodPrice + $prodPrice / 100 * $tax->rate; + + $productPrice = $prodPrice - $item['discount']; + $productPrice = $productPrice - ($prodPrice / 100 * $item['discountPercent']); + $productPrice = $prodPrice - $item['discountTotal']; + + $productPrice = round($productPrice, 2); + + Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail` + SET + `unit_price_tax_incl` = '.$productPrice.' + WHERE + `id_order_detail` = '.$orderItem['id_order_detail']); + } + + // quantity + if (isset($item['quantity']) && $item['quantity'] != $orderItem['product_quantity']) { + Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail` + SET + `product_quantity` = '.$item['quantity'].', + `product_quantity_in_stock` = '.$item['quantity'].' + WHERE + `id_order_detail` = '.$orderItem['id_order_detail']); + } + + $ItemDiscount = true; + unset($order['items'][$key]); + } + } + } + + /* + * Check new items + */ + if (!empty($order['items'])) { + $query = 'INSERT `'._DB_PREFIX_.'order_detail` + ( + `id_order`, `id_order_invoice`, `id_shop`, `product_id`, `product_attribute_id`, + `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, + `product_reference`, `total_price_tax_excl`, `total_price_tax_incl`, + `unit_price_tax_excl`, `unit_price_tax_incl`, `original_product_price` + ) + + VALUES'; + + foreach ($order['items'] as $key => $newItem) { + $product_id = $newItem['offer']['externalId']; + $product_attribute_id = 0; + if (strpos($product_id, '#') !== false) { + $product_id = explode('#', $product_id); + + $product_attribute_id = $product_id[1]; + $product_id = $product_id[0]; + } + + $product = new Product((int) $product_id, false, $default_lang); + $tax = new TaxCore($product->id_tax_rules_group); + + if ($product_attribute_id != 0) { + $productName = htmlspecialchars( + strip_tags(Product::getProductName($product_id, $product_attribute_id)) + ); + $productPrice = Combination::getPrice($product_attribute_id); + $productPrice = $productPrice > 0 ? $productPrice : $product->price; + } else { + $productName = htmlspecialchars(strip_tags($product->name)); + $productPrice = $product->price; + } + + // discount + if ($newItem['discount'] || $newItem['discountPercent']|| $newItem['discountTotal']) { + $productPrice = $productPrice - $newItem['discount']; + $productPrice = $productPrice - $newItem['discountTotal']; + $productPrice = $productPrice - ($prodPrice / 100 * $newItem['discountPercent']); + $ItemDiscount = true; + } + + $query .= '(' + .(int) $orderToUpdate->id.', + 0, + '. Context::getContext()->shop->id.', + '.(int) $product_id.', + '.(int) $product_attribute_id.', + '.implode('', array('\'', $productName, '\'')).', + '.(int) $newItem['quantity'].', + '.(int) $newItem['quantity'].', + '.$productPrice.', + '.implode('', array('\'', $product->reference, '\'')).', + '.$productPrice * $newItem['quantity'].', + '.($productPrice + $productPrice / 100 * $tax->rate) * $newItem['quantity'].', + '.$productPrice.', + '.($productPrice + $productPrice / 100 * $tax->rate).', + '.$productPrice.' + ),'; + + unset($order['items'][$key]); + } + + Db::getInstance()->execute(rtrim($query, ',')); + } + + /* + * Fix prices & discounts + * Discounts only for whole order + */ + if (isset($order['discount']) || + isset($order['discountPercent']) || + isset($order['delivery']['cost']) || + isset($order['discountTotal']) || + $ItemDiscount) { + $infoOrd = $api->ordersGet($order['externalId']); + $infoOrder = $infoOrd->order; + $orderTotalProducts = $infoOrder['summ']; + $totalPaid = $infoOrder['totalSumm']; + $deliveryCost = $infoOrder['delivery']['cost']; + $totalDiscount = $deliveryCost + $orderTotalProducts - $totalPaid; + + $orderCartRules = $orderToUpdate->getCartRules(); + foreach ($orderCartRules as $valCartRules) { + $order_cart_rule = new OrderCartRule($valCartRules['id_order_cart_rule']); + $order_cart_rule->delete(); + } + $orderToUpdate->update(); + + Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'orders` + SET + `total_discounts` = '.$totalDiscount.', + `total_discounts_tax_incl` = '.$totalDiscount.', + `total_discounts_tax_excl` = '.$totalDiscount.', + `total_shipping` = '.$deliveryCost.', + `total_shipping_tax_incl` = '.$deliveryCost.', + `total_shipping_tax_excl` = '.$deliveryCost.', + `total_paid` = '.$totalPaid.', + `total_paid_tax_incl` = '.$totalPaid.', + `total_paid_tax_excl` = '.$totalPaid.', + `total_products_wt` = '.$orderTotalProducts.' + WHERE `id_order` = '.(int) $order['externalId']); + + unset($ItemDiscount); + } + + /* + * check status + */ + if (!empty($order['status'])) { + $stype = $order['status']; + + if ($statuses[$stype] != null) { + if ($statuses[$stype] != $orderToUpdate->current_state) { + Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_history` + (`id_employee`, `id_order`, `id_order_state`, `date_add`) + VALUES + (0, ' . $orderToUpdate->id . ', + ' . $statuses[$stype] . ', + "' . date('Y-m-d H:i:s') . '")'); + + Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` + SET + `current_state` = \'' . $statuses[$stype] . '\' + WHERE + `id_order` = ' . (int)$order['externalId']); + } + } + } + } + } + /* + * Update last sync timestamp + */ + Configuration::updateValue('RETAILCRM_LAST_SYNC', $history->generatedAt); +} else { + return 'Nothing to sync'; +} diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index 96c97b0..a875c0b 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -80,7 +80,7 @@ class RetailCRM extends Module } public function getContent() - { + { $output = null; $address = Configuration::get('RETAILCRM_ADDRESS'); $token = Configuration::get('RETAILCRM_API_TOKEN'); @@ -420,7 +420,7 @@ class RetailCRM extends Module unset($comment); foreach ($orderdb->getProducts() as $item) { - if (isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { + if(isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { $productId = $item['product_id'] . '#' . $item['product_attribute_id']; } else { $productId = $item['product_id']; @@ -439,7 +439,7 @@ class RetailCRM extends Module } public function hookActionOrderStatusPostUpdate($params) - { + { $delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true); $payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true); $status = json_decode(Configuration::get('RETAILCRM_API_STATUS'), true); From 54a476eed0cbb0673dda235e45f2f9dfad308c3d Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 1 Sep 2017 10:10:46 +0300 Subject: [PATCH 02/11] fix for validation on marketplace, edit validation form for saving settings --- retailcrm/config_ru.xml | 13 ------------- retailcrm/retailcrm.php | 9 +++++---- 2 files changed, 5 insertions(+), 17 deletions(-) delete mode 100644 retailcrm/config_ru.xml diff --git a/retailcrm/config_ru.xml b/retailcrm/config_ru.xml deleted file mode 100644 index d684978..0000000 --- a/retailcrm/config_ru.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - retailcrm - - - - - - - 1 - 1 - - \ No newline at end of file diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index a875c0b..617ff03 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -3,7 +3,7 @@ * @author Retail Driver LCC * @copyright RetailCRM * @license GPL - * @version 2.2.0 + * @version 2.1.2 * @link https://retailcrm.ru * */ @@ -80,7 +80,7 @@ class RetailCRM extends Module } public function getContent() - { + { $output = null; $address = Configuration::get('RETAILCRM_ADDRESS'); $token = Configuration::get('RETAILCRM_API_TOKEN'); @@ -420,7 +420,7 @@ class RetailCRM extends Module unset($comment); foreach ($orderdb->getProducts() as $item) { - if(isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { + if (isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { $productId = $item['product_id'] . '#' . $item['product_attribute_id']; } else { $productId = $item['product_id']; @@ -439,7 +439,7 @@ class RetailCRM extends Module } public function hookActionOrderStatusPostUpdate($params) - { + { $delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true); $payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true); $status = json_decode(Configuration::get('RETAILCRM_API_STATUS'), true); @@ -679,6 +679,7 @@ class RetailCRM extends Module $response = $api->deliveryTypesList(); if ($response !== false) { + return true; } From 575c9f55c19738d6d117f4a86aa7bb07c91a5bb8 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Thu, 21 Sep 2017 10:19:43 +0300 Subject: [PATCH 03/11] Bug fix --- retailcrm/retailcrm.php | 1 - 1 file changed, 1 deletion(-) diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index 617ff03..29cbf12 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -679,7 +679,6 @@ class RetailCRM extends Module $response = $api->deliveryTypesList(); if ($response !== false) { - return true; } From 6c0993cd0393908052a7168eb4b749c29e56fe94 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 28 Feb 2018 15:55:07 +0300 Subject: [PATCH 04/11] Customers history, fix attribute value --- retailcrm/job/sync.php | 694 +--------------------------------------- retailcrm/retailcrm.php | 2 +- 2 files changed, 3 insertions(+), 693 deletions(-) diff --git a/retailcrm/job/sync.php b/retailcrm/job/sync.php index 6f72a0c..1ce1dd1 100644 --- a/retailcrm/job/sync.php +++ b/retailcrm/job/sync.php @@ -27,695 +27,5 @@ if (!empty($apiUrl) && !empty($apiKey)) { exit(); } -$lastSync = Configuration::get('RETAILCRM_LAST_SYNC'); -$references = new RetailcrmReferences($api); -$startFrom = ($lastSync === false) - ? date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s')))) - : $lastSync -; - -$customerFix = array(); -$orderFix = array(); -$startDate = new DateTime($startFrom); -$history = $api->ordersHistory(array( - 'startDate' => $startDate->format('Y-m-d H:i:s') -)); - -if ($history->isSuccessful() && count($history->history) > 0) { - $statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true))); - $deliveries = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true))); - $payments = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true))); - $deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true); - $paymentDefault = json_decode(Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT'), true); - $orders = RetailcrmHistoryHelper::assemblyOrder($history->history); - - foreach ($orders as $order_history) { - if (isset($order_history['deleted']) && $order_history['deleted'] == true) { - continue; - } - - if (!array_key_exists('externalId', $order_history)) { - $responce = $api->ordersGet($order_history['id'], 'id'); - - if ($responce->isSuccessful()) { - $order = $responce['order']; - } else { - continue; - } - - $delivery = $order['delivery']['code']; - - if (array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') { - $deliveryType = $deliveries[$delivery]; - } - - if ($apiVersion != 5) { - $payment = $order['paymentType']; - } else { - if (isset($order['payments']) && count($order['payments']) == 1) { - $paymentCRM = end($order['payments']); - $payment = $paymentCRM['type']; - } elseif (isset($order['payments']) && count($order['payments']) > 1) { - foreach ($order['payments'] as $paymentCRM) { - if ($payment['status'] != 'paid') { - $payment = $paymentCRM['type']; - } - } - } - } - - if (array_key_exists($payment, $payments) && $payments[$payment] != '') { - if (Module::getInstanceByName($payments[$payment])) { - $paymentType = Module::getModuleName($payments[$payment]); - } else { - $paymentType = $payments[$payment]; - } - $paymentId = $payments[$payment]; - } - - $state = $order['status']; - - if (array_key_exists($state, $statuses) && $statuses[$state] != '') { - $orderStatus = $statuses[$state]; - } - if (!isset($paymentId) || !$paymentId) { - $paymentId = $paymentDefault; - } - - if (!$paymentType) { - if ($paymentDefault) { - if (Module::getInstanceByName($paymentDefault)) { - $paymentType = Module::getModuleName($paymentDefault); - } else { - $paymentType = $paymentDefault; - } - } else { - error_log( - 'orderHistory: set default payment(error in order where id = '.$order['id'].')', - 3, - _PS_ROOT_DIR_ . '/retailcrm.log' - ); - - continue; - } - } - - if (!$deliveryType) { - if ($deliveryDefault) { - $deliveryType = $deliveryDefault; - } else { - error_log( - 'orderHistory: set default delivery(error in order where id = '.$order['id'].')', - 3, - _PS_ROOT_DIR_ . '/retailcrm.log' - ); - continue; - } - } - - $customer = new Customer(); - if (!empty($order['customer']['email'])) { - $customer->getByEmail($order['customer']['email'], null, false); - } - - if (!array_key_exists('externalId', $order['customer'])) { - if (!$customer->id) { - $customer->firstname = $order['customer']['firstName']; - $customer->lastname = !empty($order['customer']['lastName']) ? $order['customer']['lastName'] : '-'; - $customer->email = Validate::isEmail($order['customer']['email']) ? - $order['customer']['email'] : - md5($order['customer']['firstName']) . '@retailcrm.ru'; - $customer->passwd = Tools::substr(str_shuffle(Tools::strtolower(sha1(rand() . time()))), 0, 5); - - $customer->add(); - } - - array_push( - $customerFix, - array( - 'id' => $order['customer']['id'], - 'externalId' => $customer->id - ) - ); - } - - $address = new Address(); - $address->id_customer = $customer->id; - $address->id_country = $default_country; - $address->lastname = $customer->lastname; - $address->firstname = $customer->firstname; - $address->alias = 'default'; - $address->postcode = $order['delivery']['address']['index']; - $address->city = !empty($order['delivery']['address']['city']) ? - $order['delivery']['address']['city'] : '-'; - $address->address1 = !empty($order['delivery']['address']['text']) ? - $order['delivery']['address']['text'] : '-'; - $address->phone = $order['phone']; - $address->add(); - - $cart = new Cart(); - $cart->id_currency = $default_currency; - $cart->id_lang = $default_lang; - $cart->id_customer = $customer->id; - $cart->id_address_delivery = (int) $address->id; - $cart->id_address_invoice = (int) $address->id; - $cart->id_carrier = (int) $deliveryType; - - $cart->add(); - - $products = array(); - - if (!empty($order['items'])) { - foreach ($order['items'] as $item) { - $productId = explode('#', $item['offer']['externalId']); - - $product = array(); - $product['id_product'] = (int) $productId[0]; - $product['id_product_attribute'] = !empty($productId[1]) ? $productId[1] : 0; - $product['quantity'] = $item['quantity']; - $product['id_address_delivery'] = (int) $address->id; - $products[] = $product; - } - } - - $cart->setWsCartRows($products); - $cart->update(); - - /* - * Create order - */ - $newOrder = new Order(); - $shops = Shop::getShops(); - $newOrder->id_shop = Context::getContext()->shop->id; - $newOrder->id_shop_group = (int)$shops[Context::getContext()->shop->id]['id_shop_group']; - $newOrder->reference = $newOrder->generateReference(); - $newOrder->id_address_delivery = (int) $address->id; - $newOrder->id_address_invoice = (int) $address->id; - $newOrder->id_cart = (int) $cart->id; - $newOrder->id_currency = $default_currency; - $newOrder->id_lang = $default_lang; - $newOrder->id_customer = (int) $customer->id; - if (isset($deliveryType)) { - $newOrder->id_carrier = (int) $deliveryType; - } - if (isset($paymentType)) { - $newOrder->payment = $paymentType; - $newOrder->module = $paymentId; - } - $newOrder->total_paid = $order['summ'] + $order['delivery']['cost']; - $newOrder->total_paid_tax_incl = $order['summ'] + $order['delivery']['cost']; - $newOrder->total_paid_tax_excl = $order['summ'] + $order['delivery']['cost']; - $newOrder->total_paid_real = $order['summ'] + $order['delivery']['cost']; - $newOrder->total_products = $order['summ']; - $newOrder->total_products_wt = $order['summ']; - $newOrder->total_shipping = $order['delivery']['cost']; - $newOrder->total_shipping_tax_incl = $order['delivery']['cost']; - $newOrder->total_shipping_tax_excl = $order['delivery']['cost']; - $newOrder->conversion_rate = 1.000000; - if (isset($orderStatus)) { - $newOrder->current_state = (int) $orderStatus; - } - if (!empty($order['delivery']['date'])) { - $newOrder->delivery_date = $order['delivery']['date']; - } - $newOrder->date_add = $order['createdAt']; - $newOrder->date_upd = $order['createdAt']; - $newOrder->invoice_date = $order['createdAt']; - $newOrder->valid = 1; - $newOrder->secure_key = md5(time()); - - if (isset($order['discount'])) { - $newOrder->total_discounts = $order['discount']; - } - - $product_list = array(); - - foreach ($order['items'] as $item) { - $product = new Product((int) $item['offer']['externalId'], false, $default_lang); - $product_id = $item['offer']['externalId']; - $product_attribute_id = 0; - if (strpos($item['offer']['externalId'], '#') !== false) { - $product_id = explode('#', $item['offer']['externalId']); - $product_attribute_id = $product_id[1]; - $product_id = $product_id[0]; - } - - if ($product_attribute_id != 0) { - $productName = htmlspecialchars( - strip_tags(Product::getProductName($product_id, $product_attribute_id)) - ); - - $combinationPrice = Combination::getPrice($product_attribute_id); - $productPrice = $combinationPrice > 0 ? $product->getPrice()+ $combinationPrice : $product->getPrice(); - } else { - $productName = htmlspecialchars(strip_tags($product->name)); - $productPrice = $product->getPrice(); - } - - $product_list[] = array( - 'product' => $product, - 'product_attribute_id' => $product_attribute_id, - 'product_price' => $product->price, - 'product_price_inc_tax' => $productPrice, - 'product_name' => $productName, - 'quantity' => $item['quantity'] - ); - - if (isset($item['discountTotal']) && $apiVersion == 5) { - $newOrder->total_discounts += $item['discountTotal'] * $item['quantity']; - } - } - - $newOrder->add(false, false); - - foreach ($order['payments'] as $pay) { - if (!isset($pay['externalId']) && $pay['status'] == 'paid') { - $ptype = $payment['type']; - $ptypes = $references->getSystemPaymentModules(); - if ($payments[$ptype] != null) { - foreach ($ptypes as $pay) { - if ($pay['code'] == $payments[$ptype]) { - $payType = $pay['name']; - } - } - $paymentType = Module::getModuleName($payments[$ptype]); - Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` - (`payment_method`, `order_reference` , `amount`, `date_add`) - VALUES - (\'' . $payType . '\', - \'' . $newOrder->reference . '\', - \'' . $payment['amount'] . '\', - \'' . $payment['paidAt'] . '\')'); - } - } - } - - $carrier = new OrderCarrierCore(); - $carrier->id_order = $newOrder->id; - $carrier->id_carrier = $deliveryType; - $carrier->shipping_cost_tax_excl = $order['delivery']['cost']; - $carrier->shipping_cost_tax_incl = $order['delivery']['cost']; - $carrier->date_add = $order['delivery']['date']; - $carrier->add(false, false); - - /* - * collect order ids for single fix request - */ - array_push($orderFix, array('id' => $order['id'], 'externalId' => $newOrder->id)); - - /* - * Create order details - */ - $query = 'INSERT `'._DB_PREFIX_.'order_detail` - ( - `id_order`, `id_order_invoice`, `id_shop`, `product_id`, `product_attribute_id`, - `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, - `product_reference`, `total_price_tax_excl`, `total_price_tax_incl`, - `unit_price_tax_excl`, `unit_price_tax_incl`, `original_product_price` - ) - - VALUES'; - - $context = new Context(); - foreach ($product_list as $product) { - $query .= '(' - .(int) $newOrder->id.', - 0, - '. Context::getContext()->shop->id.', - '.(int) $product['product']->id.', - '.$product['product_attribute_id'].', - '.implode('', array('\'', $product['product_name'], '\'')).', - '.(int) $product['quantity'].', - '.(int) $product['quantity'].', - '.$product['product_price'].', - '.implode('', array('\'', $product['product']->reference, '\'')).', - '.$product['product_price'].', - '.$product['product_price_inc_tax'].', - '.$product['product_price'].', - '.$product['product_price_inc_tax'].', - '.$product['product_price'].' - ),'; - } - - Db::getInstance()->execute(rtrim($query, ',')); - - if (!empty($customerFix)) { - $api->customersFixExternalIds($customerFix); - } - if (!empty($orderFix)) { - $api->ordersFixExternalIds($orderFix); - } - } else { - $order = $order_history; - $orderToUpdate = new Order((int) $order['externalId']); - - /* - * check delivery type - */ - if (!empty($order['delivery']['code'])) { - $dtype = $order['delivery']['code']; - $dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null; - - if ($deliveries[$dtype] != null) { - if ($deliveries[$dtype] != $orderToUpdate->id_carrier or $dcost != null) { - if ($dtype != null) { - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` - SET - `id_carrier` = \'' . $deliveries[$dtype] . '\' - WHERE - `id_order` = ' . (int)$order['externalId']); - } - - $updateCarrierFields = array(); - if ($dtype != null) { - $updateCarrierFields[] = '`id_carrier` = \'' . $deliveries[$dtype] . '\' '; - } - if ($dcost != null) { - $updateCarrierFields[] = '`shipping_cost_tax_incl` = \'' . $dcost . '\' '; - $updateCarrierFields[] = '`shipping_cost_tax_excl` = \'' . $dcost . '\' '; - } - $updateCarrierFields = implode(', ', $updateCarrierFields); - - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_carrier` - SET - '.$updateCarrierFields.' - WHERE - `id_order` = \'' . $orderToUpdate->id . '\''); - } - } - } - - /* - * check payment type - */ - - if (!empty($order['paymentType']) && $apiVersion != 5) { - $ptype = $order['paymentType']; - - if ($payments[$ptype] != null) { - $paymentType = Module::getModuleName($payments[$ptype]); - if ($payments[$ptype] != $orderToUpdate->payment) { - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` - SET - `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' - WHERE - `id_order` = ' . (int)$order['externalId']); - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_payment` - SET - `payment_method` = \'' . $payments[$ptype] . '\' - WHERE - `order_reference` = \'' . $orderToUpdate->reference . '\''); - } - } - } elseif (!empty($order['payments']) && $apiVersion == 5) { - if ($order['payments']) { - foreach ($order['payments'] as $payment) { - if (!isset($payment['externalId']) && $payment['status'] == 'paid') { - $ptype = $payment['type']; - $ptypes = $references->getSystemPaymentModules(); - if ($payments[$ptype] != null) { - foreach ($ptypes as $pay) { - if ($pay['code'] == $payments[$ptype]) { - $payType = $pay['name']; - } - } - $paymentType = Module::getModuleName($payments[$ptype]); - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` - SET - `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' - WHERE - `id_order` = ' . (int)$order['externalId']); - - Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` - (`payment_method`, `order_reference` , `amount`, `date_add`) - VALUES - (\'' . $payType . '\', - \'' . $orderToUpdate->reference . '\', - \'' . $payment['amount'] . '\', - \'' . $payment['paidAt'] . '\')'); - } - } - } - } - } elseif (!empty($order['payments']) && $apiVersion == 5) { - if ($order['payments']) { - foreach ($order['payments'] as $payment) { - if (!isset($payment['externalId']) && $payment['status'] == 'paid') { - $ptype = $payment['type']; - $ptypes = $references->getSystemPaymentModules(); - if ($payments[$ptype] != null) { - foreach ($ptypes as $pay) { - if ($pay['code'] == $payments[$ptype]) { - $payType = $pay['name']; - } - } - $paymentType = Module::getModuleName($payments[$ptype]); - - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` - SET - `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\' - WHERE - `id_order` = ' . (int)$order['externalId']); - - Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment` - (`payment_method`, `order_reference` , `amount`, `date_add`) - VALUES - (\'' . $payType . '\', - \'' . $orderToUpdate->reference . '\', - \'' . $payment['amount'] . '\', - \'' . $payment['paidAt'] . '\')'); - } - } - } - } - } - - /* - * Clean deleted items - */ - foreach ($order['items'] as $key => $item) { - if (isset($item['delete']) && $item['delete'] == true) { - if (strpos($item['offer']['externalId'], '#') !== false) { - $itemId = explode('#', $item['offer']['externalId']); - $product_id = $itemId[0]; - $product_attribute_id = $itemId[1]; - } else { - $product_id = $item['offer']['externalId']; - $product_attribute_id = 0; - } - - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail` - WHERE - `id_order` = '. $orderToUpdate->id .' - AND - `product_id` = '.$product_id. ' AND `product_attribute_id` = '.$product_attribute_id); - - unset($order['items'][$key]); - $ItemDiscount = true; - } - } - - /* - * Check items quantity and discount - */ - foreach ($orderToUpdate->getProductsDetail() as $orderItem) { - foreach ($order['items'] as $key => $item) { - if (strpos($item['offer']['externalId'], '#') !== false) { - $itemId = explode('#', $item['offer']['externalId']); - $product_id = $itemId[0]; - $product_attribute_id = $itemId[1]; - } else { - $product_id = $item['offer']['externalId']; - $product_attribute_id = 0; - } - - if ($product_id == $orderItem['product_id'] && - $product_attribute_id == $orderItem['product_attribute_id']) { - // discount - if (isset($item['discount']) || - isset($item['discountPercent']) || - isset($item['discountTotal'])) { - - $product = new Product((int) $product_id, false, $default_lang); - $tax = new TaxCore($product->id_tax_rules_group); - - if ($product_attribute_id != 0) { - $prodPrice = Combination::getPrice($product_attribute_id); - $prodPrice = $prodPrice > 0 ? $prodPrice : $product->price; - } else { - $prodPrice = $product->price; - } - - $prodPrice = $prodPrice + $prodPrice / 100 * $tax->rate; - - $productPrice = $prodPrice - $item['discount']; - $productPrice = $productPrice - ($prodPrice / 100 * $item['discountPercent']); - $productPrice = $prodPrice - $item['discountTotal']; - - $productPrice = round($productPrice, 2); - - Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail` - SET - `unit_price_tax_incl` = '.$productPrice.' - WHERE - `id_order_detail` = '.$orderItem['id_order_detail']); - } - - // quantity - if (isset($item['quantity']) && $item['quantity'] != $orderItem['product_quantity']) { - Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail` - SET - `product_quantity` = '.$item['quantity'].', - `product_quantity_in_stock` = '.$item['quantity'].' - WHERE - `id_order_detail` = '.$orderItem['id_order_detail']); - } - - $ItemDiscount = true; - unset($order['items'][$key]); - } - } - } - - /* - * Check new items - */ - if (!empty($order['items'])) { - $query = 'INSERT `'._DB_PREFIX_.'order_detail` - ( - `id_order`, `id_order_invoice`, `id_shop`, `product_id`, `product_attribute_id`, - `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, - `product_reference`, `total_price_tax_excl`, `total_price_tax_incl`, - `unit_price_tax_excl`, `unit_price_tax_incl`, `original_product_price` - ) - - VALUES'; - - foreach ($order['items'] as $key => $newItem) { - $product_id = $newItem['offer']['externalId']; - $product_attribute_id = 0; - if (strpos($product_id, '#') !== false) { - $product_id = explode('#', $product_id); - - $product_attribute_id = $product_id[1]; - $product_id = $product_id[0]; - } - - $product = new Product((int) $product_id, false, $default_lang); - $tax = new TaxCore($product->id_tax_rules_group); - - if ($product_attribute_id != 0) { - $productName = htmlspecialchars( - strip_tags(Product::getProductName($product_id, $product_attribute_id)) - ); - $productPrice = Combination::getPrice($product_attribute_id); - $productPrice = $productPrice > 0 ? $productPrice : $product->price; - } else { - $productName = htmlspecialchars(strip_tags($product->name)); - $productPrice = $product->price; - } - - // discount - if ($newItem['discount'] || $newItem['discountPercent']|| $newItem['discountTotal']) { - $productPrice = $productPrice - $newItem['discount']; - $productPrice = $productPrice - $newItem['discountTotal']; - $productPrice = $productPrice - ($prodPrice / 100 * $newItem['discountPercent']); - $ItemDiscount = true; - } - - $query .= '(' - .(int) $orderToUpdate->id.', - 0, - '. Context::getContext()->shop->id.', - '.(int) $product_id.', - '.(int) $product_attribute_id.', - '.implode('', array('\'', $productName, '\'')).', - '.(int) $newItem['quantity'].', - '.(int) $newItem['quantity'].', - '.$productPrice.', - '.implode('', array('\'', $product->reference, '\'')).', - '.$productPrice * $newItem['quantity'].', - '.($productPrice + $productPrice / 100 * $tax->rate) * $newItem['quantity'].', - '.$productPrice.', - '.($productPrice + $productPrice / 100 * $tax->rate).', - '.$productPrice.' - ),'; - - unset($order['items'][$key]); - } - - Db::getInstance()->execute(rtrim($query, ',')); - } - - /* - * Fix prices & discounts - * Discounts only for whole order - */ - if (isset($order['discount']) || - isset($order['discountPercent']) || - isset($order['delivery']['cost']) || - isset($order['discountTotal']) || - $ItemDiscount) { - $infoOrd = $api->ordersGet($order['externalId']); - $infoOrder = $infoOrd->order; - $orderTotalProducts = $infoOrder['summ']; - $totalPaid = $infoOrder['totalSumm']; - $deliveryCost = $infoOrder['delivery']['cost']; - $totalDiscount = $deliveryCost + $orderTotalProducts - $totalPaid; - - $orderCartRules = $orderToUpdate->getCartRules(); - foreach ($orderCartRules as $valCartRules) { - $order_cart_rule = new OrderCartRule($valCartRules['id_order_cart_rule']); - $order_cart_rule->delete(); - } - $orderToUpdate->update(); - - Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'orders` - SET - `total_discounts` = '.$totalDiscount.', - `total_discounts_tax_incl` = '.$totalDiscount.', - `total_discounts_tax_excl` = '.$totalDiscount.', - `total_shipping` = '.$deliveryCost.', - `total_shipping_tax_incl` = '.$deliveryCost.', - `total_shipping_tax_excl` = '.$deliveryCost.', - `total_paid` = '.$totalPaid.', - `total_paid_tax_incl` = '.$totalPaid.', - `total_paid_tax_excl` = '.$totalPaid.', - `total_products_wt` = '.$orderTotalProducts.' - WHERE `id_order` = '.(int) $order['externalId']); - - unset($ItemDiscount); - } - - /* - * check status - */ - if (!empty($order['status'])) { - $stype = $order['status']; - - if ($statuses[$stype] != null) { - if ($statuses[$stype] != $orderToUpdate->current_state) { - Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_history` - (`id_employee`, `id_order`, `id_order_state`, `date_add`) - VALUES - (0, ' . $orderToUpdate->id . ', - ' . $statuses[$stype] . ', - "' . date('Y-m-d H:i:s') . '")'); - - Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders` - SET - `current_state` = \'' . $statuses[$stype] . '\' - WHERE - `id_order` = ' . (int)$order['externalId']); - } - } - } - } - } - /* - * Update last sync timestamp - */ - Configuration::updateValue('RETAILCRM_LAST_SYNC', $history->generatedAt); -} else { - return 'Nothing to sync'; -} +RetailcrmHistory::customersHistory(); +RetailcrmHistory::ordersHistory(); diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index 29cbf12..96c97b0 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -3,7 +3,7 @@ * @author Retail Driver LCC * @copyright RetailCRM * @license GPL - * @version 2.1.2 + * @version 2.2.0 * @link https://retailcrm.ru * */ From 8f99d5514471e80403d33a23bfbb6391a50453d6 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Mon, 28 May 2018 17:09:31 +0300 Subject: [PATCH 05/11] Travis tests --- .travis.yml | 48 ++++ Makefile | 14 ++ VERSION | 1 + phpunit.xml.dist | 33 +++ retailcrm/lib/RetailcrmCatalog.php | 3 + retailcrm/lib/RetailcrmReferences.php | 65 ++++- retailcrm/lib/RetailcrmService.php | 1 - retailcrm/retailcrm.php | 131 ++++++---- tests/bin/install.sh | 36 +++ tests/helpers/RetailcrmTestCase.php | 25 ++ tests/helpers/RetailcrmTestHelper.php | 26 ++ tests/phpunit/RetailcrmReferencesTest.php | 40 +++ tests/phpunit/RetailcrmTest.php | 281 ++++++++++++++++++++++ tests/phpunit/bootstrap.php | 11 + 14 files changed, 661 insertions(+), 54 deletions(-) create mode 100644 .travis.yml create mode 100644 Makefile create mode 100644 VERSION create mode 100644 phpunit.xml.dist create mode 100644 tests/bin/install.sh create mode 100644 tests/helpers/RetailcrmTestCase.php create mode 100644 tests/helpers/RetailcrmTestHelper.php create mode 100644 tests/phpunit/RetailcrmReferencesTest.php create mode 100644 tests/phpunit/RetailcrmTest.php create mode 100644 tests/phpunit/bootstrap.php diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d9723b8 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,48 @@ +language: php + +sudo: false + +php: + - 5.6 + - 7.0 + - 7.1 + - 7.2 + +env: + global: + - DB_USER=root + - DB_HOST=localhost + - DB_NAME=test_prestashop + +matrix: + include: + - php: 5.3 + dist: precise + env: BRANCH=1.6.1.x + - php: 5.4 + env: BRANCH=1.6.1.x + - php: 5.5 + env: BRANCH=1.6.1.x + - php: 5.6 + env: BRANCH=1.6.1.x + - php: 7.0 + env: BRANCH=1.6.1.x + - php: 7.1 + env: BRANCH=1.6.1.x + - php: 7.2 + env: BRANCH=1.6.1.x + +before_script: + - bash tests/bin/install.sh + +script: + - phpunit -c phpunit.xml.dist + +deploy: + skip_cleanup: true + provider: script + script: make + on: + php: 7.2 + branch: master + condition: "$DEPLOY = true" diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d6c7ae8 --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +FILE = $(TRAVIS_BUILD_DIR)/VERSION +VERSION = `cat $(FILE)` +ARCHIVE_NAME = '/tmp/prestashop-'$(VERSION)'.zip' + +all: build_archive send_to_ftp delete_archive + +build_archive: + zip -r $(ARCHIVE_NAME) ./retailcrm/* + +send_to_ftp: + curl -T $(ARCHIVE_NAME) -u $(FTP_USER):$(FTP_PASSWORD) ftp://$(FTP_HOST) + +delete_archive: + rm -f $(ARCHIVE_NAME) diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..fae692e --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +2.2.1 \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..c76fd75 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,33 @@ + + + + + tests/phpunit + + + + + retailcrm + + retailcrm/translations + retailcrm/job + bootstrap.php + index.php + logo.gif + logo.png + objects.xml + + + + \ No newline at end of file diff --git a/retailcrm/lib/RetailcrmCatalog.php b/retailcrm/lib/RetailcrmCatalog.php index 2414979..691bd1b 100644 --- a/retailcrm/lib/RetailcrmCatalog.php +++ b/retailcrm/lib/RetailcrmCatalog.php @@ -2,6 +2,9 @@ class RetailcrmCatalog { + public $default_lang; + public $default_currency; + public $default_country; public function __construct() { diff --git a/retailcrm/lib/RetailcrmReferences.php b/retailcrm/lib/RetailcrmReferences.php index 4bba661..c5a3957 100644 --- a/retailcrm/lib/RetailcrmReferences.php +++ b/retailcrm/lib/RetailcrmReferences.php @@ -2,6 +2,11 @@ class RetailcrmReferences { + public $default_lang; + public $carriers; + public $payment_modules = array(); + + private $api; public function __construct($client) { @@ -158,7 +163,7 @@ class RetailcrmReferences return $paymentDeliveryTypes; } - public function getSystemPaymentModules() + public function getSystemPaymentModules($active = true) { $shop_id = Context::getContext()->shop->id; @@ -189,7 +194,7 @@ class RetailcrmReferences $module->group = null; } - if ($module->active != 0) { + if ($module->active != 0 || $active === false) { $this->payment_modules[] = array( 'id' => $module->id, 'code' => $module->name, @@ -270,4 +275,60 @@ class RetailcrmReferences return $crmPaymentTypes; } + public function getStores() + { + $storesShop = $this->getShopStores(); + $retailcrmStores = $this->getApiStores(); + + foreach ($storesShop as $key => $storeShop) { + $stores[] = array( + 'type' => 'select', + 'name' => 'RETAILCRM_STORES['. $key .']', + 'label' => $storeShop, + 'options' => array( + 'query' => $retailcrmStores, + 'id' => 'id_option', + 'name' => 'name' + ) + ); + } + + return $stores; + } + + protected function getShopStores() + { + $stores = array(); + $warehouses = Warehouse::getWarehouses(); + + foreach ($warehouses as $warehouse) { + $arrayName = explode('-', $warehouse['name']); + $warehouseName = trim($arrayName[1]); + $stores[$warehouse['id_warehouse']] = $warehouseName; + } + + return $stores; + } + + protected function getApiStores() + { + $crmStores = array(); + $response = $this->api->storesList(); + + if ($response) { + $crmStores[] = array( + 'id_option' => '', + 'name' => '' + ); + + foreach ($response->stores as $store) { + $crmStores[] = array( + 'id_option' => $store['code'], + 'name' => $store['name'] + ); + } + } + + return $crmStores; + } } diff --git a/retailcrm/lib/RetailcrmService.php b/retailcrm/lib/RetailcrmService.php index 9a94694..86df68d 100644 --- a/retailcrm/lib/RetailcrmService.php +++ b/retailcrm/lib/RetailcrmService.php @@ -2,7 +2,6 @@ class Service { - public static function getDate($file) { if (file_exists($file)) { diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index 96c97b0..f858715 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -20,11 +20,15 @@ require_once(dirname(__FILE__) . '/bootstrap.php'); class RetailCRM extends Module { + public $api = false; + + private $use_new_hooks = true; + public function __construct() { $this->name = 'retailcrm'; $this->tab = 'export'; - $this->version = '2.2.0'; + $this->version = '2.2.1'; $this->author = 'Retail Driver LCC'; $this->displayName = $this->l('RetailCRM'); $this->description = $this->l('Integration module for RetailCRM'); @@ -135,7 +139,7 @@ class RetailCRM extends Module $this->l('Timezone settings must be identical to both of your crm and shop') . " $address/admin/settings#t-main" ); - + $this->display(__FILE__, 'retailcrm.tpl'); return $output . $this->displayForm(); @@ -350,29 +354,35 @@ class RetailCRM extends Module public function hookActionCustomerAccountAdd($params) { - $this->api->customersCreate( - array( - 'externalId' => $params['newCustomer']->id, - 'firstName' => $params['newCustomer']->firstname, - 'lastName' => $params['newCustomer']->lastname, - 'email' => $params['newCustomer']->email, - 'createdAt' => $params['newCustomer']->date_add - ) + $customer = $params['newCustomer']; + $customerSend = array( + 'externalId' => $customer->id, + 'firstName' => $customer->firstname, + 'lastName' => $customer->lastname, + 'email' => $customer->email, + 'createdAt' => $customer->date_add ); + + $this->api->customersCreate($customerSend); + + return $customerSend; } // this hook added in 1.7 public function hookActionCustomerAccountUpdate($params) { - $this->api->customersEdit( - array( - 'externalId' => $params['customer']->id, - 'firstName' => $params['customer']->firstname, - 'lastName' => $params['customer']->lastname, - 'email' => $params['customer']->email, - 'birthday' => $params['customer']->birthday - ) + $customer = $params['customer']; + $customerSend = array( + 'externalId' => $customer->id, + 'firstName' => $customer->firstname, + 'lastName' => $customer->lastname, + 'email' => $customer->email, + 'birthday' => $customer->birthday ); + + $this->api->customersEdit($customerSend); + + return $customerSend; } public function hookNewOrder($params) @@ -382,19 +392,20 @@ class RetailCRM extends Module public function hookActionPaymentConfirmation($params) { - $this->api->ordersEdit( - array( - 'externalId' => $params['id_order'], - 'paymentStatus' => 'paid' - ) - ); + if ($this->apiVersion == 4) { + $this->api->ordersEdit( + array( + 'externalId' => $params['id_order'], + 'paymentStatus' => 'paid' + ) + ); + } return $this->hookActionOrderStatusPostUpdate($params); } public function hookActionOrderEdited($params) { - $apiVersion = Configuration::get('RETAILCRM_API_VERSION'); $order = array( 'externalId' => $params['order']->id, 'firstName' => $params['customer']->firstname, @@ -404,7 +415,7 @@ class RetailCRM extends Module 'delivery' => array('cost' => $params['order']->total_shipping) ); - if ($apiVersion != 5) { + if ($this->apiVersion != 5) { $order['discount'] = $params['order']->total_discounts; } else { $order['discountManualAmount'] = $params['order']->total_discounts; @@ -436,6 +447,8 @@ class RetailCRM extends Module $order['customer']['externalId'] = $params['order']->id_customer; $this->api->ordersEdit($order); + + return $order; } public function hookActionOrderStatusPostUpdate($params) @@ -443,7 +456,6 @@ class RetailCRM extends Module $delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true); $payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true); $status = json_decode(Configuration::get('RETAILCRM_API_STATUS'), true); - $apiVersion = Configuration::get('RETAILCRM_API_VERSION'); if (isset($params['orderStatus'])) { $customer = array( @@ -463,13 +475,13 @@ class RetailCRM extends Module 'delivery' => array('cost' => $params['order']->total_shipping) ); - if ($apiVersion != 5) { + if ($this->apiVersion != 5) { $order['discount'] = $params['order']->total_discounts; } else { $order['discountManualAmount'] = $params['order']->total_discounts; } - $cart = new Cart($params['cart']->id); + $cart = $params['cart']; $addressCollection = $cart->getAddressCollection(); $address = array_shift($addressCollection); @@ -502,7 +514,7 @@ class RetailCRM extends Module $customer['phones'][] = array('number' => $phone); $order['phone'] = $phone; } - + foreach ($cart->getProducts() as $item) { if (isset($item['id_product_attribute']) && $item['id_product_attribute'] > 0) { $productId = $item['id_product'] . '#' . $item['id_product_attribute']; @@ -527,16 +539,21 @@ class RetailCRM extends Module } } - $order['items'][] = array( + $orderItem = array( 'initialPrice' => !empty($item['rate']) ? $item['price'] + ($item['price'] * $item['rate'] / 100) : $item['price'], 'quantity' => $item['quantity'], 'offer' => array('externalId' => $productId), - 'productName' => $item['name'], - 'properties' => $arProp + 'productName' => $item['name'] ); + if (isset($arProp)) { + $orderItem['properties'] = $arProp; + } + + $order['items'][] = $orderItem; + unset($arAttr); unset($count); unset($arProp); @@ -554,20 +571,20 @@ class RetailCRM extends Module $paymentCode = $params['order']->payment; } - if ($apiVersion != 5) { + if ($this->apiVersion != 5) { if (array_key_exists($paymentCode, $payment) && !empty($payment[$paymentCode])) { $order['paymentType'] = $payment[$paymentCode]; } } else { - $payment = array( + $paymentSend = array( 'externalId' => $params['order']->id .'#'. $params['order']->reference, 'amount' => $params['order']->total_paid, 'type' => $payment[$paymentCode] ? $payment[$paymentCode] : '' ); } - if (isset($payment)) { - $order['payments'][] = $payment; + if (isset($paymentSend)) { + $order['payments'][] = $paymentSend; } $statusCode = $params['orderStatus']->id; @@ -587,6 +604,9 @@ class RetailCRM extends Module $order['customer']['externalId'] = $customer['externalId']; $this->api->ordersCreate($order); + + return $order; + } elseif (isset($params['newOrderStatus'])) { $statusCode = $params['newOrderStatus']->id; @@ -601,8 +621,12 @@ class RetailCRM extends Module 'status' => $orderStatus ) ); + + return $orderStatus; } } + + return false; } public function hookActionPaymentCCAdd($params) @@ -620,11 +644,12 @@ class RetailCRM extends Module if (array_key_exists($payCode, $paymentCRM) && !empty($paymentCRM[$payCode])) { $payment = $paymentCRM[$payCode]; } - + $response = $this->api->ordersGet($order_id); if ($response !== false) { $orderCRM = $response['order']; + if ($orderCRM && $orderCRM['payments']) { foreach ($orderCRM['payments'] as $orderPayment) { if ($orderPayment['type'] == $payment) { @@ -641,27 +666,31 @@ class RetailCRM extends Module if (isset($updatePayment)) { $this->api->ordersPaymentEdit($updatePayment); + + return $updatePayment; } else { - $this->api->ordersPaymentCreate( - array( - 'externalId' => $params['paymentCC']->id, - 'amount' => $params['paymentCC']->amount, - 'paidAt' => $params['paymentCC']->date_add, - 'type' => $payment, - 'status' => 'paid', - 'order' => array( - 'externalId' => $order_id, - ), - ) + $createPayment = array( + 'externalId' => $params['paymentCC']->id, + 'amount' => $params['paymentCC']->amount, + 'paidAt' => $params['paymentCC']->date_add, + 'type' => $payment, + 'status' => 'paid', + 'order' => array( + 'externalId' => $order_id, + ), ); + + $this->api->ordersPaymentCreate($createPayment); + + return $createPayment; } - return true; + + return false; } private function validateCrmAddress($address) { if (preg_match("/https:\/\/(.*).retailcrm.ru/", $address) === 1) { - return true; } diff --git a/tests/bin/install.sh b/tests/bin/install.sh new file mode 100644 index 0000000..a9c6dfc --- /dev/null +++ b/tests/bin/install.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop + +create_db() { + mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS" +} + +clone_prestashop() { + cd .. + git clone https://github.com/PrestaShop/PrestaShop + cd PrestaShop + if ! [ -z $BRANCH ]; then + git checkout $BRANCH; + else + composer install; + fi +} + +install_prestashop() { + cd $PRESTASHOP_DIR + + php install-dev/index_cli.php \ + --domain=example.com \ + --db_server=$DB_HOST \ + --db_name=$DB_NAME \ + --db_user=$DB_USER +} + +create_db +clone_prestashop +install_prestashop diff --git a/tests/helpers/RetailcrmTestCase.php b/tests/helpers/RetailcrmTestCase.php new file mode 100644 index 0000000..a274f40 --- /dev/null +++ b/tests/helpers/RetailcrmTestCase.php @@ -0,0 +1,25 @@ +contextMock = $contextMocker->mockContext(); + } + + protected function setConfig() + { + $delivery = json_encode(array('delivery' => 'delivery')); + $status = json_encode(array('status' => 'status', 'new' => 'new', 'completed'=> 'completed')); + $payment = json_encode(array('ps_checkpayment' => 'ps_checkpayment', 'bankwire' => 'bankwire', 'cheque' => 'cheque')); + + Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery); + Configuration::updateValue('RETAILCRM_API_STATUS', $status); + Configuration::updateValue('RETAILCRM_API_PAYMENT', $payment); + } +} diff --git a/tests/helpers/RetailcrmTestHelper.php b/tests/helpers/RetailcrmTestHelper.php new file mode 100644 index 0000000..58e2172 --- /dev/null +++ b/tests/helpers/RetailcrmTestHelper.php @@ -0,0 +1,26 @@ +order_reference = $order_reference; + $orderPayment->id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT'); + $orderPayment->conversion_rate = 1.000000; + $orderPayment->amount = 100; + $orderPayment->payment_method = 'Bank wire'; + $orderPayment->date_add = date('Y-m-d H:i:s'); + + $orderPayment->save(); + + return $orderPayment; + } + + public static function deleteOrderPayment($id) + { + $orderPayment = new OrderPayment($id); + + return $orderPayment->delete(); + } +} diff --git a/tests/phpunit/RetailcrmReferencesTest.php b/tests/phpunit/RetailcrmReferencesTest.php new file mode 100644 index 0000000..0d9904d --- /dev/null +++ b/tests/phpunit/RetailcrmReferencesTest.php @@ -0,0 +1,40 @@ +createMock('RetailcrmProxy'); + $this->retailcrmReferences = new RetailcrmReferences($apiMock); + $this->retailcrmReferences->getSystemPaymentModules(false); + } + + public function testCarriers() + { + $this->assertInternalType('array', $this->retailcrmReferences->carriers); + $this->assertNotEmpty($this->retailcrmReferences->carriers); + $this->assertArrayHasKey('name', $this->retailcrmReferences->carriers[0]); + $this->assertArrayHasKey('id_carrier', $this->retailcrmReferences->carriers[0]); + } + + public function testGetSystemPaymentModules() + { + $this->assertInternalType('array', $this->retailcrmReferences->payment_modules); + $this->assertNotEmpty($this->retailcrmReferences->payment_modules); + $this->assertArrayHasKey('name', $this->retailcrmReferences->payment_modules[0]); + $this->assertArrayHasKey('code', $this->retailcrmReferences->payment_modules[0]); + $this->assertArrayHasKey('id', $this->retailcrmReferences->payment_modules[0]); + } + + public function testGetStatuses() + { + $statuses = $this->retailcrmReferences->getStatuses(); + + $this->assertInternalType('array', $statuses); + $this->assertNotEmpty($statuses); + } +} diff --git a/tests/phpunit/RetailcrmTest.php b/tests/phpunit/RetailcrmTest.php new file mode 100644 index 0000000..8bd3dba --- /dev/null +++ b/tests/phpunit/RetailcrmTest.php @@ -0,0 +1,281 @@ +setConfig(); + + $this->apiMock = $this->getMockBuilder('RetailcrmProxy') + ->disableOriginalConstructor() + ->setMethods( + array( + 'customersCreate', + 'customersEdit', + 'customersGet', + 'ordersCreate', + 'ordersEdit', + 'ordersGet', + 'ordersPaymentEdit', + 'ordersPaymentCreate' + ) + ) + ->getMock(); + + $this->retailcrmModule = new RetailCRM(); + $this->retailcrmModule->api = $this->apiMock; + } + + public function testHookActionCustomerAccountAdd() + { + $newCustomer = new Customer(1); + $params = array('newCustomer' => $newCustomer); + $customer = $this->retailcrmModule->hookActionCustomerAccountAdd($params); + + $this->assertNotEmpty($customer); + $this->assertArrayHasKey('externalId', $customer); + $this->assertArrayHasKey('firstName', $customer); + $this->assertArrayHasKey('lastName', $customer); + $this->assertArrayHasKey('email', $customer); + $this->assertArrayHasKey('createdAt', $customer); + } + + public function testHookActionCustomerAccountUpdate() + { + $customer = new Customer(1); + $params = array('customer' => $customer); + $customer = $this->retailcrmModule->hookActionCustomerAccountUpdate($params); + + $this->assertNotEmpty($customer); + $this->assertArrayHasKey('externalId', $customer); + $this->assertArrayHasKey('firstName', $customer); + $this->assertArrayHasKey('lastName', $customer); + $this->assertArrayHasKey('email', $customer); + $this->assertArrayHasKey('birthday', $customer); + } + + public function testHookActionOrderEdited() + { + $order = new Order(1); + $customer = new Customer($order->id_customer); + $params = array('order' => $order, 'customer' => $customer); + + $orderSend = $this->retailcrmModule->hookActionOrderEdited($params); + + $this->assertNotNull($orderSend); + $this->assertArrayHasKey('externalId', $orderSend); + $this->assertArrayHasKey('firstName', $orderSend); + $this->assertArrayHasKey('lastName', $orderSend); + $this->assertArrayHasKey('email', $orderSend); + $this->assertArrayHasKey('delivery', $orderSend); + $this->assertArrayHasKey('items', $orderSend); + } + + /** + * @param $newOrder + * @param $apiVersion + * @dataProvider dataProvider + */ + public function testHookActionOrderStatusPostUpdate($newOrder, $apiVersion) + { + $this->retailcrmModule->apiVersion = $apiVersion; + $order = new Order(1); + $customer = new Customer($order->id_customer); + $cart = $this->createMock('Cart'); + $cart->expects($this->any())->method('getProducts')->willReturn($this->getProducts()); + $cart->expects($this->any())->method('getAddressCollection')->willReturn($this->getAddressCollection()); + $status = new StdClass(); + + if ($newOrder === false) { + $status->id = 'completed'; + + $params = array( + 'newOrderStatus' => $status, + 'id_order' => $order->id + ); + } else { + $status->id = 'new'; + + $params = array( + 'orderStatus' => $status, + 'customer' => $customer, + 'order' => $order, + 'cart' => $cart, + ); + } + + $result = $this->retailcrmModule->hookActionOrderStatusPostUpdate($params); + + if ($newOrder === false) { + $this->assertEquals('completed', $result); + } else { + $this->assertArrayHasKey('status', $result); + $this->assertArrayHasKey('externalId', $result); + $this->assertArrayHasKey('firstName', $result); + $this->assertArrayHasKey('lastName', $result); + $this->assertArrayHasKey('email', $result); + $this->assertArrayHasKey('delivery', $result); + $this->assertArrayHasKey('items', $result); + $this->assertArrayHasKey('customer', $result); + $this->assertArrayHasKey('externalId', $result['customer']); + + if ($apiVersion == 5) { + $this->assertArrayHasKey('payments', $result); + $this->assertInternalType('array', $result['payments']); + } else { + $this->assertArrayHasKey('paymentType', $result); + } + } + } + + /** + * @param $ordersGet + * @dataProvider ordersGetDataProvider + */ + public function testHookActionPaymentCCAdd($ordersGet) + { + $order = new Order(1); + + $orderPayment = RetailcrmTestHelper::createOrderPayment($order->reference); + $cart = new Cart($order->id_cart); + + $params = array( + 'paymentCC' => $orderPayment, + 'cart' => $cart + ); + + $referenceMock = $this->createMock('RetailcrmReferences'); + $referenceMock->expects($this->once())->method('getSystemPaymentModules')->willReturn($this->getSystemPaymentModules()); + $this->retailcrmModule->reference = $referenceMock; + $this->apiMock->expects($this->any())->method('ordersGet')->willReturn($ordersGet); + + $result = $this->retailcrmModule->hookActionPaymentCCAdd($params); + + $this->assertInternalType('array', $result); + $this->assertArrayHasKey('type', $result); + $this->assertArrayHasKey('amount', $result); + + RetailcrmTestHelper::deleteOrderPayment($orderPayment->id); + } + + /** + * @return array + */ + public function dataProvider() + { + return array( + array( + 'newOrder' => true, + 'apiVersion' => 4 + ), + array( + 'newOrder' => false, + 'apiVersion' => 4 + ), + array( + 'newOrder' => true, + 'apiVersion' => 5 + ), + array( + 'newOrder' => false, + 'apiVersion' => 5 + ) + ); + } + + /** + * @return array + */ + public function ordersGetDataProvider() + { + return array( + array( + 'ordersGet' => array( + 'success' => true, + 'order' => array( + 'payments' => array( + array( + 'type' => 'bankwire' + ) + ), + 'totalSumm' => 1500 + ) + ) + ), + array( + 'ordersGet' => array( + 'success' => true, + 'order' => array( + 'payments' => array( + array( + 'type' => 'cheque' + ) + ), + 'totalSumm' => 1500 + ) + ) + ) + ); + } + + /** + * @return array + */ + private function getProducts() + { + return array( + array( + 'id_product_attribute' => 1, + 'id_product' => 1, + 'attributes' => '', + 'rate' => 1, + 'price' => 100, + 'name' => 'Test product 1', + 'quantity' => 2 + ), + array( + 'id_product_attribute' => 1, + 'id_product' => 2, + 'attributes' => '', + 'rate' => 1, + 'price' => 100, + 'name' => 'Test product 2', + 'quantity' => 1 + ) + ); + } + + /** + * @return array + */ + private function getAddressCollection() + { + $address = new Address(1); + + return array($address); + } + + /** + * @return array + */ + private function getSystemPaymentModules() + { + return array ( + array ( + 'id' => '3', + 'code' => 'bankwire', + 'name' => 'Bank wire', + ), + array ( + 'id' => '30', + 'code' => 'cheque', + 'name' => 'Payment by check', + ) + ); + } +} diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php new file mode 100644 index 0000000..8dcecee --- /dev/null +++ b/tests/phpunit/bootstrap.php @@ -0,0 +1,11 @@ +install(); From d1db728a7b401651120eeb9a0d65b4c9b33993cb Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Tue, 29 May 2018 13:15:18 +0300 Subject: [PATCH 06/11] Update .travis.yml and bash scripts --- .travis.yml | 30 ++++++----------------------- retailcrm/retailcrm.php | 12 +++++++++++- tests/bin/clone_prestashop.sh | 17 +++++++++++++++++ tests/bin/install.sh | 36 ----------------------------------- tests/bin/script.sh | 10 ++++++++++ tests/phpunit/bootstrap.php | 7 ++++--- 6 files changed, 48 insertions(+), 64 deletions(-) create mode 100644 tests/bin/clone_prestashop.sh delete mode 100644 tests/bin/install.sh create mode 100644 tests/bin/script.sh diff --git a/.travis.yml b/.travis.yml index d9723b8..deed3cd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,6 @@ sudo: false php: - 5.6 - - 7.0 - - 7.1 - - 7.2 env: global: @@ -14,35 +11,20 @@ env: - DB_HOST=localhost - DB_NAME=test_prestashop -matrix: - include: - - php: 5.3 - dist: precise - env: BRANCH=1.6.1.x - - php: 5.4 - env: BRANCH=1.6.1.x - - php: 5.5 - env: BRANCH=1.6.1.x - - php: 5.6 - env: BRANCH=1.6.1.x - - php: 7.0 - env: BRANCH=1.6.1.x - - php: 7.1 - env: BRANCH=1.6.1.x - - php: 7.2 - env: BRANCH=1.6.1.x - before_script: - - bash tests/bin/install.sh + - bash tests/bin/clone_prestashop.sh + - cp ../PrestaShop/tests/parameters.yml.travis ../PrestaShop/app/config/parameters.yml + - bash ../PrestaShop/travis-scripts/install-prestashop script: - - phpunit -c phpunit.xml.dist + - bash tests/bin/script.sh + - php ../PrestaShop/vendor/bin/phpunit -c phpunit.xml.dist deploy: skip_cleanup: true provider: script script: make on: - php: 7.2 + php: 5.6 branch: master condition: "$DEPLOY = true" diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index f858715..2275803 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -21,6 +21,16 @@ require_once(dirname(__FILE__) . '/bootstrap.php'); class RetailCRM extends Module { public $api = false; + public $default_lang; + public $default_currency; + public $default_country; + public $apiUrl; + public $apiKey; + public $apiVersion; + public $psVersion; + public $log; + public $confirmUninstall; + public $reference; private $use_new_hooks = true; @@ -570,7 +580,7 @@ class RetailCRM extends Module } else { $paymentCode = $params['order']->payment; } - +var_dump($paymentCode); if ($this->apiVersion != 5) { if (array_key_exists($paymentCode, $payment) && !empty($payment[$paymentCode])) { $order['paymentType'] = $payment[$paymentCode]; diff --git a/tests/bin/clone_prestashop.sh b/tests/bin/clone_prestashop.sh new file mode 100644 index 0000000..4413ab9 --- /dev/null +++ b/tests/bin/clone_prestashop.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop + +cd .. +git clone https://github.com/PrestaShop/PrestaShop +cd PrestaShop + +if ! [ -z $BRANCH ]; then + git checkout $BRANCH; +else + composer install --prefer-dist --no-interaction --no-progress +fi diff --git a/tests/bin/install.sh b/tests/bin/install.sh deleted file mode 100644 index a9c6dfc..0000000 --- a/tests/bin/install.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash - -if [ -z $TRAVIS_BUILD_DIR ]; then - exit 0; -fi - -PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop - -create_db() { - mysqladmin create $DB_NAME --user="$DB_USER" --password="$DB_PASS" -} - -clone_prestashop() { - cd .. - git clone https://github.com/PrestaShop/PrestaShop - cd PrestaShop - if ! [ -z $BRANCH ]; then - git checkout $BRANCH; - else - composer install; - fi -} - -install_prestashop() { - cd $PRESTASHOP_DIR - - php install-dev/index_cli.php \ - --domain=example.com \ - --db_server=$DB_HOST \ - --db_name=$DB_NAME \ - --db_user=$DB_USER -} - -create_db -clone_prestashop -install_prestashop diff --git a/tests/bin/script.sh b/tests/bin/script.sh new file mode 100644 index 0000000..58c2c7b --- /dev/null +++ b/tests/bin/script.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop + +cd $PRESTASHOP_DIR +composer run-script create-test-db --timeout=0 diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php index 8dcecee..8cf5da5 100644 --- a/tests/phpunit/bootstrap.php +++ b/tests/phpunit/bootstrap.php @@ -1,11 +1,12 @@ install(); From c0fbb05e4fc04a23766a7a453c02522b2b36bb81 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Tue, 29 May 2018 13:22:49 +0300 Subject: [PATCH 07/11] Edit travis config --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index deed3cd..6a17278 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,10 +13,12 @@ env: before_script: - bash tests/bin/clone_prestashop.sh - - cp ../PrestaShop/tests/parameters.yml.travis ../PrestaShop/app/config/parameters.yml - - bash ../PrestaShop/travis-scripts/install-prestashop + - cd ../PrestaShop + - cp tests/parameters.yml.travis app/config/parameters.yml + - bash travis-scripts/install-prestashop script: + - cd $TRAVIS_BUILD_DIR - bash tests/bin/script.sh - php ../PrestaShop/vendor/bin/phpunit -c phpunit.xml.dist From ad60c20cf9315dcf7465166e896be9b81b0d9443 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 30 May 2018 09:58:53 +0300 Subject: [PATCH 08/11] Update travis config for run tests --- .travis.yml | 31 +++++++++++++++-------- retailcrm/retailcrm.php | 2 +- tests/bin/before_script.sh | 11 ++++++++ tests/bin/clone_prestashop.sh | 2 ++ tests/bin/script.sh | 9 +++++-- tests/helpers/RetailcrmTestCase.php | 6 +++-- tests/phpunit/RetailcrmReferencesTest.php | 11 +++++--- 7 files changed, 53 insertions(+), 19 deletions(-) create mode 100644 tests/bin/before_script.sh diff --git a/.travis.yml b/.travis.yml index 6a17278..bf9d0d4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,23 +4,34 @@ sudo: false php: - 5.6 + - 7.0 + - 7.1 + - 7.2 -env: - global: - - DB_USER=root - - DB_HOST=localhost - - DB_NAME=test_prestashop +matrix: + include: + - php: 5.3 + dist: precise + env: BRANCH=1.6.1.x + - php: 5.4 + env: BRANCH=1.6.1.x + - php: 5.5 + env: BRANCH=1.6.1.x + - php: 5.6 + env: BRANCH=1.6.1.x + - php: 7.0 + env: BRANCH=1.6.1.x + - php: 7.1 + env: BRANCH=1.6.1.x + - php: 7.2 + env: BRANCH=1.6.1.x before_script: - bash tests/bin/clone_prestashop.sh - - cd ../PrestaShop - - cp tests/parameters.yml.travis app/config/parameters.yml - - bash travis-scripts/install-prestashop + - bash tests/bin/before_script.sh script: - - cd $TRAVIS_BUILD_DIR - bash tests/bin/script.sh - - php ../PrestaShop/vendor/bin/phpunit -c phpunit.xml.dist deploy: skip_cleanup: true diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index 2275803..3e2ec69 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -580,7 +580,7 @@ class RetailCRM extends Module } else { $paymentCode = $params['order']->payment; } -var_dump($paymentCode); + if ($this->apiVersion != 5) { if (array_key_exists($paymentCode, $payment) && !empty($payment[$paymentCode])) { $order['paymentType'] = $payment[$paymentCode]; diff --git a/tests/bin/before_script.sh b/tests/bin/before_script.sh new file mode 100644 index 0000000..05799b4 --- /dev/null +++ b/tests/bin/before_script.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +if [ -z $TRAVIS_BUILD_DIR ]; then + exit 0; +fi + +PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop + +cd $PRESTASHOP_DIR +cp tests/parameters.yml.travis app/config/parameters.yml +bash travis-scripts/install-prestashop diff --git a/tests/bin/clone_prestashop.sh b/tests/bin/clone_prestashop.sh index 4413ab9..fde2403 100644 --- a/tests/bin/clone_prestashop.sh +++ b/tests/bin/clone_prestashop.sh @@ -12,6 +12,8 @@ cd PrestaShop if ! [ -z $BRANCH ]; then git checkout $BRANCH; + cd tests + composer install else composer install --prefer-dist --no-interaction --no-progress fi diff --git a/tests/bin/script.sh b/tests/bin/script.sh index 58c2c7b..a104a9e 100644 --- a/tests/bin/script.sh +++ b/tests/bin/script.sh @@ -6,5 +6,10 @@ fi PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop -cd $PRESTASHOP_DIR -composer run-script create-test-db --timeout=0 +if ! [ -z $BRANCH ]; then + phpunit +else + cd $PRESTASHOP_DIR + composer run-script create-test-db --timeout=0 + php ../PrestaShop/vendor/bin/phpunit -c $TRAVIS_BUILD_DIR/phpunit.xml.dist +fi diff --git a/tests/helpers/RetailcrmTestCase.php b/tests/helpers/RetailcrmTestCase.php index a274f40..10a33e6 100644 --- a/tests/helpers/RetailcrmTestCase.php +++ b/tests/helpers/RetailcrmTestCase.php @@ -8,8 +8,10 @@ abstract class RetailcrmTestCase extends \PHPUnit\Framework\TestCase { parent::setUp(); - $contextMocker = new \Tests\Unit\ContextMocker(); - $this->contextMock = $contextMocker->mockContext(); + if (version_compare(_PS_VERSION_, '1.7', '>')) { + $contextMocker = new \Tests\Unit\ContextMocker(); + $this->contextMock = $contextMocker->mockContext(); + } } protected function setConfig() diff --git a/tests/phpunit/RetailcrmReferencesTest.php b/tests/phpunit/RetailcrmReferencesTest.php index 0d9904d..64acd5c 100644 --- a/tests/phpunit/RetailcrmReferencesTest.php +++ b/tests/phpunit/RetailcrmReferencesTest.php @@ -24,10 +24,13 @@ class RetailcrmReferencesTest extends RetailcrmTestCase public function testGetSystemPaymentModules() { $this->assertInternalType('array', $this->retailcrmReferences->payment_modules); - $this->assertNotEmpty($this->retailcrmReferences->payment_modules); - $this->assertArrayHasKey('name', $this->retailcrmReferences->payment_modules[0]); - $this->assertArrayHasKey('code', $this->retailcrmReferences->payment_modules[0]); - $this->assertArrayHasKey('id', $this->retailcrmReferences->payment_modules[0]); + + if (version_compare(_PS_VERSION_, '1.7', '>')) { + $this->assertNotEmpty($this->retailcrmReferences->payment_modules); + $this->assertArrayHasKey('name', $this->retailcrmReferences->payment_modules[0]); + $this->assertArrayHasKey('code', $this->retailcrmReferences->payment_modules[0]); + $this->assertArrayHasKey('id', $this->retailcrmReferences->payment_modules[0]); + } } public function testGetStatuses() From f2943d6f08fe58fd740f4441a599c41042201319 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 30 May 2018 10:14:25 +0300 Subject: [PATCH 09/11] Update before script --- tests/bin/before_script.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/bin/before_script.sh b/tests/bin/before_script.sh index 05799b4..9fe7261 100644 --- a/tests/bin/before_script.sh +++ b/tests/bin/before_script.sh @@ -7,5 +7,9 @@ fi PRESTASHOP_DIR=$TRAVIS_BUILD_DIR/../PrestaShop cd $PRESTASHOP_DIR -cp tests/parameters.yml.travis app/config/parameters.yml + +if [ -z $BRANCH ]; then + cp tests/parameters.yml.travis app/config/parameters.yml +fi + bash travis-scripts/install-prestashop From 5fa0d18692ea48b3b1947636beb99e8b0e84a127 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 30 May 2018 10:30:06 +0300 Subject: [PATCH 10/11] Update script for travis --- .travis.yml | 2 +- tests/bin/before_script.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bf9d0d4..be7b2d2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,6 +38,6 @@ deploy: provider: script script: make on: - php: 5.6 + php: 7.2 branch: master condition: "$DEPLOY = true" diff --git a/tests/bin/before_script.sh b/tests/bin/before_script.sh index 9fe7261..efd0fea 100644 --- a/tests/bin/before_script.sh +++ b/tests/bin/before_script.sh @@ -12,4 +12,4 @@ if [ -z $BRANCH ]; then cp tests/parameters.yml.travis app/config/parameters.yml fi -bash travis-scripts/install-prestashop +bash travis-scripts/install-prestashop.sh From 72913dee21e540c84d4627a05434721832752f61 Mon Sep 17 00:00:00 2001 From: Akolzin Dmitry Date: Wed, 30 May 2018 11:22:53 +0300 Subject: [PATCH 11/11] Update call prestashop install script --- .travis.yml | 9 --------- tests/bin/before_script.sh | 5 +++-- 2 files changed, 3 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index be7b2d2..c160e2b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,21 +10,12 @@ php: matrix: include: - - php: 5.3 - dist: precise - env: BRANCH=1.6.1.x - - php: 5.4 - env: BRANCH=1.6.1.x - - php: 5.5 - env: BRANCH=1.6.1.x - php: 5.6 env: BRANCH=1.6.1.x - php: 7.0 env: BRANCH=1.6.1.x - php: 7.1 env: BRANCH=1.6.1.x - - php: 7.2 - env: BRANCH=1.6.1.x before_script: - bash tests/bin/clone_prestashop.sh diff --git a/tests/bin/before_script.sh b/tests/bin/before_script.sh index efd0fea..3fe6e86 100644 --- a/tests/bin/before_script.sh +++ b/tests/bin/before_script.sh @@ -10,6 +10,7 @@ cd $PRESTASHOP_DIR if [ -z $BRANCH ]; then cp tests/parameters.yml.travis app/config/parameters.yml + bash travis-scripts/install-prestashop +else + bash travis-scripts/install-prestashop.sh fi - -bash travis-scripts/install-prestashop.sh