From e21486e7b2be03e8c526a0f9a80cd7c5f0aba347 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Wed, 22 Mar 2017 11:51:48 +0300 Subject: [PATCH 01/40] restruct for 2.3 --- admin/controller/module/retailcrm.php | 341 ------------- admin/language/english/module/retailcrm.php | 31 -- admin/language/russian/module/retailcrm.php | 31 -- admin/model/retailcrm/custom/.gitkeep | 0 admin/model/retailcrm/customer.php | 51 -- admin/model/retailcrm/history.php | 470 ------------------ admin/model/retailcrm/icml.php | 337 ------------- admin/model/retailcrm/order.php | 116 ----- admin/model/retailcrm/references.php | 138 ----- admin/view/template/module/retailcrm.tpl | 110 ---- catalog/controller/module/retailcrm.php | 117 ----- catalog/model/retailcrm/customer.php | 42 -- catalog/model/retailcrm/order.php | 260 ---------- system/cron/dispatch.php | 46 +- system/cron/export.php | 2 +- system/cron/history.php | 2 +- system/cron/icml.php | 2 +- .../library/retailcrm/OpencartApiClient.php | 47 +- .../retailcrm/RetailcrmHistoryHelper.php | 18 +- 19 files changed, 46 insertions(+), 2115 deletions(-) delete mode 100644 admin/controller/module/retailcrm.php delete mode 100644 admin/language/english/module/retailcrm.php delete mode 100644 admin/language/russian/module/retailcrm.php delete mode 100644 admin/model/retailcrm/custom/.gitkeep delete mode 100644 admin/model/retailcrm/customer.php delete mode 100644 admin/model/retailcrm/history.php delete mode 100644 admin/model/retailcrm/icml.php delete mode 100644 admin/model/retailcrm/order.php delete mode 100644 admin/model/retailcrm/references.php delete mode 100644 admin/view/template/module/retailcrm.tpl delete mode 100644 catalog/controller/module/retailcrm.php delete mode 100644 catalog/model/retailcrm/customer.php delete mode 100644 catalog/model/retailcrm/order.php diff --git a/admin/controller/module/retailcrm.php b/admin/controller/module/retailcrm.php deleted file mode 100644 index 3daf847..0000000 --- a/admin/controller/module/retailcrm.php +++ /dev/null @@ -1,341 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 - */ -class ControllerModuleRetailcrm extends Controller -{ - private $_error = array(); - protected $log, $statuses, $payments, $deliveryTypes, $retailcrm; - public $children, $template; - - /** - * Install method - * - * @return void - */ - public function install() - { - $this->load->model('setting/setting'); - $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 1)); - - $this->load->model('extension/event'); - - $this->model_extension_event - ->addEvent( - 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/checkout/order/addOrder/after' : 'post.order.add', - 'module/retailcrm/order_create' - ); - - $this->model_extension_event - ->addEvent( - 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/checkout/order/addOrderHistory/after' : 'post.order.history.add', - 'module/retailcrm/order_edit' - ); - - $this->model_extension_event - ->addEvent( - 'retailcrm', - version_compare(VERSION, '2.2', '>=') ? 'catalog/model/account/customer/addCustomer/after' : 'post.customer.add', - 'module/retailcrm/customer_create' - ); - } - - /** - * Uninstall method - * - * @return void - */ - public function uninstall() - { - $this->load->model('setting/setting'); - $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 0)); - - $this->load->model('extension/event'); - $this->model_extension_event->deleteEvent('retailcrm'); - } - - /** - * Setup page - * - * @return void - */ - public function index() - { - - $this->load->model('setting/setting'); - $this->load->model('extension/module'); - $this->load->model('retailcrm/references'); - $this->load->language('module/retailcrm'); - $this->document->setTitle($this->language->get('heading_title')); - $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); - - if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { - $this->model_setting_setting->editSetting( - 'retailcrm', - $this->request->post - ); - - $this->session->data['success'] = $this->language->get('text_success'); - $redirect = $this->url->link( - 'module/retailcrm', 'token=' . $this->session->data['token'], - 'SSL' - ); - - $this->response->redirect($redirect); - } - - $text_strings = array( - 'heading_title', - 'text_enabled', - 'text_disabled', - 'button_save', - 'button_cancel', - 'text_notice', - 'retailcrm_title', - 'retailcrm_url', - 'retailcrm_apikey', - 'retailcrm_base_settings', - 'retailcrm_dict_settings', - 'retailcrm_dict_delivery', - 'retailcrm_dict_status', - 'retailcrm_dict_payment', - ); - - $this->load->model('extension/extension'); - $_data = &$data; - - foreach ($text_strings as $text) { - $_data[$text] = $this->language->get($text); - } - - $_data['retailcrm_errors'] = array(); - $_data['saved_settings'] = $this->model_setting_setting - ->getSetting('retailcrm'); - - $url = isset($_data['saved_settings']['retailcrm_url']) - ? $_data['saved_settings']['retailcrm_url'] - : null; - $key = isset($_data['saved_settings']['retailcrm_apikey']) - ? $_data['saved_settings']['retailcrm_apikey'] - : null; - - if (!empty($url) && !empty($key)) { - - $this->retailcrm = new RetailcrmProxy( - $url, - $key, - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $_data['delivery'] = $this->model_retailcrm_references - ->getDeliveryTypes(); - $_data['statuses'] = $this->model_retailcrm_references - ->getOrderStatuses(); - $_data['payments'] = $this->model_retailcrm_references - ->getPaymentTypes(); - - } - - $config_data = array( - 'retailcrm_status' - ); - - foreach ($config_data as $conf) { - if (isset($this->request->post[$conf])) { - $_data[$conf] = $this->request->post[$conf]; - } else { - $_data[$conf] = $this->config->get($conf); - } - } - - if (isset($this->error['warning'])) { - $_data['error_warning'] = $this->error['warning']; - } else { - $_data['error_warning'] = ''; - } - - $_data['breadcrumbs'] = array(); - - $_data['breadcrumbs'][] = array( - 'text' => $this->language->get('text_home'), - 'href' => $this->url->link( - 'common/home', - 'token=' . $this->session->data['token'], 'SSL' - ), - 'separator' => false - ); - - $_data['breadcrumbs'][] = array( - 'text' => $this->language->get('text_module'), - 'href' => $this->url->link( - 'extension/module', - 'token=' . $this->session->data['token'], 'SSL' - ), - 'separator' => ' :: ' - ); - - $_data['breadcrumbs'][] = array( - 'text' => $this->language->get('retailcrm_title'), - 'href' => $this->url->link( - 'module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' - ), - 'separator' => ' :: ' - ); - - $_data['action'] = $this->url->link( - 'module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' - ); - - $_data['cancel'] = $this->url->link( - 'extension/module', - 'token=' . $this->session->data['token'], 'SSL' - ); - - $_data['modules'] = array(); - - if (isset($this->request->post['retailcrm_module'])) { - $_data['modules'] = $this->request->post['retailcrm_module']; - } elseif ($this->config->get('retailcrm_module')) { - $_data['modules'] = $this->config->get('retailcrm_module'); - } - - $this->load->model('design/layout'); - $_data['layouts'] = $this->model_design_layout->getLayouts(); - - $_data['header'] = $this->load->controller('common/header'); - $_data['column_left'] = $this->load->controller('common/column_left'); - $_data['footer'] = $this->load->controller('common/footer'); - - $this->response->setOutput( - $this->load->view('module/retailcrm.tpl', $_data) - ); - } - - /** - * History method - * - * @return void - */ - public function history() - { - if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/history.php')) { - $this->load->model('retailcrm/custom/history'); - $this->model_retailcrm_custom_history->request(); - } else { - $this->load->model('retailcrm/history'); - $this->model_retailcrm_history->request(); - } - } - - /** - * ICML generation - * - * @return void - */ - public function icml() - { - if (file_exists(DIR_APPLICATION . 'model/retailcrm/custom/icml.php')) { - $this->load->model('retailcrm/custom/icml'); - $this->model_retailcrm_custom_icml->generateICML(); - } else { - $this->load->model('retailcrm/icml'); - $this->model_retailcrm_icml->generateICML(); - } - } - - /** - * Create order on event - * - * @param int $order_id order identificator - * - * @return void - */ - public function order_create($order_id) - { - $this->load->model('checkout/order'); - $this->load->model('account/order'); - - $data = $this->model_checkout_order->getOrder($order_id); - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - - if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; - - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->sendToCrm($data, $data['order_id']); - } - } - - /** - * Export orders - * - * - */ - public function export() { - if(version_compare(VERSION, '2.1', '<')) { - $this->load->model('sale/customer'); - $customers = $this->model_sale_customer->getCustomers(); - } else { - $this->load->model('customer/customer'); - $customers = $this->model_customer_customer->getCustomers(); - } - - $this->load->model('retailcrm/customer'); - $this->model_retailcrm_customer->uploadToCrm($customers); - - $this->load->model('sale/order'); - $orders = $this->model_sale_order->getOrders(); - - $fullOrders = array(); - foreach($orders as $order) { - $fullOrder = $this->model_sale_order->getOrder($order['order_id']); - - $fullOrder['order_total'] = $this->model_sale_order->getOrderTotals($order['order_id']); - - $fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']); - foreach($fullOrder['products'] as $key=>$product) { - $fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); - } - - $fullOrders[] = $fullOrder; - } - - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->uploadToCrm($fullOrders); - } - - /** - * Validate - * - * @return bool - */ - private function validate() - { - if (!$this->user->hasPermission('modify', 'module/retailcrm')) { - $this->_error['warning'] = $this->language->get('error_permission'); - } - - if (!$this->_error) { - return true; - } else { - return false; - } - } -} diff --git a/admin/language/english/module/retailcrm.php b/admin/language/english/module/retailcrm.php deleted file mode 100644 index f1baabb..0000000 --- a/admin/language/english/module/retailcrm.php +++ /dev/null @@ -1,31 +0,0 @@ -load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(empty($customers)) - return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $customersToCrm = array(); - - foreach($customers as $customer) { - $customersToCrm[] = $this->process($customer); - } - - $chunkedCustomers = array_chunk($customersToCrm, 50); - - foreach($chunkedCustomers as $customersPart) { - $this->retailcrmApi->customersUpload($customersPart); - } - } - - private function process($customer) { - $customerToCrm = array( - 'externalId' => $customer['customer_id'], - 'firstName' => $customer['firstname'], - 'lastName' => $customer['lastname'], - 'email' => $customer['email'], - 'phones' => array( - array( - 'number' => $customer['telephone'] - ) - ), - 'createdAt' => $customer['date_added'] - ); - - return $customerToCrm; - } -} diff --git a/admin/model/retailcrm/history.php b/admin/model/retailcrm/history.php deleted file mode 100644 index b984635..0000000 --- a/admin/model/retailcrm/history.php +++ /dev/null @@ -1,470 +0,0 @@ -load->model('setting/setting'); - $this->load->model('setting/store'); - $this->load->model('user/api'); - $this->load->model('sale/order'); - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $this->load->model('customer/customer'); - } else { - $this->load->model('sale/customer'); - } - $this->load->model('retailcrm/references'); - $this->load->model('catalog/product'); - $this->load->model('catalog/option'); - $this->load->model('localisation/zone'); - - $this->load->language('module/retailcrm'); - - $settings = $this->model_setting_setting->getSetting('retailcrm'); - $history = $this->model_setting_setting->getSetting('retailcrm_history'); - $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - - $url = isset($settings['retailcrm_url']) ? $settings['retailcrm_url'] : null; - $key = isset($settings['retailcrm_apikey']) ? $settings['retailcrm_apikey'] : null; - - if (empty($url) || empty($key)) { - $this->log->addNotice('You need to configure retailcrm module first.'); - return false; - } - - $this->opencartApiClient = new OpencartApiClient($this->registry); - - $crm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $lastRun = !empty($history['retailcrm_history']) - ? new DateTime($history['retailcrm_history']) - : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); - - $packs = $crm->ordersHistory(array( - 'startDate' => $lastRun->format('Y-m-d H:i:s'), - ), 1, 100); - if(!$packs->isSuccessful() && count($packs->history) <= 0) - return false; - $orders = RetailcrmHistoryHelper::assemblyOrder($packs->history); - - $generatedAt = $packs['generatedAt']; - - $this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting('total'); - $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); - - $this->delivery = array_flip($settings['retailcrm_delivery']); - $this->payment = array_flip($settings['retailcrm_payment']); - $this->status = array_flip($settings['retailcrm_status']); - - $this->ocPayment = $this->model_retailcrm_references - ->getOpercartPaymentTypes(); - - $this->ocDelivery = $this->model_retailcrm_references - ->getOpercartDeliveryTypes(); - - $this->zones = $this->model_localisation_zone->getZones(); - - $updatedOrders = array(); - $newOrders = array(); - - foreach ($orders as $order) { - - if (isset($order['deleted'])) continue; - - if (isset($order['externalId'])) { - $updatedOrders[] = $order['id']; - } else { - $newOrders[] = $order['id']; - } - } - - unset($orders); - - if (!empty($newOrders)) { - $orders = $crm->ordersList($filter = array('ids' => $newOrders)); - if ($orders) { - $this->createResult = $this->createOrders($orders['orders']); - } - } - - if (!empty($updatedOrders)) { - $orders = $crm->ordersList($filter = array('ids' => $updatedOrders)); - if ($orders) { - $this->updateOrders($orders['orders']); - } - } - - $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); - - if (!empty($this->createResult['customers'])) { - $crm->customersFixExternalIds($this->createResult['customers']); - } - - if (!empty($this->createResult['orders'])) { - $crm->ordersFixExternalIds($this->createResult['orders']); - } - } - - protected function updateOrders($orders) - { - foreach ($orders as $order) { - $store = $this->config->get('config_store_id'); - - $data = array(); - - $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; - $data['firstname'] = $order['firstName']; - $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $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']; - - $region = ''; - - if (is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; - } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } - } - } - - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; - - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; - - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $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'] = $this->delivery[$order['delivery']['code']]; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; - $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; - - $data['payment'] = $this->payment[$order['paymentType']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$order['paymentType']]; - - // 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) { - //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); - $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['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['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) { - $cData = array( - 'store_id' => 0, - 'customer_group_id' => '1', - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', - 'email' => $order['email'], - 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', - 'fax' => '', - 'newsletter' => 0, - 'password' => 'tmppass', - 'status' => 1, - 'address' => array( - array( - 'firstname' => $order['firstName'], - 'lastname' => (!empty($order['lastName'])) ? $order['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' => '0', - 'country_id' => 0 - ) - ), - ); - - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $this->model_customer_customer->addCustomer($cData); - } else { - $this->model_sale_customer->addCustomer($cData); - } - - if (!empty($order['email'])) { - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); - } else { - $tryToFind = $this->model_sale_customer->getCustomerByEmail($order['email']); - } - $customer_id = $tryToFind['customer_id']; - } else { - if (version_compare(VERSION, '2.1.0.0', '>=')) { - $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - } else { - $last = $this->model_sale_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); - } - $customer_id = $last[0]['customer_id']; - } - - $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); - } - - $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'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $data['email'] = $order['email']; - $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; - $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; - $data['fax'] = ''; - $data['payment_address'] = '0'; - $data['payment_firstname'] = $order['firstName']; - $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $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']; - - $region = ''; - - if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { - $region = $order['delivery']['address']['region']; - } else { - foreach ($this->zones as $zone) { - if ($order['delivery']['address']['region'] == $zone['name']) { - $region = $zone['zone_id']; - } - } - } - - $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; - $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; - $data['shipping_zone_id'] = $region; - $data['shipping_address'] = '0'; - $data['shipping_firstname'] = $order['firstName']; - $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; - $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'] = $this->delivery[$order['delivery']['code']]; - $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; - $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; - $data['payment'] = $this->payment[$order['paymentType']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$order['paymentType']]; - - // 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) { - $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); - $data['order_product'][] = array( - 'product_id' => $item['offer']['externalId'], - 'name' => $item['offer']['name'], - 'quantity' => $item['quantity'], - 'price' => $item['initialPrice'], - 'total' => $item['initialPrice'] * $item['quantity'], - 'model' => $product['model'], - - // this data will not retrive from crm - 'order_product_id' => '', - 'tax' => 0, - 'reward' => 0 - ); - } - - $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['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['total_sort_order'] - ) - ); - - $data['fromApi'] = true; - $data['order_status_id'] = 1; - - $this->opencartApiClient->addOrder($data); - - $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); - - $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']); - } - - return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); - } -} diff --git a/admin/model/retailcrm/icml.php b/admin/model/retailcrm/icml.php deleted file mode 100644 index 2d6b5c5..0000000 --- a/admin/model/retailcrm/icml.php +++ /dev/null @@ -1,337 +0,0 @@ -load->language('module/retailcrm'); - $this->load->model('catalog/category'); - $this->load->model('catalog/product'); - $this->load->model('catalog/option'); - $this->load->model('catalog/manufacturer'); - - $string = ' - - - '.$this->config->get('config_name').' - - - - - '; - - $xml = new SimpleXMLElement( - $string, - LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE - ); - - $this->dd = new DOMDocument(); - $this->dd->preserveWhiteSpace = false; - $this->dd->formatOutput = true; - $this->dd->loadXML($xml->asXML()); - - $this->eCategories = $this->dd - ->getElementsByTagName('categories')->item(0); - $this->eOffers = $this->dd - ->getElementsByTagName('offers')->item(0); - - $this->addCategories(); - $this->addOffers(); - - $this->dd->saveXML(); - - $downloadPath = DIR_SYSTEM . '/../'; - - if (!file_exists($downloadPath)) { - mkdir($downloadPath, 0755); - } - - $this->dd->save($downloadPath . 'retailcrm.xml'); - } - - /** - * - */ - private function addCategories() - { - $categories = $this->model_catalog_category->getCategories(array()); - foreach($categories as $category) { - $category = $this->model_catalog_category->getCategory($category['category_id']); - - $e = $this->eCategories->appendChild( - $this->dd->createElement( - 'category', $category['name'] - ) - ); - - $e->setAttribute('id', $category['category_id']); - - if ($category['parent_id'] > 0) { - $e->setAttribute('parentId', $category['parent_id']); - } - } - - } - - private function addOffers() - { - $offerManufacturers = array(); - - $manufacturers = $this->model_catalog_manufacturer - ->getManufacturers(array()); - - foreach ($manufacturers as $manufacturer) { - $offerManufacturers[ - $manufacturer['manufacturer_id'] - ] = $manufacturer['name']; - } - - $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']] = (float)$optionValue['price']; - } - } else { - foreach($offers as $optionKey => $optionCost) { - unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями - foreach($requiredOption['product_option_value'] as $optionValue) { - $offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price']; - } - } - } - } - // Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть. - 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']] = (float)$optionValue['price']; - } - } else { - foreach($offers as $optionKey => $optionCost) { - foreach($notRequiredOption['product_option_value'] as $optionValue) { - $offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price']; - } - } - } - } - if(empty($offers)) { - $offers = array('0:0-0' => '0'); - } - - foreach($offers as $optionsString => $optionsTotalCost) { - $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); - $e = $this->eOffers->appendChild($this->dd->createElement('offer')); - if(!empty($offerId)) - $e->setAttribute('id', $product['product_id'].'#'.$offerId); - else - $e->setAttribute('id', $product['product_id']); - $e->setAttribute('productId', $product['product_id']); - $e->setAttribute('quantity', $product['quantity']); - /** - * Offer activity - */ - $activity = $product['status'] == 1 ? 'Y' : 'N'; - $e->appendChild( - $this->dd->createElement('productActivity') - )->appendChild( - $this->dd->createTextNode($activity) - ); - /** - * Offer categories - */ - $categories = $this->model_catalog_product - ->getProductCategories($product['product_id']); - if (!empty($categories)) { - foreach ($categories as $category) { - $e->appendChild($this->dd->createElement('categoryId')) - ->appendChild( - $this->dd->createTextNode($category) - ); - } - } - /** - * Name & price - */ - $e->appendChild($this->dd->createElement('productName')) - ->appendChild($this->dd->createTextNode($product['name'])); - if(!empty($options)) { - $optionsString = array(); - foreach($options as $option) { - $optionsString[] = $option['name'].': '.$option['value']; - } - $optionsString = ' ('.implode(', ', $optionsString).')'; - $e->appendChild($this->dd->createElement('name')) - ->appendChild($this->dd->createTextNode($product['name'].$optionsString)); - } else { - $e->appendChild($this->dd->createElement('name')) - ->appendChild($this->dd->createTextNode($product['name'])); - } - $e->appendChild($this->dd->createElement('price')) - ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); - /** - * Vendor - */ - if ($product['manufacturer_id'] != 0) { - $e->appendChild($this->dd->createElement('vendor')) - ->appendChild( - $this->dd->createTextNode( - $offerManufacturers[$product['manufacturer_id']] - ) - ); - } - /** - * Image - */ - if ($product['image']) { - $image = $this->generateImage($product['image']); - $e->appendChild($this->dd->createElement('picture')) - ->appendChild($this->dd->createTextNode($image)); - } - /** - * Url - */ - $this->url = new Url( - HTTP_CATALOG, - $this->config->get('config_secure') - ? HTTP_CATALOG - : HTTPS_CATALOG - ); - $e->appendChild($this->dd->createElement('url')) - ->appendChild( - $this->dd->createTextNode( - $this->url->link( - 'product/product&product_id=' . $product['product_id'] - ) - ) - ); - // Options - if(!empty($options)) { - foreach($options as $optionKey => $optionData) { - $param = $this->dd->createElement('param'); - $param->setAttribute('code', $optionKey); - $param->setAttribute('name', $optionData['name']); - $param->appendChild($this->dd->createTextNode($optionData['value'])); - $e->appendChild($param); - } - } - if ($product['sku']) { - $sku = $this->dd->createElement('param'); - $sku->setAttribute('code', 'article'); - $sku->setAttribute('name', $this->language->get('article')); - $sku->appendChild($this->dd->createTextNode($product['sku'])); - $e->appendChild($sku); - } - if ($product['weight'] != '') { - $weight = $this->dd->createElement('param'); - $weight->setAttribute('code', 'weight'); - $weight->setAttribute('name', $this->language->get('weight')); - $weightValue = (isset($offer['weight_class'])) - ? round($product['weight'], 3) . ' ' . $product['weight_class'] - : round($product['weight'], 3) - ; - $weight->appendChild($this->dd->createTextNode($weightValue)); - $e->appendChild($weight); - } - } - } - } - - /** - * @param $image - * @return mixed - */ - private function generateImage($image) - { - $this->load->model('tool/image'); - - if (version_compare(VERSION, '2.2', '>=')) { - $currentTheme = $this->config->get('config_theme'); - $width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200; - $height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200; - - return $this->model_tool_image->resize( - $image, - $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])) { - $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'] - ); - } -} diff --git a/admin/model/retailcrm/order.php b/admin/model/retailcrm/order.php deleted file mode 100644 index c9cd423..0000000 --- a/admin/model/retailcrm/order.php +++ /dev/null @@ -1,116 +0,0 @@ -load->model('catalog/product'); - - $this->load->model('setting/setting'); - $this->settings = $this->model_setting_setting->getSetting('retailcrm'); - - $ordersToCrm = array(); - - foreach($orders as $order) { - $ordersToCrm[] = $this->process($order); - } - - $chunkedOrders = array_chunk($ordersToCrm, 50); - - foreach($chunkedOrders as $ordersPart) { - $this->retailcrmApi->ordersUpload($ordersPart); - } - } - - private function process($order_data) { - $order = array(); - - $payment_code = $order_data['payment_code']; - $delivery_code = $order_data['shipping_code']; - - $order['externalId'] = $order_data['order_id']; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - $order['customer']['externalId'] = $order_data['customer_id']; - - $deliveryCost = 0; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - } - - $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $this->settings['retailcrm_payment'][$payment_code]; - - $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $this->settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'country' => $order_data['shipping_country_id'], - 'region' => $order_data['shipping_zone_id'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - $country, - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if(!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - foreach($product['option'] as $option) { - if(!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - $order['items'][] = array( - 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'], - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - } - - return $order; - } -} diff --git a/admin/model/retailcrm/references.php b/admin/model/retailcrm/references.php deleted file mode 100644 index b5aef36..0000000 --- a/admin/model/retailcrm/references.php +++ /dev/null @@ -1,138 +0,0 @@ - $this->getOpercartDeliveryTypes(), - 'retailcrm' => $this->getApiDeliveryTypes() - ); - } - - public function getOrderStatuses() - { - return array( - 'opencart' => $this->getOpercartOrderStatuses(), - 'retailcrm' => $this->getApiOrderStatuses() - ); - } - - public function getPaymentTypes() - { - return array( - 'opencart' => $this->getOpercartPaymentTypes(), - 'retailcrm' => $this->getApiPaymentTypes() - ); - } - - public function getOpercartDeliveryTypes() - { - $deliveryMethods = array(); - $files = glob(DIR_APPLICATION . 'controller/shipping/*.php'); - - if ($files) { - foreach ($files as $file) { - $extension = basename($file, '.php'); - - $this->load->language('shipping/' . $extension); - - if ($this->config->get($extension . '_status')) { - $deliveryMethods[$extension.'.'.$extension] = strip_tags( - $this->language->get('heading_title') - ); - } - } - } - - return $deliveryMethods; - } - - public function getOpercartOrderStatuses() - { - $this->load->model('localisation/order_status'); - - return $this->model_localisation_order_status - ->getOrderStatuses(array()); - } - - public function getOpercartPaymentTypes() - { - $paymentTypes = array(); - $files = glob(DIR_APPLICATION . 'controller/payment/*.php'); - - if ($files) { - foreach ($files as $file) { - $extension = basename($file, '.php'); - - $this->load->language('payment/' . $extension); - - if ($this->config->get($extension . '_status')) { - $paymentTypes[$extension] = strip_tags( - $this->language->get('heading_title') - ); - } - } - } - - return $paymentTypes; - } - - public function getApiDeliveryTypes() - { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $response = $this->retailcrm->deliveryTypesList(); - - return ($response === false) ? array() : $response->deliveryTypes; - } - } - - public function getApiOrderStatuses() - { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $response = $this->retailcrm->statusesList(); - - return ($response === false) ? array() : $response->statuses; - } - } - - public function getApiPaymentTypes() - { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $response = $this->retailcrm->paymentTypesList(); - - return ($response === false) ? array() : $response->paymentTypes; - } - } -} diff --git a/admin/view/template/module/retailcrm.tpl b/admin/view/template/module/retailcrm.tpl deleted file mode 100644 index 144f68b..0000000 --- a/admin/view/template/module/retailcrm.tpl +++ /dev/null @@ -1,110 +0,0 @@ - - - -
- -
- -
- - -
- - - - - - -
-
-
- - -

-
-
- -
-
-
- -
- - - - - -
- - -

- -

- $value): ?> -
- - -
- - -

- - -
- - -
- - -

- $value): ?> -
- - -
- - - - - -
-
-
-
-
- - diff --git a/catalog/controller/module/retailcrm.php b/catalog/controller/module/retailcrm.php deleted file mode 100644 index 27a368f..0000000 --- a/catalog/controller/module/retailcrm.php +++ /dev/null @@ -1,117 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 - */ -class ControllerModuleRetailcrm extends Controller -{ - /** - * Create order on event - * - * @param int $order_id order identificator - * - * @return void - */ - public function order_create($parameter1, $parameter2 = null) - { - $this->load->model('checkout/order'); - $this->load->model('account/order'); - - if($parameter2 != null) - $order_id = $parameter2; - else - $order_id = $parameter1; - - $data = $this->model_checkout_order->getOrder($order_id); - - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - foreach($data['products'] as $key => $product) { - $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); - - if(!empty($productOptions)) - $data['products'][$key]['option'] = $productOptions; - } - - if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); - if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; - } - - $data['totals'][] = array( - 'code' => 'shipping', - 'value' => $this->session->data['shipping_method']['cost'] - ); - - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->sendToCrm($data, $data['order_id']); - } - } - - public function order_edit($parameter1, $parameter2 = null, $parameter3 = null, $parameter4 = null) { - if($parameter4 != null) - $order_id = $parameter3; - else - $order_id = $parameter1; - - $this->load->model('checkout/order'); - $this->load->model('account/order'); - - $data = $this->model_checkout_order->getOrder($order_id); - - if($data['order_status_id'] == 0) return; - - $data['products'] = $this->model_account_order->getOrderProducts($order_id); - - foreach($data['products'] as $key => $product) { - $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); - - if(!empty($productOptions)) - $data['products'][$key]['option'] = $productOptions; - } - - if (!isset($data['fromApi'])) { - $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); - - if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; - } - - $data['totals'][] = array( - 'code' => 'shipping', - 'value' => isset($this->session->data['shipping_method']) ? $this->session->data['shipping_method']['cost'] : '' - ); - - $this->load->model('retailcrm/order'); - $this->model_retailcrm_order->changeInCrm($data, $data['order_id']); - } - } - - /** - * Create customer on event - * - * @param int $customerId customer identificator - * - * @return void - */ - public function customer_create($parameter1, $parameter2 = null) { - if($parameter2 != null) - $customerId = $parameter2; - else - $customerId = $parameter1; - - $this->load->model('account/customer'); - $customer = $this->model_account_customer->getCustomer($customerId); - - $this->load->model('retailcrm/customer'); - $this->model_retailcrm_customer->sendToCrm($customer); - } -} diff --git a/catalog/model/retailcrm/customer.php b/catalog/model/retailcrm/customer.php deleted file mode 100644 index 093a109..0000000 --- a/catalog/model/retailcrm/customer.php +++ /dev/null @@ -1,42 +0,0 @@ -load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(empty($customer)) - return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $customerToCrm = $this->process($customer); - - $this->retailcrmApi->customersCreate($customerToCrm); - } - - private function process($customer) { - $customerToCrm = array( - 'externalId' => $customer['customer_id'], - 'firstName' => $customer['firstname'], - 'lastName' => $customer['lastname'], - 'email' => $customer['email'], - 'phones' => array( - array( - 'number' => $customer['telephone'] - ) - ), - 'createdAt' => $customer['date_added'] - ); - - return $customerToCrm; - } -} diff --git a/catalog/model/retailcrm/order.php b/catalog/model/retailcrm/order.php deleted file mode 100644 index f59f82d..0000000 --- a/catalog/model/retailcrm/order.php +++ /dev/null @@ -1,260 +0,0 @@ -request->post['fromApi'])) return; - - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $order = array(); - - $customers = $this->retailcrm->customersList( - array( - 'name' => $order_data['telephone'], - 'email' => $order_data['email'] - ), - 1, - 100 - ); - - if($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } - } - - unset($customers); - - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - $deliveryCost = 0; - $altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : ""; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ; - - if (!empty($orderTotals)) { - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - } - } - - $order['createdAt'] = $order_data['date_added']; - - $payment_code = $order_data['payment_code']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; - - if(!isset($order_data['shipping_iso_code_2']) && isset($order_data['shipping_country_id'])) { - $this->load->model('localisation/country'); - $shipping_country = $this->model_localisation_country->getCountry($order_data['shipping_country_id']); - $order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2']; - } - - $delivery_code = $order_data['shipping_code']; - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'countryIso' => $order_data['shipping_iso_code_2'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '', - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if(!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - foreach($product['option'] as $option) { - if(!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - $order['items'][] = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - } - - if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; - } - - $this->retailcrm->ordersCreate($order); - } - } - - public function changeInCrm($order_data, $order_id) - { - if(isset($this->request->post['fromApi'])) return; - - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'logs/retailcrm.log' - ); - - $order = array(); - - $payment_code = $order_data['payment_code']; - $delivery_code = $order_data['shipping_code']; - - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - $deliveryCost = 0; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - } - - $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; - - $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'country' => $order_data['shipping_country_id'], - 'region' => $order_data['shipping_zone_id'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - $country, - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if(!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - foreach($product['option'] as $option) { - if(!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - $order['items'][] = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - } - - if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; - } - - $this->retailcrm->ordersEdit($order); - } - } -} diff --git a/system/cron/dispatch.php b/system/cron/dispatch.php index dfd546b..69ee0ed 100644 --- a/system/cron/dispatch.php +++ b/system/cron/dispatch.php @@ -34,17 +34,12 @@ if (!defined('DIR_APPLICATION')) { require_once(DIR_SYSTEM . 'startup.php'); // Application Classes -if (version_compare(VERSION, '2.2', '>=')) { - require_once(DIR_SYSTEM . 'library/cart/currency.php'); - require_once(DIR_SYSTEM . 'library/cart/user.php'); - require_once(DIR_SYSTEM . 'library/cart/weight.php'); - require_once(DIR_SYSTEM . 'library/cart/length.php'); -} else { - require_once(DIR_SYSTEM . 'library/currency.php'); - require_once(DIR_SYSTEM . 'library/user.php'); - require_once(DIR_SYSTEM . 'library/weight.php'); - require_once(DIR_SYSTEM . 'library/length.php'); -} +require_once(DIR_SYSTEM . 'library/cart/currency.php'); +require_once(DIR_SYSTEM . 'library/cart/user.php'); +require_once(DIR_SYSTEM . 'library/cart/weight.php'); +require_once(DIR_SYSTEM . 'library/cart/length.php'); + + // Registry $registry = new Registry(); @@ -68,10 +63,7 @@ foreach ($query->rows as $setting) { if (!$setting['serialized']) { $config->set($setting['key'], $setting['value']); } else { - if (version_compare(VERSION, '2.1', '>=')) - $config->set($setting['key'], json_decode($setting['value']), true); - else - $config->set($setting['key'], unserialize($setting['value'])); + $config->set($setting['key'], json_decode($setting['value']), true); } } @@ -85,10 +77,9 @@ $registry->set('log', $log); // Event -if (version_compare(VERSION, '2.2', '>=')) { - $event = new Event($registry); - $registry->set('event', $event); -} +$event = new Event($registry); +$registry->set('event', $event); + function error_handler($errno, $errstr, $errfile, $errline) { global $log, $config; @@ -153,17 +144,12 @@ $registry->set('language', $language); $document = new Document(); $registry->set('document', $document); -if (version_compare(VERSION, '2.2', '>=')) { - $registry->set('currency', new Cart\Currency($registry)); - $registry->set('weight', new Cart\Weight($registry)); - $registry->set('length', new Cart\Length($registry)); - $registry->set('user', new Cart\User($registry)); -} else { - $registry->set('currency', new Currency($registry)); - $registry->set('weight', new Weight($registry)); - $registry->set('length', new Length($registry)); - $registry->set('user', new User($registry)); -} + +$registry->set('currency', new Cart\Currency($registry)); +$registry->set('weight', new Cart\Weight($registry)); +$registry->set('length', new Cart\Length($registry)); +$registry->set('user', new Cart\User($registry)); + $controller = new Front($registry); $action = new Action($cli_action); diff --git a/system/cron/export.php b/system/cron/export.php index 8da82f4..5880920 100644 --- a/system/cron/export.php +++ b/system/cron/export.php @@ -1,3 +1,3 @@ model_setting_store->getStore($this->opencartStoreId); - if(version_compare(VERSION, '2.1.0', '>=') && !empty($this->apiToken)) { + if(!empty($this->apiToken)) { $getParams['token'] = $this->apiToken; } @@ -89,19 +89,10 @@ class OpencartApiClient { $api = array(); foreach ($apiUsers as $apiUser) { if($apiUser['status'] == 1) { - if(version_compare(VERSION, '2.1.0', '>=')) { - $api = array( - 'api_id' => $apiUser['api_id'], - 'key' => $apiUser['key'] - ); - } else { - $api = array( - 'api_id' => $apiUser['api_id'], - 'username' => $apiUser['username'], - 'password' => $apiUser['password'] - ); - } - + $api = array( + 'api_id' => $apiUser['api_id'], + 'key' => $apiUser['key'] + ); break; } } @@ -109,26 +100,24 @@ class OpencartApiClient { if(!isset($api['api_id'])) return false; - if(version_compare(VERSION, '2.1.0', '>=')) { - $alreadyBinded = false; + + $alreadyBinded = false; - $innerIp = $this->getInnerIpAddr(); - $apiIps = $this->model_user_api->getApiIps($api['api_id']); - foreach($apiIps as $apiIp) { - if($apiIp['ip'] == $innerIp) - $alreadyBinded = true; - } - - if(!$alreadyBinded) { - $this->model_user_api->addApiIp($api['api_id'], $innerIp); - } + $innerIp = $this->getInnerIpAddr(); + $apiIps = $this->model_user_api->getApiIps($api['api_id']); + foreach($apiIps as $apiIp) { + if($apiIp['ip'] == $innerIp) + $alreadyBinded = true; } + if(!$alreadyBinded) { + $this->model_user_api->addApiIp($api['api_id'], $innerIp); + } + + $apiAnswer = $this->request('login', array(), $apiUser); - if(version_compare(VERSION, '2.1.0', '>=')) { - $this->apiToken = $apiAnswer['token']; - } + $this->apiToken = $apiAnswer['token']; return $apiAnswer; } diff --git a/system/library/retailcrm/RetailcrmHistoryHelper.php b/system/library/retailcrm/RetailcrmHistoryHelper.php index bc5a718..d21b327 100644 --- a/system/library/retailcrm/RetailcrmHistoryHelper.php +++ b/system/library/retailcrm/RetailcrmHistoryHelper.php @@ -12,7 +12,7 @@ class RetailcrmHistoryHelper { $orders = array(); foreach ($orderHistory as $change) { $change['order'] = self::removeEmpty($change['order']); - if($change['order']['items']) { + if(isset($change['order']['items']) && $change['order']['items']) { $items = array(); foreach($change['order']['items'] as $item) { if(isset($change['created'])) { @@ -23,18 +23,18 @@ class RetailcrmHistoryHelper { $change['order']['items'] = $items; } - if($change['order']['contragent']['contragentType']) { + if(isset($change['order']['contragent']['contragentType']) && $change['order']['contragent']['contragentType']) { $change['order']['contragentType'] = $change['order']['contragent']['contragentType']; unset($change['order']['contragent']); } - if($orders[$change['order']['id']]) { + if(!empty($orders) && $orders[$change['order']['id']]) { $orders[$change['order']['id']] = array_merge($orders[$change['order']['id']], $change['order']); } else { $orders[$change['order']['id']] = $change['order']; } - if($change['item']) { + if(isset($change['item']) && $change['item']) { if($orders[$change['order']['id']]['items'][$change['item']['id']]) { $orders[$change['order']['id']]['items'][$change['item']['id']] = array_merge($orders[$change['order']['id']]['items'][$change['item']['id']], $change['item']); } else { @@ -51,15 +51,15 @@ class RetailcrmHistoryHelper { $orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue']; } } else { - if($fields['delivery'][$change['field']] == 'service') { + if(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']] == 'service'){ $orders[$change['order']['id']]['delivery']['service']['code'] = self::newValue($change['newValue']); - } elseif($fields['delivery'][$change['field']]) { + } elseif(isset($fields['delivery'][$change['field']]) && $fields['delivery'][$change['field']]) { $orders[$change['order']['id']]['delivery'][$fields['delivery'][$change['field']]] = self::newValue($change['newValue']); - } elseif($fields['orderAddress'][$change['field']]) { + } elseif(isset($fields['orderAddress'][$change['field']]) && $fields['orderAddress'][$change['field']]){ $orders[$change['order']['id']]['delivery']['address'][$fields['orderAddress'][$change['field']]] = $change['newValue']; - } elseif($fields['integrationDelivery'][$change['field']]) { + } elseif(isset($fields['integrationDelivery'][$change['field']]) && $fields['integrationDelivery'][$change['field']]) { $orders[$change['order']['id']]['delivery']['service'][$fields['integrationDelivery'][$change['field']]] = self::newValue($change['newValue']); - } elseif($fields['customerContragent'][$change['field']]) { + } elseif(isset($fields['customerContragent'][$change['field']]) && $fields['customerContragent'][$change['field']]) { $orders[$change['order']['id']][$fields['customerContragent'][$change['field']]] = self::newValue($change['newValue']); } elseif(strripos($change['field'], 'custom_') !== false) { $orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']); From 9d9218cf7724583069b798052b93d3bdb22a410a Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Wed, 22 Mar 2017 11:52:11 +0300 Subject: [PATCH 02/40] new files for 2.3 --- .../controller/extension/module/retailcrm.php | 348 ++++++++++++++ .../en-gb/extension/module/retailcrm.php | 31 ++ .../ru-ru/extension/module/retailcrm.php | 31 ++ .../model/extension/retailcrm/custom/.gitkeep | 0 admin/model/extension/retailcrm/customer.php | 51 ++ admin/model/extension/retailcrm/history.php | 455 ++++++++++++++++++ admin/model/extension/retailcrm/icml.php | 336 +++++++++++++ admin/model/extension/retailcrm/order.php | 116 +++++ .../model/extension/retailcrm/references.php | 138 ++++++ .../template/extension/module/retailcrm.tpl | 110 +++++ .../controller/extension/module/retailcrm.php | 108 +++++ .../model/extension/retailcrm/customer.php | 42 ++ catalog/model/extension/retailcrm/order.php | 262 ++++++++++ 13 files changed, 2028 insertions(+) create mode 100644 admin/controller/extension/module/retailcrm.php create mode 100644 admin/language/en-gb/extension/module/retailcrm.php create mode 100644 admin/language/ru-ru/extension/module/retailcrm.php create mode 100644 admin/model/extension/retailcrm/custom/.gitkeep create mode 100644 admin/model/extension/retailcrm/customer.php create mode 100644 admin/model/extension/retailcrm/history.php create mode 100644 admin/model/extension/retailcrm/icml.php create mode 100644 admin/model/extension/retailcrm/order.php create mode 100644 admin/model/extension/retailcrm/references.php create mode 100644 admin/view/template/extension/module/retailcrm.tpl create mode 100644 catalog/controller/extension/module/retailcrm.php create mode 100644 catalog/model/extension/retailcrm/customer.php create mode 100644 catalog/model/extension/retailcrm/order.php diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php new file mode 100644 index 0000000..fc5500f --- /dev/null +++ b/admin/controller/extension/module/retailcrm.php @@ -0,0 +1,348 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ +class ControllerExtensionModuleRetailcrm extends Controller +{ + private $_error = array(); + protected $log, $statuses, $payments, $deliveryTypes, $retailcrm; + public $children, $template; + + /** + * Install method + * + * @return void + */ + public function install() + { + $this->load->model('setting/setting'); + $this->model_setting_setting + ->editSetting('retailcrm', array('retailcrm_status' => 1)); + + $this->load->model('extension/event'); + + $this->model_extension_event + ->addEvent( + 'retailcrm', + 'catalog/model/checkout/order/addOrder/after', + 'extension/module/retailcrm/order_create' + ); + + $this->model_extension_event + ->addEvent( + 'retailcrm', + 'catalog/model/checkout/order/addOrderHistory/after', + 'extension/module/retailcrm/order_edit' + ); + + $this->model_extension_event + ->addEvent( + 'retailcrm', + 'catalog/model/account/customer/addCustomer/after', + 'extension/module/retailcrm/customer_create' + ); + + $this->model_extension_event + ->addEvent( + 'retailcrm', + 'catalog/model/checkout/order/editOrder/after', + 'extension/module/retailcrm/order_edit' + ); + } + + /** + * Uninstall method + * + * @return void + */ + public function uninstall() + { + $this->load->model('setting/setting'); + $this->model_setting_setting + ->editSetting('retailcrm', array('retailcrm_status' => 0)); + + $this->load->model('extension/event'); + $this->model_extension_event->deleteEvent('retailcrm'); + } + + /** + * Setup page + * + * @return void + */ + public function index() + { + + $this->load->model('setting/setting'); + $this->load->model('extension/module'); + $this->load->model('extension/retailcrm/references'); + $this->load->language('extension/module/retailcrm'); + $this->document->setTitle($this->language->get('heading_title')); + $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); + + if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { + if (parse_url($this->request->post['retailcrm_url'])){ + $crm_url = parse_url($this->request->post['retailcrm_url'], PHP_URL_HOST); + $this->request->post['retailcrm_url'] = 'https://'.$crm_url; + } + $this->model_setting_setting->editSetting( + 'retailcrm', + $this->request->post + ); + + $this->session->data['success'] = $this->language->get('text_success'); + $redirect = $this->url->link( + 'extension/module/retailcrm', 'token=' . $this->session->data['token'], + 'SSL' + ); + + $this->response->redirect($redirect); + } + + $text_strings = array( + 'heading_title', + 'text_enabled', + 'text_disabled', + 'button_save', + 'button_cancel', + 'text_notice', + 'retailcrm_title', + 'retailcrm_url', + 'retailcrm_apikey', + 'retailcrm_base_settings', + 'retailcrm_dict_settings', + 'retailcrm_dict_delivery', + 'retailcrm_dict_status', + 'retailcrm_dict_payment', + ); + + $this->load->model('extension/extension'); + $_data = &$data; + + foreach ($text_strings as $text) { + $_data[$text] = $this->language->get($text); + } + + $_data['retailcrm_errors'] = array(); + $_data['saved_settings'] = $this->model_setting_setting + ->getSetting('retailcrm'); + + $url = isset($_data['saved_settings']['retailcrm_url']) + ? $_data['saved_settings']['retailcrm_url'] + : null; + $key = isset($_data['saved_settings']['retailcrm_apikey']) + ? $_data['saved_settings']['retailcrm_apikey'] + : null; + + if (!empty($url) && !empty($key)) { + + $this->retailcrm = new RetailcrmProxy( + $url, + $key, + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $_data['delivery'] = $this->model_extension_retailcrm_references + ->getDeliveryTypes(); + $_data['statuses'] = $this->model_extension_retailcrm_references + ->getOrderStatuses(); + $_data['payments'] = $this->model_extension_retailcrm_references + ->getPaymentTypes(); + + } + + $config_data = array( + 'retailcrm_status' + ); + + foreach ($config_data as $conf) { + if (isset($this->request->post[$conf])) { + $_data[$conf] = $this->request->post[$conf]; + } else { + $_data[$conf] = $this->config->get($conf); + } + } + + if (isset($this->error['warning'])) { + $_data['error_warning'] = $this->error['warning']; + } else { + $_data['error_warning'] = ''; + } + + $_data['breadcrumbs'] = array(); + + $_data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_home'), + 'href' => $this->url->link( + 'common/home', + 'token=' . $this->session->data['token'], 'SSL' + ), + 'separator' => false + ); + + $_data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_module'), + 'href' => $this->url->link( + 'extension/extension/module', + 'token=' . $this->session->data['token'], 'SSL' + ), + 'separator' => ' :: ' + ); + + $_data['breadcrumbs'][] = array( + 'text' => $this->language->get('retailcrm_title'), + 'href' => $this->url->link( + 'extension/module/retailcrm', + 'token=' . $this->session->data['token'], 'SSL' + ), + 'separator' => ' :: ' + ); + + $_data['action'] = $this->url->link( + 'extension/module/retailcrm', + 'token=' . $this->session->data['token'], 'SSL' + ); + + $_data['cancel'] = $this->url->link( + 'extension/extension', + 'token=' . $this->session->data['token'], 'SSL' + ); + + $_data['modules'] = array(); + + if (isset($this->request->post['retailcrm_module'])) { + $_data['modules'] = $this->request->post['retailcrm_module']; + } elseif ($this->config->get('retailcrm_module')) { + $_data['modules'] = $this->config->get('retailcrm_module'); + } + + $this->load->model('design/layout'); + $_data['layouts'] = $this->model_design_layout->getLayouts(); + + $_data['header'] = $this->load->controller('common/header'); + $_data['column_left'] = $this->load->controller('common/column_left'); + $_data['footer'] = $this->load->controller('common/footer'); + + $this->response->setOutput( + $this->load->view('extension/module/retailcrm.tpl', $_data) + ); + } + + /** + * History method + * + * @return void + */ + public function history() + { + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history.php')) { + $this->load->model('extension/retailcrm/custom/history'); + $this->model_extension_retailcrm_custom_history->request(); + } else { + $this->load->model('extension/retailcrm/history'); + $this->model_extension_retailcrm_history->request(); + } + } + + /** + * ICML generation + * + * @return void + */ + public function icml() + { + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/icml.php')) { + $this->load->model('extension/retailcrm/custom/icml'); + $this->model_extension_retailcrm_custom_icml->generateICML(); + } else { + $this->load->model('extension/retailcrm/icml'); + $this->model_extension_retailcrm_icml->generateICML(); + } + } + + /** + * Create order on event + * + * @param int $order_id order identificator + * + * @return void + */ + public function order_create($order_id) + { + $this->load->model('checkout/order'); + $this->load->model('account/order'); + + $data = $this->model_checkout_order->getOrder($order_id); + $data['products'] = $this->model_account_order->getOrderProducts($order_id); + + if (!isset($data['fromApi'])) { + $this->load->model('setting/setting'); + $status = $this->model_setting_setting->getSetting('retailcrm'); + $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']); + } + } + + /** + * Export orders + * + * + */ + public function export() { + + $this->load->model('customer/customer'); + $customers = $this->model_customer_customer->getCustomers(); + + $this->load->model('extension/retailcrm/customer'); + $this->model_extension_retailcrm_customer->uploadToCrm($customers); + + $this->load->model('sale/order'); + $orders = $this->model_sale_order->getOrders(); + + $fullOrders = array(); + foreach($orders as $order) { + $fullOrder = $this->model_sale_order->getOrder($order['order_id']); + + $fullOrder['order_total'] = $this->model_sale_order->getOrderTotals($order['order_id']); + + $fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']); + foreach($fullOrder['products'] as $key=>$product) { + $fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); + } + + $fullOrders[] = $fullOrder; + } + + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->uploadToCrm($fullOrders); + } + + /** + * Validate + * + * @return bool + */ + private function validate() + { + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { + $this->_error['warning'] = $this->language->get('error_permission'); + } + + if (!$this->_error) { + return true; + } else { + return false; + } + } +} diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php new file mode 100644 index 0000000..f1baabb --- /dev/null +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -0,0 +1,31 @@ +load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(empty($customers)) + return false; + if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $customersToCrm = array(); + + foreach($customers as $customer) { + $customersToCrm[] = $this->process($customer); + } + + $chunkedCustomers = array_chunk($customersToCrm, 50); + + foreach($chunkedCustomers as $customersPart) { + $this->retailcrmApi->customersUpload($customersPart); + } + } + + private function process($customer) { + $customerToCrm = array( + 'externalId' => $customer['customer_id'], + 'firstName' => $customer['firstname'], + 'lastName' => $customer['lastname'], + 'email' => $customer['email'], + 'phones' => array( + array( + 'number' => $customer['telephone'] + ) + ), + 'createdAt' => $customer['date_added'] + ); + + return $customerToCrm; + } +} diff --git a/admin/model/extension/retailcrm/history.php b/admin/model/extension/retailcrm/history.php new file mode 100644 index 0000000..eb19ffb --- /dev/null +++ b/admin/model/extension/retailcrm/history.php @@ -0,0 +1,455 @@ +load->model('setting/setting'); + $this->load->model('setting/store'); + $this->load->model('user/api'); + $this->load->model('sale/order'); + $this->load->model('customer/customer'); + $this->load->model('extension/retailcrm/references'); + $this->load->model('catalog/product'); + $this->load->model('catalog/option'); + $this->load->model('localisation/zone'); + + $this->load->language('extension/module/retailcrm'); + + $settings = $this->model_setting_setting->getSetting('retailcrm'); + $history = $this->model_setting_setting->getSetting('retailcrm_history'); + $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); + + $url = isset($settings['retailcrm_url']) ? $settings['retailcrm_url'] : null; + $key = isset($settings['retailcrm_apikey']) ? $settings['retailcrm_apikey'] : null; + + if (empty($url) || empty($key)) { + $this->log->addNotice('You need to configure retailcrm module first.'); + return false; + } + + $this->opencartApiClient = new OpencartApiClient($this->registry); + + $crm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $lastRun = !empty($history['retailcrm_history']) + ? new DateTime($history['retailcrm_history']) + : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); + + $packs = $crm->ordersHistory(array( + 'startDate' => $lastRun->format('Y-m-d H:i:s'), + ), 1, 100); + if(!$packs->isSuccessful() && count($packs->history) <= 0) + return false; + $orders = RetailcrmHistoryHelper::assemblyOrder($packs->history); + + $generatedAt = $packs['generatedAt']; + + $this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); + $this->totalSettings = $this->model_setting_setting->getSetting('total'); + $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); + + $this->delivery = array_flip($settings['retailcrm_delivery']); + $this->payment = array_flip($settings['retailcrm_payment']); + $this->status = array_flip($settings['retailcrm_status']); + + $this->ocPayment = $this->model_extension_retailcrm_references + ->getOpercartPaymentTypes(); + + $this->ocDelivery = $this->model_extension_retailcrm_references + ->getOpercartDeliveryTypes(); + + $this->zones = $this->model_localisation_zone->getZones(); + + $updatedOrders = array(); + $newOrders = array(); + + foreach ($orders as $order) { + + if (isset($order['deleted'])) continue; + + if (isset($order['externalId'])) { + $updatedOrders[] = $order['id']; + } else { + $newOrders[] = $order['id']; + } + } + + unset($orders); + + if (!empty($newOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $newOrders)); + if ($orders) { + $this->createResult = $this->createOrders($orders['orders']); + } + } + + if (!empty($updatedOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $updatedOrders)); + if ($orders) { + $this->updateOrders($orders['orders']); + } + } + + $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); + + if (!empty($this->createResult['customers'])) { + $crm->customersFixExternalIds($this->createResult['customers']); + } + + if (!empty($this->createResult['orders'])) { + $crm->ordersFixExternalIds($this->createResult['orders']); + } + } + + protected function updateOrders($orders) + { + foreach ($orders as $order) { + $store = $this->config->get('config_store_id'); + + $data = array(); + + $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; + $data['firstname'] = $order['firstName']; + $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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']; + + $region = ''; + + if (is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + + $data['payment'] = $this->payment[$order['paymentType']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$order['paymentType']]; + + // 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) { + //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $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['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['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) { + $cData = array( + 'store_id' => 0, + 'customer_group_id' => '1', + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'email' => $order['email'], + 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', + 'fax' => '', + 'newsletter' => 0, + 'password' => 'tmppass', + 'status' => 1, + 'address' => array( + array( + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['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' => '0', + 'country_id' => 0 + ) + ), + ); + + + $this->model_customer_customer->addCustomer($cData); + + if (!empty($order['email'])) { + $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); + $customer_id = $tryToFind['customer_id']; + } else { + $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); + $customer_id = $last[0]['customer_id']; + } + + $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); + } + + $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'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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']; + + $region = ''; + + if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + $data['payment'] = $this->payment[$order['paymentType']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$order['paymentType']]; + + // 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) { + $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $data['order_product'][] = array( + 'product_id' => $item['offer']['externalId'], + 'name' => $item['offer']['name'], + 'quantity' => $item['quantity'], + 'price' => $item['initialPrice'], + 'total' => $item['initialPrice'] * $item['quantity'], + 'model' => $product['model'], + + // this data will not retrive from crm + 'order_product_id' => '', + 'tax' => 0, + 'reward' => 0 + ); + } + + $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['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['total_sort_order'] + ) + ); + + $data['fromApi'] = true; + $data['order_status_id'] = 1; + + $this->opencartApiClient->addOrder($data); + + $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); + + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['order_id']); + } + + return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix); + } +} diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php new file mode 100644 index 0000000..f2f3d47 --- /dev/null +++ b/admin/model/extension/retailcrm/icml.php @@ -0,0 +1,336 @@ +load->language('extension/module/retailcrm'); + $this->load->model('catalog/category'); + $this->load->model('catalog/product'); + $this->load->model('catalog/option'); + $this->load->model('catalog/manufacturer'); + + $string = ' + + + '.$this->config->get('config_name').' + + + + + '; + + $xml = new SimpleXMLElement( + $string, + LIBXML_NOENT |LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_PARSEHUGE + ); + + $this->dd = new DOMDocument(); + $this->dd->preserveWhiteSpace = false; + $this->dd->formatOutput = true; + $this->dd->loadXML($xml->asXML()); + + $this->eCategories = $this->dd + ->getElementsByTagName('categories')->item(0); + $this->eOffers = $this->dd + ->getElementsByTagName('offers')->item(0); + + $this->addCategories(); + $this->addOffers(); + + $this->dd->saveXML(); + + $downloadPath = DIR_SYSTEM . '/../'; + + if (!file_exists($downloadPath)) { + mkdir($downloadPath, 0755); + } + + $this->dd->save($downloadPath . 'retailcrm.xml'); + } + + /** + * + */ + private function addCategories() + { + $categories = $this->model_catalog_category->getCategories(array()); + foreach($categories as $category) { + $category = $this->model_catalog_category->getCategory($category['category_id']); + + $e = $this->eCategories->appendChild( + $this->dd->createElement( + 'category', $category['name'] + ) + ); + + $e->setAttribute('id', $category['category_id']); + + if ($category['parent_id'] > 0) { + $e->setAttribute('parentId', $category['parent_id']); + } + } + + } + + private function addOffers() + { + $offerManufacturers = array(); + + $manufacturers = $this->model_catalog_manufacturer + ->getManufacturers(array()); + + foreach ($manufacturers as $manufacturer) { + $offerManufacturers[ + $manufacturer['manufacturer_id'] + ] = $manufacturer['name']; + } + + $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']] = (float)$optionValue['price']; + } + } else { + foreach($offers as $optionKey => $optionCost) { + unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями + foreach($requiredOption['product_option_value'] as $optionValue) { + $offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price']; + } + } + } + } + // Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть. + 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']] = (float)$optionValue['price']; + } + } else { + foreach($offers as $optionKey => $optionCost) { + foreach($notRequiredOption['product_option_value'] as $optionValue) { + $offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = $optionCost + (float)$optionValue['price']; + } + } + } + } + if(empty($offers)) { + $offers = array('0:0-0' => '0'); + } + + foreach($offers as $optionsString => $optionsTotalCost) { + $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); + $e = $this->eOffers->appendChild($this->dd->createElement('offer')); + if(!empty($offerId)) + $e->setAttribute('id', $product['product_id'].'#'.$offerId); + else + $e->setAttribute('id', $product['product_id']); + $e->setAttribute('productId', $product['product_id']); + $e->setAttribute('quantity', $product['quantity']); + /** + * Offer activity + */ + $activity = $product['status'] == 1 ? 'Y' : 'N'; + $e->appendChild( + $this->dd->createElement('productActivity') + )->appendChild( + $this->dd->createTextNode($activity) + ); + /** + * Offer categories + */ + $categories = $this->model_catalog_product + ->getProductCategories($product['product_id']); + if (!empty($categories)) { + foreach ($categories as $category) { + $e->appendChild($this->dd->createElement('categoryId')) + ->appendChild( + $this->dd->createTextNode($category) + ); + } + } + /** + * Name & price + */ + $e->appendChild($this->dd->createElement('productName')) + ->appendChild($this->dd->createTextNode($product['name'])); + if(!empty($options)) { + $optionsString = array(); + foreach($options as $option) { + $optionsString[] = $option['name'].': '.$option['value']; + } + $optionsString = ' ('.implode(', ', $optionsString).')'; + $e->appendChild($this->dd->createElement('name')) + ->appendChild($this->dd->createTextNode($product['name'].$optionsString)); + } else { + $e->appendChild($this->dd->createElement('name')) + ->appendChild($this->dd->createTextNode($product['name'])); + } + $e->appendChild($this->dd->createElement('price')) + ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); + /** + * Vendor + */ + if ($product['manufacturer_id'] != 0) { + $e->appendChild($this->dd->createElement('vendor')) + ->appendChild( + $this->dd->createTextNode( + $offerManufacturers[$product['manufacturer_id']] + ) + ); + } + /** + * Image + */ + if ($product['image']) { + $image = $this->generateImage($product['image']); + $e->appendChild($this->dd->createElement('picture')) + ->appendChild($this->dd->createTextNode($image)); + } + /** + * Url + */ + $this->url = new Url( + HTTP_CATALOG, + $this->config->get('config_secure') + ? HTTP_CATALOG + : HTTPS_CATALOG + ); + $e->appendChild($this->dd->createElement('url')) + ->appendChild( + $this->dd->createTextNode( + $this->url->link( + 'product/product&product_id=' . $product['product_id'] + ) + ) + ); + // Options + if(!empty($options)) { + foreach($options as $optionKey => $optionData) { + $param = $this->dd->createElement('param'); + $param->setAttribute('code', $optionKey); + $param->setAttribute('name', $optionData['name']); + $param->appendChild($this->dd->createTextNode($optionData['value'])); + $e->appendChild($param); + } + } + if ($product['sku']) { + $sku = $this->dd->createElement('param'); + $sku->setAttribute('code', 'article'); + $sku->setAttribute('name', $this->language->get('article')); + $sku->appendChild($this->dd->createTextNode($product['sku'])); + $e->appendChild($sku); + } + if ($product['weight'] != '') { + $weight = $this->dd->createElement('param'); + $weight->setAttribute('code', 'weight'); + $weight->setAttribute('name', $this->language->get('weight')); + $weightValue = (isset($offer['weight_class'])) + ? round($product['weight'], 3) . ' ' . $product['weight_class'] + : round($product['weight'], 3) + ; + $weight->appendChild($this->dd->createTextNode($weightValue)); + $e->appendChild($weight); + } + } + } + } + + /** + * @param $image + * @return mixed + */ + private function generateImage($image) + { + $this->load->model('tool/image'); + + $currentTheme = $this->config->get('config_theme'); + $width = $this->config->get($currentTheme . '_image_related_width') ? $this->config->get($currentTheme . '_image_related_width') : 200; + $height = $this->config->get($currentTheme . '_image_related_height') ? $this->config->get($currentTheme . '_image_related_height') : 200; + + return $this->model_tool_image->resize( + $image, + $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])) { + $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'] + ); + } +} diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php new file mode 100644 index 0000000..77fa54d --- /dev/null +++ b/admin/model/extension/retailcrm/order.php @@ -0,0 +1,116 @@ +load->model('catalog/product'); + + $this->load->model('setting/setting'); + $this->settings = $this->model_setting_setting->getSetting('retailcrm'); + + $ordersToCrm = array(); + + foreach($orders as $order) { + $ordersToCrm[] = $this->process($order); + } + + $chunkedOrders = array_chunk($ordersToCrm, 50); + + foreach($chunkedOrders as $ordersPart) { + $this->retailcrmApi->ordersUpload($ordersPart); + } + } + + private function process($order_data) { + $order = array(); + + $payment_code = $order_data['payment_code']; + $delivery_code = $order_data['shipping_code']; + + $order['externalId'] = $order_data['order_id']; + $order['firstName'] = $order_data['firstname']; + $order['lastName'] = $order_data['lastname']; + $order['phone'] = $order_data['telephone']; + $order['customerComment'] = $order_data['comment']; + + if(!empty($order_data['email'])) { + $order['email'] = $order_data['email']; + } + + $order['customer']['externalId'] = $order_data['customer_id']; + + $deliveryCost = 0; + $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; + + foreach ($orderTotals as $totals) { + if ($totals['code'] == 'shipping') { + $deliveryCost = $totals['value']; + } + } + + $order['createdAt'] = $order_data['date_added']; + $order['paymentType'] = $this->settings['retailcrm_payment'][$payment_code]; + + $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; + + $order['delivery'] = array( + 'code' => !empty($delivery_code) ? $this->settings['retailcrm_delivery'][$delivery_code] : '', + 'cost' => $deliveryCost, + 'address' => array( + 'index' => $order_data['shipping_postcode'], + 'city' => $order_data['shipping_city'], + 'country' => $order_data['shipping_country_id'], + 'region' => $order_data['shipping_zone_id'], + 'text' => implode(', ', array( + $order_data['shipping_postcode'], + $country, + $order_data['shipping_city'], + $order_data['shipping_address_1'], + $order_data['shipping_address_2'] + )) + ) + ); + + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; + $offerOptions = array('select', 'radio'); + + foreach ($orderProducts as $product) { + $offerId = ''; + + if(!empty($product['option'])) { + $options = array(); + + $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + + foreach($product['option'] as $option) { + if(!in_array($option['type'], $offerOptions)) continue; + foreach($productOptions as $productOption) { + if($productOption['product_option_id'] = $option['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; + } + } + } + } + } + + ksort($options); + + $offerId = array(); + foreach($options as $optionKey => $optionValue) { + $offerId[] = $optionKey.'-'.$optionValue; + } + $offerId = implode('_', $offerId); + } + + $order['items'][] = array( + 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'], + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + } + + return $order; + } +} diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php new file mode 100644 index 0000000..b764c55 --- /dev/null +++ b/admin/model/extension/retailcrm/references.php @@ -0,0 +1,138 @@ + $this->getOpercartDeliveryTypes(), + 'retailcrm' => $this->getApiDeliveryTypes() + ); + } + + public function getOrderStatuses() + { + return array( + 'opencart' => $this->getOpercartOrderStatuses(), + 'retailcrm' => $this->getApiOrderStatuses() + ); + } + + public function getPaymentTypes() + { + return array( + 'opencart' => $this->getOpercartPaymentTypes(), + 'retailcrm' => $this->getApiPaymentTypes() + ); + } + + public function getOpercartDeliveryTypes() + { + $deliveryMethods = array(); + $files = glob(DIR_APPLICATION . 'controller/extension/shipping/*.php'); + + if ($files) { + foreach ($files as $file) { + $extension = basename($file, '.php'); + + $this->load->language('extension/shipping/' . $extension); + + if ($this->config->get($extension . '_status')) { + $deliveryMethods[$extension.'.'.$extension] = strip_tags( + $this->language->get('heading_title') + ); + } + } + } + + return $deliveryMethods; + } + + public function getOpercartOrderStatuses() + { + $this->load->model('localisation/order_status'); + + return $this->model_localisation_order_status + ->getOrderStatuses(array()); + } + + public function getOpercartPaymentTypes() + { + $paymentTypes = array(); + $files = glob(DIR_APPLICATION . 'controller/extension/payment/*.php'); + + if ($files) { + foreach ($files as $file) { + $extension = basename($file, '.php'); + + $this->load->language('extension/payment/' . $extension); + + if ($this->config->get($extension . '_status')) { + $paymentTypes[$extension] = strip_tags( + $this->language->get('heading_title') + ); + } + } + } + + return $paymentTypes; + } + + public function getApiDeliveryTypes() + { + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $response = $this->retailcrm->deliveryTypesList(); + + return ($response === false) ? array() : $response->deliveryTypes; + } + } + + public function getApiOrderStatuses() + { + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $response = $this->retailcrm->statusesList(); + + return ($response === false) ? array() : $response->statuses; + } + } + + public function getApiPaymentTypes() + { + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $response = $this->retailcrm->paymentTypesList(); + + return ($response === false) ? array() : $response->paymentTypes; + } + } +} diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl new file mode 100644 index 0000000..144f68b --- /dev/null +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -0,0 +1,110 @@ + + + +
+ +
+ +
+ + +
+ + + + + + +
+
+
+ + +

+
+
+ +
+
+
+ +
+ + + + + +
+ + +

+ +

+ $value): ?> +
+ + +
+ + +

+ + +
+ + +
+ + +

+ $value): ?> +
+ + +
+ + + + + +
+
+
+
+
+ + diff --git a/catalog/controller/extension/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php new file mode 100644 index 0000000..7b8455d --- /dev/null +++ b/catalog/controller/extension/module/retailcrm.php @@ -0,0 +1,108 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + */ +class ControllerExtensionModuleRetailcrm extends Controller +{ + /** + * Create order on event + * + * @param int $order_id order identificator + * + * @return void + */ + public function order_create($parameter1, $parameter2 = null, $parameter3 = null) + { + $this->load->model('checkout/order'); + $this->load->model('account/order'); + + $order_id = $parameter3; + + $data = $this->model_checkout_order->getOrder($order_id); + + $data['products'] = $this->model_account_order->getOrderProducts($order_id); + foreach($data['products'] as $key => $product) { + $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); + + if(!empty($productOptions)) + $data['products'][$key]['option'] = $productOptions; + } + + if (!isset($data['fromApi'])) { + $this->load->model('setting/setting'); + $status = $this->model_setting_setting->getSetting('retailcrm'); + if ($data['order_status_id'] > 0) { + $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + } + + $data['totals'][] = array( + 'code' => 'shipping', + 'value' => $this->session->data['shipping_method']['cost'] + ); + + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']); + } + } + + public function order_edit($parameter1, $parameter2 = null) { + $order_id = $parameter2[0]; + + $this->load->model('checkout/order'); + $this->load->model('account/order'); + + $data = $this->model_checkout_order->getOrder($order_id); + + if($data['order_status_id'] == 0) return; + + $data['products'] = $this->model_account_order->getOrderProducts($order_id); + + foreach($data['products'] as $key => $product) { + $productOptions = $this->model_account_order->getOrderOptions($order_id, $product['order_product_id']); + + if(!empty($productOptions)) + $data['products'][$key]['option'] = $productOptions; + } + + if (!isset($data['fromApi'])) { + $this->load->model('setting/setting'); + $status = $this->model_setting_setting->getSetting('retailcrm'); + + if ($data['order_status_id'] > 0) { + $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + } + + $data['totals'][] = array( + 'code' => 'shipping', + 'value' => isset($this->session->data['shipping_method']) ? $this->session->data['shipping_method']['cost'] : '' + ); + + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->changeInCrm($data, $data['order_id']); + } + } + + /** + * Create customer on event + * + * @param int $customerId customer identificator + * + * @return void + */ + public function customer_create($parameter1, $parameter2 = null, $parameter3 = null) { + $customerId = $parameter3; + + $this->load->model('account/customer'); + $customer = $this->model_account_customer->getCustomer($customerId); + + $this->load->model('extension/retailcrm/customer'); + $this->model_extension_retailcrm_customer->sendToCrm($customer); + } +} diff --git a/catalog/model/extension/retailcrm/customer.php b/catalog/model/extension/retailcrm/customer.php new file mode 100644 index 0000000..1b1f768 --- /dev/null +++ b/catalog/model/extension/retailcrm/customer.php @@ -0,0 +1,42 @@ +load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(empty($customer)) + return false; + if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $customerToCrm = $this->process($customer); + + $this->retailcrmApi->customersCreate($customerToCrm); + } + + private function process($customer) { + $customerToCrm = array( + 'externalId' => $customer['customer_id'], + 'firstName' => $customer['firstname'], + 'lastName' => $customer['lastname'], + 'email' => $customer['email'], + 'phones' => array( + array( + 'number' => $customer['telephone'] + ) + ), + 'createdAt' => $customer['date_added'] + ); + + return $customerToCrm; + } +} diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php new file mode 100644 index 0000000..873d2ff --- /dev/null +++ b/catalog/model/extension/retailcrm/order.php @@ -0,0 +1,262 @@ +request->post['fromApi'])) return; + + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->load->model('catalog/product'); + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $order = array(); + + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; + } + } + + unset($customers); + + $order['externalId'] = $order_id; + $order['firstName'] = $order_data['firstname']; + $order['lastName'] = $order_data['lastname']; + $order['phone'] = $order_data['telephone']; + $order['customerComment'] = $order_data['comment']; + + if(!empty($order_data['email'])) { + $order['email'] = $order_data['email']; + } + + $deliveryCost = 0; + $altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : ""; + $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ; + + if (!empty($orderTotals)) { + foreach ($orderTotals as $totals) { + if ($totals['code'] == 'shipping') { + $deliveryCost = $totals['value']; + } + } + } + + $order['createdAt'] = $order_data['date_added']; + + $payment_code = $order_data['payment_code']; + $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; + + if(!isset($order_data['shipping_iso_code_2']) && isset($order_data['shipping_country_id'])) { + $this->load->model('localisation/country'); + $shipping_country = $this->model_localisation_country->getCountry($order_data['shipping_country_id']); + $order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2']; + } + + $delivery_code = $order_data['shipping_code']; + $order['delivery'] = array( + 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', + 'cost' => $deliveryCost, + 'address' => array( + 'index' => $order_data['shipping_postcode'], + 'city' => $order_data['shipping_city'], + 'countryIso' => $order_data['shipping_iso_code_2'], + 'region' => $order_data['shipping_zone'], + 'text' => implode(', ', array( + $order_data['shipping_postcode'], + (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '', + $order_data['shipping_city'], + $order_data['shipping_address_1'], + $order_data['shipping_address_2'] + )) + ) + ); + + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; + $offerOptions = array('select', 'radio'); + + foreach ($orderProducts as $product) { + $offerId = ''; + + if(!empty($product['option'])) { + $options = array(); + + $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + + foreach($product['option'] as $option) { + if(!in_array($option['type'], $offerOptions)) continue; + foreach($productOptions as $productOption) { + if($productOption['product_option_id'] = $option['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; + } + } + } + } + } + + ksort($options); + + $offerId = array(); + foreach($options as $optionKey => $optionValue) { + $offerId[] = $optionKey.'-'.$optionValue; + } + $offerId = implode('_', $offerId); + } + + $order['items'][] = array( + 'offer' => array( + 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + } + + if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { + $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; + } + + $this->retailcrm->ordersCreate($order); + } + } + + public function changeInCrm($order_data, $order_id) + { + if(isset($this->request->post['fromApi'])) return; + + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->load->model('catalog/product'); + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $order = array(); + + $payment_code = $order_data['payment_code']; + $delivery_code = $order_data['shipping_code']; + + $order['externalId'] = $order_id; + $order['firstName'] = $order_data['firstname']; + $order['lastName'] = $order_data['lastname']; + $order['phone'] = $order_data['telephone']; + $order['customerComment'] = $order_data['comment']; + + if(!empty($order_data['email'])) { + $order['email'] = $order_data['email']; + } + + $deliveryCost = 0; + $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; + + foreach ($orderTotals as $totals) { + if ($totals['code'] == 'shipping') { + $deliveryCost = $totals['value']; + } + } + + $order['createdAt'] = $order_data['date_added']; + $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; + + $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; + + $order['delivery'] = array( + 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', + 'address' => array( + 'index' => $order_data['shipping_postcode'], + 'city' => $order_data['shipping_city'], + 'country' => $order_data['shipping_country_id'], + 'region' => $order_data['shipping_zone_id'], + 'text' => implode(', ', array( + $order_data['shipping_postcode'], + $country, + $order_data['shipping_city'], + $order_data['shipping_address_1'], + $order_data['shipping_address_2'] + )) + ) + ); + if(!empty($deliveryCost)){ + $order['delivery']['cost'] = $deliveryCost; + } + + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; + $offerOptions = array('select', 'radio'); + + foreach ($orderProducts as $product) { + $offerId = ''; + + if(!empty($product['option'])) { + $options = array(); + + $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + + foreach($product['option'] as $option) { + if(!in_array($option['type'], $offerOptions)) continue; + foreach($productOptions as $productOption) { + if($productOption['product_option_id'] = $option['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; + } + } + } + } + } + + ksort($options); + + $offerId = array(); + foreach($options as $optionKey => $optionValue) { + $offerId[] = $optionKey.'-'.$optionValue; + } + $offerId = implode('_', $offerId); + } + + $order['items'][] = array( + 'offer' => array( + 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + } + + if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { + $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; + } + + $this->retailcrm->ordersEdit($order); + } + } +} From 3e70d2efadb75d2370ed959ada1c35827ea6a771 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Wed, 22 Mar 2017 12:04:42 +0300 Subject: [PATCH 03/40] docs --- Changelog.md | 39 --------------------------------------- README.md | 7 ++++++- README.ru.md | 7 ++++++- 3 files changed, 12 insertions(+), 41 deletions(-) delete mode 100644 Changelog.md diff --git a/Changelog.md b/Changelog.md deleted file mode 100644 index 47bf1b0..0000000 --- a/Changelog.md +++ /dev/null @@ -1,39 +0,0 @@ -Changelog -========= - -####v0.3.0 - -* Расширена библиотека клиента -* Добавлена возможность кастомизации моделей заказа через vqmod -* Устранены мелкие баги, проведен рефакторинг кода. - - -####v0.2.0 - -Общие изменения - -* Код приведен в состоянии совместимости с PHP 5.2 -* Убрана необходимость собирать пакет через composer -* Библиотека api-client-php обновлена до последней версии и добавлена в стандартную поставку -* Переименованы методы, пути и значения ключей конфигурации в связи с ребрендингом -* Временая метка последнего запуска получения истории перенесена в таблицу конфигурации БД - -Выгрузка каталога (ICML) - -* Генерация обновлена в соответствии с последними измениями формата файла выгрузки -* Генерация вынесена в отдельный класс -* Добавлена возможность добавлять подкатегории -* Скорректировано указание активности офера -* Убрана генерация размера офера вследствие кастомизации этого параметра в разных магазинах - -####v0.1.1 -* Устранена ошибка редактирования, при которой терялась часть данных при получении истории из CRM -* Оптимизирован код получения и обработки истории заказов -* Актуализированы переводы - -####v.0.1 -* Реализован интерфейс настроек модуля -* Реализована отправка данных о заказе/клиенте в CRM -* Реализована выгрузка каталога (cron only) -* Реализовано получение данных о заказах, сделанных на стороне CRM (cron only) - diff --git a/README.md b/README.md index efa3e3e..a9a14ff 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,12 @@ Opencart module =============== -Module allows integrate CMS Opencart 2.x with [retailCRM](http://retailcrm.pro) +Module allows integrate CMS Opencart >= 2.3 with [retailCRM](http://retailcrm.pro) + +### Previous versions: + +[v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) +[v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Features: diff --git a/README.ru.md b/README.ru.md index 44bc3ef..8a79141 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,7 +1,12 @@ Opencart module =============== -Модуль интеграции CMS Openacart 2.x c [RetailCRM](http://retailcrm.ru) +Модуль интеграции CMS Opencart >= 2.3 c [RetailCRM](http://retailcrm.ru) + +### Предыдущие версии: + +[v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) +[v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Модуль позволяет: From cbbf80bb44927c6486ea60d859b4f206c91f6794 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Wed, 22 Mar 2017 12:06:44 +0300 Subject: [PATCH 04/40] docs --- README.md | 1 + README.ru.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README.md b/README.md index a9a14ff..417fc0e 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ Module allows integrate CMS Opencart >= 2.3 with [retailCRM](http://retailcrm.pr ### Previous versions: [v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) + [v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Features: diff --git a/README.ru.md b/README.ru.md index 8a79141..0e5d119 100644 --- a/README.ru.md +++ b/README.ru.md @@ -6,6 +6,7 @@ Opencart module ### Предыдущие версии: [v1.x](https://github.com/retailcrm/opencart-module/tree/v1.x) + [v2.x (2.0, 2.1, 2.2)](https://github.com/retailcrm/opencart-module/tree/v2.2) #### Модуль позволяет: From 66054723296c455ad1f38177bc6cd5fdf88d169a Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Mon, 27 Mar 2017 16:09:27 +0300 Subject: [PATCH 05/40] =?UTF-8?q?=09=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE:=20=20=20=20=20=20admin/controller/extension/modul?= =?UTF-8?q?e/retailcrm.php=20=09=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=BE:=20=20=20=20=20=20admin/model/extension/retailcrm/refere?= =?UTF-8?q?nces.php=20=09=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=BE:?= =?UTF-8?q?=20=20=20=20=20=20admin/view/stylesheet/retailcrm.css=20=09?= =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=BE:=20=20=20=20?= =?UTF-8?q?=20=20admin/view/template/extension/module/retailcrm.tpl=20=09?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D1=8B=D0=B9=20=D1=84=D0=B0=D0=B9=D0=BB:=20?= =?UTF-8?q?=20=20=20catalog/controller/api/retailcrm.php?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/extension/module/retailcrm.php | 5 +- .../model/extension/retailcrm/references.php | 33 +++------ admin/view/stylesheet/retailcrm.css | 1 + .../template/extension/module/retailcrm.tpl | 30 ++++++-- catalog/controller/api/retailcrm.php | 74 +++++++++++++++++++ 5 files changed, 113 insertions(+), 30 deletions(-) create mode 100644 catalog/controller/api/retailcrm.php diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index fc5500f..24c26dd 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -81,7 +81,7 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function index() { - + $this->load->model('localisation/country'); $this->load->model('setting/setting'); $this->load->model('extension/module'); $this->load->model('extension/retailcrm/references'); @@ -231,7 +231,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['header'] = $this->load->controller('common/header'); $_data['column_left'] = $this->load->controller('common/column_left'); $_data['footer'] = $this->load->controller('common/footer'); - + $_data['countries'] = $this->model_localisation_country->getCountries(); + $this->response->setOutput( $this->load->view('extension/module/retailcrm.tpl', $_data) ); diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index b764c55..79d7564 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -5,9 +5,20 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; class ModelExtensionRetailcrmReferences extends Model { protected $retailcrm; + private $opencartApiClient; + + public function getOpercartDeliveryTypes() + { + $this->load->model('user/api'); + $this->opencartApiClient = new OpencartApiClient($this->registry); + + return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array()); + } public function getDeliveryTypes() { + $this->load->model('setting/store'); + return array( 'opencart' => $this->getOpercartDeliveryTypes(), 'retailcrm' => $this->getApiDeliveryTypes() @@ -30,28 +41,6 @@ class ModelExtensionRetailcrmReferences extends Model ); } - public function getOpercartDeliveryTypes() - { - $deliveryMethods = array(); - $files = glob(DIR_APPLICATION . 'controller/extension/shipping/*.php'); - - if ($files) { - foreach ($files as $file) { - $extension = basename($file, '.php'); - - $this->load->language('extension/shipping/' . $extension); - - if ($this->config->get($extension . '_status')) { - $deliveryMethods[$extension.'.'.$extension] = strip_tags( - $this->language->get('heading_title') - ); - } - } - } - - return $deliveryMethods; - } - public function getOpercartOrderStatuses() { $this->load->model('localisation/order_status'); diff --git a/admin/view/stylesheet/retailcrm.css b/admin/view/stylesheet/retailcrm.css index 43cbeb6..5c3b88f 100644 --- a/admin/view/stylesheet/retailcrm.css +++ b/admin/view/stylesheet/retailcrm.css @@ -1,2 +1,3 @@ .retailcrm_unit {margin-bottom: 10px;} .retailcrm_unit input {width: 30%;} +.checkbox input{width: auto;} diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index 144f68b..a77bb21 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -45,6 +45,19 @@
+

+
+
+ +
+ +
+ +
+
@@ -56,16 +69,21 @@

- $value): ?> -
- $v): ?> - + - + +
@@ -107,4 +125,4 @@ - + \ No newline at end of file diff --git a/catalog/controller/api/retailcrm.php b/catalog/controller/api/retailcrm.php new file mode 100644 index 0000000..00ad266 --- /dev/null +++ b/catalog/controller/api/retailcrm.php @@ -0,0 +1,74 @@ +load->model('localisation/country'); + $this->load->model('setting/setting'); + + $countries = $this->model_setting_setting->getSetting('retailcrm')['retailcrm_country']; + $deliveryTypes = array(); + + foreach ($countries as $country) { + $deliveryTypes = array_merge($deliveryTypes, $this->getDeliveryTypesByZones($country)); + } + + if (isset($this->request->server['HTTP_ORIGIN'])) { + $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']); + $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); + $this->response->addHeader('Access-Control-Max-Age: 1000'); + $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); + } + + $this->response->addHeader('Content-Type: application/json'); + $this->response->setOutput(json_encode($deliveryTypes)); + } + + protected function getDeliveryTypesByZones($country_id) + { + $this->load->model('localisation/zone'); + $this->load->model('localisation/country'); + $this->load->model('extension/extension'); + + $shippingModules = $this->model_extension_extension->getExtensions('shipping'); + $zones = $this->model_localisation_zone->getZonesByCountryId($country_id); + $country = $this->model_localisation_country->getCountry($country_id); + $quote_data = array(); + + foreach ($zones as $zone) { + $address = array( + 'country_id' => $country_id, + 'zone_id' => $zone['zone_id'], + 'iso_code_2' => $country['iso_code_2'], + 'iso_code_3' => $country['iso_code_3'], + 'zone_code' => $zone['code'], + 'postcode' => '', + 'city' => '' + ); + + foreach ($shippingModules as $shippingModule) { + + $this->load->model('extension/shipping/' . $shippingModule['code']); + + if ($this->config->get($shippingModule['code'] . '_status')) { + if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { + $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); + } + } + } + } + + $deliveryTypes = array(); + + foreach ($quote_data as $shipping) { + + foreach ($shipping['quote'] as $shippingMethod) { + $deliveryTypes[$shipping['code']]['title'] = $shipping['title']; + $deliveryTypes[$shipping['code']][$shippingMethod['code']] = $shippingMethod; + } + + } + + return $deliveryTypes; + } +} From 617ee4491cbbd1e935370e67472b12c08662f584 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Mon, 27 Mar 2017 16:37:03 +0300 Subject: [PATCH 06/40] =?UTF-8?q?=09=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE:=20=20=20=20=20=20admin/language/en-gb/extension/m?= =?UTF-8?q?odule/retailcrm.php=20=09=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE:=20=20=20=20=20=20admin/language/ru-ru/extension/m?= =?UTF-8?q?odule/retailcrm.php?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- admin/language/en-gb/extension/module/retailcrm.php | 1 + admin/language/ru-ru/extension/module/retailcrm.php | 1 + 2 files changed, 2 insertions(+) diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index f1baabb..b3e8e7e 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -10,6 +10,7 @@ $_['text_success'] = 'Setting saved'; $_['text_notice'] = 'Warning! Timezone in CRM & your shop must be equal, you must setup it here:'; $_['retailcrm_base_settings'] = 'Connection settings'; $_['retailcrm_dict_settings'] = 'Dictionary settings'; +$_['retailcrm_countries_settings'] = 'Trading zones setting'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index b2062ff..892924d 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -10,6 +10,7 @@ $_['text_success'] = 'Настройки успешно сохра $_['text_notice'] = 'Внимание! Часовой пояс в CRM должен совпадать с часовым поясом в магазине, настроки часового пояса CRM можно задать по адресу:'; $_['retailcrm_base_settings'] = 'Настройки соединения'; $_['retailcrm_dict_settings'] = 'Настройки соответствия справочников'; +$_['retailcrm_countries_settings'] = 'Настройка торговых зон'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; From fd3793b8127305ef750c04fd8931947baf7b1be0 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Mon, 27 Mar 2017 16:48:39 +0300 Subject: [PATCH 07/40] last edit --- admin/controller/extension/module/retailcrm.php | 1 + 1 file changed, 1 insertion(+) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 24c26dd..8f8e286 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -123,6 +123,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'retailcrm_dict_delivery', 'retailcrm_dict_status', 'retailcrm_dict_payment', + 'retailcrm_countries_settings' ); $this->load->model('extension/extension'); From 83fb02bf09253749273d5870c0894052bd5b61c5 Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Mon, 27 Mar 2017 17:07:54 +0300 Subject: [PATCH 08/40] update installer --- admin/controller/extension/module/retailcrm.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 8f8e286..591eea1 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -26,7 +26,11 @@ class ControllerExtensionModuleRetailcrm extends Controller { $this->load->model('setting/setting'); $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 1)); + ->editSetting('retailcrm', array( + 'retailcrm_status' => 1, + 'retailcrm_country' => array($this->config->get('config_country_id')) + ) + ); $this->load->model('extension/event'); From be14df7c7a0cdf7941ae10754d2f899738bdaf8f Mon Sep 17 00:00:00 2001 From: Dmitry Akolzin Date: Tue, 4 Apr 2017 16:45:39 +0300 Subject: [PATCH 09/40] update: admin/controller/extension/module/retailcrm.php update: admin/language/en-gb/extension/module/retailcrm.php update: admin/language/ru-ru/extension/module/retailcrm.php update: admin/model/extension/retailcrm/icml.php update: admin/model/extension/retailcrm/order.php update: admin/view/template/extension/module/retailcrm.tpl --- .../controller/extension/module/retailcrm.php | 34 ++++++++-- .../en-gb/extension/module/retailcrm.php | 8 +++ .../ru-ru/extension/module/retailcrm.php | 8 +++ admin/model/extension/retailcrm/icml.php | 2 +- admin/model/extension/retailcrm/order.php | 42 ++++++++++++ .../template/extension/module/retailcrm.tpl | 66 ++++++++++++++++++- 6 files changed, 150 insertions(+), 10 deletions(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 591eea1..b5a2855 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -54,13 +54,6 @@ class ControllerExtensionModuleRetailcrm extends Controller 'catalog/model/account/customer/addCustomer/after', 'extension/module/retailcrm/customer_create' ); - - $this->model_extension_event - ->addEvent( - 'retailcrm', - 'catalog/model/checkout/order/editOrder/after', - 'extension/module/retailcrm/order_edit' - ); } /** @@ -237,6 +230,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['column_left'] = $this->load->controller('common/column_left'); $_data['footer'] = $this->load->controller('common/footer'); $_data['countries'] = $this->model_localisation_country->getCountries(); + $_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG; + $_data['token'] = $this->request->get['token']; $this->response->setOutput( $this->load->view('extension/module/retailcrm.tpl', $_data) @@ -300,6 +295,31 @@ class ControllerExtensionModuleRetailcrm extends Controller } } + /** + * Export single order + * + * + */ + public function exportOrder() + { + $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; + $this->load->model('sale/order'); + + $data = $this->model_sale_order->getOrder($order_id); + $data['products'] = $this->model_sale_order->getOrderProducts($order_id); + $data['totals'] = $this->model_sale_order->getOrderTotals($order_id); + + if (!isset($data['fromApi'])) { + $this->load->model('setting/setting'); + $status = $this->model_setting_setting->getSetting('retailcrm'); + $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + + $this->load->model('extension/retailcrm/order'); + $this->model_extension_retailcrm_order->uploadOrder($data); + } + + } + /** * Export orders * diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index b3e8e7e..266b1bc 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -11,10 +11,18 @@ $_['text_notice'] = 'Warning! Timezone in CRM & your shop must be $_['retailcrm_base_settings'] = 'Connection settings'; $_['retailcrm_dict_settings'] = 'Dictionary settings'; $_['retailcrm_countries_settings'] = 'Trading zones setting'; +$_['retailcrm_upload_order'] = 'Unload single order'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; +$_['text_success_export'] = 'Orders and customers successfully unloaded'; +$_['text_success_export_order'] = 'Order successfully unloaded'; +$_['text_button_export'] = 'Unload all orders and customers'; +$_['text_button_export_order'] = 'Unload order'; +$_['text_button_catalog'] = 'Unload catalog'; +$_['text_success_catalog'] = 'Catalog successfully unloaded'; + $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; $_['retailcrm_dict_payment'] = 'Payment methods'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 892924d..85bbdd0 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -11,10 +11,18 @@ $_['text_notice'] = 'Внимание! Часовой пояс в $_['retailcrm_base_settings'] = 'Настройки соединения'; $_['retailcrm_dict_settings'] = 'Настройки соответствия справочников'; $_['retailcrm_countries_settings'] = 'Настройка торговых зон'; +$_['retailcrm_upload_order'] = 'Выгрузка одного заказа'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; +$_['text_success_export'] = 'Заказы и клиенты успешно выгружены'; +$_['text_success_export_order'] = 'Заказ успешно выгружен'; +$_['text_button_export'] = 'Выгрузить все заказы и клиентов'; +$_['text_button_export_order'] = 'Выгрузить заказ'; +$_['text_button_catalog'] = 'Выгрузить каталог'; +$_['text_success_catalog'] = 'Каталог успешно выгружен'; + $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; $_['retailcrm_dict_payment'] = 'Способы оплаты'; diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index f2f3d47..d1dea3e 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -220,7 +220,7 @@ class ModelExtensionRetailcrmIcml extends Model ->appendChild($this->dd->createTextNode($product['name'])); } $e->appendChild($this->dd->createElement('price')) - ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); + ->appendChild($this->dd->createTextNode($productPrice + $optionsTotalCost)); /** * Vendor */ diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index 77fa54d..253d31c 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -1,6 +1,7 @@ load->model('catalog/product'); @@ -20,6 +21,47 @@ class ModelExtensionRetailcrmOrder extends Model { } } + public function uploadOrder($order) + { + if(isset($this->request->post['fromApi'])) return; + + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting('retailcrm'); + + if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + $this->load->model('catalog/product'); + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings['retailcrm_url'], + $settings['retailcrm_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log' + ); + + $customers = $this->retailcrm->customersList( + array( + 'name' => $order['telephone'], + 'email' => $order['email'] + ), + 1, + 100 + ); + + $order = $this->process($order); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; + } + } + + unset($customers); + + $this->retailcrm->ordersCreate($order); + } + } + private function process($order_data) { $order = array(); diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index a77bb21..b9c84bc 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -5,6 +5,8 @@ - - - - + diff --git a/catalog/controller/extension/analytics/daemon_collector.php b/catalog/controller/extension/analytics/daemon_collector.php new file mode 100644 index 0000000..23ac623 --- /dev/null +++ b/catalog/controller/extension/analytics/daemon_collector.php @@ -0,0 +1,22 @@ +config->get('retailcrm_collector_site_key'); + + if ($this->customer->isLogged()) $customerId = $this->customer->getID(); + + $customer = isset($customerId) ? "'customerId': '" . $customerId . "'" : ""; + + $js = ""; + + return html_entity_decode($js, ENT_QUOTES, 'UTF-8'); + } +} From 19ceeae2b0923a97e8200647722d9536029cb325 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Wed, 31 May 2017 13:08:07 +0300 Subject: [PATCH 30/40] Daemon Collector settings interface, update contoller Daemon Collector --- .../controller/extension/module/retailcrm.php | 36 ++++++- .../en-gb/extension/module/retailcrm.php | 11 ++ .../ru-ru/extension/module/retailcrm.php | 12 ++- admin/view/stylesheet/retailcrm.css | 1 + .../template/extension/module/retailcrm.tpl | 101 ++++++++++++++---- .../extension/analytics/daemon_collector.php | 65 ++++++++++- .../controller/extension/module/retailcrm.php | 5 - catalog/model/extension/retailcrm/order.php | 5 + 8 files changed, 201 insertions(+), 35 deletions(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index f4595fc..2af82fb 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -195,7 +195,14 @@ class ControllerExtensionModuleRetailcrm extends Controller 'collector_tab_text', 'text_yes', 'text_no', - 'collector_site_key' + 'collector_site_key', + 'text_collector_activity', + 'text_collector_form_capture', + 'text_collector_period', + 'text_label_promo', + 'text_label_send', + 'collector_custom_text', + 'text_require' ); $this->load->model('extension/extension'); @@ -245,8 +252,14 @@ class ControllerExtensionModuleRetailcrm extends Controller } } - if (isset($this->error['warning'])) { - $_data['error_warning'] = $this->error['warning']; + if (isset($this->_error['warning'])) { + $_data['error_warning'] = $this->_error['warning']; + } else { + $_data['error_warning'] = ''; + } + + if (isset($this->_error['fields'])) { + $_data['error_warning'] = $this->_error['fields']; } else { $_data['error_warning'] = ''; } @@ -314,6 +327,14 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['export_file'] = true; } + $collectorFields = array( + 'name' => $this->language->get('field_name'), + 'email' => $this->language->get('field_email'), + 'phone' => $this->language->get('field_phone') + ); + + $_data['collectorFields'] = $collectorFields; + $this->response->setOutput( $this->load->view('extension/module/retailcrm.tpl', $_data) ); @@ -486,6 +507,15 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->_error['warning'] = $this->language->get('error_permission'); } + if (isset($this->request->post['retailcrm_collector']['custom']) && + $this->request->post['retailcrm_collector']['custom_form'] == 1) { + $customField = $this->request->post['retailcrm_collector']['custom']; + + if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { + $this->_error['fields'] = $this->language->get('text_error_collector_fields'); + } + } + if (!$this->_error) { return true; } else { diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 3ba4800..3e55368 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Daemon Collector'; $_['general_tab_text'] = 'General'; $_['references_tab_text'] = 'References'; $_['collector_tab_text'] = 'Collector'; +$_['collector_custom_text'] = 'Custom form'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; @@ -29,6 +30,16 @@ $_['text_button_catalog'] = 'Unload catalog'; $_['text_success_catalog'] = 'Catalog successfully unloaded'; $_['text_error_order'] = 'Error! Order is not unloaded!'; $_['text_error_order_id'] = 'Error! Enter the correct order number!'; +$_['text_collector_activity'] = 'Use Daemon Collector'; +$_['text_collector_form_capture']= 'Show capture form'; +$_['text_collector_period'] = 'Form show period (in minutes)'; +$_['text_label_promo'] = 'Text form title'; +$_['text_label_send'] = 'Text button'; +$_['field_name'] = 'Name'; +$_['field_email'] = 'Email'; +$_['field_phone'] = 'Phone'; +$_['text_require'] = 'Require'; +$_['text_error_collector_fields']= 'Fill in the field names Daemon Collector'; $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 9b6c7c6..0c99f25 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -16,6 +16,7 @@ $_['daemon_collector'] = 'Демон Collector'; $_['general_tab_text'] = 'Главная'; $_['references_tab_text'] = 'Справочники'; $_['collector_tab_text'] = 'Collector'; +$_['collector_custom_text'] = 'Настройка полей формы'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; @@ -29,7 +30,16 @@ $_['text_button_catalog'] = 'Выгрузить каталог'; $_['text_success_catalog'] = 'Каталог успешно выгружен'; $_['text_error_order'] = 'Ошибка! Заказ не выгружен!'; $_['text_error_order_id'] = 'Ошибка! Введите корректный номер заказа!'; - +$_['text_collector_activity'] = 'Использовать Демон Collector'; +$_['text_collector_form_capture']= 'Показывать форму захвата'; +$_['text_collector_period'] = 'Периодичность всплывания формы (в минутах)'; +$_['text_label_promo'] = 'Текст заголовка формы'; +$_['text_label_send'] = 'Текст кнопки'; +$_['field_name'] = 'Имя'; +$_['field_email'] = 'Email'; +$_['field_phone'] = 'Телефон'; +$_['text_require'] = 'Обязательно для заполнения'; +$_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; diff --git a/admin/view/stylesheet/retailcrm.css b/admin/view/stylesheet/retailcrm.css index 5c3b88f..2efb7ae 100644 --- a/admin/view/stylesheet/retailcrm.css +++ b/admin/view/stylesheet/retailcrm.css @@ -1,3 +1,4 @@ .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 diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index a2768c7..6ee4124 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -38,7 +38,6 @@
-
-

- +

-
- - + + + +
+
+ + +
+ +
+ + + +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + + +
+ + $label) : ?> +
+ +
+ + > +
- -
-
- -
+ + + +
- -
diff --git a/catalog/controller/extension/analytics/daemon_collector.php b/catalog/controller/extension/analytics/daemon_collector.php index 23ac623..a8278d3 100644 --- a/catalog/controller/extension/analytics/daemon_collector.php +++ b/catalog/controller/extension/analytics/daemon_collector.php @@ -1,19 +1,78 @@ config->get('retailcrm_collector_site_key'); + $this->load->model('setting/setting'); + + $settings = $this->model_setting_setting->getSetting('retailcrm'); + $setting = $settings['retailcrm_collector']; + $siteCode = isset($setting['site_key']) ? $setting['site_key'] : ''; if ($this->customer->isLogged()) $customerId = $this->customer->getID(); $customer = isset($customerId) ? "'customerId': '" . $customerId . "'" : ""; + $labelPromo = !empty($setting['label_promo']) ? $setting['label_promo'] : null; + $labelSend = !empty($setting['label_send']) ? $setting['label_send'] : null; + $customForm = ''; - $js = ""; diff --git a/catalog/controller/extension/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php index 7222576..20efee9 100644 --- a/catalog/controller/extension/module/retailcrm.php +++ b/catalog/controller/extension/module/retailcrm.php @@ -43,11 +43,6 @@ class ControllerExtensionModuleRetailcrm extends Controller $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; } - $data['totals'][] = array( - 'code' => 'shipping', - 'value' => $this->session->data['shipping_method']['cost'] - ); - $this->load->model('extension/retailcrm/order'); $this->model_extension_retailcrm_order->sendToCrm($data, $data['order_id']); } diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 55f5ddb..de2973e 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -204,8 +204,13 @@ class ModelExtensionRetailcrmOrder extends Model { if ($totals['code'] == 'shipping') { $deliveryCost = $totals['value']; } + + if ($totals['code'] == 'coupon') { + $couponTotal = abs($totals['value']); + } } + $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; From 9146ebd2f6892f3e664e4961ff9b5ceac058a590 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 2 Jun 2017 15:04:22 +0300 Subject: [PATCH 31/40] fix items property --- catalog/model/extension/retailcrm/order.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index de2973e..09347f5 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -114,7 +114,7 @@ class ModelExtensionRetailcrmOrder extends Model { $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); foreach($product['option'] as $option) { - if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox') { + if ($option['type'] == 'checkbox') { $properties[] = array( 'code' => $option['product_option_value_id'], 'name' => $option['name'], @@ -255,7 +255,7 @@ class ModelExtensionRetailcrmOrder extends Model { $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); foreach($product['option'] as $option) { - if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox') { + if ($option['type'] == 'checkbox') { $properties[] = array( 'code' => $option['product_option_value_id'], 'name' => $option['name'], From 14840711222e1e60e80a7f9b7e3350b437a94618 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 2 Jun 2017 15:21:46 +0300 Subject: [PATCH 32/40] quantity for offers in icml --- admin/model/extension/retailcrm/icml.php | 32 +++++++++++++++++------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index f2f3d47..69f87b1 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -121,13 +121,20 @@ class ModelExtensionRetailcrmIcml extends Model // Если первая итерация if(empty($offers)) { foreach($requiredOption['product_option_value'] as $optionValue) { - $offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = (float)$optionValue['price']; + $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 => $optionCost) { + 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']] = $optionCost + (float)$optionValue['price']; + $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'] + ); } } } @@ -138,21 +145,28 @@ class ModelExtensionRetailcrmIcml extends Model 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']] = (float)$optionValue['price']; + $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 => $optionCost) { + 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']] = $optionCost + (float)$optionValue['price']; + $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' => '0'); + $offers = array('0:0-0' => array('price' => '0', 'qty' => '0')); } - foreach($offers as $optionsString => $optionsTotalCost) { + foreach($offers as $optionsString => $optionsValues) { $optionsString = explode('_', $optionsString); $options = array(); foreach($optionsString as $optionString) { @@ -220,7 +234,7 @@ class ModelExtensionRetailcrmIcml extends Model ->appendChild($this->dd->createTextNode($product['name'])); } $e->appendChild($this->dd->createElement('price')) - ->appendChild($this->dd->createTextNode($product['price'] + $optionsTotalCost)); + ->appendChild($this->dd->createTextNode($product['price'] + $optionsValues['price'])); /** * Vendor */ From 647d5e8427fc5d50c6a1584d9310357936aea443 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 2 Jun 2017 15:33:05 +0300 Subject: [PATCH 33/40] fix icml --- admin/model/extension/retailcrm/icml.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index 69f87b1..f3476bb 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -188,12 +188,14 @@ class ModelExtensionRetailcrmIcml extends Model } $offerId = implode('_', $offerId); $e = $this->eOffers->appendChild($this->dd->createElement('offer')); - if(!empty($offerId)) + if(!empty($offerId)) { $e->setAttribute('id', $product['product_id'].'#'.$offerId); - else + $e->setAttribute('quantity', $optionsValues['qty']); + } + else { $e->setAttribute('id', $product['product_id']); - $e->setAttribute('productId', $product['product_id']); - $e->setAttribute('quantity', $product['quantity']); + $e->setAttribute('quantity', $product['quantity']); + } /** * Offer activity */ From b1f0835b9cb398fa5864af37e3b25a2f08ec981b Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 2 Jun 2017 15:49:43 +0300 Subject: [PATCH 34/40] fix icml --- admin/model/extension/retailcrm/icml.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/admin/model/extension/retailcrm/icml.php b/admin/model/extension/retailcrm/icml.php index f3476bb..5535e3a 100644 --- a/admin/model/extension/retailcrm/icml.php +++ b/admin/model/extension/retailcrm/icml.php @@ -190,10 +190,12 @@ class ModelExtensionRetailcrmIcml extends Model $e = $this->eOffers->appendChild($this->dd->createElement('offer')); if(!empty($offerId)) { $e->setAttribute('id', $product['product_id'].'#'.$offerId); + $e->setAttribute('productId', $product['product_id']); $e->setAttribute('quantity', $optionsValues['qty']); } else { $e->setAttribute('id', $product['product_id']); + $e->setAttribute('productId', $product['product_id']); $e->setAttribute('quantity', $product['quantity']); } /** From dca2b67a5b73f308a6b43af20c6845a507610e9c Mon Sep 17 00:00:00 2001 From: iyzoer Date: Mon, 5 Jun 2017 12:49:29 +0300 Subject: [PATCH 35/40] fix country and region in delivery address on update order --- catalog/model/extension/retailcrm/order.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 09347f5..5354944 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -227,8 +227,8 @@ class ModelExtensionRetailcrmOrder extends Model { 'address' => array( 'index' => $order_data['shipping_postcode'], 'city' => $order_data['shipping_city'], - 'country' => $order_data['shipping_country_id'], - 'region' => $order_data['shipping_zone_id'], + 'countryIso' => $order_data['shipping_iso_code_2'], + 'region' => $order_data['shipping_zone'], 'text' => implode(', ', array( $order_data['shipping_postcode'], $country, From 12cc1c620ae9340d770f831917d3d77960a525eb Mon Sep 17 00:00:00 2001 From: iyzoer Date: Mon, 26 Jun 2017 12:21:11 +0300 Subject: [PATCH 36/40] Check the existence of the coupon --- catalog/model/extension/retailcrm/order.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 5354944..6f93c0b 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -66,7 +66,7 @@ class ModelExtensionRetailcrmOrder extends Model { } } - $order['discount'] = $couponTotal; + if(isset($couponTotal)) $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; $payment_code = $order_data['payment_code']; @@ -210,7 +210,7 @@ class ModelExtensionRetailcrmOrder extends Model { } } - $order['discount'] = $couponTotal; + if(isset($couponTotal)) $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; From 71537c74820260e794e0d46ad80a3ef08b74e915 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Tue, 11 Jul 2017 17:39:48 +0300 Subject: [PATCH 37/40] compatibility with opencart versions 2.3-3.0 and RetailCRM API v3, v4, v5 --- .../controller/extension/module/retailcrm.php | 231 +- .../en-gb/extension/module/retailcrm.php | 1 + .../ru-ru/extension/module/retailcrm.php | 1 + admin/model/extension/retailcrm/customer.php | 64 +- .../model/extension/retailcrm/history/v3.php | 475 ++++ .../{history.php => history/v4_5.php} | 77 +- admin/model/extension/retailcrm/order.php | 174 +- .../model/extension/retailcrm/references.php | 78 +- .../template/extension/module/retailcrm.tpl | 10 +- .../template/extension/module/retailcrm.twig | 314 +++ catalog/controller/api/retailcrm.php | 37 +- .../extension/analytics/daemon_collector.php | 16 +- .../controller/extension/module/retailcrm.php | 23 +- .../model/extension/retailcrm/customer.php | 74 +- catalog/model/extension/retailcrm/order.php | 505 ++-- system/cron/dispatch.php | 20 +- .../library/retailcrm/OpencartApiClient.php | 24 +- .../library/retailcrm/RetailcrmApiClient3.php | 811 +++++++ .../library/retailcrm/RetailcrmApiClient4.php | 1723 ++++++++++++++ .../library/retailcrm/RetailcrmApiClient5.php | 2098 +++++++++++++++++ system/library/retailcrm/RetailcrmProxy.php | 24 +- 21 files changed, 6278 insertions(+), 502 deletions(-) create mode 100644 admin/model/extension/retailcrm/history/v3.php rename admin/model/extension/retailcrm/{history.php => history/v4_5.php} (90%) create mode 100644 admin/view/template/extension/module/retailcrm.twig create mode 100644 system/library/retailcrm/RetailcrmApiClient3.php create mode 100644 system/library/retailcrm/RetailcrmApiClient4.php create mode 100644 system/library/retailcrm/RetailcrmApiClient5.php diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 2af82fb..610d636 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -9,7 +9,7 @@ require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; * @package RetailCrm * @author RetailCrm * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion5 */ class ControllerExtensionModuleRetailcrm extends Controller { @@ -24,54 +24,56 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function install() { + $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); + $this->model_setting_setting - ->editSetting('retailcrm', array( - 'retailcrm_status' => 1, - 'retailcrm_country' => array($this->config->get('config_country_id')) + ->editSetting($moduleTitle, array( + $moduleTitle . '_status' => 1, + $moduleTitle . '_country' => array($this->config->get('config_country_id')) ) ); + + $this->loadModels(); - $this->load->model('extension/event'); - - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/checkout/order/addOrder/after', 'extension/module/retailcrm/order_create' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/retailcrm/order_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/customer/addCustomer/after', 'extension/module/retailcrm/customer_create' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'catalog/model/account/address/editAddress/after', 'extension/module/retailcrm/customer_edit' ); - $this->model_extension_event + $this->{'model_' . $this->modelEvent} ->addEvent( - 'retailcrm', + $moduleTitle, 'admin/model/customer/customer/editCustomer/after', 'extension/module/retailcrm/customer_edit' ); @@ -84,13 +86,15 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function uninstall() { + $moduleTitle = $this->getModuleTitle(); $this->uninstall_collector(); $this->load->model('setting/setting'); $this->model_setting_setting - ->editSetting('retailcrm', array('retailcrm_status' => 0)); + ->editSetting($moduleTitle, array($moduleTitle . '_status' => 0)); - $this->load->model('extension/event'); - $this->model_extension_event->deleteEvent('retailcrm'); + $this->loadModels(); + + $this->{'model_' . $this->modelEvent}->deleteEvent($moduleTitle); } /** @@ -99,11 +103,13 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function install_collector() - { - $this->load->model('extension/extension'); + { + $collector = $this->getCollectorTitle(); + $moduleTitle = $this->getModuleTitle(); + $this->loadModels(); $this->load->model('setting/setting'); - $this->model_extension_extension->install('analytics', 'daemon_collector'); - $this->model_setting_setting->editSetting('daemon_collector', array('daemon_collector_status' => 1)); + $this->{'model_' . $this->modelExtension}->install('analytics', $collector); + $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 1)); } /** @@ -112,11 +118,12 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function uninstall_collector() - { - $this->load->model('extension/extension'); + { + $collector = $this->getCollectorTitle(); + $this->loadModels(); $this->load->model('setting/setting'); - $this->model_setting_setting->editSetting('daemon_collector', array('daemon_collector_status' => 0)); - $this->model_extension_extension->uninstall('analytics', 'daemon_collector'); + $this->model_setting_setting->editSetting($collector, array($collector . '_status' => 0)); + $this->{'model_' . $this->modelExtension}->uninstall('analytics', $collector); } /** @@ -126,38 +133,41 @@ class ControllerExtensionModuleRetailcrm extends Controller */ public function index() { - $this->load->model('extension/extension'); + $this->loadModels(); $this->load->model('localisation/country'); $this->load->model('setting/setting'); - $this->load->model('extension/module'); $this->load->model('extension/retailcrm/references'); $this->load->language('extension/module/retailcrm'); $this->document->setTitle($this->language->get('heading_title')); $this->document->addStyle('/admin/view/stylesheet/retailcrm.css'); + $tokenTitle = $this->getTokenTitle(); + $moduleTitle = $this->getModuleTitle(); + $collector = $this->getCollectorTitle(); + if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) { - $analytics = $this->model_extension_extension->getInstalled('analytics'); - - if ($this->request->post['retailcrm_collector_active'] == 1 && - !in_array('daemon_collector', $analytics)) { + $analytics = $this->{'model_' . $this->modelExtension}->getInstalled('analytics'); + + if ($this->request->post[$moduleTitle . '_collector_active'] == 1 && + !in_array($collector, $analytics)) { $this->install_collector(); - } elseif ($this->request->post['retailcrm_collector_active'] == 0 && - in_array('daemon_collector', $analytics)) { + } elseif ($this->request->post[$moduleTitle . '_collector_active'] == 0 && + in_array($collector, $analytics)) { $this->uninstall_collector(); } - if (parse_url($this->request->post['retailcrm_url'])){ - $crm_url = parse_url($this->request->post['retailcrm_url'], PHP_URL_HOST); - $this->request->post['retailcrm_url'] = 'https://'.$crm_url; + if (parse_url($this->request->post[$moduleTitle . '_url'])){ + $crm_url = parse_url($this->request->post[$moduleTitle . '_url'], PHP_URL_HOST); + $this->request->post[$moduleTitle . '_url'] = 'https://'.$crm_url; } $this->model_setting_setting->editSetting( - 'retailcrm', + $moduleTitle, $this->request->post ); $this->session->data['success'] = $this->language->get('text_success'); $redirect = $this->url->link( - 'extension/module/retailcrm', 'token=' . $this->session->data['token'], + 'extension/module/retailcrm', $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); @@ -172,6 +182,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'button_cancel', 'text_notice', 'retailcrm_title', + 'retailcrm_apiversion', 'retailcrm_url', 'retailcrm_apikey', 'retailcrm_base_settings', @@ -205,7 +216,6 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text_require' ); - $this->load->model('extension/extension'); $_data = &$data; foreach ($text_strings as $text) { @@ -214,13 +224,16 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['retailcrm_errors'] = array(); $_data['saved_settings'] = $this->model_setting_setting - ->getSetting('retailcrm'); + ->getSetting($moduleTitle); - $url = isset($_data['saved_settings']['retailcrm_url']) - ? $_data['saved_settings']['retailcrm_url'] + $url = isset($_data['saved_settings'][$moduleTitle . '_url']) + ? $_data['saved_settings'][$moduleTitle . '_url'] : null; - $key = isset($_data['saved_settings']['retailcrm_apikey']) - ? $_data['saved_settings']['retailcrm_apikey'] + $key = isset($_data['saved_settings'][$moduleTitle . '_apikey']) + ? $_data['saved_settings'][$moduleTitle . '_apikey'] + : null; + $apiVersion = isset($_data['saved_settings'][$moduleTitle . '_apiversion']) + ? $_data['saved_settings'][$moduleTitle . '_apiversion'] : null; if (!empty($url) && !empty($key)) { @@ -228,7 +241,8 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->retailcrm = new RetailcrmProxy( $url, $key, - DIR_SYSTEM . 'storage/logs/retailcrm.log' + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $apiVersion ); $_data['delivery'] = $this->model_extension_retailcrm_references @@ -241,7 +255,7 @@ class ControllerExtensionModuleRetailcrm extends Controller } $config_data = array( - 'retailcrm_status' + $moduleTitle . '_status' ); foreach ($config_data as $conf) { @@ -270,7 +284,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('text_home'), 'href' => $this->url->link( 'common/home', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => false ); @@ -279,7 +293,7 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('text_module'), 'href' => $this->url->link( 'extension/extension/module', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => ' :: ' ); @@ -288,19 +302,19 @@ class ControllerExtensionModuleRetailcrm extends Controller 'text' => $this->language->get('retailcrm_title'), 'href' => $this->url->link( 'extension/module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ), 'separator' => ' :: ' ); $_data['action'] = $this->url->link( 'extension/module/retailcrm', - 'token=' . $this->session->data['token'], 'SSL' + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); $_data['cancel'] = $this->url->link( - 'extension/extension', - 'token=' . $this->session->data['token'], 'SSL' + version_compare(VERSION, '3.0', '<') ? 'extension/extension' : 'marketplace/extension', + $tokenTitle . '=' . $this->session->data[$tokenTitle], 'SSL' ); $_data['modules'] = array(); @@ -319,7 +333,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['footer'] = $this->load->controller('common/footer'); $_data['countries'] = $this->model_localisation_country->getCountries(); $_data['catalog'] = $this->request->server['HTTPS'] ? HTTPS_CATALOG : HTTP_CATALOG; - $_data['token'] = $this->request->get['token']; + $_data[$tokenTitle] = $this->request->get[$tokenTitle]; if(file_exists(DIR_SYSTEM . '/cron/export_done')) { $_data['export_file'] = false; @@ -334,10 +348,13 @@ class ControllerExtensionModuleRetailcrm extends Controller ); $_data['collectorFields'] = $collectorFields; + $_data['api_versions'] = array('v3', 'v4', 'v5'); + $_data['default_apiversion'] = 'v5'; $this->response->setOutput( - $this->load->view('extension/module/retailcrm.tpl', $_data) + $this->load->view('extension/module/retailcrm', $_data) ); + } /** @@ -346,13 +363,29 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function history() - { - if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history.php')) { - $this->load->model('extension/retailcrm/custom/history'); - $this->model_extension_retailcrm_custom_history->request(); + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if ($settings[$moduleTitle . '_apiversion'] == 'v3') { + + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v3.php')) { + $this->load->model('extension/retailcrm/custom/history/v3'); + $this->model_extension_retailcrm_custom_history_v3->request(); + } else { + $this->load->model('extension/retailcrm/history/v3'); + $this->model_extension_retailcrm_history_v3->request(); + } } else { - $this->load->model('extension/retailcrm/history'); - $this->model_extension_retailcrm_history->request(); + + if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/history/v4-5.php')) { + $this->load->model('extension/retailcrm/custom/history/v4-5'); + $this->model_extension_retailcrm_custom_history_v4_5->request(); + } else { + $this->load->model('extension/retailcrm/history/v4_5'); + $this->model_extension_retailcrm_history_v4_5->request(); + } } } @@ -444,6 +477,7 @@ class ControllerExtensionModuleRetailcrm extends Controller { $order_id = isset($this->request->get['order_id']) ? $this->request->get['order_id'] : ''; $this->load->model('sale/order'); + $moduleTitle = $this->getModuleTitle(); $data = $this->model_sale_order->getOrder($order_id); $data['products'] = $this->model_sale_order->getOrderProducts($order_id); @@ -451,8 +485,8 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $status = $this->model_setting_setting->getSetting($moduleTitle); + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; $this->load->model('extension/retailcrm/order'); $result = $this->model_extension_retailcrm_order->uploadOrder($data); @@ -478,12 +512,13 @@ class ControllerExtensionModuleRetailcrm extends Controller $orders = $this->model_sale_order->getOrders(); $fullOrders = array(); + foreach($orders as $order) { $fullOrder = $this->model_sale_order->getOrder($order['order_id']); $fullOrder['order_total'] = $this->model_sale_order->getOrderTotals($order['order_id']); - $fullOrder['products'] = $this->model_sale_order->getOrderProducts($order['order_id']); + foreach($fullOrder['products'] as $key=>$product) { $fullOrder['products'][$key]['option'] = $this->model_sale_order->getOrderOptions($product['order_id'], $product['order_product_id']); } @@ -503,13 +538,15 @@ class ControllerExtensionModuleRetailcrm extends Controller */ private function validate() { + $moduleTitle = $this->getModuleTitle(); + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { $this->_error['warning'] = $this->language->get('error_permission'); } - if (isset($this->request->post['retailcrm_collector']['custom']) && - $this->request->post['retailcrm_collector']['custom_form'] == 1) { - $customField = $this->request->post['retailcrm_collector']['custom']; + if (isset($this->request->post[$moduleTitle . '_collector']['custom']) && + $this->request->post[$moduleTitle . '_collector']['custom_form'] == 1) { + $customField = $this->request->post[$moduleTitle . '_collector']['custom']; if (empty($customField['name']) && empty($customField['email']) && empty($customField['phone'])) { $this->_error['fields'] = $this->language->get('text_error_collector_fields'); @@ -522,4 +559,58 @@ class ControllerExtensionModuleRetailcrm extends Controller return false; } } + + private function loadModels() + { + if (version_compare(VERSION, '3.0', '<')) { + $this->load->model('extension/event'); + $this->load->model('extension/extension'); + // $this->load->model('extension/module'); + + $this->modelEvent = 'extension_event'; + $this->modelExtension = 'extension_extension'; + // $this->modelModule = 'extension_module'; + } else { + $this->load->model('setting/event'); + $this->load->model('setting/extension'); + // $this->load->model('setting/module'); + + $this->modelEvent = 'setting_event'; + $this->modelExtension = 'setting_extension'; + // $this->modelModule = 'setting_module'; + } + } + + private function getTokenTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $token = 'token'; + } else { + $token = 'user_token'; + } + + return $token; + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } + + private function getCollectorTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'daemon_collector'; + } else { + $title = 'analytics_daemon_collector'; + } + + return $title; + } } diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 3e55368..67eeac7 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -18,6 +18,7 @@ $_['references_tab_text'] = 'References'; $_['collector_tab_text'] = 'Collector'; $_['collector_custom_text'] = 'Custom form'; +$_['retailcrm_apiversion'] = 'API Version'; $_['retailcrm_url'] = 'RetailCRM URL'; $_['retailcrm_apikey'] = 'RetailCRM API Key'; $_['collector_site_key'] = 'Site key'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index 0c99f25..ef726e7 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -18,6 +18,7 @@ $_['references_tab_text'] = 'Справочники'; $_['collector_tab_text'] = 'Collector'; $_['collector_custom_text'] = 'Настройка полей формы'; +$_['retailcrm_apiversion'] = 'Версия API'; $_['retailcrm_url'] = 'Адрес RetailCRM'; $_['retailcrm_apikey'] = 'Api ключ RetailCRM'; $_['collector_site_key'] = 'Ключ сайта'; diff --git a/admin/model/extension/retailcrm/customer.php b/admin/model/extension/retailcrm/customer.php index b05975f..1448b0b 100644 --- a/admin/model/extension/retailcrm/customer.php +++ b/admin/model/extension/retailcrm/customer.php @@ -2,22 +2,12 @@ class ModelExtensionRetailcrmCustomer extends Model { - public function uploadToCrm($customers) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function uploadToCrm($customers) + { + $this->initApi(); if(empty($customers)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); $customersToCrm = array(); @@ -32,23 +22,13 @@ class ModelExtensionRetailcrmCustomer extends Model { } } - public function changeInCrm($customer) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function changeInCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - + $customerToCrm = $this->process($customer); $this->retailcrmApi->customersEdit($customerToCrm); @@ -80,4 +60,34 @@ class ModelExtensionRetailcrmCustomer extends Model { return $customerToCrm; } + + protected function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/model/extension/retailcrm/history/v3.php b/admin/model/extension/retailcrm/history/v3.php new file mode 100644 index 0000000..f486c26 --- /dev/null +++ b/admin/model/extension/retailcrm/history/v3.php @@ -0,0 +1,475 @@ +getModuleTitle(); + $this->load->model('setting/setting'); + $this->load->model('setting/store'); + $this->load->model('user/api'); + $this->load->model('sale/order'); + $this->load->model('customer/customer'); + $this->load->model('extension/retailcrm/references'); + $this->load->model('catalog/product'); + $this->load->model('catalog/option'); + $this->load->model('localisation/zone'); + + $this->load->language('extension/module/retailcrm'); + + $settings = $this->model_setting_setting->getSetting($moduleTitle); + $history = $this->model_setting_setting->getSetting('retailcrm_history'); + $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); + + $url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; + $key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; + + if (empty($url) || empty($key)) { + $this->log->addNotice('You need to configure retailcrm module first.'); + return false; + } + + $this->opencartApiClient = new OpencartApiClient($this->registry); + + $crm = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + + $lastRun = !empty($history['retailcrm_history']) + ? new DateTime($history['retailcrm_history']) + : new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); + + $packsOrders = $crm->ordersHistory($lastRun); + + if(!$packsOrders->isSuccessful() && count($packsOrders['orders']) <= 0) + return false; + + $generatedAt = $packsOrders['generatedAt']; + + $this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); + $this->totalSettings = $this->model_setting_setting->getSetting('total'); + $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); + + $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); + $this->payment = array_flip($settings[$moduleTitle . '_payment']); + $this->status = array_flip($settings[$moduleTitle . '_status']); + + $this->ocPayment = $this->model_extension_retailcrm_references + ->getOpercartPaymentTypes(); + + $this->ocDelivery = $settings[$moduleTitle . '_delivery']; + + $this->zones = $this->model_localisation_zone->getZones(); + + $updatedOrders = array(); + $newOrders = array(); + $orders = $packsOrders['orders']; + + foreach ($orders as $order) { + + if (isset($order['deleted'])) continue; + + if (isset($order['externalId'])) { + $updatedOrders[] = $order['id']; + } else { + $newOrders[] = $order['id']; + } + } + + unset($orders); + + if (!empty($newOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $newOrders)); + if ($orders) { + $this->createResult = $this->createOrders($orders['orders']); + } + } + + if (!empty($updatedOrders)) { + $orders = $crm->ordersList($filter = array('ids' => $updatedOrders)); + if ($orders) { + $this->updateOrders($orders['orders']); + } + } + + $this->model_setting_setting->editSetting('retailcrm_history', array('retailcrm_history' => $generatedAt)); + + if (!empty($this->createResult['customers'])) { + $crm->customersFixExternalIds($this->createResult['customers']); + } + + if (!empty($this->createResult['orders'])) { + $crm->ordersFixExternalIds($this->createResult['orders']); + } + } + + protected function updateOrders($orders) + { + foreach ($orders as $order) { + $store = $this->config->get('config_store_id'); + + $data = array(); + + $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; + $data['firstname'] = $order['firstName']; + $data['lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['phone'])) ? $order['phone'] : ''; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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']; + + $region = ''; + + if (is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + + $data['payment'] = $this->payment[$order['paymentType']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$order['paymentType']]; + + // 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) { + //$product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $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['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['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) { + $cData = array( + 'store_id' => 0, + 'customer_group_id' => '1', + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['lastName'] : ' ', + 'email' => $order['email'], + 'telephone' => (!empty($order['customer']['phones'][0]['number']) ) ? $order['customer']['phones'][0]['number'] : ' ', + 'fax' => '', + 'newsletter' => 0, + 'password' => 'tmppass', + 'status' => 1, + 'address' => array( + array( + 'firstname' => $order['firstName'], + 'lastname' => (!empty($order['lastName'])) ? $order['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' => '0', + 'country_id' => 0 + ) + ), + ); + + + $this->model_customer_customer->addCustomer($cData); + + if (!empty($order['email'])) { + $tryToFind = $this->model_customer_customer->getCustomerByEmail($order['email']); + $customer_id = $tryToFind['customer_id']; + } else { + $last = $this->model_customer_customer->getCustomers($data = array('order' => 'DESC', 'limit' => 1)); + $customer_id = $last[0]['customer_id']; + } + + $customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id); + } + + $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'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $data['email'] = $order['email']; + $data['telephone'] = (!empty($order['customer']['phones'][0]['number'])) ? $order['customer']['phones'][0]['number'] : ' '; + $data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : ''; + $data['fax'] = ''; + $data['payment_address'] = '0'; + $data['payment_firstname'] = $order['firstName']; + $data['payment_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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']; + + $region = ''; + + if (!empty($order['delivery']['address']['region']) && is_int($order['delivery']['address']['region'])) { + $region = $order['delivery']['address']['region']; + } else { + foreach ($this->zones as $zone) { + if ($order['delivery']['address']['region'] == $zone['name']) { + $region = $zone['zone_id']; + } + } + } + + $data['payment_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['payment_zone_id'] = !empty($order['delivery']['address']['region']) ? $order['delivery']['address']['region'] : $region; + $data['shipping_country_id'] = !empty($order['delivery']['address']['country']) ? $order['delivery']['address']['country'] : 0; + $data['shipping_zone_id'] = $region; + $data['shipping_address'] = '0'; + $data['shipping_firstname'] = $order['firstName']; + $data['shipping_lastname'] = (!empty($order['lastName'])) ? $order['lastName'] : ' '; + $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'] = $this->delivery[$order['delivery']['code']]; + $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; + $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; + $data['payment'] = $this->payment[$order['paymentType']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$order['paymentType']]; + + // 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) { + $product = $this->model_catalog_product->getProduct($item['offer']['externalId']); + $data['order_product'][] = array( + 'product_id' => $item['offer']['externalId'], + 'name' => $item['offer']['name'], + 'quantity' => $item['quantity'], + 'price' => $item['initialPrice'], + 'total' => $item['initialPrice'] * $item['quantity'], + 'model' => $product['model'], + + // this data will not retrive from crm + 'order_product_id' => '', + 'tax' => 0, + 'reward' => 0 + ); + } + + $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['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['total_sort_order'] + ) + ); + + $data['fromApi'] = true; + $data['order_status_id'] = 1; + + $this->opencartApiClient->addOrder($data); + + $last = $this->model_sale_order->getOrders($data = array('order' => 'DESC', 'limit' => 1, 'start' => 0)); + + $ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $last[0]['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; + } +} diff --git a/admin/model/extension/retailcrm/history.php b/admin/model/extension/retailcrm/history/v4_5.php similarity index 90% rename from admin/model/extension/retailcrm/history.php rename to admin/model/extension/retailcrm/history/v4_5.php index 35755e0..7b936b1 100644 --- a/admin/model/extension/retailcrm/history.php +++ b/admin/model/extension/retailcrm/history/v4_5.php @@ -1,6 +1,6 @@ getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('setting/store'); $this->load->model('user/api'); @@ -20,12 +21,12 @@ class ModelExtensionRetailcrmHistory extends Model $this->load->language('extension/module/retailcrm'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); $history = $this->model_setting_setting->getSetting('retailcrm_history'); $settings['domain'] = parse_url(HTTP_SERVER, PHP_URL_HOST); - $url = isset($settings['retailcrm_url']) ? $settings['retailcrm_url'] : null; - $key = isset($settings['retailcrm_apikey']) ? $settings['retailcrm_apikey'] : null; + $url = isset($settings[$moduleTitle . '_url']) ? $settings[$moduleTitle . '_url'] : null; + $key = isset($settings[$moduleTitle . '_apikey']) ? $settings[$moduleTitle . '_apikey'] : null; if (empty($url) || empty($key)) { $this->log->addNotice('You need to configure retailcrm module first.'); @@ -35,9 +36,10 @@ class ModelExtensionRetailcrmHistory extends Model $this->opencartApiClient = new OpencartApiClient($this->registry); $crm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] ); $lastRun = !empty($history['retailcrm_history']) @@ -62,14 +64,14 @@ class ModelExtensionRetailcrmHistory extends Model $this->totalSettings = $this->model_setting_setting->getSetting('total'); $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); - $this->delivery = array_flip($settings['retailcrm_delivery']); - $this->payment = array_flip($settings['retailcrm_payment']); - $this->status = array_flip($settings['retailcrm_status']); + $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); + $this->payment = array_flip($settings[$moduleTitle . '_payment']); + $this->status = array_flip($settings[$moduleTitle . '_status']); $this->ocPayment = $this->model_extension_retailcrm_references ->getOpercartPaymentTypes(); - $this->ocDelivery = $settings['retailcrm_delivery']; + $this->ocDelivery = $settings[$moduleTitle . '_delivery']; $this->zones = $this->model_localisation_zone->getZones(); @@ -135,10 +137,22 @@ class ModelExtensionRetailcrmHistory extends Model } protected function updateOrders($orders) - { + { foreach ($orders as $order) { $store = $this->config->get('config_store_id'); + if ($order['payments']) { + foreach ($order['payments'] as $orderPayment) { + if (isset($orderPayment['externalId'])) { + $payment = $orderPayment; + } + } + + if (!isset($payment) && count($order['payments']) == 1) { + $payment = end($order['payments']); + } + } + $data = array(); $data['store_id'] = $store == null ? 0 : $store; @@ -194,9 +208,16 @@ class ModelExtensionRetailcrmHistory extends Model $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; - $data['payment'] = $this->payment[$order['paymentType']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$order['paymentType']]; + if (isset($payment)) { + $data['payment'] = $this->payment[$payment['type']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$payment['type']]; + } 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']; + } // this data will not retrive from crm for now $data['tax'] = ''; @@ -301,13 +322,17 @@ class ModelExtensionRetailcrmHistory extends Model } protected function createOrders($orders) - { + { $customersIdsFix = array(); $ordersIdsFix = array(); foreach ($orders as $order) { $store = $this->config->get('config_store_id'); + if ($order['payments']) { + $payment = end($order['payments']); + } + $customer_id = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0; @@ -406,10 +431,13 @@ class ModelExtensionRetailcrmHistory extends Model $data['shipping'] = $this->delivery[$order['delivery']['code']]; $data['shipping_method'] = $this->ocDelivery[$data['shipping']]; $data['shipping_code'] = $this->delivery[$order['delivery']['code']]; - $data['payment'] = $this->payment[$order['paymentType']]; - $data['payment_method'] = $this->ocPayment[$data['payment']]; - $data['payment_code'] = $this->payment[$order['paymentType']]; + if (isset($payment)) { + $data['payment'] = $this->payment[$payment['type']]; + $data['payment_method'] = $this->ocPayment[$data['payment']]; + $data['payment_code'] = $this->payment[$payment['type']]; + } + // this data will not retrive from crm for now $data['tax'] = ''; $data['tax_id'] = ''; @@ -510,4 +538,15 @@ class ModelExtensionRetailcrmHistory 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; + } } diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index f3d3963..f6e0e3f 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -3,10 +3,8 @@ class ModelExtensionRetailcrmOrder extends Model { public function uploadToCrm($orders) { - $this->load->model('catalog/product'); - $this->load->model('setting/setting'); - $this->settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); $ordersToCrm = array(); @@ -17,48 +15,40 @@ class ModelExtensionRetailcrmOrder extends Model { $chunkedOrders = array_chunk($ordersToCrm, 50); foreach($chunkedOrders as $ordersPart) { - $this->retailcrmApi->ordersUpload($ordersPart); + $this->retailcrm->ordersUpload($ordersPart); } } - public function uploadOrder($order) + public function uploadOrder($order_data) { if(isset($this->request->post['fromApi'])) return; - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $customers = $this->retailcrm->customersList( - array( - 'name' => $order['telephone'], - 'email' => $order['email'] - ), - 1, - 100 - ); - - $order = $this->process($order); + $moduleTitle = $this->getModuleTitle(); + $this->initApi(); - if($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); + + $order = $this->process($order_data); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; } + } - unset($customers); + unset($customers); - $result = $this->retailcrm->ordersCreate($order); + $result = $this->retailcrm->ordersCreate($order); + + if ($this->settings[$moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) { + $this->createPayment($order_data, $order_data['order_id']); } return $result; @@ -67,6 +57,7 @@ class ModelExtensionRetailcrmOrder extends Model { private function process($order_data) { $order = array(); + $moduleTitle = $this->getModuleTitle(); $payment_code = $order_data['payment_code']; $delivery_code = $order_data['shipping_code']; @@ -92,12 +83,15 @@ class ModelExtensionRetailcrmOrder extends Model { } $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $this->settings['retailcrm_payment'][$payment_code]; + + if ($this->settings[$moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $this->settings[$moduleTitle . '_payment'][$payment_code]; + } $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $this->settings['retailcrm_delivery'][$delivery_code] : '', + 'code' => !empty($delivery_code) ? $this->settings[$moduleTitle . '_delivery'][$delivery_code] : '', 'cost' => $deliveryCost, 'address' => array( 'index' => $order_data['shipping_postcode'], @@ -126,6 +120,14 @@ class ModelExtensionRetailcrmOrder extends Model { $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); foreach($product['option'] as $option) { + if ($option['type'] == 'checkbox') { + $properties[] = array( + 'code' => $option['product_option_value_id'], + 'name' => $option['name'], + 'value' => $option['value'] + ); + } + if(!in_array($option['type'], $offerOptions)) continue; foreach($productOptions as $productOption) { if($productOption['product_option_id'] = $option['product_option_id']) { @@ -147,16 +149,98 @@ class ModelExtensionRetailcrmOrder extends Model { $offerId = implode('_', $offerId); } - $order['items'][] = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); + if ($this->settings[$moduleTitle . '_apiversion'] != 'v3') { + $item = array( + 'offer' => array( + 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ), + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + ); + } else { + $item = array( + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ); + } + + if (isset($properties)) $item['properties'] = $properties; + $order['items'][] = $item; } return $order; } + + protected function createPayment($order, $order_id) + { + $moduleTitle = $this->getModuleTitle(); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $payment['order'] = array( + 'externalId' => $order_id + ); + + $this->retailcrm->ordersPaymentCreate($payment); + } + + private function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $this->settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(!empty($this->settings[$moduleTitle . '_url']) && !empty($this->settings[$moduleTitle . '_apikey'])) { + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $this->settings[$moduleTitle . '_url'], + $this->settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $this->settings[$moduleTitle . '_apiversion'] + ); + } + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/model/extension/retailcrm/references.php b/admin/model/extension/retailcrm/references.php index 79d7564..54d7edc 100644 --- a/admin/model/extension/retailcrm/references.php +++ b/admin/model/extension/retailcrm/references.php @@ -59,8 +59,14 @@ class ModelExtensionRetailcrmReferences extends Model $extension = basename($file, '.php'); $this->load->language('extension/payment/' . $extension); + + if (version_compare(VERSION, '3.0', '<')) { + $configStatus = $extension . '_status'; + } else { + $configStatus = 'payment_' . $extension . '_status'; + } - if ($this->config->get($extension . '_status')) { + if ($this->config->get($configStatus)) { $paymentTypes[$extension] = strip_tags( $this->language->get('heading_title') ); @@ -72,56 +78,56 @@ class ModelExtensionRetailcrmReferences extends Model } public function getApiDeliveryTypes() - { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + { + $this->initApi(); + + $response = $this->retailcrm->deliveryTypesList(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $response = $this->retailcrm->deliveryTypesList(); - - return ($response === false) ? array() : $response->deliveryTypes; - } + return ($response === false) ? array() : $response->deliveryTypes; } public function getApiOrderStatuses() { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); + $response = $this->retailcrm->statusesList(); - $response = $this->retailcrm->statusesList(); - - return ($response === false) ? array() : $response->statuses; - } + return ($response === false) ? array() : $response->statuses; } public function getApiPaymentTypes() + { + $this->initApi(); + + $response = $this->retailcrm->paymentTypesList(); + + return ($response === false) ? array() : $response->paymentTypes; + } + + protected function initApi() { + $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { + if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) { $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] ); - - $response = $this->retailcrm->paymentTypesList(); - - return ($response === false) ? array() : $response->paymentTypes; } } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/admin/view/template/extension/module/retailcrm.tpl b/admin/view/template/extension/module/retailcrm.tpl index 6ee4124..cd3d8eb 100644 --- a/admin/view/template/extension/module/retailcrm.tpl +++ b/admin/view/template/extension/module/retailcrm.tpl @@ -51,6 +51,14 @@

+
+
+ +

@@ -106,8 +114,8 @@ +
-

diff --git a/admin/view/template/extension/module/retailcrm.twig b/admin/view/template/extension/module/retailcrm.twig new file mode 100644 index 0000000..f76247b --- /dev/null +++ b/admin/view/template/extension/module/retailcrm.twig @@ -0,0 +1,314 @@ +{{ header }}{{ column_left }} + +
+ +
+ {% if error_warning %} +
+ + {{ error_warning }} +
+ {% endif %} + {% if saved_settings.module_retailcrm_url is defined %} + + + {% endif %} + +
+
+
+ + +
+
+ + +

{{ retailcrm_base_settings }}

+
+
+ +
+
+
+ +
+
+
+ +
+ +

{{ retailcrm_countries_settings }}

+
+
+ {% for country in countries %} +
+ +
+ {% endfor %} +
+
+ + {% if saved_settings.module_retailcrm_apikey is defined and saved_settings.module_retailcrm_apikey and saved_settings.module_retailcrm_url is defined and saved_settings.module_retailcrm_url %} + + {% if retailcrm_errors|length %} + {% for retailcrm_error in retailcrm_errors %} +
{{ retailcrm_error }}
+ {% endfor %} + {% else %} +

{{ retailcrm_upload_order }}

+
+ + +
+
+ +
+

{{ retailcrm_dict_settings }}

+ +

{{ retailcrm_dict_delivery }}

+ {% for value in delivery.opencart %} + +
{{ value.title ~ ':' }}
+ + {% for key, val in value %} + {% if key != 'title' %} +
+ + +
+ {% endif %} + {% endfor %} + {% endfor %} + +

{{ retailcrm_dict_status }}

+ {% for status in statuses.opencart %} + {% set uid = status.order_status_id %} +
+ + +
+ {% endfor %} + +

{{ retailcrm_dict_payment }}

+ {% for key, value in payments.opencart %} +
+ + +
+ {% endfor %} + + {% endif %} + + {% endif %} +
+ +
+

{{ daemon_collector }}

+
+ + + +
+
+ + +
+ {% if saved_settings.module_retailcrm_collector.site_key is not empty and + saved_settings.module_retailcrm_collector_active == 1 %} +
+ + + +
+ {% if saved_settings.module_retailcrm_collector.form_capture is defined and + saved_settings.module_retailcrm_collector.form_capture == 1 %} +
+ + +
+
+ + +
+
+ + +
+
+ + + +
+ {% if saved_settings.module_retailcrm_collector.custom_form is defined and + saved_settings.module_retailcrm_collector.custom_form == 1 %} + {% for field, label in collectorFields %} +
+ +
+ {# #} + + +
+
+ {% endfor %} + {% endif %} + {% endif %} + {% endif %} +
+
+
+
+
+
+
+ +{{ footer }} + + \ No newline at end of file diff --git a/catalog/controller/api/retailcrm.php b/catalog/controller/api/retailcrm.php index 823258c..b1441ce 100644 --- a/catalog/controller/api/retailcrm.php +++ b/catalog/controller/api/retailcrm.php @@ -26,11 +26,11 @@ class ControllerApiRetailcrm extends Controller protected function getDeliveryTypesByZones($country_id) { + $this->loadModels(); $this->load->model('localisation/zone'); $this->load->model('localisation/country'); - $this->load->model('extension/extension'); - $shippingModules = $this->model_extension_extension->getExtensions('shipping'); + $shippingModules = $this->{'model_' . $this->modelExtension}->getExtensions('shipping'); $zones = $this->model_localisation_zone->getZonesByCountryId($country_id); $country = $this->model_localisation_country->getCountry($country_id); $quote_data = array(); @@ -48,8 +48,13 @@ class ControllerApiRetailcrm extends Controller foreach ($shippingModules as $shippingModule) { $this->load->model('extension/shipping/' . $shippingModule['code']); - - if ($this->config->get($shippingModule['code'] . '_status')) { + if (version_compare(VERSION, '3.0', '<')) { + $shippingCode = $shippingModule['code']; + } else { + $shippingCode = 'shipping_' . $shippingModule['code']; + } + + if ($this->config->get($shippingCode . '_status')) { if($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) { $quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address); } @@ -70,4 +75,28 @@ class ControllerApiRetailcrm extends Controller return $deliveryTypes; } + + private function loadModels() + { + if (version_compare(VERSION, '3.0', '<')) { + $this->load->model('extension/extension'); + + $this->modelExtension = 'extension_extension'; + } else { + $this->load->model('setting/extension'); + + $this->modelExtension = 'setting_extension'; + } + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/controller/extension/analytics/daemon_collector.php b/catalog/controller/extension/analytics/daemon_collector.php index a8278d3..623a31a 100644 --- a/catalog/controller/extension/analytics/daemon_collector.php +++ b/catalog/controller/extension/analytics/daemon_collector.php @@ -2,9 +2,10 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller { public function index() { $this->load->model('setting/setting'); + $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - $setting = $settings['retailcrm_collector']; + $settings = $this->model_setting_setting->getSetting($moduleTitle); + $setting = $settings[$moduleTitle . '_collector']; $siteCode = isset($setting['site_key']) ? $setting['site_key'] : ''; if ($this->customer->isLogged()) $customerId = $this->customer->getID(); @@ -78,4 +79,15 @@ class ControllerExtensionAnalyticsDaemonCollector extends Controller { return html_entity_decode($js, ENT_QUOTES, 'UTF-8'); } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/controller/extension/module/retailcrm.php b/catalog/controller/extension/module/retailcrm.php index 20efee9..b056e93 100644 --- a/catalog/controller/extension/module/retailcrm.php +++ b/catalog/controller/extension/module/retailcrm.php @@ -19,7 +19,8 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function order_create($parameter1, $parameter2 = null, $parameter3 = null) - { + { + $moduleTitle = $this->getModuleTitle(); $this->load->model('checkout/order'); $this->load->model('account/order'); @@ -38,9 +39,9 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); + $status = $this->model_setting_setting->getSetting($moduleTitle); if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; } $this->load->model('extension/retailcrm/order'); @@ -56,6 +57,7 @@ class ControllerExtensionModuleRetailcrm extends Controller * @return void */ public function order_edit($parameter1, $parameter2 = null) { + $moduleTitle = $this->getModuleTitle(); $order_id = $parameter2[0]; $this->load->model('checkout/order'); @@ -77,10 +79,10 @@ class ControllerExtensionModuleRetailcrm extends Controller if (!isset($data['fromApi'])) { $this->load->model('setting/setting'); - $status = $this->model_setting_setting->getSetting('retailcrm'); + $status = $this->model_setting_setting->getSetting($moduleTitle); if ($data['order_status_id'] > 0) { - $data['order_status'] = $status['retailcrm_status'][$data['order_status_id']]; + $data['order_status'] = $status[$moduleTitle . '_status'][$data['order_status_id']]; } $this->load->model('extension/retailcrm/order'); @@ -140,4 +142,15 @@ class ControllerExtensionModuleRetailcrm extends Controller $this->load->model('extension/retailcrm/customer'); $this->model_extension_retailcrm_customer->changeInCrm($customer); } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/model/extension/retailcrm/customer.php b/catalog/model/extension/retailcrm/customer.php index 251683b..c51f73a 100644 --- a/catalog/model/extension/retailcrm/customer.php +++ b/catalog/model/extension/retailcrm/customer.php @@ -1,44 +1,24 @@ load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function sendToCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - + $customerToCrm = $this->process($customer); $this->retailcrmApi->customersCreate($customerToCrm); } - public function changeInCrm($customer) { - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + public function changeInCrm($customer) + { + $this->initApi(); if(empty($customer)) return false; - if(empty($settings['retailcrm_url']) || empty($settings['retailcrm_apikey'])) - return false; - - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; - - $this->retailcrmApi = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); $customerToCrm = $this->process($customer); @@ -59,6 +39,46 @@ class ModelExtensionRetailcrmCustomer extends Model { 'createdAt' => $customer['date_added'] ); + if (isset($customer['address'])) { + $customerToCrm['address'] = array( + 'index' => $customer['address']['postcode'], + 'countryIso' => $customer['address']['iso_code_2'], + 'region' => $customer['address']['zone'], + 'city' => $customer['address']['city'], + 'text' => $customer['address']['address_1'] . ' ' . $customer['address']['address_2'] + ); + } + return $customerToCrm; } + + protected function initApi() + { + $this->load->model('setting/setting'); + $moduleTitle = $this->getModuleTitle(); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(empty($settings[$moduleTitle . '_url']) || empty($settings[$moduleTitle . '_apikey'])) + return false; + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrmApi = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); + } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } } diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 3a3a7a1..45cd15a 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -6,162 +6,32 @@ class ModelExtensionRetailcrmOrder extends Model { { if(isset($this->request->post['fromApi'])) return; - $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); + $this->initApi(); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); + $order = array(); - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); - - $order = array(); - - $customers = $this->retailcrm->customersList( - array( - 'name' => $order_data['telephone'], - 'email' => $order_data['email'] - ), - 1, - 100 - ); - - if($customers) { - foreach ($customers['customers'] as $customer) { - $order['customer']['id'] = $customer['id']; - } + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; } + } - unset($customers); + unset($customers); - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; + $order = $this->processOrder($order_data, $order_id); + $response = $this->retailcrm->ordersCreate($order); - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; - } - - $deliveryCost = 0; - $altTotals = isset($order_data['order_total']) ? $order_data['order_total'] : ""; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $altTotals ; - $couponTotal = 0; - - if (!empty($orderTotals)) { - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - - if ($totals['code'] == 'coupon') { - $couponTotal = abs($totals['value']); - } - } - } - - if(isset($couponTotal)) $order['discount'] = $couponTotal; - $order['createdAt'] = $order_data['date_added']; - - $payment_code = $order_data['payment_code']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; - - if(!isset($order_data['shipping_iso_code_2']) && isset($order_data['shipping_country_id'])) { - $this->load->model('localisation/country'); - $shipping_country = $this->model_localisation_country->getCountry($order_data['shipping_country_id']); - $order_data['shipping_iso_code_2'] = $shipping_country['iso_code_2']; - } - - if(isset($settings['retailcrm_delivery'][$order_data['shipping_code']])) { - $delivery_code = $order_data['shipping_code']; - } else { - $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); - } - - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'cost' => $deliveryCost, - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'countryIso' => $order_data['shipping_iso_code_2'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '', - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); - - foreach ($orderProducts as $product) { - $offerId = ''; - - if(!empty($product['option'])) { - $options = array(); - - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); - - foreach($product['option'] as $option) { - if ($option['type'] == 'checkbox') { - $properties[] = array( - 'code' => $option['product_option_value_id'], - 'name' => $option['name'], - 'value' => $option['value'] - ); - } - - if(!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } - } - } - } - } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); - } - - $item = array( - 'offer' => array( - 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] - ), - 'productName' => $product['name'], - 'initialPrice' => $product['price'], - 'quantity' => $product['quantity'], - ); - - if (isset($properties)) $item['properties'] = $properties; - - $order['items'][] = $item; - } - - if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; - } - - $this->retailcrm->ordersCreate($order); + if ($settings[$moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + $this->createPayment($order_data, $order_id); } } @@ -169,121 +39,134 @@ class ModelExtensionRetailcrmOrder extends Model { { if(isset($this->request->post['fromApi'])) return; + $this->initApi(); + + $order = array(); + + $order = $this->processOrder($order_data, $order_id); + + $response = $this->retailcrm->ordersEdit($order); + + if ($settings[$moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + $this->editPayment($order_data, $order_id); + } + } + + protected function processOrder($order_data, $order_id) + { + $moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); - $settings = $this->model_setting_setting->getSetting('retailcrm'); - $settingPaid = $this->model_setting_setting->getSetting($order_data['payment_code']); + $this->load->model('catalog/product'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); - if(!empty($settings['retailcrm_url']) && !empty($settings['retailcrm_apikey'])) { - $this->load->model('catalog/product'); + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order_data['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order_data['payment_code']); + } - require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + $payment_code = $order_data['payment_code']; + $order['externalId'] = $order_id; + $order['firstName'] = $order_data['firstname']; + $order['lastName'] = $order_data['lastname']; + $order['phone'] = $order_data['telephone']; + $order['customerComment'] = $order_data['comment']; - $this->retailcrm = new RetailcrmProxy( - $settings['retailcrm_url'], - $settings['retailcrm_apikey'], - DIR_SYSTEM . 'storage/logs/retailcrm.log' - ); + if(!empty($order_data['email'])) { + $order['email'] = $order_data['email']; + } - $order = array(); + $deliveryCost = 0; + $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - $payment_code = $order_data['payment_code']; - $order['externalId'] = $order_id; - $order['firstName'] = $order_data['firstname']; - $order['lastName'] = $order_data['lastname']; - $order['phone'] = $order_data['telephone']; - $order['customerComment'] = $order_data['comment']; - - if(!empty($order_data['email'])) { - $order['email'] = $order_data['email']; + foreach ($orderTotals as $totals) { + if ($totals['code'] == 'shipping') { + $deliveryCost = $totals['value']; } - $deliveryCost = 0; - $orderTotals = isset($order_data['totals']) ? $order_data['totals'] : $order_data['order_total'] ; - - foreach ($orderTotals as $totals) { - if ($totals['code'] == 'shipping') { - $deliveryCost = $totals['value']; - } - - if ($totals['code'] == 'coupon') { - $couponTotal = abs($totals['value']); - } + if ($totals['code'] == 'coupon') { + $couponTotal = abs($totals['value']); } - - if(isset($couponTotal)) $order['discount'] = $couponTotal; - $order['createdAt'] = $order_data['date_added']; - $order['paymentType'] = $settings['retailcrm_payment'][$payment_code]; + } - $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; + if (isset($couponTotal)) $order['discount'] = $couponTotal; + $order['createdAt'] = $order_data['date_added']; - if(isset($settings['retailcrm_delivery'][$order_data['shipping_code']])) { - $delivery_code = $order_data['shipping_code']; - } else { - $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); - } + if ($settings[$moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $settings[$moduleTitle . '_payment'][$payment_code]; + } - $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings['retailcrm_delivery'][$delivery_code] : '', - 'address' => array( - 'index' => $order_data['shipping_postcode'], - 'city' => $order_data['shipping_city'], - 'countryIso' => $order_data['shipping_iso_code_2'], - 'region' => $order_data['shipping_zone'], - 'text' => implode(', ', array( - $order_data['shipping_postcode'], - $country, - $order_data['shipping_city'], - $order_data['shipping_address_1'], - $order_data['shipping_address_2'] - )) - ) - ); + $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - if(!empty($deliveryCost)){ - $order['delivery']['cost'] = $deliveryCost; - } - - $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; - $offerOptions = array('select', 'radio'); + if(isset($settings[$moduleTitle . '_delivery'][$order_data['shipping_code']])) { + $delivery_code = $order_data['shipping_code']; + } else { + $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); + } - foreach ($orderProducts as $product) { - $offerId = ''; + $order['delivery'] = array( + 'code' => !empty($delivery_code) ? $settings[$moduleTitle . '_delivery'][$delivery_code] : '', + 'address' => array( + 'index' => $order_data['shipping_postcode'], + 'city' => $order_data['shipping_city'], + 'countryIso' => $order_data['shipping_iso_code_2'], + 'region' => $order_data['shipping_zone'], + 'text' => implode(', ', array( + $order_data['shipping_postcode'], + $country, + $order_data['shipping_city'], + $order_data['shipping_address_1'], + $order_data['shipping_address_2'] + )) + ) + ); - if (!empty($product['option'])) { - $options = array(); + if(!empty($deliveryCost)){ + $order['delivery']['cost'] = $deliveryCost; + } + + $orderProducts = isset($order_data['products']) ? $order_data['products'] : $order_data['order_product']; + $offerOptions = array('select', 'radio'); - $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + foreach ($orderProducts as $product) { + $offerId = ''; - foreach($product['option'] as $option) { - if ($option['type'] == 'checkbox') { - $properties[] = array( - 'code' => $option['product_option_value_id'], - 'name' => $option['name'], - 'value' => $option['value'] - ); - } - - if(!in_array($option['type'], $offerOptions)) continue; - foreach($productOptions as $productOption) { - if($productOption['product_option_id'] = $option['product_option_id']) { - foreach($productOption['product_option_value'] as $productOptionValue) { - if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { - $options[$option['product_option_id']] = $productOptionValue['option_value_id']; - } + if (!empty($product['option'])) { + $options = array(); + + $productOptions = $this->model_catalog_product->getProductOptions($product['product_id']); + + foreach($product['option'] as $option) { + if ($option['type'] == 'checkbox') { + $properties[] = array( + 'code' => $option['product_option_value_id'], + 'name' => $option['name'], + 'value' => $option['value'] + ); + } + + if(!in_array($option['type'], $offerOptions)) continue; + foreach($productOptions as $productOption) { + if($productOption['product_option_id'] = $option['product_option_id']) { + foreach($productOption['product_option_value'] as $productOptionValue) { + if($productOptionValue['product_option_value_id'] == $option['product_option_value_id']) { + $options[$option['product_option_id']] = $productOptionValue['option_value_id']; } } } } - - ksort($options); - - $offerId = array(); - foreach($options as $optionKey => $optionValue) { - $offerId[] = $optionKey.'-'.$optionValue; - } - $offerId = implode('_', $offerId); } + ksort($options); + + $offerId = array(); + foreach($options as $optionKey => $optionValue) { + $offerId[] = $optionKey.'-'.$optionValue; + } + $offerId = implode('_', $offerId); + } + + if ($settings[$moduleTitle . '_apiversion'] != 'v3') { $item = array( 'offer' => array( 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] @@ -292,21 +175,143 @@ class ModelExtensionRetailcrmOrder extends Model { 'initialPrice' => $product['price'], 'quantity' => $product['quantity'], ); - - if (isset($properties)) $item['properties'] = $properties; - - $order['items'][] = $item; + } else { + $item = array( + 'productName' => $product['name'], + 'initialPrice' => $product['price'], + 'quantity' => $product['quantity'], + 'productId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] + ); } + if (isset($properties)) $item['properties'] = $properties; + + $order['items'][] = $item; + if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings['retailcrm_status'][$order_data['order_status_id']]; + $order['status'] = $settings[$moduleTitle . '_status'][$order_data['order_status_id']]; } - if ($order_data['order_status_id'] == $settingPaid[$order_data['payment_code'] . '_order_status_id']) { - $order['paymentStatus'] = 'paid'; + if ($settings[$moduleTitle . '_apiversion'] != 'v5') { + if (version_compare(VERSION, '3.0', '<')) { + if ($order_data['order_status_id'] == $settingPaid[$order_data['payment_code'] . '_order_status_id']) { + $order['paymentStatus'] = 'paid'; + } + } else { + if ($order_data['order_status_id'] == $settingPaid['payment_' . $order_data['payment_code'] . '_order_status_id']) { + $order['paymentStatus'] = 'paid'; + } + } } - - $this->retailcrm->ordersEdit($order); + } + + return $order; + } + + protected function createPayment($order, $order_id) + { + $moduleTitle = $this->getModuleTitle(); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $payment['order'] = array( + 'externalId' => $order_id + ); + + $this->retailcrm->ordersPaymentCreate($payment); + } + + protected function editPayment($order, $order_id) + { + $moduleTitle = $this->getModuleTitle(); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if (version_compare(VERSION, '3.0', '<')) { + $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); + } else { + $settingPaid = $this->model_setting_setting->getSetting('payment_' . $order['payment_code']); + } + + $payment_code = $order['payment_code']; + + foreach ($order['totals'] as $total) { + if ($total['code'] == 'total') $amount = $total['value']; + } + + $payment = array( + 'externalId' => $order_id, + 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'amount' => $amount + ); + + if (version_compare(VERSION, '3.0', '<')) { + if ($order['order_status_id'] == $settingPaid[$order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } else { + if ($order['order_status_id'] == $settingPaid['payment_' . $order['payment_code'] . '_order_status_id']) { + $payment['status'] = 'paid'; + } + } + + $this->retailcrm->ordersPaymentEdit($payment); + } + + private function initApi() + { + $moduleTitle = $this->getModuleTitle(); + $this->load->model('setting/setting'); + $settings = $this->model_setting_setting->getSetting($moduleTitle); + + if(!empty($settings[$moduleTitle . '_url']) && !empty($settings[$moduleTitle . '_apikey'])) { + + require_once DIR_SYSTEM . 'library/retailcrm/bootstrap.php'; + + $this->retailcrm = new RetailcrmProxy( + $settings[$moduleTitle . '_url'], + $settings[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $settings[$moduleTitle . '_apiversion'] + ); } } + + private function getModuleTitle() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = 'retailcrm'; + } else { + $title = 'module_retailcrm'; + } + + return $title; + } + } diff --git a/system/cron/dispatch.php b/system/cron/dispatch.php index 69ee0ed..e1ababf 100644 --- a/system/cron/dispatch.php +++ b/system/cron/dispatch.php @@ -50,6 +50,12 @@ $registry->set('load', $loader); // Config $config = new Config(); + +if (version_compare(VERSION, '3.0', '>=')) { + $config->load('default'); + $config->load('catalog'); +} + $registry->set('config', $config); // Database @@ -122,7 +128,13 @@ $cache = new Cache('file'); $registry->set('cache', $cache); $registry->set('response', $response); -$session = new Session(); + +if (version_compare(VERSION, '3.0', '<')) { + $session = new Session(); +} else { + $session = new Session($config->get('session_engine'), $registry); +} + $registry->set('session', $session); $languages = array(); @@ -150,8 +162,12 @@ $registry->set('weight', new Cart\Weight($registry)); $registry->set('length', new Cart\Length($registry)); $registry->set('user', new Cart\User($registry)); +if (version_compare(VERSION, '3.0', '<')) { + $controller = new Front($registry); +} else { + $controller = new Router($registry); +} -$controller = new Front($registry); $action = new Action($cli_action); $controller->dispatch($action, new Action('error/not_found')); diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index c9e3569..13f9b91 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -44,7 +44,12 @@ class OpencartApiClient { $opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId); if(!empty($this->apiToken)) { - $getParams['token'] = $this->apiToken; + if (version_compare(VERSION, '3.0', '<')) { + $getParams['token'] = $this->apiToken; + } else { + $getParams['api_token'] = $this->apiToken; + } + } $postParams['fromApi'] = true; @@ -89,10 +94,7 @@ class OpencartApiClient { $api = array(); foreach ($apiUsers as $apiUser) { if($apiUser['status'] == 1) { - $api = array( - 'api_id' => $apiUser['api_id'], - 'key' => $apiUser['key'] - ); + $api = $apiUser; break; } } @@ -114,10 +116,14 @@ class OpencartApiClient { $this->model_user_api->addApiIp($api['api_id'], $innerIp); } - - $apiAnswer = $this->request('login', array(), $apiUser); - - $this->apiToken = $apiAnswer['token']; + if (version_compare(VERSION, '3.0', '<')){ + $apiAnswer = $this->request('login', array(), $api); + $this->apiToken = $apiAnswer['token']; + } else { + $this->apiToken = $this->session->getID(); + $apiAnswer = $this->request('login', array(), $api); + } + return $apiAnswer; } diff --git a/system/library/retailcrm/RetailcrmApiClient3.php b/system/library/retailcrm/RetailcrmApiClient3.php new file mode 100644 index 0000000..82631e0 --- /dev/null +++ b/system/library/retailcrm/RetailcrmApiClient3.php @@ -0,0 +1,811 @@ +client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * Create a order + * + * @param array $order + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function ordersCreate(array $order, $site = null) + { + if (!sizeof($order)) { + throw new InvalidArgumentException('Parameter `order` must contains a data'); + } + + return $this->client->makeRequest("/orders/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( + 'order' => json_encode($order) + ))); + } + + /** + * Edit a order + * + * @param array $order + * @param string $by + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function ordersEdit(array $order, $by = 'externalId', $site = null) + { + if (!sizeof($order)) { + throw new InvalidArgumentException('Parameter `order` must contains a data'); + } + + $this->checkIdParameter($by); + + if (!isset($order[$by])) { + throw new InvalidArgumentException(sprintf('Order array must contain the "%s" parameter.', $by)); + } + + return $this->client->makeRequest( + "/orders/" . $order[$by] . "/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array( + 'order' => json_encode($order), + 'by' => $by, + )) + ); + } + + /** + * Upload array of the orders + * + * @param array $orders + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function ordersUpload(array $orders, $site = null) + { + if (!sizeof($orders)) { + throw new InvalidArgumentException('Parameter `orders` must contains array of the orders'); + } + + return $this->client->makeRequest("/orders/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( + 'orders' => json_encode($orders), + ))); + } + + /** + * Get order by id or externalId + * + * @param string $id + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function ordersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest("/orders/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( + 'by' => $by + ))); + } + + /** + * Returns a orders history + * + * @param DateTime $startDate (default: null) + * @param DateTime $endDate (default: null) + * @param int $limit (default: 100) + * @param int $offset (default: 0) + * @param bool $skipMyChanges (default: true) + * @return RetailcrmApiResponse + */ + public function ordersHistory( + DateTime $startDate = null, + DateTime $endDate = null, + $limit = 100, + $offset = 0, + $skipMyChanges = true + ) { + $parameters = array(); + + if ($startDate) { + $parameters['startDate'] = $startDate->format('Y-m-d H:i:s'); + } + if ($endDate) { + $parameters['endDate'] = $endDate->format('Y-m-d H:i:s'); + } + if ($limit) { + $parameters['limit'] = (int) $limit; + } + if ($offset) { + $parameters['offset'] = (int) $offset; + } + if ($skipMyChanges) { + $parameters['skipMyChanges'] = (bool) $skipMyChanges; + } + + return $this->client->makeRequest('/orders/history', RetailcrmHttpClient::METHOD_GET, $parameters); + } + + /** + * Returns filtered orders list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @return RetailcrmApiResponse + */ + public function ordersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (sizeof($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest('/orders', RetailcrmHttpClient::METHOD_GET, $parameters); + } + + /** + * Returns statuses of the orders + * + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * @return RetailcrmApiResponse + */ + public function ordersStatuses(array $ids = array(), array $externalIds = array()) + { + $parameters = array(); + + if (sizeof($ids)) { + $parameters['ids'] = $ids; + } + if (sizeof($externalIds)) { + $parameters['externalIds'] = $externalIds; + } + + return $this->client->makeRequest('/orders/statuses', RetailcrmHttpClient::METHOD_GET, $parameters); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids + * @return RetailcrmApiResponse + */ + public function ordersFixExternalIds(array $ids) + { + if (!sizeof($ids)) { + throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); + } + + return $this->client->makeRequest("/orders/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( + 'orders' => json_encode($ids), + )); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @return RetailcrmApiResponse + */ + public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (sizeof($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest('/orders/packs/history', RetailcrmHttpClient::METHOD_GET, $parameters); + } + + /** + * Create a customer + * + * @param array $customer + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function customersCreate(array $customer, $site = null) + { + if (!sizeof($customer)) { + throw new InvalidArgumentException('Parameter `customer` must contains a data'); + } + + return $this->client->makeRequest("/customers/create", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( + 'customer' => json_encode($customer) + ))); + } + + /** + * Edit a customer + * + * @param array $customer + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function customersEdit(array $customer, $by = 'externalId', $site = null) + { + if (!sizeof($customer)) { + throw new InvalidArgumentException('Parameter `customer` must contains a data'); + } + + $this->checkIdParameter($by); + + if (!isset($customer[$by])) { + throw new InvalidArgumentException(sprintf('Customer array must contain the "%s" parameter.', $by)); + } + + return $this->client->makeRequest( + "/customers/" . $customer[$by] . "/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array( + 'customer' => json_encode($customer), + 'by' => $by + ) + ) + ); + } + + /** + * Upload array of the customers + * + * @param array $customers + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function customersUpload(array $customers, $site = null) + { + if (!sizeof($customers)) { + throw new InvalidArgumentException('Parameter `customers` must contains array of the customers'); + } + + return $this->client->makeRequest("/customers/upload", RetailcrmHttpClient::METHOD_POST, $this->fillSite($site, array( + 'customers' => json_encode($customers), + ))); + } + + /** + * Get customer by id or externalId + * + * @param string $id + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest("/customers/$id", RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, array( + 'by' => $by + ))); + } + + /** + * Returns filtered customers list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @return RetailcrmApiResponse + */ + public function customersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (sizeof($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest('/customers', RetailcrmHttpClient::METHOD_GET, $parameters); + } + + /** + * Save customer IDs' (id and externalId) association in the CRM + * + * @param array $ids + * @return RetailcrmApiResponse + */ + public function customersFixExternalIds(array $ids) + { + if (!sizeof($ids)) { + throw new InvalidArgumentException('Method parameter must contains at least one IDs pair'); + } + + return $this->client->makeRequest("/customers/fix-external-ids", RetailcrmHttpClient::METHOD_POST, array( + 'customers' => json_encode($ids), + )); + } + + /** + * Get purchace prices & stock balance + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null) + { + $parameters = array(); + + if (sizeof($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest('/store/inventories', RetailcrmHttpClient::METHOD_GET, $this->fillSite($site, $parameters)); + } + + /** + * Upload store inventories + * + * @param array $offers + * @param string $site (default: null) + * @return RetailcrmApiResponse + */ + public function storeInventoriesUpload(array $offers, $site = null) + { + if (!sizeof($offers)) { + throw new InvalidArgumentException('Parameter `offers` must contains array of the customers'); + } + + return $this->client->makeRequest( + "/store/inventories/upload", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('offers' => json_encode($offers))) + ); + } + + /** + * Returns deliveryServices list + * + * @return RetailcrmApiResponse + */ + public function deliveryServicesList() + { + return $this->client->makeRequest('/reference/delivery-services', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns deliveryTypes list + * + * @return RetailcrmApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest('/reference/delivery-types', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns orderMethods list + * + * @return RetailcrmApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest('/reference/order-methods', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns orderTypes list + * + * @return RetailcrmApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest('/reference/order-types', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns paymentStatuses list + * + * @return RetailcrmApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest('/reference/payment-statuses', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns paymentTypes list + * + * @return RetailcrmApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest('/reference/payment-types', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns productStatuses list + * + * @return RetailcrmApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest('/reference/product-statuses', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns statusGroups list + * + * @return RetailcrmApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest('/reference/status-groups', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns statuses list + * + * @return RetailcrmApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest('/reference/statuses', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns sites list + * + * @return RetailcrmApiResponse + */ + public function sitesList() + { + return $this->client->makeRequest('/reference/sites', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns stores list + * + * @return RetailcrmApiResponse + */ + public function storesList() + { + return $this->client->makeRequest('/reference/stores', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Edit deliveryService + * + * @param array $data delivery service data + * @return RetailcrmApiResponse + */ + public function deliveryServicesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/delivery-services/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'deliveryService' => json_encode($data) + ) + ); + } + + /** + * Edit deliveryType + * + * @param array $data delivery type data + * @return RetailcrmApiResponse + */ + public function deliveryTypesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/delivery-types/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'deliveryType' => json_encode($data) + ) + ); + } + + /** + * Edit orderMethod + * + * @param array $data order method data + * @return RetailcrmApiResponse + */ + public function orderMethodsEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/order-methods/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'orderMethod' => json_encode($data) + ) + ); + } + + /** + * Edit orderType + * + * @param array $data order type data + * @return RetailcrmApiResponse + */ + public function orderTypesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/order-types/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'orderType' => json_encode($data) + ) + ); + } + + /** + * Edit paymentStatus + * + * @param array $data payment status data + * @return RetailcrmApiResponse + */ + public function paymentStatusesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/payment-statuses/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'paymentStatus' => json_encode($data) + ) + ); + } + + /** + * Edit paymentType + * + * @param array $data payment type data + * @return RetailcrmApiResponse + */ + public function paymentTypesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/payment-types/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'paymentType' => json_encode($data) + ) + ); + } + + /** + * Edit productStatus + * + * @param array $data product status data + * @return RetailcrmApiResponse + */ + public function productStatusesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/product-statuses/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'productStatus' => json_encode($data) + ) + ); + } + + /** + * Edit order status + * + * @param array $data status data + * @return RetailcrmApiResponse + */ + public function statusesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/statuses/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'status' => json_encode($data) + ) + ); + } + + /** + * Edit site + * + * @param array $data site data + * @return RetailcrmApiResponse + */ + public function sitesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + return $this->client->makeRequest( + '/reference/sites/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'site' => json_encode($data) + ) + ); + } + + /** + * Edit store + * + * @param array $data site data + * @return RetailcrmApiResponse + */ + public function storesEdit(array $data) + { + if (!isset($data['code'])) { + throw new InvalidArgumentException('Data must contain "code" parameter.'); + } + + if (!isset($data['name'])) { + throw new InvalidArgumentException('Data must contain "name" parameter.'); + } + + return $this->client->makeRequest( + '/reference/stores/' . $data['code'] . '/edit', + RetailcrmHttpClient::METHOD_POST, + array( + 'store' => json_encode($data) + ) + ); + } + + /** + * Update CRM basic statistic + * + * @return RetailcrmApiResponse + */ + public function statisticUpdate() + { + return $this->client->makeRequest('/statistic/update', RetailcrmHttpClient::METHOD_GET); + } + + /** + * Return current site + * + * @return string + */ + public function getSite() + { + return $this->siteCode; + } + + /** + * Set site + * + * @param string $site + * @return void + */ + public function setSite($site) + { + $this->siteCode = $site; + } + + /** + * Check ID parameter + * + * @param string $by + * @return bool + */ + protected function checkIdParameter($by) + { + $allowedForBy = array('externalId', 'id'); + if (!in_array($by, $allowedForBy)) { + throw new InvalidArgumentException(sprintf( + 'Value "%s" for parameter "by" is not valid. Allowed values are %s.', + $by, + implode(', ', $allowedForBy) + )); + } + + return true; + } + + /** + * Fill params by site value + * + * @param string $site + * @param array $params + * @return array + */ + protected function fillSite($site, array $params) + { + if ($site) { + $params['site'] = $site; + } elseif ($this->siteCode) { + $params['site'] = $this->siteCode; + } + + return $params; + } +} diff --git a/system/library/retailcrm/RetailcrmApiClient4.php b/system/library/retailcrm/RetailcrmApiClient4.php new file mode 100644 index 0000000..eca5eb5 --- /dev/null +++ b/system/library/retailcrm/RetailcrmApiClient4.php @@ -0,0 +1,1723 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class RetailcrmApiClient4 +{ + + const VERSION = 'v4'; + + protected $client; + + /** + * Site code + */ + protected $siteCode; + + /** + * Client creating + * + * @param string $url api url + * @param string $apiKey api key + * @param string $site site code + * + * @throws \InvalidArgumentException + * + * @return mixed + */ + public function __construct($url, $apiKey, $site = null) + { + if ('/' !== $url[strlen($url) - 1]) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * Returns users list + * + * @param array $filter + * @param null $page + * @param null $limit + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/users', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Returns user data + * + * @param integer $id user ID + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersGet($id) + { + return $this->client->makeRequest("/users/$id", RetailcrmHttpClient::METHOD_GET); + } + + /** + * Returns filtered orders list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create a order + * + * @param array $order order data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersCreate(array $order, $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('order' => json_encode($order))) + ); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids order identificators + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/orders/fix-external-ids', + RetailcrmHttpClient::METHOD_POST, + array('orders' => json_encode($ids) + ) + ); + } + + /** + * Returns statuses of the orders + * + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersStatuses(array $ids = array(), array $externalIds = array()) + { + $parameters = array(); + + if (count($ids)) { + $parameters['ids'] = $ids; + } + if (count($externalIds)) { + $parameters['externalIds'] = $externalIds; + } + + return $this->client->makeRequest( + '/orders/statuses', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Upload array of the orders + * + * @param array $orders array of orders + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersUpload(array $orders, $site = null) + { + if (!count($orders)) { + throw new \InvalidArgumentException( + 'Parameter `orders` must contains array of the orders' + ); + } + + return $this->client->makeRequest( + '/orders/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('orders' => json_encode($orders))) + ); + } + + /** + * Get order by id or externalId + * + * @param string $id order identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/orders/$id", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a order + * + * @param array $order order data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersEdit(array $order, $by = 'externalId', $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $order)) { + throw new \InvalidArgumentException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/orders/%s/edit', $order[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('order' => json_encode($order), 'by' => $by) + ) + ); + } + + /** + * Get orders history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function ordersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Returns filtered customers list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create a customer + * + * @param array $customer customer data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersCreate(array $customer, $site = null) + { + if (! count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('customer' => json_encode($customer))) + ); + } + + /** + * Save customer IDs' (id and externalId) association in the CRM + * + * @param array $ids ids mapping + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/customers/fix-external-ids', + RetailcrmHttpClient::METHOD_POST, + array('customers' => json_encode($ids)) + ); + } + + /** + * Upload array of the customers + * + * @param array $customers array of customers + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersUpload(array $customers, $site = null) + { + if (! count($customers)) { + throw new \InvalidArgumentException( + 'Parameter `customers` must contains array of the customers' + ); + } + + return $this->client->makeRequest( + '/customers/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('customers' => json_encode($customers))) + ); + } + + /** + * Get customer by id or externalId + * + * @param string $id customer identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/customers/$id", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a customer + * + * @param array $customer customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersEdit(array $customer, $by = 'externalId', $site = null) + { + if (!count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $customer)) { + throw new \InvalidArgumentException( + sprintf('Customer array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/customers/%s/edit', $customer[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('customer' => json_encode($customer), 'by' => $by) + ) + ); + } + + /** + * Get customers history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function customersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksCreate(array $pack, $site = null) + { + if (!count($pack)) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/packs/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksGet($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + "/orders/packs/$id", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Delete orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/delete', $id), + RetailcrmHttpClient::METHOD_POST + ); + } + + /** + * Edit orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksEdit(array $pack, $site = null) + { + if (!count($pack) || empty($pack['id'])) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data & pack `id` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/edit', $pack['id']), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get purchace prices & stock balance + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventories(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/inventories', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get store settings + * + * @param string $code get settings code + * + * @return ApiResponse + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/store/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit store configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/store/setting/%s/edit', $configuration['code']), + RetailcrmHttpClient::METHOD_POST, + $configuration + ); + } + + /** + * Upload store inventories + * + * @param array $offers offers data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventoriesUpload(array $offers, $site = null) + { + if (!count($offers)) { + throw new \InvalidArgumentException( + 'Parameter `offers` must contains array of the offers' + ); + } + + return $this->client->makeRequest( + '/store/inventories/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('offers' => json_encode($offers))) + ); + } + + /** + * Get products + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeProducts(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/products', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get delivery settings + * + * @param string $code + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliverySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/delivery/generic/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit delivery configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliverySettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), + RetailcrmHttpClient::METHOD_POST, + array('configuration' => json_encode($configuration)) + ); + } + + /** + * Delivery tracking update + * + * @param string $code + * @param array $statusUpdate + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliveryTracking($code, array $statusUpdate) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + if (!count($statusUpdate)) { + throw new \InvalidArgumentException( + 'Parameter `statusUpdate` must contains a data' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/%s/tracking', $code), + RetailcrmHttpClient::METHOD_POST, + $statusUpdate + ); + } + + /** + * Returns available county list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function countriesList() + { + return $this->client->makeRequest( + '/reference/countries', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Returns deliveryServices list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesList() + { + return $this->client->makeRequest( + '/reference/delivery-services', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit deliveryService + * + * @param array $data delivery service data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-services/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('deliveryService' => json_encode($data)) + ); + } + + /** + * Returns deliveryTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest( + '/reference/delivery-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit deliveryType + * + * @param array $data delivery type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('deliveryType' => json_encode($data)) + ); + } + + /** + * Returns orderMethods list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest( + '/reference/order-methods', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit orderMethod + * + * @param array $data order method data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-methods/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('orderMethod' => json_encode($data)) + ); + } + + /** + * Returns orderTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest( + '/reference/order-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit orderType + * + * @param array $data order type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('orderType' => json_encode($data)) + ); + } + + /** + * Returns paymentStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest( + '/reference/payment-statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit paymentStatus + * + * @param array $data payment status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('paymentStatus' => json_encode($data)) + ); + } + + /** + * Returns paymentTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest( + '/reference/payment-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit paymentType + * + * @param array $data payment type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('paymentType' => json_encode($data)) + ); + } + + /** + * Returns productStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest( + '/reference/product-statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit productStatus + * + * @param array $data product status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/product-statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('productStatus' => json_encode($data)) + ); + } + + /** + * Returns sites list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesList() + { + return $this->client->makeRequest( + '/reference/sites', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit site + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/sites/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('site' => json_encode($data)) + ); + } + + /** + * Returns statusGroups list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest( + '/reference/status-groups', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Returns statuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest( + '/reference/statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit order status + * + * @param array $data status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('status' => json_encode($data)) + ); + } + + /** + * Returns stores list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesList() + { + return $this->client->makeRequest( + '/reference/stores', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit store + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + if (!array_key_exists('name', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "name" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/stores/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('store' => json_encode($data)) + ); + } + + /** + * Get telephony settings + * + * @param string $code + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function telephonySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/telephony/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit telephony settings + * + * @param string $code symbolic code + * @param string $clientId client id + * @param boolean $active telephony activity + * @param mixed $name service name + * @param mixed $makeCallUrl service init url + * @param mixed $image service logo url(svg file) + * + * @param array $additionalCodes + * @param array $externalPhones + * @param bool $allowEdit + * @param bool $inputEventSupported + * @param bool $outputEventSupported + * @param bool $hangupEventSupported + * @param bool $changeUserStatusUrl + * + * @return ApiResponse + */ + public function telephonySettingsEdit( + $code, + $clientId, + $active = false, + $name = false, + $makeCallUrl = false, + $image = false, + $additionalCodes = array(), + $externalPhones = array(), + $allowEdit = false, + $inputEventSupported = false, + $outputEventSupported = false, + $hangupEventSupported = false, + $changeUserStatusUrl = false + ) + { + if (!isset($code)) { + throw new \InvalidArgumentException('Code must be set'); + } + + $parameters['code'] = $code; + + if (!isset($clientId)) { + throw new \InvalidArgumentException('client id must be set'); + } + + $parameters['clientId'] = $clientId; + + if (!isset($active)) { + $parameters['active'] = false; + } else { + $parameters['active'] = $active; + } + + if (!isset($name)) { + throw new \InvalidArgumentException('name must be set'); + } + + if (isset($name)) { + $parameters['name'] = $name; + } + + if (isset($makeCallUrl)) { + $parameters['makeCallUrl'] = $makeCallUrl; + } + + if (isset($image)) { + $parameters['image'] = $image; + } + + if (isset($additionalCodes)) { + $parameters['additionalCodes'] = $additionalCodes; + } + + if (isset($externalPhones)) { + $parameters['externalPhones'] = $externalPhones; + } + + if (isset($allowEdit)) { + $parameters['allowEdit'] = $allowEdit; + } + + if (isset($inputEventSupported)) { + $parameters['inputEventSupported'] = $inputEventSupported; + } + + if (isset($outputEventSupported)) { + $parameters['outputEventSupported'] = $outputEventSupported; + } + + if (isset($hangupEventSupported)) { + $parameters['hangupEventSupported'] = $hangupEventSupported; + } + + if (isset($changeUserStatusUrl)) { + $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; + } + + return $this->client->makeRequest( + "/telephony/setting/$code/edit", + RetailcrmHttpClient::METHOD_POST, + array('configuration' => json_encode($parameters)) + ); + } + + /** + * Call event + * + * @param string $phone phone number + * @param string $type call type + * @param array $codes + * @param string $hangupStatus + * @param string $externalPhone + * @param array $webAnalyticsData + * + * @return ApiResponse + * @internal param string $code additional phone code + * @internal param string $status call status + * + */ + public function telephonyCallEvent( + $phone, + $type, + $codes, + $hangupStatus, + $externalPhone = null, + $webAnalyticsData = array() + ) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + if (!isset($type)) { + throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); + } + + if (empty($codes)) { + throw new \InvalidArgumentException('Codes array must be set'); + } + + $parameters['phone'] = $phone; + $parameters['type'] = $type; + $parameters['codes'] = $codes; + $parameters['hangupStatus'] = $hangupStatus; + $parameters['callExternalId'] = $externalPhone; + $parameters['webAnalyticsData'] = $webAnalyticsData; + + + return $this->client->makeRequest( + '/telephony/call/event', + RetailcrmHttpClient::METHOD_POST, + array('event' => json_encode($parameters)) + ); + } + + /** + * Upload calls + * + * @param array $calls calls data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallsUpload(array $calls) + { + if (!count($calls)) { + throw new \InvalidArgumentException( + 'Parameter `calls` must contains array of the calls' + ); + } + + return $this->client->makeRequest( + '/telephony/calls/upload', + RetailcrmHttpClient::METHOD_POST, + array('calls' => json_encode($calls)) + ); + } + + /** + * Get call manager + * + * @param string $phone phone number + * @param bool $details detailed information + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallManager($phone, $details) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + $parameters['phone'] = $phone; + $parameters['details'] = isset($details) ? $details : 0; + + return $this->client->makeRequest( + '/telephony/manager', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Update CRM basic statistic + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statisticUpdate() + { + return $this->client->makeRequest( + '/statistic/update', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Return current site + * + * @return string + */ + public function getSite() + { + return $this->siteCode; + } + + /** + * Set site + * + * @param string $site site code + * + * @return void + */ + public function setSite($site) + { + $this->siteCode = $site; + } + + /** + * Check ID parameter + * + * @param string $by identify by + * + * @throws \InvalidArgumentException + * + * @return bool + */ + protected function checkIdParameter($by) + { + $allowedForBy = array( + 'externalId', + 'id' + ); + + if (!in_array($by, $allowedForBy, false)) { + throw new \InvalidArgumentException( + sprintf( + 'Value "%s" for "by" param is not valid. Allowed values are %s.', + $by, + implode(', ', $allowedForBy) + ) + ); + } + + return true; + } + + /** + * Fill params by site value + * + * @param string $site site code + * @param array $params input parameters + * + * @return array + */ + protected function fillSite($site, array $params) + { + if ($site) { + $params['site'] = $site; + } elseif ($this->siteCode) { + $params['site'] = $this->siteCode; + } + + return $params; + } +} diff --git a/system/library/retailcrm/RetailcrmApiClient5.php b/system/library/retailcrm/RetailcrmApiClient5.php new file mode 100644 index 0000000..9b2057b --- /dev/null +++ b/system/library/retailcrm/RetailcrmApiClient5.php @@ -0,0 +1,2098 @@ + + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + */ +class RetailcrmApiClient5 +{ + + const VERSION = 'v5'; + + protected $client; + + /** + * Site code + */ + protected $siteCode; + + /** + * Client creating + * + * @param string $url api url + * @param string $apiKey api key + * @param string $site site code + * + * @throws \InvalidArgumentException + * + * @return mixed + */ + public function __construct($url, $apiKey, $site = null) + { + if ('/' !== $url[strlen($url) - 1]) { + $url .= '/'; + } + + $url = $url . 'api/' . self::VERSION; + + $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); + $this->siteCode = $site; + } + + /** + * Returns users list + * + * @param array $filter + * @param null $page + * @param null $limit + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/users', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Returns user data + * + * @param integer $id user ID + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function usersGet($id) + { + return $this->client->makeRequest("/users/$id", RetailcrmHttpClient::METHOD_GET); + } + + public function usersStatus($id, $status) + { + $statuses = array("free", "busy", "dinner", "break"); + + if (empty($status) || !in_array($status, $statuses)) { + throw new \InvalidArgumentException( + 'Parameter `status` must be not empty & must be equal one of these values: free|busy|dinner|break' + ); + } + + return $this->client->makeRequest( + "/users/$id/status", + RetailcrmHttpClient::METHOD_POST, + array('status' => $status) + ); + } + + public function segmentsList(array $filter = array(), $limit = null, $page = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/segments', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function customFieldsList(array $filter = array(), $limit = null, $page = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/custom-fields', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function customFieldsCreate($entity, $customField) + { + if (!count($customField) || + empty($customField['code']) || + empty($customField['name']) || + empty($customField['type']) + ) { + throw new \InvalidArgumentException( + 'Parameter `customField` must contain a data & fields `code`, `name` & `type` must be set' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/create", + RetailcrmHttpClient::METHOD_POST, + array('customField' => json_encode($customField)) + ); + } + + public function customFieldsEdit($entity, $customField) + { + if (!count($customField) || empty($customField['code'])) { + throw new \InvalidArgumentException( + 'Parameter `customField` must contain a data & fields `code` must be set' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/edit/{$customField['code']}", + $this->client::METHOD_POST, + array('customField' => json_encode($customField)) + ); + } + + public function customFieldsGet($entity, $code) + { + if (empty($code)) { + throw new \InvalidArgumentException( + 'Parameter `code` must be not empty' + ); + } + + if (empty($entity) || $entity != 'customer' || $entity != 'order') { + throw new \InvalidArgumentException( + 'Parameter `entity` must contain a data & value must be `order` or `customer`' + ); + } + + return $this->client->makeRequest( + "/custom-fields/$entity/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + public function customDictionariesList(array $filter = [], $limit = null, $page = null) + { + $parameters = []; + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/custom-fields/dictionaries', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function customDictionariesCreate($customDictionary) + { + if (!count($customDictionary) || + empty($customDictionary['code']) || + empty($customDictionary['elements']) + ) { + throw new \InvalidArgumentException( + 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/{$customDictionary['code']}/create", + RetailcrmHttpClient::METHOD_POST, + array('customDictionary' => json_encode($customDictionary)) + ); + } + + public function customDictionariesEdit($customDictionary) + { + if (!count($customDictionary) || + empty($customDictionary['code']) || + empty($customDictionary['elements']) + ) { + throw new \InvalidArgumentException( + 'Parameter `dictionary` must contain a data & fields `code` & `elemets` must be set' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/{$customDictionary['code']}/edit", + RetailcrmHttpClient::METHOD_POST, + array('customDictionary' => json_encode($customDictionary)) + ); + } + + public function customDictionariesGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException( + 'Parameter `code` must be not empty' + ); + } + + return $this->client->makeRequest( + "/custom-fields/dictionaries/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Returns filtered orders list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create a order + * + * @param array $order order data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersCreate(array $order, $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('order' => json_encode($order))) + ); + } + + /** + * Save order IDs' (id and externalId) association in the CRM + * + * @param array $ids order identificators + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/orders/fix-external-ids', + RetailcrmHttpClient::METHOD_POST, + array('orders' => json_encode($ids) + ) + ); + } + + /** + * Returns statuses of the orders + * + * @param array $ids (default: array()) + * @param array $externalIds (default: array()) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersStatuses(array $ids = array(), array $externalIds = array()) + { + $parameters = array(); + + if (count($ids)) { + $parameters['ids'] = $ids; + } + if (count($externalIds)) { + $parameters['externalIds'] = $externalIds; + } + + return $this->client->makeRequest( + '/orders/statuses', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Upload array of the orders + * + * @param array $orders array of orders + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersUpload(array $orders, $site = null) + { + if (!count($orders)) { + throw new \InvalidArgumentException( + 'Parameter `orders` must contains array of the orders' + ); + } + + return $this->client->makeRequest( + '/orders/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('orders' => json_encode($orders))) + ); + } + + /** + * Get order by id or externalId + * + * @param string $id order identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/orders/$id", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a order + * + * @param array $order order data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersEdit(array $order, $by = 'externalId', $site = null) + { + if (!count($order)) { + throw new \InvalidArgumentException( + 'Parameter `order` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $order)) { + throw new \InvalidArgumentException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/orders/%s/edit', $order[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('order' => json_encode($order), 'by' => $by) + ) + ); + } + + /** + * Get orders history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function ordersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function ordersCombine($order, $resultOrder, $technique = 'ours') + { + $techniques = array('ours', 'summ', 'theirs'); + + if (!count($order) || !count($resultOrder)) { + throw new \InvalidArgumentException( + 'Parameters `order` & `resultOrder` must contains a data' + ); + } + + if (!in_array($technique, $techniques)) { + throw new \InvalidArgumentException( + 'Parameter `technique` must be on of ours|summ|theirs' + ); + } + + return $this->client->makeRequest( + '/orders/combine', + RetailcrmHttpClient::METHOD_POST, + array( + 'technique' => $technique, + 'order' => json_encode($order), + 'resultOrder' => json_encode($resultOrder) + ) + ); + } + + public function ordersPaymentCreate(array $payment) + { + if (!count($payment)) { + throw new \InvalidArgumentException( + 'Parameter `payment` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/payments/create', + RetailcrmHttpClient::METHOD_POST, + array('payment' => json_encode($payment)) + ); + } + + public function ordersPaymentEdit(array $payment, $by = 'externalId', $site = null) + { + if (!count($payment)) { + throw new \InvalidArgumentException( + 'Parameter `payment` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $payment)) { + throw new \InvalidArgumentException( + sprintf('Order array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/orders/payments/%s/edit', $payment[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('payment' => json_encode($payment), 'by' => $by) + ) + ); + } + + /** + * Returns filtered customers list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create a customer + * + * @param array $customer customer data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersCreate(array $customer, $site = null) + { + if (! count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('customer' => json_encode($customer))) + ); + } + + /** + * Save customer IDs' (id and externalId) association in the CRM + * + * @param array $ids ids mapping + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersFixExternalIds(array $ids) + { + if (! count($ids)) { + throw new \InvalidArgumentException( + 'Method parameter must contains at least one IDs pair' + ); + } + + return $this->client->makeRequest( + '/customers/fix-external-ids', + RetailcrmHttpClient::METHOD_POST, + array('customers' => json_encode($ids)) + ); + } + + /** + * Upload array of the customers + * + * @param array $customers array of customers + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersUpload(array $customers, $site = null) + { + if (! count($customers)) { + throw new \InvalidArgumentException( + 'Parameter `customers` must contains array of the customers' + ); + } + + return $this->client->makeRequest( + '/customers/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('customers' => json_encode($customers))) + ); + } + + /** + * Get customer by id or externalId + * + * @param string $id customer identificator + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersGet($id, $by = 'externalId', $site = null) + { + $this->checkIdParameter($by); + + return $this->client->makeRequest( + "/customers/$id", + RetailcrmHttpClient::METHOD_GET, + $this->fillSite($site, array('by' => $by)) + ); + } + + /** + * Edit a customer + * + * @param array $customer customer data + * @param string $by (default: 'externalId') + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersEdit(array $customer, $by = 'externalId', $site = null) + { + if (!count($customer)) { + throw new \InvalidArgumentException( + 'Parameter `customer` must contains a data' + ); + } + + $this->checkIdParameter($by); + + if (!array_key_exists($by, $customer)) { + throw new \InvalidArgumentException( + sprintf('Customer array must contain the "%s" parameter.', $by) + ); + } + + return $this->client->makeRequest( + sprintf('/customers/%s/edit', $customer[$by]), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('customer' => json_encode($customer), 'by' => $by) + ) + ); + } + + /** + * Get customers history + * @param array $filter + * @param null $page + * @param null $limit + * + * @return ApiResponse + */ + public function customersHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/customers/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function customersCombine(array $customers, $resultCustomer) + { + + if (!count($customers) || !count($resultCustomer)) { + throw new \InvalidArgumentException( + 'Parameters `customers` & `resultCustomer` must contains a data' + ); + } + + return $this->client->makeRequest( + '/customers/combine', + RetailcrmHttpClient::METHOD_POST, + array( + 'customers' => json_encode($customers), + 'resultCustomer' => json_encode($resultCustomer) + ) + ); + } + + /** + * Get orders assembly list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksCreate(array $pack, $site = null) + { + if (!count($pack)) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data' + ); + } + + return $this->client->makeRequest( + '/orders/packs/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + /** + * Get orders assembly history + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/orders/packs/history', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksGet($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + "/orders/packs/$id", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Delete orders assembly by id + * + * @param string $id pack identificator + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException('Parameter `id` must be set'); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/delete', $id), + RetailcrmHttpClient::METHOD_POST + ); + } + + /** + * Edit orders assembly + * + * @param array $pack pack data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function ordersPacksEdit(array $pack, $site = null) + { + if (!count($pack) || empty($pack['id'])) { + throw new \InvalidArgumentException( + 'Parameter `pack` must contains a data & pack `id` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/orders/packs/%s/edit', $pack['id']), + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('pack' => json_encode($pack))) + ); + } + + public function tasksList(array $filter = array(), $limit = null, $page = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/tasks', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + public function tasksCreate($task, $site = null) + { + if (!count($task)) { + throw new \InvalidArgumentException( + 'Parameter `task` must contain a data' + ); + } + + return $this->client->makeRequest( + "/tasks/create", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('task' => json_encode($task)) + ) + ); + } + + public function tasksEdit($task, $site = null) + { + if (!count($task)) { + throw new \InvalidArgumentException( + 'Parameter `task` must contain a data' + ); + } + + return $this->client->makeRequest( + "/tasks/{$task['id']}/edit", + RetailcrmHttpClient::METHOD_POST, + $this->fillSite( + $site, + array('task' => json_encode($task)) + ) + ); + } + + public function tasksGet($id) + { + if (empty($id)) { + throw new \InvalidArgumentException( + 'Parameter `id` must be not empty' + ); + } + + return $this->client->makeRequest( + "/tasks/$id", + RetailcrmHttpClient::METHOD_GET + ); + } + + public function storeProductsGroups(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/product-groups', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get purchace prices & stock balance + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventories(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/inventories', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get store settings + * + * @param string $code get settings code + * + * @return ApiResponse + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/store/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit store configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function storeSettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/store/setting/%s/edit', $configuration['code']), + RetailcrmHttpClient::METHOD_POST, + $configuration + ); + } + + /** + * Upload store inventories + * + * @param array $offers offers data + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeInventoriesUpload(array $offers, $site = null) + { + if (!count($offers)) { + throw new \InvalidArgumentException( + 'Parameter `offers` must contains array of the offers' + ); + } + + return $this->client->makeRequest( + '/store/inventories/upload', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('offers' => json_encode($offers))) + ); + } + + /** + * Get products + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storeProducts(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + + return $this->client->makeRequest( + '/store/products', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Get delivery settings + * + * @param string $code + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliverySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/delivery/generic/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit delivery configuration + * + * @param array $configuration + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliverySettingsEdit(array $configuration) + { + if (!count($configuration) || empty($configuration['code'])) { + throw new \InvalidArgumentException( + 'Parameter `configuration` must contains a data & configuration `code` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), + RetailcrmHttpClient::METHOD_POST, + array('configuration' => json_encode($configuration)) + ); + } + + /** + * Delivery tracking update + * + * @param string $code + * @param array $statusUpdate + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function deliveryTracking($code, array $statusUpdate) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + if (!count($statusUpdate)) { + throw new \InvalidArgumentException( + 'Parameter `statusUpdate` must contains a data' + ); + } + + return $this->client->makeRequest( + sprintf('/delivery/generic/%s/tracking', $code), + RetailcrmHttpClient::METHOD_POST, + $statusUpdate + ); + } + + /** + * Returns available county list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function countriesList() + { + return $this->client->makeRequest( + '/reference/countries', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Returns deliveryServices list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesList() + { + return $this->client->makeRequest( + '/reference/delivery-services', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit deliveryService + * + * @param array $data delivery service data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryServicesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-services/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('deliveryService' => json_encode($data)) + ); + } + + /** + * Returns deliveryTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesList() + { + return $this->client->makeRequest( + '/reference/delivery-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit deliveryType + * + * @param array $data delivery type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function deliveryTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/delivery-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('deliveryType' => json_encode($data)) + ); + } + + /** + * Returns orderMethods list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsList() + { + return $this->client->makeRequest( + '/reference/order-methods', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit orderMethod + * + * @param array $data order method data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderMethodsEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-methods/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('orderMethod' => json_encode($data)) + ); + } + + /** + * Returns orderTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesList() + { + return $this->client->makeRequest( + '/reference/order-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit orderType + * + * @param array $data order type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function orderTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/order-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('orderType' => json_encode($data)) + ); + } + + /** + * Returns paymentStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesList() + { + return $this->client->makeRequest( + '/reference/payment-statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit paymentStatus + * + * @param array $data payment status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('paymentStatus' => json_encode($data)) + ); + } + + /** + * Returns paymentTypes list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesList() + { + return $this->client->makeRequest( + '/reference/payment-types', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit paymentType + * + * @param array $data payment type data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function paymentTypesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/payment-types/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('paymentType' => json_encode($data)) + ); + } + + /** + * Returns productStatuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesList() + { + return $this->client->makeRequest( + '/reference/product-statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit productStatus + * + * @param array $data product status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function productStatusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/product-statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('productStatus' => json_encode($data)) + ); + } + + /** + * Returns sites list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesList() + { + return $this->client->makeRequest( + '/reference/sites', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit site + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function sitesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/sites/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('site' => json_encode($data)) + ); + } + + /** + * Returns statusGroups list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusGroupsList() + { + return $this->client->makeRequest( + '/reference/status-groups', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Returns statuses list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesList() + { + return $this->client->makeRequest( + '/reference/statuses', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit order status + * + * @param array $data status data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statusesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/statuses/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('status' => json_encode($data)) + ); + } + + /** + * Returns stores list + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesList() + { + return $this->client->makeRequest( + '/reference/stores', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit store + * + * @param array $data site data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function storesEdit(array $data) + { + if (!array_key_exists('code', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "code" parameter.' + ); + } + + if (!array_key_exists('name', $data)) { + throw new \InvalidArgumentException( + 'Data must contain "name" parameter.' + ); + } + + return $this->client->makeRequest( + sprintf('/reference/stores/%s/edit', $data['code']), + RetailcrmHttpClient::METHOD_POST, + array('store' => json_encode($data)) + ); + } + + /** + * Get telephony settings + * + * @param string $code + * + * @throws \RetailCrm\Exception\InvalidJsonException + * @throws \RetailCrm\Exception\CurlException + * @throws \InvalidArgumentException + * + * @return ApiResponse + */ + public function telephonySettingsGet($code) + { + if (empty($code)) { + throw new \InvalidArgumentException('Parameter `code` must be set'); + } + + return $this->client->makeRequest( + "/telephony/setting/$code", + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Edit telephony settings + * + * @param string $code symbolic code + * @param string $clientId client id + * @param boolean $active telephony activity + * @param mixed $name service name + * @param mixed $makeCallUrl service init url + * @param mixed $image service logo url(svg file) + * + * @param array $additionalCodes + * @param array $externalPhones + * @param bool $allowEdit + * @param bool $inputEventSupported + * @param bool $outputEventSupported + * @param bool $hangupEventSupported + * @param bool $changeUserStatusUrl + * + * @return ApiResponse + */ + public function telephonySettingsEdit( + $code, + $clientId, + $active = false, + $name = false, + $makeCallUrl = false, + $image = false, + $additionalCodes = array(), + $externalPhones = array(), + $allowEdit = false, + $inputEventSupported = false, + $outputEventSupported = false, + $hangupEventSupported = false, + $changeUserStatusUrl = false + ) + { + if (!isset($code)) { + throw new \InvalidArgumentException('Code must be set'); + } + + $parameters['code'] = $code; + + if (!isset($clientId)) { + throw new \InvalidArgumentException('client id must be set'); + } + + $parameters['clientId'] = $clientId; + + if (!isset($active)) { + $parameters['active'] = false; + } else { + $parameters['active'] = $active; + } + + if (!isset($name)) { + throw new \InvalidArgumentException('name must be set'); + } + + if (isset($name)) { + $parameters['name'] = $name; + } + + if (isset($makeCallUrl)) { + $parameters['makeCallUrl'] = $makeCallUrl; + } + + if (isset($image)) { + $parameters['image'] = $image; + } + + if (isset($additionalCodes)) { + $parameters['additionalCodes'] = $additionalCodes; + } + + if (isset($externalPhones)) { + $parameters['externalPhones'] = $externalPhones; + } + + if (isset($allowEdit)) { + $parameters['allowEdit'] = $allowEdit; + } + + if (isset($inputEventSupported)) { + $parameters['inputEventSupported'] = $inputEventSupported; + } + + if (isset($outputEventSupported)) { + $parameters['outputEventSupported'] = $outputEventSupported; + } + + if (isset($hangupEventSupported)) { + $parameters['hangupEventSupported'] = $hangupEventSupported; + } + + if (isset($changeUserStatusUrl)) { + $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; + } + + return $this->client->makeRequest( + "/telephony/setting/$code/edit", + RetailcrmHttpClient::METHOD_POST, + array('configuration' => json_encode($parameters)) + ); + } + + /** + * Call event + * + * @param string $phone phone number + * @param string $type call type + * @param array $codes + * @param string $hangupStatus + * @param string $externalPhone + * @param array $webAnalyticsData + * + * @return ApiResponse + * @internal param string $code additional phone code + * @internal param string $status call status + * + */ + public function telephonyCallEvent( + $phone, + $type, + $codes, + $hangupStatus, + $externalPhone = null, + $webAnalyticsData = array() + ) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + if (!isset($type)) { + throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); + } + + if (empty($codes)) { + throw new \InvalidArgumentException('Codes array must be set'); + } + + $parameters['phone'] = $phone; + $parameters['type'] = $type; + $parameters['codes'] = $codes; + $parameters['hangupStatus'] = $hangupStatus; + $parameters['callExternalId'] = $externalPhone; + $parameters['webAnalyticsData'] = $webAnalyticsData; + + + return $this->client->makeRequest( + '/telephony/call/event', + RetailcrmHttpClient::METHOD_POST, + array('event' => json_encode($parameters)) + ); + } + + /** + * Upload calls + * + * @param array $calls calls data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallsUpload(array $calls) + { + if (!count($calls)) { + throw new \InvalidArgumentException( + 'Parameter `calls` must contains array of the calls' + ); + } + + return $this->client->makeRequest( + '/telephony/calls/upload', + RetailcrmHttpClient::METHOD_POST, + array('calls' => json_encode($calls)) + ); + } + + /** + * Get call manager + * + * @param string $phone phone number + * @param bool $details detailed information + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function telephonyCallManager($phone, $details) + { + if (!isset($phone)) { + throw new \InvalidArgumentException('Phone number must be set'); + } + + $parameters['phone'] = $phone; + $parameters['details'] = isset($details) ? $details : 0; + + return $this->client->makeRequest( + '/telephony/manager', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Update CRM basic statistic + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function statisticUpdate() + { + return $this->client->makeRequest( + '/statistic/update', + RetailcrmHttpClient::METHOD_GET + ); + } + + /** + * Return current site + * + * @return string + */ + public function getSite() + { + return $this->siteCode; + } + + /** + * Set site + * + * @param string $site site code + * + * @return void + */ + public function setSite($site) + { + $this->siteCode = $site; + } + + /** + * Check ID parameter + * + * @param string $by identify by + * + * @throws \InvalidArgumentException + * + * @return bool + */ + protected function checkIdParameter($by) + { + $allowedForBy = array( + 'externalId', + 'id' + ); + + if (!in_array($by, $allowedForBy, false)) { + throw new \InvalidArgumentException( + sprintf( + 'Value "%s" for "by" param is not valid. Allowed values are %s.', + $by, + implode(', ', $allowedForBy) + ) + ); + } + + return true; + } + + /** + * Fill params by site value + * + * @param string $site site code + * @param array $params input parameters + * + * @return array + */ + protected function fillSite($site, array $params) + { + if ($site) { + $params['site'] = $site; + } elseif ($this->siteCode) { + $params['site'] = $this->siteCode; + } + + return $params; + } +} diff --git a/system/library/retailcrm/RetailcrmProxy.php b/system/library/retailcrm/RetailcrmProxy.php index 1f7442c..591245a 100644 --- a/system/library/retailcrm/RetailcrmProxy.php +++ b/system/library/retailcrm/RetailcrmProxy.php @@ -10,17 +10,31 @@ class RetailcrmProxy private $api; private $log; - public function __construct($url, $key, $log) - { - $this->api = new RetailcrmApiClient($url, $key); + public function __construct($url, $key, $log, $version = 'v4') + { + switch ($version) { + case 'v5': + $this->api = new RetailcrmApiClient5($url, $key); + break; + + case 'v4': + $this->api = new RetailcrmApiClient4($url, $key); + break; + + case 'v3': + $this->api = new RetailcrmApiClient3($url, $key); + break; + } + $this->log = $log; } public function __call($method, $arguments) - { + { + $date = date('[Y-m-d H:i:s]'); + try { $response = call_user_func_array(array($this->api, $method), $arguments); - $date = date('[Y-m-d H:i:s]'); if (!$response->isSuccessful()) { error_log($date . " [$method] " . $response->getErrorMsg() . "\n", 3, $this->log); From 5b7b2c3c362623a36db9b01925dd542b4f85c3d8 Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 21 Jul 2017 10:27:08 +0300 Subject: [PATCH 38/40] fix for api v3-v5 --- .../controller/extension/module/retailcrm.php | 24 +++++--- .../en-gb/extension/module/retailcrm.php | 1 + .../ru-ru/extension/module/retailcrm.php | 1 + .../extension/retailcrm/history/v4_5.php | 34 ++++++++--- admin/model/extension/retailcrm/order.php | 17 +++--- catalog/model/extension/retailcrm/order.php | 56 +++++++++++-------- .../library/retailcrm/OpencartApiClient.php | 26 +++++++-- 7 files changed, 106 insertions(+), 53 deletions(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 610d636..121a2ee 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -272,12 +272,6 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['error_warning'] = ''; } - if (isset($this->_error['fields'])) { - $_data['error_warning'] = $this->_error['fields']; - } else { - $_data['error_warning'] = ''; - } - $_data['breadcrumbs'] = array(); $_data['breadcrumbs'][] = array( @@ -349,7 +343,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $_data['collectorFields'] = $collectorFields; $_data['api_versions'] = array('v3', 'v4', 'v5'); - $_data['default_apiversion'] = 'v5'; + $_data['default_apiversion'] = 'v4'; $this->response->setOutput( $this->load->view('extension/module/retailcrm', $_data) @@ -540,6 +534,22 @@ class ControllerExtensionModuleRetailcrm extends Controller { $moduleTitle = $this->getModuleTitle(); + if (!empty($this->request->post[$moduleTitle . '_url']) && !empty($this->request->post[$moduleTitle . '_apikey'])) { + + $this->retailcrm = new RetailcrmProxy( + $this->request->post[$moduleTitle . '_url'], + $this->request->post[$moduleTitle . '_apikey'], + DIR_SYSTEM . 'storage/logs/retailcrm.log', + $this->request->post[$moduleTitle . '_apiversion'] + ); + } + + $response = $this->retailcrm->statisticUpdate(); + + if (!$response) { + $this->_error['warning'] = $this->language->get('text_error_api'); + } + if (!$this->user->hasPermission('modify', 'extension/module/retailcrm')) { $this->_error['warning'] = $this->language->get('error_permission'); } diff --git a/admin/language/en-gb/extension/module/retailcrm.php b/admin/language/en-gb/extension/module/retailcrm.php index 67eeac7..1d59139 100644 --- a/admin/language/en-gb/extension/module/retailcrm.php +++ b/admin/language/en-gb/extension/module/retailcrm.php @@ -41,6 +41,7 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Phone'; $_['text_require'] = 'Require'; $_['text_error_collector_fields']= 'Fill in the field names Daemon Collector'; +$_['text_error_api'] = 'The selected version of the API is unavailable'; $_['retailcrm_dict_delivery'] = 'Shipment methods'; $_['retailcrm_dict_status'] = 'Order statuses'; diff --git a/admin/language/ru-ru/extension/module/retailcrm.php b/admin/language/ru-ru/extension/module/retailcrm.php index ef726e7..1e6c044 100644 --- a/admin/language/ru-ru/extension/module/retailcrm.php +++ b/admin/language/ru-ru/extension/module/retailcrm.php @@ -41,6 +41,7 @@ $_['field_email'] = 'Email'; $_['field_phone'] = 'Телефон'; $_['text_require'] = 'Обязательно для заполнения'; $_['text_error_collector_fields']= 'Заполните названия полей формы Демон Collector'; +$_['text_error_api'] = 'Недоступна выбранная версия API'; $_['retailcrm_dict_delivery'] = 'Способы доставки'; $_['retailcrm_dict_status'] = 'Статусы'; diff --git a/admin/model/extension/retailcrm/history/v4_5.php b/admin/model/extension/retailcrm/history/v4_5.php index 7b936b1..6c56b07 100644 --- a/admin/model/extension/retailcrm/history/v4_5.php +++ b/admin/model/extension/retailcrm/history/v4_5.php @@ -60,9 +60,10 @@ class ModelExtensionRetailcrmHistoryV45 extends Model $generatedAt = $packsOrders['generatedAt']; - $this->subtotalSettings = $this->model_setting_setting->getSetting('sub_total'); - $this->totalSettings = $this->model_setting_setting->getSetting('total'); - $this->shippingSettings = $this->model_setting_setting->getSetting('shipping'); + $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'); + $this->shippingSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'shipping'); $this->delivery = array_flip($settings[$moduleTitle . '_delivery']); $this->payment = array_flip($settings[$moduleTitle . '_payment']); @@ -141,7 +142,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($orders as $order) { $store = $this->config->get('config_store_id'); - if ($order['payments']) { + if (isset($order['payments'])) { foreach ($order['payments'] as $orderPayment) { if (isset($orderPayment['externalId'])) { $payment = $orderPayment; @@ -151,6 +152,8 @@ class ModelExtensionRetailcrmHistoryV45 extends Model if (!isset($payment) && count($order['payments']) == 1) { $payment = end($order['payments']); } + } elseif (isset($order['paymentType'])) { + $payment = $order['paymentType']; } $data = array(); @@ -296,7 +299,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model 'title' => $this->ocDelivery[$data['shipping_code']], 'value' => $deliveryCost, 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings['shipping_sort_order'] + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] ), array( 'order_total_id' => '', @@ -304,7 +307,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model '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['total_sort_order'] + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] ) ); @@ -329,8 +332,10 @@ class ModelExtensionRetailcrmHistoryV45 extends Model foreach ($orders as $order) { $store = $this->config->get('config_store_id'); - if ($order['payments']) { + if (isset($order['payments'])) { $payment = end($order['payments']); + } elseif (isset($order['paymentType'])) { + $payment = $order['paymentType']; } $customer_id = (!empty($order['customer']['externalId'])) @@ -489,7 +494,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model 'title' => $this->ocDelivery[$data['shipping_code']], 'value' => $deliveryCost, 'text' => $deliveryCost, - 'sort_order' => $this->shippingSettings['shipping_sort_order'] + 'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order'] ), array( 'order_total_id' => '', @@ -497,7 +502,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model '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['total_sort_order'] + 'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order'] ) ); @@ -549,4 +554,15 @@ class ModelExtensionRetailcrmHistoryV45 extends Model return $title; } + + private function totalTitles() + { + if (version_compare(VERSION, '3.0', '<')) { + $title = ''; + } else { + $title = 'total_'; + } + + return $title; + } } diff --git a/admin/model/extension/retailcrm/order.php b/admin/model/extension/retailcrm/order.php index f6e0e3f..a097a04 100644 --- a/admin/model/extension/retailcrm/order.php +++ b/admin/model/extension/retailcrm/order.php @@ -47,7 +47,7 @@ class ModelExtensionRetailcrmOrder extends Model { $result = $this->retailcrm->ordersCreate($order); - if ($this->settings[$moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) { + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $result->isSuccessful()) { $this->createPayment($order_data, $order_data['order_id']); } @@ -57,7 +57,7 @@ class ModelExtensionRetailcrmOrder extends Model { private function process($order_data) { $order = array(); - $moduleTitle = $this->getModuleTitle(); + $this->moduleTitle = $this->getModuleTitle(); $payment_code = $order_data['payment_code']; $delivery_code = $order_data['shipping_code']; @@ -84,14 +84,14 @@ class ModelExtensionRetailcrmOrder extends Model { $order['createdAt'] = $order_data['date_added']; - if ($this->settings[$moduleTitle . '_apiversion'] != 'v5') { - $order['paymentType'] = $this->settings[$moduleTitle . '_payment'][$payment_code]; + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; } $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $this->settings[$moduleTitle . '_delivery'][$delivery_code] : '', + 'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', 'cost' => $deliveryCost, 'address' => array( 'index' => $order_data['shipping_postcode'], @@ -149,7 +149,7 @@ class ModelExtensionRetailcrmOrder extends Model { $offerId = implode('_', $offerId); } - if ($this->settings[$moduleTitle . '_apiversion'] != 'v3') { + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') { $item = array( 'offer' => array( 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] @@ -176,8 +176,7 @@ class ModelExtensionRetailcrmOrder extends Model { protected function createPayment($order, $order_id) { - $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting($moduleTitle); + $this->moduleTitle = $this->getModuleTitle(); if (version_compare(VERSION, '3.0', '<')) { $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); @@ -193,7 +192,7 @@ class ModelExtensionRetailcrmOrder extends Model { $payment = array( 'externalId' => $order_id, - 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], 'amount' => $amount ); diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index 45cd15a..f3623bf 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -8,7 +8,7 @@ class ModelExtensionRetailcrmOrder extends Model { $this->initApi(); - $order = array(); + $order = $this->processOrder($order_data, $order_id); $customers = $this->retailcrm->customersList( array( @@ -27,10 +27,9 @@ class ModelExtensionRetailcrmOrder extends Model { unset($customers); - $order = $this->processOrder($order_data, $order_id); $response = $this->retailcrm->ordersCreate($order); - if ($settings[$moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { $this->createPayment($order_data, $order_id); } } @@ -41,23 +40,38 @@ class ModelExtensionRetailcrmOrder extends Model { $this->initApi(); - $order = array(); - $order = $this->processOrder($order_data, $order_id); + $customers = $this->retailcrm->customersList( + array( + 'name' => $order_data['telephone'], + 'email' => $order_data['email'] + ), + 1, + 100 + ); + + if($customers) { + foreach ($customers['customers'] as $customer) { + $order['customer']['id'] = $customer['id']; + } + } + + unset($customers); + $response = $this->retailcrm->ordersEdit($order); - if ($settings[$moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { + if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { $this->editPayment($order_data, $order_id); } } protected function processOrder($order_data, $order_id) { - $moduleTitle = $this->getModuleTitle(); + $this->moduleTitle = $this->getModuleTitle(); $this->load->model('setting/setting'); $this->load->model('catalog/product'); - $settings = $this->model_setting_setting->getSetting($moduleTitle); + $this->settings = $this->model_setting_setting->getSetting($this->moduleTitle); if (version_compare(VERSION, '3.0', '<')) { $settingPaid = $this->model_setting_setting->getSetting($order_data['payment_code']); @@ -92,20 +106,20 @@ class ModelExtensionRetailcrmOrder extends Model { if (isset($couponTotal)) $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; - if ($settings[$moduleTitle . '_apiversion'] != 'v5') { - $order['paymentType'] = $settings[$moduleTitle . '_payment'][$payment_code]; + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { + $order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; } $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; - if(isset($settings[$moduleTitle . '_delivery'][$order_data['shipping_code']])) { + if(isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) { $delivery_code = $order_data['shipping_code']; } else { $delivery_code = stristr($order_data['shipping_code'], '.', TRUE); } $order['delivery'] = array( - 'code' => !empty($delivery_code) ? $settings[$moduleTitle . '_delivery'][$delivery_code] : '', + 'code' => !empty($delivery_code) ? $this->settings[$this->moduleTitle . '_delivery'][$delivery_code] : '', 'address' => array( 'index' => $order_data['shipping_postcode'], 'city' => $order_data['shipping_city'], @@ -166,7 +180,7 @@ class ModelExtensionRetailcrmOrder extends Model { $offerId = implode('_', $offerId); } - if ($settings[$moduleTitle . '_apiversion'] != 'v3') { + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v3') { $item = array( 'offer' => array( 'externalId' => !empty($offerId) ? $product['product_id'].'#'.$offerId : $product['product_id'] @@ -189,10 +203,10 @@ class ModelExtensionRetailcrmOrder extends Model { $order['items'][] = $item; if (isset($order_data['order_status_id']) && $order_data['order_status_id'] > 0) { - $order['status'] = $settings[$moduleTitle . '_status'][$order_data['order_status_id']]; + $order['status'] = $this->settings[$this->moduleTitle . '_status'][$order_data['order_status_id']]; } - if ($settings[$moduleTitle . '_apiversion'] != 'v5') { + if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { if (version_compare(VERSION, '3.0', '<')) { if ($order_data['order_status_id'] == $settingPaid[$order_data['payment_code'] . '_order_status_id']) { $order['paymentStatus'] = 'paid'; @@ -209,10 +223,7 @@ class ModelExtensionRetailcrmOrder extends Model { } protected function createPayment($order, $order_id) - { - $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting($moduleTitle); - + { if (version_compare(VERSION, '3.0', '<')) { $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); } else { @@ -227,7 +238,7 @@ class ModelExtensionRetailcrmOrder extends Model { $payment = array( 'externalId' => $order_id, - 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], 'amount' => $amount ); @@ -250,9 +261,6 @@ class ModelExtensionRetailcrmOrder extends Model { protected function editPayment($order, $order_id) { - $moduleTitle = $this->getModuleTitle(); - $settings = $this->model_setting_setting->getSetting($moduleTitle); - if (version_compare(VERSION, '3.0', '<')) { $settingPaid = $this->model_setting_setting->getSetting($order['payment_code']); } else { @@ -267,7 +275,7 @@ class ModelExtensionRetailcrmOrder extends Model { $payment = array( 'externalId' => $order_id, - 'type' => $settings[$moduleTitle . '_payment'][$payment_code], + 'type' => $this->settings[$this->moduleTitle . '_payment'][$payment_code], 'amount' => $amount ); diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index 13f9b91..9e8ac65 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -120,12 +120,11 @@ class OpencartApiClient { $apiAnswer = $this->request('login', array(), $api); $this->apiToken = $apiAnswer['token']; } else { - $this->apiToken = $this->session->getID(); - $apiAnswer = $this->request('login', array(), $api); + $this->apiToken = $this->apiLogin(); } - - return $apiAnswer; + if (isset($apiAnswer)) + return $apiAnswer; } public function editOrder($order_id, $data) { @@ -309,4 +308,23 @@ class OpencartApiClient { return curl_exec($curl); } + + private function apiLogin() { + $this->load->model('user/api'); + $registry = new Registry(); + $config = new Config(); + $config->load('default'); + + $api_info = $this->model_user_api->getApi($this->config->get('config_api_id')); + $session = new Session($this->config->get('session_engine'), $this->registry); + $session->start(); + + $this->model_user_api->deleteApiSessionBySessonId($session->getId()); + $this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->request->server['REMOTE_ADDR']); + + $session->data['api_id'] = $api_info['api_id']; + $api_token = $session->getId(); + + return $api_token; + } } From cbbfc67cd8f063de0c08d95820eed6fb44fb960f Mon Sep 17 00:00:00 2001 From: iyzoer Date: Thu, 27 Jul 2017 14:41:58 +0300 Subject: [PATCH 39/40] fixes for API v5 --- .../controller/extension/module/retailcrm.php | 2 +- catalog/model/extension/retailcrm/order.php | 21 +- .../library/retailcrm/OpencartApiClient.php | 4 + .../library/retailcrm/RetailcrmApiClient3.php | 88 +++--- .../library/retailcrm/RetailcrmApiClient4.php | 1 - .../library/retailcrm/RetailcrmApiClient5.php | 274 +++++++++++++++++- 6 files changed, 342 insertions(+), 48 deletions(-) diff --git a/admin/controller/extension/module/retailcrm.php b/admin/controller/extension/module/retailcrm.php index 121a2ee..13533e7 100644 --- a/admin/controller/extension/module/retailcrm.php +++ b/admin/controller/extension/module/retailcrm.php @@ -546,7 +546,7 @@ class ControllerExtensionModuleRetailcrm extends Controller $response = $this->retailcrm->statisticUpdate(); - if (!$response) { + if (!$response->isSuccessful()) { $this->_error['warning'] = $this->language->get('text_error_api'); } diff --git a/catalog/model/extension/retailcrm/order.php b/catalog/model/extension/retailcrm/order.php index f3623bf..34afee1 100644 --- a/catalog/model/extension/retailcrm/order.php +++ b/catalog/model/extension/retailcrm/order.php @@ -62,7 +62,22 @@ class ModelExtensionRetailcrmOrder extends Model { $response = $this->retailcrm->ordersEdit($order); if ($this->settings[$this->moduleTitle . '_apiversion'] == 'v5' && $response->isSuccessful()) { - $this->editPayment($order_data, $order_id); + $response_order = $this->retailcrm->ordersGet($order_id); + if ($response_order->isSuccessful()) $order_info = $response_order['order']; + + foreach ($order_info['payments'] as $payment_data) { + if ($payment_data['externalId'] == $order_id) { + $payment = $payment_data; + } + } + + if (isset($payment) && $payment['type'] != $this->settings[$this->moduleTitle . '_payment'][$order_data['payment_code']]) { + $response = $this->retailcrm->ordersPaymentDelete($payment['id']); + + if ($response->isSuccessful()) { + $this->createPayment($order_data, $order_id); + } + } } } @@ -103,11 +118,13 @@ class ModelExtensionRetailcrmOrder extends Model { } } - if (isset($couponTotal)) $order['discount'] = $couponTotal; $order['createdAt'] = $order_data['date_added']; if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') { $order['paymentType'] = $this->settings[$this->moduleTitle . '_payment'][$payment_code]; + if (isset($couponTotal)) $order['discount'] = $couponTotal; + } else { + if (isset($couponTotal)) $order['discountManualAmount'] = $couponTotal; } $country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ; diff --git a/system/library/retailcrm/OpencartApiClient.php b/system/library/retailcrm/OpencartApiClient.php index 9e8ac65..47a8684 100644 --- a/system/library/retailcrm/OpencartApiClient.php +++ b/system/library/retailcrm/OpencartApiClient.php @@ -309,6 +309,10 @@ class OpencartApiClient { return curl_exec($curl); } + /** + * Login api user for opencart version > 3.0 + * + */ private function apiLogin() { $this->load->model('user/api'); $registry = new Registry(); diff --git a/system/library/retailcrm/RetailcrmApiClient3.php b/system/library/retailcrm/RetailcrmApiClient3.php index 82631e0..7a6d7df 100644 --- a/system/library/retailcrm/RetailcrmApiClient3.php +++ b/system/library/retailcrm/RetailcrmApiClient3.php @@ -1,6 +1,14 @@ + * @license https://opensource.org/licenses/MIT MIT License + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion3 */ class RetailcrmApiClient3 { @@ -38,7 +46,7 @@ class RetailcrmApiClient3 * * @param array $order * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersCreate(array $order, $site = null) { @@ -57,7 +65,7 @@ class RetailcrmApiClient3 * @param array $order * @param string $by * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersEdit(array $order, $by = 'externalId', $site = null) { @@ -86,7 +94,7 @@ class RetailcrmApiClient3 * * @param array $orders * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersUpload(array $orders, $site = null) { @@ -105,7 +113,7 @@ class RetailcrmApiClient3 * @param string $id * @param string $by (default: 'externalId') * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersGet($id, $by = 'externalId', $site = null) { @@ -124,7 +132,7 @@ class RetailcrmApiClient3 * @param int $limit (default: 100) * @param int $offset (default: 0) * @param bool $skipMyChanges (default: true) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersHistory( DateTime $startDate = null, @@ -160,7 +168,7 @@ class RetailcrmApiClient3 * @param array $filter (default: array()) * @param int $page (default: null) * @param int $limit (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersList(array $filter = array(), $page = null, $limit = null) { @@ -184,7 +192,7 @@ class RetailcrmApiClient3 * * @param array $ids (default: array()) * @param array $externalIds (default: array()) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersStatuses(array $ids = array(), array $externalIds = array()) { @@ -204,7 +212,7 @@ class RetailcrmApiClient3 * Save order IDs' (id and externalId) association in the CRM * * @param array $ids - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersFixExternalIds(array $ids) { @@ -223,7 +231,7 @@ class RetailcrmApiClient3 * @param array $filter (default: array()) * @param int $page (default: null) * @param int $limit (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) { @@ -247,7 +255,7 @@ class RetailcrmApiClient3 * * @param array $customer * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersCreate(array $customer, $site = null) { @@ -266,7 +274,7 @@ class RetailcrmApiClient3 * @param array $customer * @param string $by (default: 'externalId') * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersEdit(array $customer, $by = 'externalId', $site = null) { @@ -298,7 +306,7 @@ class RetailcrmApiClient3 * * @param array $customers * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersUpload(array $customers, $site = null) { @@ -317,7 +325,7 @@ class RetailcrmApiClient3 * @param string $id * @param string $by (default: 'externalId') * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersGet($id, $by = 'externalId', $site = null) { @@ -334,7 +342,7 @@ class RetailcrmApiClient3 * @param array $filter (default: array()) * @param int $page (default: null) * @param int $limit (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersList(array $filter = array(), $page = null, $limit = null) { @@ -357,7 +365,7 @@ class RetailcrmApiClient3 * Save customer IDs' (id and externalId) association in the CRM * * @param array $ids - * @return RetailcrmApiResponse + * @return ApiResponse */ public function customersFixExternalIds(array $ids) { @@ -377,7 +385,7 @@ class RetailcrmApiClient3 * @param int $page (default: null) * @param int $limit (default: null) * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function storeInventories(array $filter = array(), $page = null, $limit = null, $site = null) { @@ -401,7 +409,7 @@ class RetailcrmApiClient3 * * @param array $offers * @param string $site (default: null) - * @return RetailcrmApiResponse + * @return ApiResponse */ public function storeInventoriesUpload(array $offers, $site = null) { @@ -419,7 +427,7 @@ class RetailcrmApiClient3 /** * Returns deliveryServices list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function deliveryServicesList() { @@ -429,7 +437,7 @@ class RetailcrmApiClient3 /** * Returns deliveryTypes list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function deliveryTypesList() { @@ -439,7 +447,7 @@ class RetailcrmApiClient3 /** * Returns orderMethods list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function orderMethodsList() { @@ -449,7 +457,7 @@ class RetailcrmApiClient3 /** * Returns orderTypes list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function orderTypesList() { @@ -459,7 +467,7 @@ class RetailcrmApiClient3 /** * Returns paymentStatuses list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function paymentStatusesList() { @@ -469,7 +477,7 @@ class RetailcrmApiClient3 /** * Returns paymentTypes list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function paymentTypesList() { @@ -479,7 +487,7 @@ class RetailcrmApiClient3 /** * Returns productStatuses list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function productStatusesList() { @@ -489,7 +497,7 @@ class RetailcrmApiClient3 /** * Returns statusGroups list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function statusGroupsList() { @@ -499,7 +507,7 @@ class RetailcrmApiClient3 /** * Returns statuses list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function statusesList() { @@ -509,7 +517,7 @@ class RetailcrmApiClient3 /** * Returns sites list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function sitesList() { @@ -519,7 +527,7 @@ class RetailcrmApiClient3 /** * Returns stores list * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function storesList() { @@ -530,7 +538,7 @@ class RetailcrmApiClient3 * Edit deliveryService * * @param array $data delivery service data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function deliveryServicesEdit(array $data) { @@ -551,7 +559,7 @@ class RetailcrmApiClient3 * Edit deliveryType * * @param array $data delivery type data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function deliveryTypesEdit(array $data) { @@ -572,7 +580,7 @@ class RetailcrmApiClient3 * Edit orderMethod * * @param array $data order method data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function orderMethodsEdit(array $data) { @@ -593,7 +601,7 @@ class RetailcrmApiClient3 * Edit orderType * * @param array $data order type data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function orderTypesEdit(array $data) { @@ -614,7 +622,7 @@ class RetailcrmApiClient3 * Edit paymentStatus * * @param array $data payment status data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function paymentStatusesEdit(array $data) { @@ -635,7 +643,7 @@ class RetailcrmApiClient3 * Edit paymentType * * @param array $data payment type data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function paymentTypesEdit(array $data) { @@ -656,7 +664,7 @@ class RetailcrmApiClient3 * Edit productStatus * * @param array $data product status data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function productStatusesEdit(array $data) { @@ -677,7 +685,7 @@ class RetailcrmApiClient3 * Edit order status * * @param array $data status data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function statusesEdit(array $data) { @@ -698,7 +706,7 @@ class RetailcrmApiClient3 * Edit site * * @param array $data site data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function sitesEdit(array $data) { @@ -719,7 +727,7 @@ class RetailcrmApiClient3 * Edit store * * @param array $data site data - * @return RetailcrmApiResponse + * @return ApiResponse */ public function storesEdit(array $data) { @@ -743,7 +751,7 @@ class RetailcrmApiClient3 /** * Update CRM basic statistic * - * @return RetailcrmApiResponse + * @return ApiResponse */ public function statisticUpdate() { diff --git a/system/library/retailcrm/RetailcrmApiClient4.php b/system/library/retailcrm/RetailcrmApiClient4.php index eca5eb5..5a406f1 100644 --- a/system/library/retailcrm/RetailcrmApiClient4.php +++ b/system/library/retailcrm/RetailcrmApiClient4.php @@ -12,7 +12,6 @@ */ class RetailcrmApiClient4 { - const VERSION = 'v4'; protected $client; diff --git a/system/library/retailcrm/RetailcrmApiClient5.php b/system/library/retailcrm/RetailcrmApiClient5.php index 9b2057b..bf80d53 100644 --- a/system/library/retailcrm/RetailcrmApiClient5.php +++ b/system/library/retailcrm/RetailcrmApiClient5.php @@ -8,11 +8,10 @@ * @package RetailCrm * @author RetailCrm * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 + * @link http://www.retailcrm.ru/docs/Developers/ApiVersion5 */ class RetailcrmApiClient5 { - const VERSION = 'v5'; protected $client; @@ -95,6 +94,14 @@ class RetailcrmApiClient5 return $this->client->makeRequest("/users/$id", RetailcrmHttpClient::METHOD_GET); } + /** + * Change user status + * + * @param integer $id user ID + * @param string $status user status + * + * @return ApiResponse + */ public function usersStatus($id, $status) { $statuses = array("free", "busy", "dinner", "break"); @@ -112,6 +119,15 @@ class RetailcrmApiClient5 ); } + /** + * Get segments list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ public function segmentsList(array $filter = array(), $limit = null, $page = null) { $parameters = array(); @@ -133,6 +149,15 @@ class RetailcrmApiClient5 ); } + /** + * Get custom fields list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ public function customFieldsList(array $filter = array(), $limit = null, $page = null) { $parameters = array(); @@ -153,7 +178,15 @@ class RetailcrmApiClient5 $parameters ); } - + + /** + * Create custom field + * + * @param $entity + * @param $customField + * + * @return ApiResponse + */ public function customFieldsCreate($entity, $customField) { if (!count($customField) || @@ -178,7 +211,15 @@ class RetailcrmApiClient5 array('customField' => json_encode($customField)) ); } - + + /** + * Edit custom field + * + * @param $entity + * @param $customField + * + * @return ApiResponse + */ public function customFieldsEdit($entity, $customField) { if (!count($customField) || empty($customField['code'])) { @@ -200,6 +241,14 @@ class RetailcrmApiClient5 ); } + /** + * Get custom field + * + * @param $entity + * @param $code + * + * @return ApiResponse + */ public function customFieldsGet($entity, $code) { if (empty($code)) { @@ -220,6 +269,15 @@ class RetailcrmApiClient5 ); } + /** + * Get custom dictionaries list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ public function customDictionariesList(array $filter = [], $limit = null, $page = null) { $parameters = []; @@ -241,6 +299,13 @@ class RetailcrmApiClient5 ); } + /** + * Create custom dictionary + * + * @param $customDictionary + * + * @return ApiResponse + */ public function customDictionariesCreate($customDictionary) { if (!count($customDictionary) || @@ -259,6 +324,13 @@ class RetailcrmApiClient5 ); } + /** + * Edit custom dictionary + * + * @param $customDictionary + * + * @return ApiResponse + */ public function customDictionariesEdit($customDictionary) { if (!count($customDictionary) || @@ -277,6 +349,13 @@ class RetailcrmApiClient5 ); } + /** + * Get custom dictionary + * + * @param $code + * + * @return ApiResponse + */ public function customDictionariesGet($code) { if (empty($code)) { @@ -528,6 +607,15 @@ class RetailcrmApiClient5 ); } + /** + * Combine orders + * + * @param string $technique + * @param array $order + * @param array $resultOrder + * + * @return ApiResponse + */ public function ordersCombine($order, $resultOrder, $technique = 'ours') { $techniques = array('ours', 'summ', 'theirs'); @@ -555,6 +643,17 @@ class RetailcrmApiClient5 ); } + /** + * Create an order payment + * + * @param array $payment order data + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ public function ordersPaymentCreate(array $payment) { if (!count($payment)) { @@ -570,6 +669,15 @@ class RetailcrmApiClient5 ); } + /** + * Edit an order payment + * + * @param array $payment order data + * @param string $by by key + * @param null $site site code + * + * @return ApiResponse + */ public function ordersPaymentEdit(array $payment, $by = 'externalId', $site = null) { if (!count($payment)) { @@ -596,6 +704,27 @@ class RetailcrmApiClient5 ); } + /** + * Edit an order payment + * + * @param string $id payment id + * + * @return ApiResponse + */ + public function ordersPaymentDelete($id) + { + if (!$id) { + throw new \InvalidArgumentException( + 'Parameter `id` must be set' + ); + } + + return $this->client->makeRequest( + sprintf('/orders/payments/%s/delete', $id), + RetailcrmHttpClient::METHOD_POST + ); + } + /** * Returns filtered customers list * @@ -802,6 +931,14 @@ class RetailcrmApiClient5 ); } + /** + * Combine customers + * + * @param array $customers + * @param array $resultCustomer + * + * @return ApiResponse + */ public function customersCombine(array $customers, $resultCustomer) { @@ -821,6 +958,88 @@ class RetailcrmApiClient5 ); } + /** + * Returns filtered customers notes list + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersNotesList(array $filter = array(), $page = null, $limit = null) + { + $parameters = array(); + if (count($filter)) { + $parameters['filter'] = $filter; + } + if (null !== $page) { + $parameters['page'] = (int) $page; + } + if (null !== $limit) { + $parameters['limit'] = (int) $limit; + } + return $this->client->makeRequest( + '/customers/notes', + RetailcrmHttpClient::METHOD_GET, + $parameters + ); + } + + /** + * Create customer note + * + * @param array $note (default: array()) + * @param string $site (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersNotesCreate($note, $site = null) + { + if (empty($note['customer']['id']) && empty($note['customer']['externalId'])) { + throw new \InvalidArgumentException( + 'Customer identifier must be set' + ); + } + return $this->client->makeRequest( + '/customers/notes/create', + RetailcrmHttpClient::METHOD_POST, + $this->fillSite($site, array('note' => json_encode($note))) + ); + } + + /** + * Delete customer note + * + * @param integer $id + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ + public function customersNotesDelete($id) + { + if (empty($id)) { + throw new \InvalidArgumentException( + 'Note id must be set' + ); + } + return $this->client->makeRequest( + "/customers/notes/$id/delete", + RetailcrmHttpClient::METHOD_POST + ); + } + /** * Get orders assembly list * @@ -989,6 +1208,15 @@ class RetailcrmApiClient5 ); } + /** + * Get tasks list + * + * @param array $filter + * @param null $limit + * @param null $page + * + * @return ApiResponse + */ public function tasksList(array $filter = array(), $limit = null, $page = null) { $parameters = array(); @@ -1010,6 +1238,15 @@ class RetailcrmApiClient5 ); } + /** + * Create task + * + * @param array $task + * @param null $site + * + * @return ApiResponse + * + */ public function tasksCreate($task, $site = null) { if (!count($task)) { @@ -1028,6 +1265,15 @@ class RetailcrmApiClient5 ); } + /** + * Edit task + * + * @param array $task + * @param null $site + * + * @return ApiResponse + * + */ public function tasksEdit($task, $site = null) { if (!count($task)) { @@ -1046,6 +1292,13 @@ class RetailcrmApiClient5 ); } + /** + * Get custom dictionary + * + * @param $id + * + * @return ApiResponse + */ public function tasksGet($id) { if (empty($id)) { @@ -1060,6 +1313,19 @@ class RetailcrmApiClient5 ); } + /** + * Get products groups + * + * @param array $filter (default: array()) + * @param int $page (default: null) + * @param int $limit (default: null) + * + * @throws \InvalidArgumentException + * @throws \RetailCrm\Exception\CurlException + * @throws \RetailCrm\Exception\InvalidJsonException + * + * @return ApiResponse + */ public function storeProductsGroups(array $filter = array(), $page = null, $limit = null) { $parameters = array(); From 4890619c9ae4e568ca24ff7d7e7a3873e56c4f4d Mon Sep 17 00:00:00 2001 From: iyzoer Date: Fri, 28 Jul 2017 10:34:38 +0300 Subject: [PATCH 40/40] delete api client library --- .../library/retailcrm/RetailcrmApiClient.php | 1723 ----------------- 1 file changed, 1723 deletions(-) delete mode 100644 system/library/retailcrm/RetailcrmApiClient.php diff --git a/system/library/retailcrm/RetailcrmApiClient.php b/system/library/retailcrm/RetailcrmApiClient.php deleted file mode 100644 index 4363e65..0000000 --- a/system/library/retailcrm/RetailcrmApiClient.php +++ /dev/null @@ -1,1723 +0,0 @@ - - * @license https://opensource.org/licenses/MIT MIT License - * @link http://www.retailcrm.ru/docs/Developers/ApiVersion4 - */ -class RetailcrmApiClient -{ - - const VERSION = 'v4'; - - protected $client; - - /** - * Site code - */ - protected $siteCode; - - /** - * Client creating - * - * @param string $url api url - * @param string $apiKey api key - * @param string $site site code - * - * @throws \InvalidArgumentException - * - * @return mixed - */ - public function __construct($url, $apiKey, $site = null) - { - if ('/' !== $url[strlen($url) - 1]) { - $url .= '/'; - } - - $url = $url . 'api/' . self::VERSION; - - $this->client = new RetailcrmHttpClient($url, array('apiKey' => $apiKey)); - $this->siteCode = $site; - } - - /** - * Returns users list - * - * @param array $filter - * @param null $page - * @param null $limit - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function usersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/users', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Returns user data - * - * @param integer $id user ID - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function usersGet($id) - { - return $this->client->makeRequest("/users/$id", RetailcrmHttpClient::METHOD_GET); - } - - /** - * Returns filtered orders list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create a order - * - * @param array $order order data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersCreate(array $order, $site = null) - { - if (!count($order)) { - throw new \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('order' => json_encode($order))) - ); - } - - /** - * Save order IDs' (id and externalId) association in the CRM - * - * @param array $ids order identificators - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersFixExternalIds(array $ids) - { - if (! count($ids)) { - throw new \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/orders/fix-external-ids', - RetailcrmHttpClient::METHOD_POST, - array('orders' => json_encode($ids) - ) - ); - } - - /** - * Returns statuses of the orders - * - * @param array $ids (default: array()) - * @param array $externalIds (default: array()) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersStatuses(array $ids = array(), array $externalIds = array()) - { - $parameters = array(); - - if (count($ids)) { - $parameters['ids'] = $ids; - } - if (count($externalIds)) { - $parameters['externalIds'] = $externalIds; - } - - return $this->client->makeRequest( - '/orders/statuses', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Upload array of the orders - * - * @param array $orders array of orders - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersUpload(array $orders, $site = null) - { - if (!count($orders)) { - throw new \InvalidArgumentException( - 'Parameter `orders` must contains array of the orders' - ); - } - - return $this->client->makeRequest( - '/orders/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('orders' => json_encode($orders))) - ); - } - - /** - * Get order by id or externalId - * - * @param string $id order identificator - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest( - "/orders/$id", - RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) - ); - } - - /** - * Edit a order - * - * @param array $order order data - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersEdit(array $order, $by = 'externalId', $site = null) - { - if (!count($order)) { - throw new \InvalidArgumentException( - 'Parameter `order` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $order)) { - throw new \InvalidArgumentException( - sprintf('Order array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/orders/%s/edit', $order[$by]), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array('order' => json_encode($order), 'by' => $by) - ) - ); - } - - /** - * Get orders history - * @param array $filter - * @param null $page - * @param null $limit - * - * @return ApiResponse - */ - public function ordersHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Returns filtered customers list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/customers', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create a customer - * - * @param array $customer customer data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersCreate(array $customer, $site = null) - { - if (! count($customer)) { - throw new \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - return $this->client->makeRequest( - '/customers/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customer' => json_encode($customer))) - ); - } - - /** - * Save customer IDs' (id and externalId) association in the CRM - * - * @param array $ids ids mapping - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersFixExternalIds(array $ids) - { - if (! count($ids)) { - throw new \InvalidArgumentException( - 'Method parameter must contains at least one IDs pair' - ); - } - - return $this->client->makeRequest( - '/customers/fix-external-ids', - RetailcrmHttpClient::METHOD_POST, - array('customers' => json_encode($ids)) - ); - } - - /** - * Upload array of the customers - * - * @param array $customers array of customers - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersUpload(array $customers, $site = null) - { - if (! count($customers)) { - throw new \InvalidArgumentException( - 'Parameter `customers` must contains array of the customers' - ); - } - - return $this->client->makeRequest( - '/customers/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('customers' => json_encode($customers))) - ); - } - - /** - * Get customer by id or externalId - * - * @param string $id customer identificator - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersGet($id, $by = 'externalId', $site = null) - { - $this->checkIdParameter($by); - - return $this->client->makeRequest( - "/customers/$id", - RetailcrmHttpClient::METHOD_GET, - $this->fillSite($site, array('by' => $by)) - ); - } - - /** - * Edit a customer - * - * @param array $customer customer data - * @param string $by (default: 'externalId') - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function customersEdit(array $customer, $by = 'externalId', $site = null) - { - if (!count($customer)) { - throw new \InvalidArgumentException( - 'Parameter `customer` must contains a data' - ); - } - - $this->checkIdParameter($by); - - if (!array_key_exists($by, $customer)) { - throw new \InvalidArgumentException( - sprintf('Customer array must contain the "%s" parameter.', $by) - ); - } - - return $this->client->makeRequest( - sprintf('/customers/%s/edit', $customer[$by]), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite( - $site, - array('customer' => json_encode($customer), 'by' => $by) - ) - ); - } - - /** - * Get customers history - * @param array $filter - * @param null $page - * @param null $limit - * - * @return ApiResponse - */ - public function customersHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/customers/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get orders assembly list - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksList(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/packs', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Create orders assembly - * - * @param array $pack pack data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksCreate(array $pack, $site = null) - { - if (!count($pack)) { - throw new \InvalidArgumentException( - 'Parameter `pack` must contains a data' - ); - } - - return $this->client->makeRequest( - '/orders/packs/create', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) - ); - } - - /** - * Get orders assembly history - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/orders/packs/history', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get orders assembly by id - * - * @param string $id pack identificator - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksGet($id) - { - if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - "/orders/packs/$id", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Delete orders assembly by id - * - * @param string $id pack identificator - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksDelete($id) - { - if (empty($id)) { - throw new \InvalidArgumentException('Parameter `id` must be set'); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/delete', $id), - RetailcrmHttpClient::METHOD_POST - ); - } - - /** - * Edit orders assembly - * - * @param array $pack pack data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function ordersPacksEdit(array $pack, $site = null) - { - if (!count($pack) || empty($pack['id'])) { - throw new \InvalidArgumentException( - 'Parameter `pack` must contains a data & pack `id` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/orders/packs/%s/edit', $pack['id']), - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('pack' => json_encode($pack))) - ); - } - - /** - * Get purchace prices & stock balance - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeInventories(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/store/inventories', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get store settings - * - * @param string $code get settings code - * - * @return ApiResponse - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function storeSettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/store/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit store configuration - * - * @param array $configuration - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function storeSettingsEdit(array $configuration) - { - if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/store/setting/%s/edit', $configuration['code']), - RetailcrmHttpClient::METHOD_POST, - $configuration - ); - } - - /** - * Upload store inventories - * - * @param array $offers offers data - * @param string $site (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeInventoriesUpload(array $offers, $site = null) - { - if (!count($offers)) { - throw new \InvalidArgumentException( - 'Parameter `offers` must contains array of the offers' - ); - } - - return $this->client->makeRequest( - '/store/inventories/upload', - RetailcrmHttpClient::METHOD_POST, - $this->fillSite($site, array('offers' => json_encode($offers))) - ); - } - - /** - * Get products - * - * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storeProducts(array $filter = array(), $page = null, $limit = null) - { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } - - return $this->client->makeRequest( - '/store/products', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Get delivery settings - * - * @param string $code - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliverySettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/delivery/generic/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit delivery configuration - * - * @param array $configuration - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function deliverySettingsEdit(array $configuration) - { - if (!count($configuration) || empty($configuration['code'])) { - throw new \InvalidArgumentException( - 'Parameter `configuration` must contains a data & configuration `code` must be set' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/setting/%s/edit', $configuration['code']), - RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($configuration)) - ); - } - - /** - * Delivery tracking update - * - * @param string $code - * @param array $statusUpdate - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function deliveryTracking($code, array $statusUpdate) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - if (!count($statusUpdate)) { - throw new \InvalidArgumentException( - 'Parameter `statusUpdate` must contains a data' - ); - } - - return $this->client->makeRequest( - sprintf('/delivery/generic/%s/tracking', $code), - RetailcrmHttpClient::METHOD_POST, - $statusUpdate - ); - } - - /** - * Returns available county list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function countriesList() - { - return $this->client->makeRequest( - '/reference/countries', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Returns deliveryServices list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryServicesList() - { - return $this->client->makeRequest( - '/reference/delivery-services', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit deliveryService - * - * @param array $data delivery service data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryServicesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-services/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('deliveryService' => json_encode($data)) - ); - } - - /** - * Returns deliveryTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryTypesList() - { - return $this->client->makeRequest( - '/reference/delivery-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit deliveryType - * - * @param array $data delivery type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function deliveryTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/delivery-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('deliveryType' => json_encode($data)) - ); - } - - /** - * Returns orderMethods list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderMethodsList() - { - return $this->client->makeRequest( - '/reference/order-methods', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit orderMethod - * - * @param array $data order method data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderMethodsEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-methods/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('orderMethod' => json_encode($data)) - ); - } - - /** - * Returns orderTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderTypesList() - { - return $this->client->makeRequest( - '/reference/order-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit orderType - * - * @param array $data order type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function orderTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/order-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('orderType' => json_encode($data)) - ); - } - - /** - * Returns paymentStatuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentStatusesList() - { - return $this->client->makeRequest( - '/reference/payment-statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit paymentStatus - * - * @param array $data payment status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentStatusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('paymentStatus' => json_encode($data)) - ); - } - - /** - * Returns paymentTypes list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentTypesList() - { - return $this->client->makeRequest( - '/reference/payment-types', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit paymentType - * - * @param array $data payment type data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function paymentTypesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/payment-types/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('paymentType' => json_encode($data)) - ); - } - - /** - * Returns productStatuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function productStatusesList() - { - return $this->client->makeRequest( - '/reference/product-statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit productStatus - * - * @param array $data product status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function productStatusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/product-statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('productStatus' => json_encode($data)) - ); - } - - /** - * Returns sites list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function sitesList() - { - return $this->client->makeRequest( - '/reference/sites', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit site - * - * @param array $data site data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function sitesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/sites/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('site' => json_encode($data)) - ); - } - - /** - * Returns statusGroups list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusGroupsList() - { - return $this->client->makeRequest( - '/reference/status-groups', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Returns statuses list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusesList() - { - return $this->client->makeRequest( - '/reference/statuses', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit order status - * - * @param array $data status data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statusesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/statuses/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('status' => json_encode($data)) - ); - } - - /** - * Returns stores list - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storesList() - { - return $this->client->makeRequest( - '/reference/stores', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit store - * - * @param array $data site data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function storesEdit(array $data) - { - if (!array_key_exists('code', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "code" parameter.' - ); - } - - if (!array_key_exists('name', $data)) { - throw new \InvalidArgumentException( - 'Data must contain "name" parameter.' - ); - } - - return $this->client->makeRequest( - sprintf('/reference/stores/%s/edit', $data['code']), - RetailcrmHttpClient::METHOD_POST, - array('store' => json_encode($data)) - ); - } - - /** - * Get telephony settings - * - * @param string $code - * - * @throws \RetailCrm\Exception\InvalidJsonException - * @throws \RetailCrm\Exception\CurlException - * @throws \InvalidArgumentException - * - * @return ApiResponse - */ - public function telephonySettingsGet($code) - { - if (empty($code)) { - throw new \InvalidArgumentException('Parameter `code` must be set'); - } - - return $this->client->makeRequest( - "/telephony/setting/$code", - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Edit telephony settings - * - * @param string $code symbolic code - * @param string $clientId client id - * @param boolean $active telephony activity - * @param mixed $name service name - * @param mixed $makeCallUrl service init url - * @param mixed $image service logo url(svg file) - * - * @param array $additionalCodes - * @param array $externalPhones - * @param bool $allowEdit - * @param bool $inputEventSupported - * @param bool $outputEventSupported - * @param bool $hangupEventSupported - * @param bool $changeUserStatusUrl - * - * @return ApiResponse - */ - public function telephonySettingsEdit( - $code, - $clientId, - $active = false, - $name = false, - $makeCallUrl = false, - $image = false, - $additionalCodes = array(), - $externalPhones = array(), - $allowEdit = false, - $inputEventSupported = false, - $outputEventSupported = false, - $hangupEventSupported = false, - $changeUserStatusUrl = false - ) - { - if (!isset($code)) { - throw new \InvalidArgumentException('Code must be set'); - } - - $parameters['code'] = $code; - - if (!isset($clientId)) { - throw new \InvalidArgumentException('client id must be set'); - } - - $parameters['clientId'] = $clientId; - - if (!isset($active)) { - $parameters['active'] = false; - } else { - $parameters['active'] = $active; - } - - if (!isset($name)) { - throw new \InvalidArgumentException('name must be set'); - } - - if (isset($name)) { - $parameters['name'] = $name; - } - - if (isset($makeCallUrl)) { - $parameters['makeCallUrl'] = $makeCallUrl; - } - - if (isset($image)) { - $parameters['image'] = $image; - } - - if (isset($additionalCodes)) { - $parameters['additionalCodes'] = $additionalCodes; - } - - if (isset($externalPhones)) { - $parameters['externalPhones'] = $externalPhones; - } - - if (isset($allowEdit)) { - $parameters['allowEdit'] = $allowEdit; - } - - if (isset($inputEventSupported)) { - $parameters['inputEventSupported'] = $inputEventSupported; - } - - if (isset($outputEventSupported)) { - $parameters['outputEventSupported'] = $outputEventSupported; - } - - if (isset($hangupEventSupported)) { - $parameters['hangupEventSupported'] = $hangupEventSupported; - } - - if (isset($changeUserStatusUrl)) { - $parameters['changeUserStatusUrl'] = $changeUserStatusUrl; - } - - return $this->client->makeRequest( - "/telephony/setting/$code/edit", - RetailcrmHttpClient::METHOD_POST, - array('configuration' => json_encode($parameters)) - ); - } - - /** - * Call event - * - * @param string $phone phone number - * @param string $type call type - * @param array $codes - * @param string $hangupStatus - * @param string $externalPhone - * @param array $webAnalyticsData - * - * @return ApiResponse - * @internal param string $code additional phone code - * @internal param string $status call status - * - */ - public function telephonyCallEvent( - $phone, - $type, - $codes, - $hangupStatus, - $externalPhone = null, - $webAnalyticsData = array() - ) - { - if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); - } - - if (!isset($type)) { - throw new \InvalidArgumentException('Type must be set (in|out|hangup)'); - } - - if (empty($codes)) { - throw new \InvalidArgumentException('Codes array must be set'); - } - - $parameters['phone'] = $phone; - $parameters['type'] = $type; - $parameters['codes'] = $codes; - $parameters['hangupStatus'] = $hangupStatus; - $parameters['callExternalId'] = $externalPhone; - $parameters['webAnalyticsData'] = $webAnalyticsData; - - - return $this->client->makeRequest( - '/telephony/call/event', - RetailcrmHttpClient::METHOD_POST, - array('event' => json_encode($parameters)) - ); - } - - /** - * Upload calls - * - * @param array $calls calls data - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function telephonyCallsUpload(array $calls) - { - if (!count($calls)) { - throw new \InvalidArgumentException( - 'Parameter `calls` must contains array of the calls' - ); - } - - return $this->client->makeRequest( - '/telephony/calls/upload', - RetailcrmHttpClient::METHOD_POST, - array('calls' => json_encode($calls)) - ); - } - - /** - * Get call manager - * - * @param string $phone phone number - * @param bool $details detailed information - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function telephonyCallManager($phone, $details) - { - if (!isset($phone)) { - throw new \InvalidArgumentException('Phone number must be set'); - } - - $parameters['phone'] = $phone; - $parameters['details'] = isset($details) ? $details : 0; - - return $this->client->makeRequest( - '/telephony/manager', - RetailcrmHttpClient::METHOD_GET, - $parameters - ); - } - - /** - * Update CRM basic statistic - * - * @throws \InvalidArgumentException - * @throws \RetailCrm\Exception\CurlException - * @throws \RetailCrm\Exception\InvalidJsonException - * - * @return ApiResponse - */ - public function statisticUpdate() - { - return $this->client->makeRequest( - '/statistic/update', - RetailcrmHttpClient::METHOD_GET - ); - } - - /** - * Return current site - * - * @return string - */ - public function getSite() - { - return $this->siteCode; - } - - /** - * Set site - * - * @param string $site site code - * - * @return void - */ - public function setSite($site) - { - $this->siteCode = $site; - } - - /** - * Check ID parameter - * - * @param string $by identify by - * - * @throws \InvalidArgumentException - * - * @return bool - */ - protected function checkIdParameter($by) - { - $allowedForBy = array( - 'externalId', - 'id' - ); - - if (!in_array($by, $allowedForBy, false)) { - throw new \InvalidArgumentException( - sprintf( - 'Value "%s" for "by" param is not valid. Allowed values are %s.', - $by, - implode(', ', $allowedForBy) - ) - ); - } - - return true; - } - - /** - * Fill params by site value - * - * @param string $site site code - * @param array $params input parameters - * - * @return array - */ - protected function fillSite($site, array $params) - { - if ($site) { - $params['site'] = $site; - } elseif ($this->siteCode) { - $params['site'] = $this->siteCode; - } - - return $params; - } -}