diff --git a/CHANGELOG.md b/CHANGELOG.md index fc89396..ffb2271 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## v.3.0.2 +* Улучшена механика выгрузки изменений из RetailCRM на сайт +* Улучшена механика выборки типов доставки на сайте +* Добавлена возможность периодической выгрузки акционных цен для товаров +* Улучшена совместимость с Opencart 3.0 + ## v.2.4.3 * Устранены некоторые баги, добавлен вывод ошибок при выгрузке единичных заказов diff --git a/README.ru.md b/README.ru.md index 629d537..94faf29 100644 --- a/README.ru.md +++ b/README.ru.md @@ -55,6 +55,13 @@ cp -r opencart-module/* /path/to/site/root ``` http://youropencartsite.com/retailcrm.xml ``` +#### Настройка выгрузки акционных цен + +Для периодической выгрузки акционных цен в CRM в настройках модуля укажите тип цены, в который необходимо выгружать акционные цены, в крон добавьте следующую запись + +``` +0 0 * * * /usr/bin/php /path/to/opencart/system/cron/prices.php >> /path/to/opencart/system/storage/logs/cronjob_prices.log 2>&1 +``` #### Выгрузка существующих заказов и покупателей diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 7620dd4..b55fd02 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -242,7 +242,9 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text_customers_custom_fields', 'text_confirm_log', 'text_error_delivery', - 'retailcrm_missing_status' + 'retailcrm_missing_status', + 'special_price_settings', + 'special_price' ); $_data = &$data; @@ -278,6 +280,11 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['customFields'] = $this->model_extension_retailcrm_references ->getCustomFields(); } + + if ($apiVersion != 'v3') { + $_data['priceTypes'] = $this->model_extension_retailcrm_references + ->getPriceTypes(); + } } $config_data = array( @@ -507,7 +514,7 @@ class ControllerExtensionModuleRetailcrm extends Controller /** * Export single order * - * + * @return void */ public function exportOrder() { @@ -558,8 +565,8 @@ class ControllerExtensionModuleRetailcrm extends Controller * * @return void */ - public function export() { - + public function export() + { $this->load->model('customer/customer'); $customers = $this->model_customer_customer->getCustomers(); @@ -589,6 +596,25 @@ class ControllerExtensionModuleRetailcrm extends Controller fopen(DIR_SYSTEM . '/cron/export_done', "x"); } + /** + * Promotional price upload + * + * @return void + */ + public function prices() + { + $this->load->model('catalog/product'); + $products = $this->model_catalog_product->getProducts(); + + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) { + $this->load->model('extension/retailcrm/custom/prices'); + $this->model_extension_retailcrm_custom_prices->uploadPrices($products); + } else { + $this->load->model('extension/retailcrm/prices'); + $this->model_extension_retailcrm_prices->uploadPrices($products); + } + } + /** * Validate * diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 1542a1c..0fe71fc 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -23,6 +23,8 @@ $_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; $_['collector_site_key'] = 'Site key'; +$_['special_price_settings'] = 'Settings specials'; +$_['special_price'] = 'The type of price at which the share price will be unloaded'; $_['text_success_export'] = 'Orders and customers successfully unloaded'; $_['text_success_export_order'] = 'Order successfully unloaded'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 7311b02..42e8b36 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -23,6 +23,8 @@ $_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; $_['collector_site_key'] = 'Ключ сайта'; +$_['special_price_settings'] = 'Настройка выгрузки акционной цены'; +$_['special_price'] = 'Тип цены, в который будет выгружаться цена по акции'; $_['text_success_export'] = 'Заказы и клиенты успешно выгружены'; $_['text_success_export_order'] = 'Заказ успешно выгружен'; diff --git a/admin/model/extension/retailcrm/history.php b/admin/model/extension/retailcrm/history.php new file mode 100644 index 0000000..bf997d1 --- /dev/null +++ b/admin/model/extension/retailcrm/history.php @@ -0,0 +1,195 @@ +db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()"); + + $order_id = $this->db->getLastId(); + + // Products + if (isset($order['order_product']) && $order['order_product']) { + $this->addOrderProducts($order_id, $order['order_product']); + } + + // Totals + if (isset($order['order_total'])) { + $this->addOrderTotals($order_id, $order['order_total']); + } + + return $order_id; + } + + /** + * Edit order in OC + * + * @param int $order_id + * @param array $order + * + * @return void + */ + public function editOrder($order_id, $order) + { + $this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'"); + + $this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'"); + $this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "'"); + + // Products + if (isset($order['order_product']) && $order['order_product']) { + $this->addOrderProducts($order_id, $order['order_product']); + } + + // Totals + $this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'"); + + if (isset($order['order_total'])) { + $this->addOrderTotals($order_id, $order['order_total']); + } + } + + /** + * Add order products + * + * @param int $order_id + * @param array $products + * + * @return void + */ + public function addOrderProducts($order_id, $products) + { + foreach ($products as $product) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "'"); + + $order_product_id = $this->db->getLastId(); + + foreach ($product['option'] as $option) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'"); + } + } + } + + /** + * Add order totals + * + * @param int $order_id + * @param array $totals + * + * @return void + */ + public function addOrderTotals($order_id, $totals) + { + foreach ($totals as $total) { + $this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'"); + } + } + + /** + * Get total titles + * + * @return string $title + */ + protected function totalTitles() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = ''; + } else { + $title = 'total_'; + } + + return $title; + } + + /** + * Get country by iso code 2 + * + * @param string $isoCode + * + * @return array + */ + public function getCountryByIsoCode($isoCode) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); + + return $query->row; + } + + /** + * Get zone by name + * + * @param string $name + * + * @return array + */ + public function getZoneByName($name) + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); + + return $query->row; + } + + /** + * Get currency + * + * @param string $code + * @param string $field (default = '') + * + * @return mixed array | string + */ + public function getCurrencyByCode($code, $field = '') + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } + + /** + * Get language + * + * @param string $code + * @param string $field (default = '') + * + * @return mixed array | string + */ + public function getLanguageByCode($code, $field = '') + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } + + /** + * Get product option value + * + * @param int $option_value_id + * @param string $field + * + * @return mixed array | string + */ + public function getOptionValue($option_value_id, $field = '') + { + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'"); + + if (!$field) { + return $query->row; + } + + return $query->row[$field]; + } +} diff --git a/admin/model/extension/retailcrm/history/v3.php b/admin/model/extension/retailcrm/history/v3.php index 5500944..debeec6 100644 --- a/admin/model/extension/retailcrm/history/v3.php +++ b/admin/model/extension/retailcrm/history/v3.php @@ -1,14 +1,21 @@ getModuleTitle(); + $moduleTitle = $this->retailcrm->getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('setting/store'); $this->load->model('user/api'); @@ -33,8 +40,6 @@ class ModelExtensionRetailcrmHistoryV3 extends Model return false; } - $this->opencartApiClient = new OpencartApiClient($this->registry); - $crm = new RetailcrmProxy( $settings[$moduleTitle . '_url'], $settings[$moduleTitle . '_apikey'], @@ -51,7 +56,7 @@ class ModelExtensionRetailcrmHistoryV3 extends Model if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) { return false; } - + $generatedAt = $packsOrders['generatedAt']; $this->totalTitle = $this->totalTitles(); @@ -66,7 +71,9 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $settings[$moduleTitle . '_delivery']; + $this->ocDelivery = $this->model_extension_retailcrm_references + ->getOpercartDeliveryTypes(); + $this->zones = $this->model_localisation_zone->getZones(); $updatedOrders = array(); @@ -75,7 +82,9 @@ class ModelExtensionRetailcrmHistoryV3 extends Model foreach ($orders as $order) { - if (isset($order['deleted'])) continue; + if (isset($order['deleted'])) { + continue; + } if (isset($order['externalId'])) { $updatedOrders[] = $order['id']; @@ -110,468 +119,4 @@ class ModelExtensionRetailcrmHistoryV3 extends Model $crm->ordersFixExternalIds($this->createResult['orders']); } } - - protected function updateOrders($orders) - { - foreach ($orders as $order) { - $store = $this->config->get('config_store_id'); - - $data = array(); - - $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; - $phone = isset($order['phone']) ? $order['phone'] : ''; - - if (!$phone) { - $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; - } else { - $data['telephone'] = $phone; - } - - $data['store_id'] = $store == null ? 0 : $store; - $data['customer'] = $order['firstName']; - $data['customer_id'] = isset($order['customer']['externalId']) ? $order['customer']['externalId'] : 0; - $data['customer_group_id'] = 1; - $data['firstname'] = $order['firstName']; - $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; - $data['payment_address_2'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; - $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - - $shippingZone = ''; - - if (is_int($order['delivery']['address']['region'])) { - $shippingZone = $order['delivery']['address']['region']; - } else { - $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); - - if ($shippingZone) { - $shipping_zone_id = $shippingZone['zone_id']; - } else { - $shipping_zone_id = 0; - } - } - - if (isset($order['customer']['address']['region'])) { - $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - - if ($paymentZone) { - $payment_zone_id = $paymentZone['zone_id']; - } else { - $payment_zone_id = 0; - } - } - - if (isset($order['delivery']['address']['countryIso'])) { - $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); - } - - if (isset($order['customer']['address']['countryIso'])) { - $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } - - $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; - $payment = isset($order['paymentType']) ? $order['paymentType'] : null; - - $data['payment_country_id'] = isset($paymentCountry) ? $paymentCountry['country_id'] : 0; - $data['payment_zone_id'] = $payment_zone_id; - $data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0; - $data['shipping_zone_id'] = $shipping_zone_id; - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['shipping_address_1'] = $order['delivery']['address']['text']; - $data['shipping_address_2'] = ''; - $data['shipping_company'] = ''; - $data['shipping_company_id'] = ''; - $data['shipping_city'] = $order['delivery']['address']['city']; - $data['shipping_postcode'] = $order['delivery']['address']['index']; - $data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; - $data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['payment'] = $payment != null ? $this->payment[$payment] : $this->payment_default; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $payment != null ? $this->payment[$payment] : $this->payment_default; - - // this data will not retrive from crm for now - $data['tax'] = ''; - $data['tax_id'] = ''; - $data['product'] = ''; - $data['product_id'] = ''; - $data['reward'] = ''; - $data['affiliate'] = ''; - $data['affiliate_id'] = ''; - $data['payment_tax_id'] = ''; - $data['order_product_id'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['company'] = ''; - $data['company_id'] = ''; - - $data['order_product'] = array(); - - foreach ($order['items'] as $item) { - $productId = $item['offer']['externalId']; - $options = array(); - if(mb_strpos($item['offer']['externalId'], '#') > 1) { - $offer = explode('#', $item['offer']['externalId']); - $productId = $offer[0]; - $optionsFromCRM = explode('_', $offer[1]); - - foreach($optionsFromCRM as $optionFromCRM) { - $optionData = explode('-', $optionFromCRM); - $productOptionId = $optionData[0]; - $optionValueId = $optionData[1]; - - $productOptions = $this->model_catalog_product->getProductOptions($productId); - - foreach($productOptions as $productOption) { - if($productOptionId == $productOption['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['option_value_id'] == $optionValueId) { - $options[$productOptionId] = $productOptionValue['product_option_value_id']; - } - } - } - } - } - } - $data['order_product'][] = array( - 'product_id' => $productId, - 'quantity' => $item['quantity'], - 'option' => $options - ); - } - - $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; - - if(isset($order['discount']) && $order['discount'] > 0) { - $orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']); - foreach($orderTotals as $orderTotal) { - if($orderTotal['code'] == 'coupon') { - $data['order_total'][] = $orderTotal; - } - } - } - - $data['order_total'] = array( - array( - 'order_total_id' => '', - 'code' => 'sub_total', - 'title' => $this->language->get('product_summ'), - 'value' => $order['summ'], - 'text' => $order['summ'], - 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'shipping', - 'title' => $this->ocDelivery[$data['shipping_code']], - 'value' => $deliveryCost, - 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'total', - 'title' => $this->language->get('column_total'), - 'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] - ) - ); - - $data['fromApi'] = true; - - if (array_key_exists($order['status'], $this->status)) { - $data['order_status_id'] = $this->status[$order['status']]; - } else { - $tmpOrder = $this->model_sale_order->getOrder($order['externalId']); - $data['order_status_id'] = $tmpOrder['order_status_id']; - } - - $this->opencartApiClient->editOrder($order['externalId'], $data); - } - } - - protected function createOrders($orders) - { - $customersIdsFix = array(); - $ordersIdsFix = array(); - - foreach ($orders as $order) { - $store = $this->config->get('config_store_id'); - - $customer_id = (!empty($order['customer']['externalId'])) - ? $order['customer']['externalId'] - : 0; - - $data = array(); - - if ($customer_id == 0) { - if (isset($order['customer']['address']['countryIso'])) { - $customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } else { - $customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); - } - - if (isset($order['customer']['address']['region'])) { - $customerZone = $this->getZoneByName($order['customer']['address']['region']); - } else { - $customerZone = $this->getZoneByName($order['delivery']['address']['region']); - } - - $cData = array( - 'store_id' => 0, - 'customer_group_id' => '1', - 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], - 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', - 'email' => $order['customer']['email'], - 'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ', - 'fax' => '', - 'newsletter' => 0, - 'password' => 'tmppass', - 'status' => 1, - 'approved' => 1, - 'safe' => 0, - 'address' => array( - array( - 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], - 'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ', - 'address_1' => $order['customer']['address']['text'], - 'address_2' => ' ', - 'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'], - 'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'], - 'tax_id' => '1', - 'company' => '', - 'company_id' => '', - 'zone_id' => $customerZone ? $customerZone['zone_id'] : 0, - 'country_id' => $customerCountry ? $customerCountry['country_id'] : 0, - 'default' => '1' - ) - ), - ); - - $customer_id = $this->model_customer_customer->addCustomer($cData); - - $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); - } - - $mail = isset($order['email']) ? $order['email'] : $order['customer']['email']; - $phone = isset($order['phone']) ? $order['phone'] : ''; - - if (!$phone) { - $data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000'; - } else { - $data['telephone'] = $phone; - } - - $data['store_id'] = $store == null ? 0 : $store; - $data['customer'] = $order['firstName']; - $data['customer_id'] = $customer_id; - $data['customer_group_id'] = 1; - $data['firstname'] = $order['firstName']; - $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['payment_address_1'] = $order['customer']['address']['text']; - $data['payment_address_2'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; - $data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; - - $shippingZone = ''; - - if (is_int($order['delivery']['address']['region'])) { - $shippingZone = $order['delivery']['address']['region']; - } else { - $shippingZone = $this->getZoneByName($order['delivery']['address']['region']); - - if ($shippingZone) { - $shipping_zone_id = $shippingZone['zone_id']; - } else { - $shipping_zone_id = 0; - } - } - - if (isset($order['customer']['address']['region'])) { - $paymentZone = $this->getZoneByName($order['customer']['address']['region']); - - if ($paymentZone) { - $payment_zone_id = $paymentZone['zone_id']; - } else { - $payment_zone_id = 0; - } - } - - if (isset($order['delivery']['address']['countryIso'])) { - $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); - } - - if (isset($order['customer']['address']['countryIso'])) { - $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); - } - - $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; - $payment = isset($order['paymentType']) ? $order['paymentType'] : null; - - $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; - $data['payment_zone_id'] = $payment_zone_id; - $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; - $data['shipping_zone_id'] = $shipping_zone_id; - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; - $data['shipping_address_1'] = $order['delivery']['address']['text']; - $data['shipping_address_2'] = ''; - $data['shipping_company'] = ''; - $data['shipping_company_id'] = ''; - $data['shipping_city'] = $order['delivery']['address']['city']; - $data['shipping_postcode'] = $order['delivery']['address']['index']; - $data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; - $data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['payment'] = $payment != null ? $this->payment[$payment] : $this->payment_default; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $payment != null ? $this->payment[$payment] : $this->payment_default; - - // this data will not retrive from crm for now - $data['tax'] = ''; - $data['tax_id'] = ''; - $data['product'] = ''; - $data['product_id'] = ''; - $data['reward'] = ''; - $data['affiliate'] = ''; - $data['affiliate_id'] = ''; - $data['payment_tax_id'] = ''; - $data['order_product_id'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; - $data['company'] = ''; - $data['company_id'] = ''; - - $data['order_product'] = array(); - - foreach ($order['items'] as $item) { - $productId = $item['offer']['externalId']; - $options = array(); - if(mb_strpos($item['offer']['externalId'], '#') > 1) { - $offer = explode('#', $item['offer']['externalId']); - $productId = $offer[0]; - $optionsFromCRM = explode('_', $offer[1]); - - foreach($optionsFromCRM as $optionFromCRM) { - $optionData = explode('-', $optionFromCRM); - $productOptionId = $optionData[0]; - $optionValueId = $optionData[1]; - - $productOptions = $this->model_catalog_product->getProductOptions($productId); - - foreach($productOptions as $productOption) { - if($productOptionId == $productOption['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['option_value_id'] == $optionValueId) { - $options[$productOptionId] = $productOptionValue['product_option_value_id']; - } - } - } - } - } - } - $data['order_product'][] = array( - 'product_id' => $productId, - 'quantity' => $item['quantity'], - 'option' => $options - ); - } - - $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; - - $data['order_total'] = array( - array( - 'order_total_id' => '', - 'code' => 'sub_total', - 'title' => $this->language->get('product_summ'), - 'value' => $order['summ'], - 'text' => $order['summ'], - 'sort_order' => $this->subtotalSettings['sub_total_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'shipping', - 'title' => $this->ocDelivery[$data['shipping_code']], - 'value' => $deliveryCost, - 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] - ), - array( - 'order_total_id' => '', - 'code' => 'total', - 'title' => $this->language->get('column_total'), - 'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost, - 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] - ) - ); - - $data['fromApi'] = true; - $data['order_status_id'] = 1; - - $order_id = $this->opencartApiClient->addOrder($data); - - $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); - } - - return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); - } - - private function getModuleTitle() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = 'retailcrm'; - } else { - $title = 'module_retailcrm'; - } - - return $title; - } - - private function totalTitles() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = ''; - } else { - $title = 'total_'; - } - - return $title; - } - - public function getCountryByIsoCode($isoCode) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); - - return $query->row; - } - - public function getZoneByName($name) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); - - return $query->row; - } } diff --git a/admin/model/extension/retailcrm/history/v4_5.php b/admin/model/extension/retailcrm/history/v4_5.php index 4463cf3..a3ee710 100644 --- a/admin/model/extension/retailcrm/history/v4_5.php +++ b/admin/model/extension/retailcrm/history/v4_5.php @@ -1,15 +1,33 @@ load->library('retailcrm/retailcrm'); + $this->moduleTitle = $this->retailcrm->getModuleTitle(); + $this->opencartApiClient = $this->retailcrm->getOcApiClient($registry); + } + + /** + * Getting changes from RetailCRM + * + * @return boolean + */ public function request() { - $this->moduleTitle = $this->getModuleTitle(); + $this->load->library('retailcrm/retailcrm'); + $this->moduleTitle = $this->retailcrm->getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('setting/store'); $this->load->model('user/api'); @@ -75,6 +93,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $sinceIdCustomers = $lastChangeCustomers['id']; } + $this->settings = $settings; $this->totalTitle = $this->totalTitles(); $this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total'); $this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total'); @@ -88,8 +107,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $settings[$this->moduleTitle . '_delivery']; - + $this->ocDelivery = $this->model_extension_retailcrm_references + ->getOpercartDeliveryTypes(); + $this->zones = $this->model_localisation_zone->getZones(); if (isset($settings[$this->moduleTitle . '_custom_field'])) { @@ -101,7 +121,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($orders as $order) { - if (isset($order['deleted'])) continue; + if (isset($order['deleted'])) { + continue; + } if (isset($order['externalId'])) { $updatedOrders[] = $order['id']; @@ -116,7 +138,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($customers as $customer) { - if (isset($customer['deleted'])) continue; + if (isset($customer['deleted'])) { + continue; + } if (isset($customer['externalId'])) { $updateCustomers[] = $customer['id']; @@ -164,12 +188,19 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } } + /** + * Update orders from history + * + * @param array $orders + * + * @return void + */ protected function updateOrders($orders) { foreach ($orders as $order) { - $store = $this->config->get('config_store_id'); + $ocOrder = $this->model_sale_order->getOrder($order['externalId']); - if ($order['payments']) { + if (isset($order['payments']) && $order['payments']) { foreach ($order['payments'] as $orderPayment) { if (isset($orderPayment['externalId'])) { $payment = $orderPayment; @@ -194,7 +225,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['telephone'] = $phone; } - $data['store_id'] = $store == null ? 0 : $store; $data['customer'] = $order['firstName']; $data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; $data['customer_group_id'] = 1; @@ -202,15 +232,11 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru'; $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - $data['payment_address'] = '0'; $data['payment_firstname'] = $order['firstName']; $data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; $data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : ''; $data['payment_address_2'] = ''; - $data['payment_company'] = ''; - $data['payment_company_id'] = ''; $data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city']; $data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index']; @@ -238,19 +264,25 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } } - if (isset($order['delivery']['address']['countryIso'])) { - $shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']); + if (isset($order['countryIso']) && !empty($order['countryIso'])) { + $shippingCountry = $this->getCountryByIsoCode($order['countryIso']); } - if (isset($order['customer']['address']['countryIso'])) { + if (isset($order['customer']['address']['countryIso']) && !empty($order['customer']['address']['countryIso'])) { $paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']); + } else { + $paymentCountry = $this->getCountryByIsoCode($order['countryIso']); } - + $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; - $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; - $data['payment_zone_id'] = $payment_zone_id; - $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; - $data['shipping_zone_id'] = $shipping_zone_id; + $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : $ocOrder['payment_country_id']; + $data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : $ocOrder['payment_country']; + $data['payment_zone_id'] = $payment_zone_id ? $payment_zone_id : $ocOrder['payment_zone_id']; + $data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : $ocOrder['payment_zone']; + $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id']; + $data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : $ocOrder['shipping_country']; + $data['shipping_zone_id'] = $shipping_zone_id ? $shipping_zone_id : $ocOrder['shipping_zone_id']; + $data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $ocOrder['shipping_zone']; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; $data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName']; @@ -260,19 +292,40 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['shipping_company_id'] = ''; $data['shipping_city'] = $order['delivery']['address']['city']; $data['shipping_postcode'] = $order['delivery']['address']['index']; - $data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; - $data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; + + if ($delivery !== null) { + if (isset($this->settings[$this->moduleTitle . '_delivery'][$ocOrder['shipping_code']]) + && isset($this->delivery[$delivery]) + ) { + $data['shipping'] = $this->delivery[$delivery]; + + $shipping = explode('.', $data['shipping']); + $shippingModule = $shipping[0]; + + if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) { + $data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title']; + } else { + $data['shipping_method'] =$this->ocDelivery[$shippingModule]['title']; + } + + $data['shipping_code'] = $data['shipping']; + } + } else { + if (!isset($this->settings[$ocOrder['shipping_code']]) + || !isset($this->delivery[$delivery]) + ) { + $data['shipping_method'] = $ocOrder['shipping_method']; + $data['shipping_code'] = $ocOrder['shipping_code']; + } + } if (isset($payment)) { $data['payment'] = $this->payment[$payment['type']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$payment['type']]; + $data['payment_method'] = isset($this->ocPayment[$data['payment']]) ? $this->ocPayment[$data['payment']] : $ocOrder['payment_method']; + $data['payment_code'] = isset($this->payment[$payment['type']]) ? $this->payment[$payment['type']] : $ocOrder['payment_code']; } else { - $this->load->model('sale/order'); - $order_data = $this->model_sale_order->getOrder($order['externalId']); - $data['payment_method'] = $order_data['payment_method']; - $data['payment_code'] = $order_data['payment_code']; + $data['payment_method'] = $ocOrder['payment_method']; + $data['payment_code'] = $ocOrder['payment_code']; } // this data will not retrive from crm for now @@ -295,7 +348,8 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($order['items'] as $item) { $productId = $item['offer']['externalId']; $options = array(); - if(mb_strpos($item['offer']['externalId'], '#') > 1) { + + if (mb_strpos($item['offer']['externalId'], '#') > 1) { $offer = explode('#', $item['offer']['externalId']); $productId = $offer[0]; $optionsFromCRM = explode('_', $offer[1]); @@ -311,14 +365,27 @@ class ModelExtensionRetailcrmHistoryV45 extends Model if($productOptionId == $productOption['product_option_id']) { foreach($productOption['product_option_value'] as $productOptionValue) { if($productOptionValue['option_value_id'] == $optionValueId) { - $options[$productOptionId] = $productOptionValue['product_option_value_id']; + $options[] = array( + 'product_option_id' => $productOptionId, + 'product_option_value_id' => $productOptionValue['product_option_value_id'], + 'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'), + 'type' => $productOption['type'], + 'name' => $productOption['name'], + ); } } } } } } + + $product = $this->model_catalog_product->getProduct($productId); + $data['order_product'][] = array( + 'name' => $product['name'], + 'model' => $product['model'], + 'price' => $item['initialPrice'], + 'total' => (float)($item['initialPrice'] * $item['quantity']), 'product_id' => $productId, 'quantity' => $item['quantity'], 'option' => $options @@ -334,6 +401,8 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } $data['custom_field'] = isset($customFields) ? $customFields : ''; + } else { + $data['custom_field'] = $ocOrder['custom_field']; } $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; @@ -347,6 +416,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model } } + $data['total'] = $order['totalSumm']; $data['order_total'] = array( array( 'order_total_id' => '', @@ -359,7 +429,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model array( 'order_total_id' => '', 'code' => 'shipping', - 'title' => $this->ocDelivery[$data['shipping_code']], + 'title' => $data['shipping_method'], 'value' => $deliveryCost, 'text' => $deliveryCost, 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] @@ -383,10 +453,18 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['order_status_id'] = $tmpOrder['order_status_id']; } - $this->opencartApiClient->editOrder($order['externalId'], $data); + $this->editOrder($order['externalId'], $data); + $this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']); } } + /** + * Create orders from history + * + * @param array $orders + * + * @return array + */ protected function createOrders($orders) { $customersIdsFix = array(); @@ -395,7 +473,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($orders as $order) { $store = $this->config->get('config_store_id'); - if ($order['payments']) { + if (isset($order['payments']) && $order['payments']) { $payment = end($order['payments']); } elseif (isset($order['paymentType'])) { $payment['type'] = $order['paymentType']; @@ -433,6 +511,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model 'status' => 1, 'approved' => 1, 'safe' => 0, + 'affiliate' => '', 'address' => array( array( 'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'], @@ -465,7 +544,12 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['telephone'] = $phone; } + $data['currency_code'] = $this->config->get('config_currency'); + $data['currency_value'] = $this->getCurrencyByCode($data['currency_code'], 'value'); + $data['currency_id'] = $this->getCurrencyByCode($data['currency_code'], 'currency_id'); + $data['language_id'] = $this->getLanguageByCode($this->config->get('config_language'), 'language_id'); $data['store_id'] = $store == null ? 0 : $store; + $data['store_name'] = $this->config->get('config_name'); $data['customer'] = $order['firstName']; $data['customer_id'] = $customer_id; $data['customer_group_id'] = 1; @@ -518,9 +602,13 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null; $data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0; + $data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : ''; $data['payment_zone_id'] = $payment_zone_id; + $data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : ''; $data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0; + $data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : ''; $data['shipping_zone_id'] = $shipping_zone_id; + $data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $data['payment_zone']; $data['shipping_address'] = '0'; $data['shipping_firstname'] = $order['firstName']; $data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName']; @@ -531,9 +619,17 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['shipping_city'] = $order['delivery']['address']['city']; $data['shipping_postcode'] = $order['delivery']['address']['index']; $data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; $data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default; + $shipping = explode('.', $data['shipping']); + $shippingModule = $shipping[0]; + + if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) { + $data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title']; + } else { + $data['shipping_method'] = $this->ocDelivery[$shippingModule]['title']; + } + if (isset($payment)) { $data['payment'] = $this->payment[$payment['type']]; $data['payment_method'] = $this->ocPayment[$data['payment']]; @@ -551,7 +647,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['product_id'] = ''; $data['reward'] = ''; $data['affiliate'] = ''; - $data['affiliate_id'] = ''; + $data['affiliate_id'] = 0; $data['payment_tax_id'] = ''; $data['order_product_id'] = ''; $data['payment_company'] = ''; @@ -564,6 +660,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($order['items'] as $item) { $productId = $item['offer']['externalId']; $options = array(); + if(mb_strpos($item['offer']['externalId'], '#') > 1) { $offer = explode('#', $item['offer']['externalId']); $productId = $offer[0]; @@ -580,14 +677,27 @@ class ModelExtensionRetailcrmHistoryV45 extends Model if($productOptionId == $productOption['product_option_id']) { foreach($productOption['product_option_value'] as $productOptionValue) { if($productOptionValue['option_value_id'] == $optionValueId) { - $options[$productOptionId] = $productOptionValue['product_option_value_id']; + $options[] = array( + 'product_option_id' => $productOptionId, + 'product_option_value_id' => $productOptionValue['product_option_value_id'], + 'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'), + 'type' => $productOption['type'], + 'name' => $productOption['name'], + ); } } } } } } + + $product = $this->model_catalog_product->getProduct($productId); + $data['order_product'][] = array( + 'name' => $product['name'], + 'model' => $product['model'], + 'price' => $item['initialPrice'], + 'total' => (float)($item['initialPrice'] * $item['quantity']), 'product_id' => $productId, 'quantity' => $item['quantity'], 'option' => $options @@ -607,6 +717,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0; + $data['total'] = $order['totalSumm']; $data['order_total'] = array( array( 'order_total_id' => '', @@ -619,7 +730,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model array( 'order_total_id' => '', 'code' => 'shipping', - 'title' => $this->ocDelivery[$data['shipping_code']], + 'title' => $data['shipping_method'], 'value' => $deliveryCost, 'text' => $deliveryCost, 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] @@ -637,7 +748,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $data['fromApi'] = true; $data['order_status_id'] = 1; - $order_id = $this->opencartApiClient->addOrder($data); + $order_id = $this->addOrder($data); $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id); } @@ -648,7 +759,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model protected function updateCustomers($customers) { foreach ($customers as $customer) { - $customer_id = $customer['externalId']; $customerData = $this->model_customer_customer->getCustomer($customer_id); @@ -677,7 +787,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $customerAddress['country_id'] = $customerCountry['country_id']; } - if (isset($customerZone)) { + if (isset($customerZone) && isset($customerZone['zone_id'])) { $customerAddress['zone_id'] = $customerZone['zone_id']; } @@ -697,40 +807,4 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $this->model_customer_customer->editCustomer($customer_id, $customerData); } } - - private function getModuleTitle() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = 'retailcrm'; - } else { - $title = 'module_retailcrm'; - } - - return $title; - } - - private function totalTitles() - { - if (version_compare(VERSION, '3.0', '<')) { - $title = ''; - } else { - $title = 'total_'; - } - - return $title; - } - - public function getCountryByIsoCode($isoCode) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'"); - - return $query->row; - } - - public function getZoneByName($name) - { - $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'"); - - return $query->row; - } } diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index 5535e3a..d0afb5c 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -13,6 +13,17 @@ class ModelExtensionRetailcrmIcml extends Model private $options; private $optionValues; + /** + * Constructor + * + * @param Registry $registry + */ + public function __construct($registry) + { + parent::__construct($registry); + $this->load->library('retailcrm/retailcrm'); + } + public function generateICML() { $this->load->language('extension/module/retailcrm'); @@ -100,79 +111,17 @@ class ModelExtensionRetailcrmIcml extends Model $products = $this->model_catalog_product->getProducts(array()); foreach ($products as $product) { - // Формируем офферы отнсительно доступных опций - $options = $this->model_catalog_product->getProductOptions($product['product_id']); - $offerOptions = array('select', 'radio'); - $requiredOptions = array(); - $notRequiredOptions = array(); - // Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет - foreach($options as $option) { - if(in_array($option['type'], $offerOptions)) { - if($option['required']) { - $requiredOptions[] = $option; - } else { - $notRequiredOptions[] = $option; - } - } - } - $offers = array(); - // Сначала совмещаем все обязательные опции - foreach($requiredOptions as $requiredOption) { - // Если первая итерация - if(empty($offers)) { - foreach($requiredOption['product_option_value'] as $optionValue) { - $offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( - 'price' => (float)$optionValue['price'], - 'qty' => $optionValue['quantity'] - ); - } - } else { - foreach($offers as $optionKey => $optionAttr) { - unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями - foreach($requiredOption['product_option_value'] as $optionValue) { - $offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( - 'price' => $optionAttr['price'] + (float)$optionValue['price'], - 'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ? - $optionValue['quantity'] : $optionAttr['qty'] - ); - } - } - } - } - // Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть. - foreach($notRequiredOptions as $notRequiredOption) { - // Если обязательных опцией не оказалось и первая итерация - if(empty($offers)) { - $offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию - foreach($notRequiredOption['product_option_value'] as $optionValue) { - $offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( - 'price' => (float)$optionValue['price'], - 'qty' => $optionValue['quantity'] - ); - } - } else { - foreach($offers as $optionKey => $optionAttr) { - foreach($notRequiredOption['product_option_value'] as $optionValue) { - $offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array( - 'price' => $optionAttr['price'] + (float)$optionValue['price'], - 'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ? - $optionValue['quantity'] : $optionAttr['qty'] - ); - } - } - } - } - if(empty($offers)) { - $offers = array('0:0-0' => array('price' => '0', 'qty' => '0')); - } + $offers = $this->retailcrm->getOffers($product); - foreach($offers as $optionsString => $optionsValues) { + foreach ($offers as $optionsString => $optionsValues) { $optionsString = explode('_', $optionsString); $options = array(); + foreach($optionsString as $optionString) { $option = explode('-', $optionString); $optionIds = explode(':', $option[0]); - if($optionString != '0:0-0') { + + if ($optionString != '0:0-0') { $optionData = $this->getOptionData($optionIds[1], $option[1]); $options[$optionIds[0]] = array( 'name' => $optionData['optionName'], @@ -181,19 +130,23 @@ class ModelExtensionRetailcrmIcml extends Model ); } } + ksort($options); + $offerId = array(); + foreach($options as $optionKey => $optionData) { $offerId[] = $optionKey.'-'.$optionData['value_id']; } + $offerId = implode('_', $offerId); $e = $this->eOffers->appendChild($this->dd->createElement('offer')); - if(!empty($offerId)) { - $e->setAttribute('id', $product['product_id'].'#'.$offerId); + + if (!empty($offerId)) { + $e->setAttribute('id', $product['product_id'] . '#' . $offerId); $e->setAttribute('productId', $product['product_id']); $e->setAttribute('quantity', $optionsValues['qty']); - } - else { + } else { $e->setAttribute('id', $product['product_id']); $e->setAttribute('productId', $product['product_id']); $e->setAttribute('quantity', $product['quantity']); @@ -324,28 +277,23 @@ class ModelExtensionRetailcrmIcml extends Model $width, $height ); - - - return $this->model_tool_image->resize( - $image, - $this->config->get('config_image_product_width'), - $this->config->get('config_image_product_height') - ); } private function getOptionData($optionId, $optionValueId) { - if(!empty($this->options[$optionId])) { + if (!empty($this->options[$optionId])) { $option = $this->options[$optionId]; } else { $option = $this->model_catalog_option->getOption($optionId); $this->options[$optionId] = $option; } - if(!empty($this->optionValues[$optionValueId])) { + + if (!empty($this->optionValues[$optionValueId])) { $optionValue = $this->optionValues[$optionValueId]; } else { $optionValue = $this->model_catalog_option->getOptionValue($optionValueId); $this->optionValues[$optionValueId] = $optionValue; } + return array( 'optionName' => $option['name'], 'optionValue' => $optionValue['name'] diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index 38e85fb..98f23d0 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -106,10 +106,15 @@ class ModelExtensionRetailcrmOrder extends Model { $payment_code = ''; } - if (!empty($order_data['shipping_code']) && isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) { - $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']]; - } else { - $delivery_code = ''; + if (!empty($order_data['shipping_code'])) { + $shippingCode = explode('.', $order_data['shipping_code']); + $shippingModule = $shippingCode[0]; + + if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) { + $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']]; + } elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) { + $delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule]; + } } $order['number'] = $order_data['order_id']; diff --git a/admin/model/extension/retailcrm/prices.php b/admin/model/extension/retailcrm/prices.php new file mode 100644 index 0000000..f190861 --- /dev/null +++ b/admin/model/extension/retailcrm/prices.php @@ -0,0 +1,201 @@ +load->library('retailcrm/retailcrm'); + $this->load->model('catalog/option'); + $this->load->model('setting/setting'); + + $this->moduleTitle = $this->retailcrm->getModuleTitle(); + $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); + $this->retailcrmApiClient = $this->retailcrm->getApiClient(); + } + + /** + * Upload prices to CRM + * + * @param array $products + * + * @return void + */ + public function uploadPrices($products) + { + $prices = $this->getPrices($products); + + $pricesUpload = array_chunk($prices, 250); + + foreach ($pricesUpload as $priceUpload) { + $this->retailcrmApiClient->storePricesUpload($priceUpload); + } + } + + /** + * Get prices + * + * @param array $products + * + * @return array $prices + */ + protected function getPrices($products) + { + $prices = array(); + $site = $this->getSite(); + + if (!isset($this->settings[$this->moduleTitle . '_special']) + || $this->settings[$this->moduleTitle . '_apiversion'] == 'v3' + ) { + return; + } + + foreach ($products as $product) { + $specials = $this->model_catalog_product->getProductSpecials($product['product_id']); + + if (!$specials) { + continue; + } + + if (is_array($specials) && count($specials)) { + $productPrice = $this->getSpecialPrice($specials); + + if (!$productPrice) { + continue; + } + } + + $offers = $this->retailcrm->getOffers($product); + + foreach ($offers as $optionsString => $optionsValues) { + $optionsString = explode('_', $optionsString); + $options = array(); + + foreach($optionsString as $optionString) { + $option = explode('-', $optionString); + $optionIds = explode(':', $option[0]); + + if ($optionString != '0:0-0') { + $optionData = $this->getOptionData($optionIds[1], $option[1]); + $options[$optionIds[0]] = array( + 'name' => $optionData['optionName'], + 'value' => $optionData['optionValue'], + 'value_id' => $option[1] + ); + } + } + + ksort($options); + + $offerId = array(); + + foreach($options as $optionKey => $optionData) { + $offerId[] = $optionKey.'-'.$optionData['value_id']; + } + + $offerId = implode('_', $offerId); + + $prices[] = array( + 'externalId' => $offerId ? $product['product_id'] . '#' . $offerId : $product['product_id'], + 'site' => $site, + 'prices' => array( + array( + 'code' => $this->settings[$this->moduleTitle . '_special'], + 'price' => $productPrice + $optionsValues['price'] + ) + ) + ); + } + } + + return $prices; + } + + /** + * Get actual special + * + * @param array $specials + * + * @return float $productPrice + */ + private function getSpecialPrice($specials) + { + $date = date('Y-m-d'); + $always = '0000-00-00'; + $productPrice = 0; + + foreach ($specials as $special) { + if (($special['date_start'] == $always && $special['date_end'] == $always) + || ($special['date_start'] <= $date && $special['date_end'] >= $date) + ) { + if ((isset($priority) && $priority > $special['priority']) + || !isset($priority) + ) { + $productPrice = $special['price']; + $priority = $special['priority']; + } + } + } + + return $productPrice; + } + + /** + * Get data option + * + * @param int $optionId + * @param int $optionValueId + * + * @return array + */ + private function getOptionData($optionId, $optionValueId) { + if (!empty($this->options[$optionId])) { + $option = $this->options[$optionId]; + } else { + $option = $this->model_catalog_option->getOption($optionId); + $this->options[$optionId] = $option; + } + + if (!empty($this->optionValues[$optionValueId])) { + $optionValue = $this->optionValues[$optionValueId]; + } else { + $optionValue = $this->model_catalog_option->getOptionValue($optionValueId); + $this->optionValues[$optionValueId] = $optionValue; + } + + return array( + 'optionName' => $option['name'], + 'optionValue' => $optionValue['name'] + ); + } + + /** + * Get site + * + * @return mixed boolean | string + */ + private function getSite() + { + $response = $this->retailcrmApiClient->sitesList(); + + if ($response && $response->isSuccessful()) { + $sites = $response->sites; + $site = end($sites); + + return $site['code']; + } + + return false; + } +} diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index 9bf781d..722c499 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -1,9 +1,11 @@ settings = $this->model_setting_setting->getSetting($this->moduleTitle); $this->retailcrmApiClient = $this->retailcrm->getApiClient(); } - + /** + * Get opencart delivery methods + * + * @return array + */ public function getOpercartDeliveryTypes() { $this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry); - return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array()); + return $this->opencartApiClient->getDeliveryTypes(); } + /** + * Get all delivery types + * + * @return array + */ public function getDeliveryTypes() { $this->load->model('setting/store'); @@ -35,6 +46,11 @@ class ModelExtensionRetailcrmReferences extends Model { ); } + /** + * Get all statuses + * + * @return array + */ public function getOrderStatuses() { return array( @@ -43,6 +59,11 @@ class ModelExtensionRetailcrmReferences extends Model { ); } + /** + * Get all payment types + * + * @return array + */ public function getPaymentTypes() { return array( @@ -51,6 +72,11 @@ class ModelExtensionRetailcrmReferences extends Model { ); } + /** + * Get all custom fields + * + * @return array + */ public function getCustomFields() { return array( @@ -59,6 +85,11 @@ class ModelExtensionRetailcrmReferences extends Model { ); } + /** + * Get opencart order statuses + * + * @return array + */ public function getOpercartOrderStatuses() { $this->load->model('localisation/order_status'); @@ -67,6 +98,11 @@ class ModelExtensionRetailcrmReferences extends Model { ->getOrderStatuses(array()); } + /** + * Get opencart payment types + * + * @return array + */ public function getOpercartPaymentTypes() { $paymentTypes = array(); @@ -94,14 +130,24 @@ class ModelExtensionRetailcrmReferences extends Model { return $paymentTypes; } - + + /** + * Get opencart custom fields + * + * @return array + */ public function getOpencartCustomFields() { $this->load->model('customer/custom_field'); return $this->model_customer_custom_field->getCustomFields(); } - + + /** + * Get RetailCRM delivery types + * + * @return array + */ public function getApiDeliveryTypes() { $response = $this->retailcrmApiClient->deliveryTypesList(); @@ -109,6 +155,11 @@ class ModelExtensionRetailcrmReferences extends Model { return (!$response->isSuccessful()) ? array() : $response->deliveryTypes; } + /** + * Get RetailCRM order statuses + * + * @return array + */ public function getApiOrderStatuses() { $response = $this->retailcrmApiClient->statusesList(); @@ -116,13 +167,23 @@ class ModelExtensionRetailcrmReferences extends Model { return (!$response->isSuccessful()) ? array() : $response->statuses; } + /** + * Get RetailCRM payment types + * + * @return array + */ public function getApiPaymentTypes() { $response = $this->retailcrmApiClient->paymentTypesList(); return (!$response->isSuccessful()) ? array() : $response->paymentTypes; } - + + /** + * Get RetailCRM custom fields + * + * @return array + */ public function getApiCustomFields() { $customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer')); @@ -137,4 +198,16 @@ class ModelExtensionRetailcrmReferences extends Model { return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders); } + + /** + * Get RetailCRM price types + * + * @return array + */ + public function getPriceTypes() + { + $response = $this->retailcrmApiClient->priceTypesList(); + + return (!$response->isSuccessful()) ? array() : $response->priceTypes; + } } diff --git a/admin/view/stylesheet/retailcrm.css b/admin/view/stylesheet/retailcrm.css index 2efb7ae..fba27ff 100644 --- a/admin/view/stylesheet/retailcrm.css +++ b/admin/view/stylesheet/retailcrm.css @@ -1,4 +1,5 @@ .retailcrm_unit {margin-bottom: 10px;} .retailcrm_unit input {width: 30%;} .checkbox input{width: auto;} -.retailcrm_unit input[type=checkbox] {width: 13px;} \ No newline at end of file +.retailcrm_unit input[type=checkbox] {width: 13px;} +.retailcrm_unit select {max-width: 500px;} \ No newline at end of file diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index f20f78f..18dc0bd 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -98,6 +98,21 @@ + +
+