Upload specials prices, new model for history handler (#74)

This commit is contained in:
Akolzin Dmitry 2018-02-26 13:22:13 +03:00 committed by GitHub
parent bf5a5b9e15
commit 1e71be6b7a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 1084 additions and 919 deletions

View File

@ -1,3 +1,9 @@
## v.3.0.2
* Улучшена механика выгрузки изменений из RetailCRM на сайт
* Улучшена механика выборки типов доставки на сайте
* Добавлена возможность периодической выгрузки акционных цен для товаров
* Улучшена совместимость с Opencart 3.0
## v.2.4.3
* Устранены некоторые баги, добавлен вывод ошибок при выгрузке единичных заказов

View File

@ -55,6 +55,13 @@ cp -r opencart-module/* /path/to/site/root
```
http://youropencartsite.com/retailcrm.xml
```
#### Настройка выгрузки акционных цен
Для периодической выгрузки акционных цен в CRM в настройках модуля укажите тип цены, в который необходимо выгружать акционные цены, в крон добавьте следующую запись
```
0 0 * * * /usr/bin/php /path/to/opencart/system/cron/prices.php >> /path/to/opencart/system/storage/logs/cronjob_prices.log 2>&1
```
#### Выгрузка существующих заказов и покупателей

View File

@ -242,7 +242,9 @@ class ControllerExtensionModuleRetailcrm extends Controller
'text_customers_custom_fields',
'text_confirm_log',
'text_error_delivery',
'retailcrm_missing_status'
'retailcrm_missing_status',
'special_price_settings',
'special_price'
);
$_data = &$data;
@ -278,6 +280,11 @@ class ControllerExtensionModuleRetailcrm extends Controller
$_data['customFields'] = $this->model_extension_retailcrm_references
->getCustomFields();
}
if ($apiVersion != 'v3') {
$_data['priceTypes'] = $this->model_extension_retailcrm_references
->getPriceTypes();
}
}
$config_data = array(
@ -507,7 +514,7 @@ class ControllerExtensionModuleRetailcrm extends Controller
/**
* Export single order
*
*
* @return void
*/
public function exportOrder()
{
@ -558,8 +565,8 @@ class ControllerExtensionModuleRetailcrm extends Controller
*
* @return void
*/
public function export() {
public function export()
{
$this->load->model('customer/customer');
$customers = $this->model_customer_customer->getCustomers();
@ -589,6 +596,25 @@ class ControllerExtensionModuleRetailcrm extends Controller
fopen(DIR_SYSTEM . '/cron/export_done', "x");
}
/**
* Promotional price upload
*
* @return void
*/
public function prices()
{
$this->load->model('catalog/product');
$products = $this->model_catalog_product->getProducts();
if (file_exists(DIR_APPLICATION . 'model/extension/retailcrm/custom/prices.php')) {
$this->load->model('extension/retailcrm/custom/prices');
$this->model_extension_retailcrm_custom_prices->uploadPrices($products);
} else {
$this->load->model('extension/retailcrm/prices');
$this->model_extension_retailcrm_prices->uploadPrices($products);
}
}
/**
* Validate
*

View File

@ -23,6 +23,8 @@ $_['retailcrm_apiversion'] = 'API Version';
$_['retailcrm_url'] = 'RetailCRM URL';
$_['retailcrm_apikey'] = 'RetailCRM API Key';
$_['collector_site_key'] = 'Site key';
$_['special_price_settings'] = 'Settings specials';
$_['special_price'] = 'The type of price at which the share price will be unloaded';
$_['text_success_export'] = 'Orders and customers successfully unloaded';
$_['text_success_export_order'] = 'Order successfully unloaded';

View File

@ -23,6 +23,8 @@ $_['retailcrm_apiversion'] = 'Версия API';
$_['retailcrm_url'] = 'Адрес RetailCRM';
$_['retailcrm_apikey'] = 'Api ключ RetailCRM';
$_['collector_site_key'] = 'Ключ сайта';
$_['special_price_settings'] = 'Настройка выгрузки акционной цены';
$_['special_price'] = 'Тип цены, в который будет выгружаться цена по акции';
$_['text_success_export'] = 'Заказы и клиенты успешно выгружены';
$_['text_success_export_order'] = 'Заказ успешно выгружен';

View File

@ -0,0 +1,195 @@
<?php
class ModelExtensionRetailcrmHistory extends Model
{
/**
* Create order in OC
*
* @param array $order
*
* @return int $order_id
*/
public function addOrder($order)
{
$this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET store_id = '" . (int)$order['store_id'] . "', store_name = '" . $order['store_name'] . "', customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(isset($order['custom_field']) ? json_encode($order['custom_field']) : '') . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', affiliate_id = '" . (int)$order['affiliate_id'] . "', language_id = '" . (int)$order['language_id'] . "', currency_id = '" . (int)$order['currency_id'] . "', currency_code = '" . $this->db->escape($order['currency_code']) . "', currency_value = '" . (float)$order['currency_value'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_added = NOW(), date_modified = NOW()");
$order_id = $this->db->getLastId();
// Products
if (isset($order['order_product']) && $order['order_product']) {
$this->addOrderProducts($order_id, $order['order_product']);
}
// Totals
if (isset($order['order_total'])) {
$this->addOrderTotals($order_id, $order['order_total']);
}
return $order_id;
}
/**
* Edit order in OC
*
* @param int $order_id
* @param array $order
*
* @return void
*/
public function editOrder($order_id, $order)
{
$this->db->query("UPDATE `" . DB_PREFIX . "order` SET customer_id = '" . (int)$order['customer_id'] . "', customer_group_id = '" . (int)$order['customer_group_id'] . "', firstname = '" . $this->db->escape($order['firstname']) . "', lastname = '" . $this->db->escape($order['lastname']) . "', email = '" . $this->db->escape($order['email']) . "', telephone = '" . $this->db->escape($order['telephone']) . "', custom_field = '" . $this->db->escape(json_encode($order['custom_field'])) . "', payment_firstname = '" . $this->db->escape($order['payment_firstname']) . "', payment_lastname = '" . $this->db->escape($order['payment_lastname']) . "', payment_address_1 = '" . $this->db->escape($order['payment_address_1']) . "', payment_address_2 = '" . $this->db->escape($order['payment_address_2']) . "', payment_city = '" . $this->db->escape($order['payment_city']) . "', payment_postcode = '" . $this->db->escape($order['payment_postcode']) . "', payment_country = '" . $this->db->escape($order['payment_country']) . "', payment_country_id = '" . (int)$order['payment_country_id'] . "', payment_zone = '" . $this->db->escape($order['payment_zone']) . "', payment_zone_id = '" . (int)$order['payment_zone_id'] . "', payment_method = '" . $this->db->escape($order['payment_method']) . "', payment_code = '" . $this->db->escape($order['payment_code']) . "', shipping_firstname = '" . $this->db->escape($order['shipping_firstname']) . "', shipping_lastname = '" . $this->db->escape($order['shipping_lastname']) . "', shipping_address_1 = '" . $this->db->escape($order['shipping_address_1']) . "', shipping_address_2 = '" . $this->db->escape($order['shipping_address_2']) . "', shipping_city = '" . $this->db->escape($order['shipping_city']) . "', shipping_postcode = '" . $this->db->escape($order['shipping_postcode']) . "', shipping_country = '" . $this->db->escape($order['shipping_country']) . "', shipping_country_id = '" . (int)$order['shipping_country_id'] . "', shipping_zone = '" . $this->db->escape($order['shipping_zone']) . "', shipping_zone_id = '" . (int)$order['shipping_zone_id'] . "', shipping_method = '" . $this->db->escape($order['shipping_method']) . "', shipping_code = '" . $this->db->escape($order['shipping_code']) . "', comment = '" . $this->db->escape($order['comment']) . "', total = '" . (float)$order['total'] . "', order_status_id = '" . (int)$order['order_status_id'] . "', date_modified = NOW() WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_product WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "order_option WHERE order_id = '" . (int)$order_id . "'");
// Products
if (isset($order['order_product']) && $order['order_product']) {
$this->addOrderProducts($order_id, $order['order_product']);
}
// Totals
$this->db->query("DELETE FROM " . DB_PREFIX . "order_total WHERE order_id = '" . (int)$order_id . "'");
if (isset($order['order_total'])) {
$this->addOrderTotals($order_id, $order['order_total']);
}
}
/**
* Add order products
*
* @param int $order_id
* @param array $products
*
* @return void
*/
public function addOrderProducts($order_id, $products)
{
foreach ($products as $product) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_product SET order_id = '" . (int)$order_id . "', product_id = '" . (int)$product['product_id'] . "', name = '" . $this->db->escape($product['name']) . "', model = '" . $this->db->escape($product['model']) . "', quantity = '" . (int)$product['quantity'] . "', price = '" . (float)$product['price'] . "', total = '" . (float)$product['total'] . "'");
$order_product_id = $this->db->getLastId();
foreach ($product['option'] as $option) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_option SET order_id = '" . (int)$order_id . "', order_product_id = '" . (int)$order_product_id . "', product_option_id = '" . (int)$option['product_option_id'] . "', product_option_value_id = '" . (int)$option['product_option_value_id'] . "', name = '" . $this->db->escape($option['name']) . "', `value` = '" . $this->db->escape($option['value']) . "', `type` = '" . $this->db->escape($option['type']) . "'");
}
}
}
/**
* Add order totals
*
* @param int $order_id
* @param array $totals
*
* @return void
*/
public function addOrderTotals($order_id, $totals)
{
foreach ($totals as $total) {
$this->db->query("INSERT INTO " . DB_PREFIX . "order_total SET order_id = '" . (int)$order_id . "', code = '" . $this->db->escape($total['code']) . "', title = '" . $this->db->escape($total['title']) . "', `value` = '" . (float)$total['value'] . "', sort_order = '" . (int)$total['sort_order'] . "'");
}
}
/**
* Get total titles
*
* @return string $title
*/
protected function totalTitles()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
} else {
$title = 'total_';
}
return $title;
}
/**
* Get country by iso code 2
*
* @param string $isoCode
*
* @return array
*/
public function getCountryByIsoCode($isoCode)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
return $query->row;
}
/**
* Get zone by name
*
* @param string $name
*
* @return array
*/
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row;
}
/**
* Get currency
*
* @param string $code
* @param string $field (default = '')
*
* @return mixed array | string
*/
public function getCurrencyByCode($code, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "currency` WHERE code = '" . $code . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
/**
* Get language
*
* @param string $code
* @param string $field (default = '')
*
* @return mixed array | string
*/
public function getLanguageByCode($code, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE code = '" . $code . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
/**
* Get product option value
*
* @param int $option_value_id
* @param string $field
*
* @return mixed array | string
*/
public function getOptionValue($option_value_id, $field = '')
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "option_value_description` WHERE option_value_id = '" . $option_value_id . "'");
if (!$field) {
return $query->row;
}
return $query->row[$field];
}
}

View File

@ -1,14 +1,21 @@
<?php
class ModelExtensionRetailcrmHistoryV3 extends Model
require_once 'v4_5.php';
class ModelExtensionRetailcrmHistoryV3 extends ModelExtensionRetailcrmHistoryV45
{
protected $createResult;
private $opencartApiClient;
/**
* Getting changes from RetailCRM
*
* @return boolean
*/
public function request()
{
$moduleTitle = $this->getModuleTitle();
$moduleTitle = $this->retailcrm->getModuleTitle();
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
@ -33,8 +40,6 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
return false;
}
$this->opencartApiClient = new OpencartApiClient($this->registry);
$crm = new RetailcrmProxy(
$settings[$moduleTitle . '_url'],
$settings[$moduleTitle . '_apikey'],
@ -66,7 +71,9 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes();
$this->ocDelivery = $settings[$moduleTitle . '_delivery'];
$this->ocDelivery = $this->model_extension_retailcrm_references
->getOpercartDeliveryTypes();
$this->zones = $this->model_localisation_zone->getZones();
$updatedOrders = array();
@ -75,7 +82,9 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
foreach ($orders as $order) {
if (isset($order['deleted'])) continue;
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
@ -110,468 +119,4 @@ class ModelExtensionRetailcrmHistoryV3 extends Model
$crm->ordersFixExternalIds($this->createResult['orders']);
}
}
protected function updateOrders($orders)
{
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
$data = array();
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
$data['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName'];
$data['customer_id'] = isset($order['customer']['externalId']) ? $order['customer']['externalId'] : 0;
$data['customer_group_id'] = 1;
$data['firstname'] = $order['firstName'];
$data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = '';
$data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName'];
$data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
$data['payment_address_2'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'];
$data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'];
$shippingZone = '';
if (is_int($order['delivery']['address']['region'])) {
$shippingZone = $order['delivery']['address']['region'];
} else {
$shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($shippingZone) {
$shipping_zone_id = $shippingZone['zone_id'];
} else {
$shipping_zone_id = 0;
}
}
if (isset($order['customer']['address']['region'])) {
$paymentZone = $this->getZoneByName($order['customer']['address']['region']);
if ($paymentZone) {
$payment_zone_id = $paymentZone['zone_id'];
} else {
$payment_zone_id = 0;
}
}
if (isset($order['delivery']['address']['countryIso'])) {
$shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
}
if (isset($order['customer']['address']['countryIso'])) {
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
}
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$payment = isset($order['paymentType']) ? $order['paymentType'] : null;
$data['payment_country_id'] = isset($paymentCountry) ? $paymentCountry['country_id'] : 0;
$data['payment_zone_id'] = $payment_zone_id;
$data['shipping_country_id'] = isset($shippingCountry) ? $shippingCountry['country_id'] : 0;
$data['shipping_zone_id'] = $shipping_zone_id;
$data['shipping_address'] = '0';
$data['shipping_firstname'] = $order['firstName'];
$data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['shipping_address_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = '';
$data['shipping_company'] = '';
$data['shipping_company_id'] = '';
$data['shipping_city'] = $order['delivery']['address']['city'];
$data['shipping_postcode'] = $order['delivery']['address']['index'];
$data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['payment'] = $payment != null ? $this->payment[$payment] : $this->payment_default;
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $payment != null ? $this->payment[$payment] : $this->payment_default;
// this data will not retrive from crm for now
$data['tax'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
foreach($optionsFromCRM as $optionFromCRM) {
$optionData = explode('-', $optionFromCRM);
$productOptionId = $optionData[0];
$optionValueId = $optionData[1];
$productOptions = $this->model_catalog_product->getProductOptions($productId);
foreach($productOptions as $productOption) {
if($productOptionId == $productOption['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['option_value_id'] == $optionValueId) {
$options[$productOptionId] = $productOptionValue['product_option_value_id'];
}
}
}
}
}
}
$data['order_product'][] = array(
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
);
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
if(isset($order['discount']) && $order['discount'] > 0) {
$orderTotals = $this->model_sale_order->getOrderTotals($order['externalId']);
foreach($orderTotals as $orderTotal) {
if($orderTotal['code'] == 'coupon') {
$data['order_total'][] = $orderTotal;
}
}
}
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'title' => $this->language->get('column_total'),
'value' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order']
)
);
$data['fromApi'] = true;
if (array_key_exists($order['status'], $this->status)) {
$data['order_status_id'] = $this->status[$order['status']];
} else {
$tmpOrder = $this->model_sale_order->getOrder($order['externalId']);
$data['order_status_id'] = $tmpOrder['order_status_id'];
}
$this->opencartApiClient->editOrder($order['externalId'], $data);
}
}
protected function createOrders($orders)
{
$customersIdsFix = array();
$ordersIdsFix = array();
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
$customer_id = (!empty($order['customer']['externalId']))
? $order['customer']['externalId']
: 0;
$data = array();
if ($customer_id == 0) {
if (isset($order['customer']['address']['countryIso'])) {
$customerCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
} else {
$customerCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
}
if (isset($order['customer']['address']['region'])) {
$customerZone = $this->getZoneByName($order['customer']['address']['region']);
} else {
$customerZone = $this->getZoneByName($order['delivery']['address']['region']);
}
$cData = array(
'store_id' => 0,
'customer_group_id' => '1',
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'email' => $order['customer']['email'],
'telephone' => $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : ' ',
'fax' => '',
'newsletter' => 0,
'password' => 'tmppass',
'status' => 1,
'approved' => 1,
'safe' => 0,
'address' => array(
array(
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
'lastname' => (!empty($order['customer']['lastName'])) ? $order['customer']['lastName'] : ' ',
'address_1' => $order['customer']['address']['text'],
'address_2' => ' ',
'city' => !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'],
'postcode' => isset($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'],
'tax_id' => '1',
'company' => '',
'company_id' => '',
'zone_id' => $customerZone ? $customerZone['zone_id'] : 0,
'country_id' => $customerCountry ? $customerCountry['country_id'] : 0,
'default' => '1'
)
),
);
$customer_id = $this->model_customer_customer->addCustomer($cData);
$customersIdsFix[] = array('id' => $order['customer']['id'], 'externalId' => (int)$customer_id);
}
$mail = isset($order['email']) ? $order['email'] : $order['customer']['email'];
$phone = isset($order['phone']) ? $order['phone'] : '';
if (!$phone) {
$data['telephone'] = $order['customer']['phones'] ? $order['customer']['phones'][0]['number'] : '80000000000';
} else {
$data['telephone'] = $phone;
}
$data['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName'];
$data['customer_id'] = $customer_id;
$data['customer_group_id'] = 1;
$data['firstname'] = $order['firstName'];
$data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = '';
$data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName'];
$data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['payment_address_1'] = $order['customer']['address']['text'];
$data['payment_address_2'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'];
$data['payment_postcode'] = !empty($order['customer']['address']['index']) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'];
$shippingZone = '';
if (is_int($order['delivery']['address']['region'])) {
$shippingZone = $order['delivery']['address']['region'];
} else {
$shippingZone = $this->getZoneByName($order['delivery']['address']['region']);
if ($shippingZone) {
$shipping_zone_id = $shippingZone['zone_id'];
} else {
$shipping_zone_id = 0;
}
}
if (isset($order['customer']['address']['region'])) {
$paymentZone = $this->getZoneByName($order['customer']['address']['region']);
if ($paymentZone) {
$payment_zone_id = $paymentZone['zone_id'];
} else {
$payment_zone_id = 0;
}
}
if (isset($order['delivery']['address']['countryIso'])) {
$shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
}
if (isset($order['customer']['address']['countryIso'])) {
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
}
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$payment = isset($order['paymentType']) ? $order['paymentType'] : null;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0;
$data['payment_zone_id'] = $payment_zone_id;
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0;
$data['shipping_zone_id'] = $shipping_zone_id;
$data['shipping_address'] = '0';
$data['shipping_firstname'] = $order['firstName'];
$data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['shipping_address_1'] = $order['delivery']['address']['text'];
$data['shipping_address_2'] = '';
$data['shipping_company'] = '';
$data['shipping_company_id'] = '';
$data['shipping_city'] = $order['delivery']['address']['city'];
$data['shipping_postcode'] = $order['delivery']['address']['index'];
$data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['payment'] = $payment != null ? $this->payment[$payment] : $this->payment_default;
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $payment != null ? $this->payment[$payment] : $this->payment_default;
// this data will not retrive from crm for now
$data['tax'] = '';
$data['tax_id'] = '';
$data['product'] = '';
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['company'] = '';
$data['company_id'] = '';
$data['order_product'] = array();
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
$optionsFromCRM = explode('_', $offer[1]);
foreach($optionsFromCRM as $optionFromCRM) {
$optionData = explode('-', $optionFromCRM);
$productOptionId = $optionData[0];
$optionValueId = $optionData[1];
$productOptions = $this->model_catalog_product->getProductOptions($productId);
foreach($productOptions as $productOption) {
if($productOptionId == $productOption['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['option_value_id'] == $optionValueId) {
$options[$productOptionId] = $productOptionValue['product_option_value_id'];
}
}
}
}
}
}
$data['order_product'][] = array(
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
);
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['order_total'] = array(
array(
'order_total_id' => '',
'code' => 'sub_total',
'title' => $this->language->get('product_summ'),
'value' => $order['summ'],
'text' => $order['summ'],
'sort_order' => $this->subtotalSettings['sub_total_sort_order']
),
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
),
array(
'order_total_id' => '',
'code' => 'total',
'title' => $this->language->get('column_total'),
'value' => !empty($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'text' => isset($order['totalSumm']) ? $order['totalSumm'] : $order['summ'] + $deliveryCost,
'sort_order' => $this->totalSettings[$this->totalTitle . 'total_sort_order']
)
);
$data['fromApi'] = true;
$data['order_status_id'] = 1;
$order_id = $this->opencartApiClient->addOrder($data);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
}
return array('customers' => $customersIdsFix, 'orders' => $ordersIdsFix);
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
private function totalTitles()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
} else {
$title = 'total_';
}
return $title;
}
public function getCountryByIsoCode($isoCode)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
return $query->row;
}
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row;
}
}

View File

@ -1,15 +1,33 @@
<?php
class ModelExtensionRetailcrmHistoryV45 extends Model
require_once __DIR__ . '/../history.php';
class ModelExtensionRetailcrmHistoryV45 extends ModelExtensionRetailcrmHistory
{
protected $createResult;
protected $settings;
protected $moduleTitle;
private $opencartApiClient;
private $customFieldSetting;
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->opencartApiClient = $this->retailcrm->getOcApiClient($registry);
}
/**
* Getting changes from RetailCRM
*
* @return boolean
*/
public function request()
{
$this->moduleTitle = $this->getModuleTitle();
$this->load->library('retailcrm/retailcrm');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->load->model('setting/setting');
$this->load->model('setting/store');
$this->load->model('user/api');
@ -75,6 +93,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$sinceIdCustomers = $lastChangeCustomers['id'];
}
$this->settings = $settings;
$this->totalTitle = $this->totalTitles();
$this->subtotalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'sub_total');
$this->totalSettings = $this->model_setting_setting->getSetting($this->totalTitle . 'total');
@ -88,7 +107,8 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$this->ocPayment = $this->model_extension_retailcrm_references
->getOpercartPaymentTypes();
$this->ocDelivery = $settings[$this->moduleTitle . '_delivery'];
$this->ocDelivery = $this->model_extension_retailcrm_references
->getOpercartDeliveryTypes();
$this->zones = $this->model_localisation_zone->getZones();
@ -101,7 +121,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
foreach ($orders as $order) {
if (isset($order['deleted'])) continue;
if (isset($order['deleted'])) {
continue;
}
if (isset($order['externalId'])) {
$updatedOrders[] = $order['id'];
@ -116,7 +138,9 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
foreach ($customers as $customer) {
if (isset($customer['deleted'])) continue;
if (isset($customer['deleted'])) {
continue;
}
if (isset($customer['externalId'])) {
$updateCustomers[] = $customer['id'];
@ -164,12 +188,19 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
}
}
/**
* Update orders from history
*
* @param array $orders
*
* @return void
*/
protected function updateOrders($orders)
{
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
$ocOrder = $this->model_sale_order->getOrder($order['externalId']);
if ($order['payments']) {
if (isset($order['payments']) && $order['payments']) {
foreach ($order['payments'] as $orderPayment) {
if (isset($orderPayment['externalId'])) {
$payment = $orderPayment;
@ -194,7 +225,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['telephone'] = $phone;
}
$data['store_id'] = $store == null ? 0 : $store;
$data['customer'] = $order['firstName'];
$data['customer_id'] = (!empty($order['customer']['externalId'])) ? $order['customer']['externalId'] : 0;
$data['customer_group_id'] = 1;
@ -202,15 +232,11 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['email'] = $mail ? $mail : uniqid() . '@retailrcm.ru';
$data['comment'] = !empty($order['customerComment']) ? $order['customerComment'] : '';
$data['fax'] = '';
$data['payment_address'] = '0';
$data['payment_firstname'] = $order['firstName'];
$data['payment_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
$data['payment_address_1'] = isset($order['customer']['address']) ? $order['customer']['address']['text'] : '';
$data['payment_address_2'] = '';
$data['payment_company'] = '';
$data['payment_company_id'] = '';
$data['payment_city'] = !empty($order['customer']['address']['city']) ? $order['customer']['address']['city'] : $order['delivery']['address']['city'];
$data['payment_postcode'] = !empty( $order['customer']['address']['index'] ) ? $order['customer']['address']['index'] : $order['delivery']['address']['index'];
@ -238,19 +264,25 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
}
}
if (isset($order['delivery']['address']['countryIso'])) {
$shippingCountry = $this->getCountryByIsoCode($order['delivery']['address']['countryIso']);
if (isset($order['countryIso']) && !empty($order['countryIso'])) {
$shippingCountry = $this->getCountryByIsoCode($order['countryIso']);
}
if (isset($order['customer']['address']['countryIso'])) {
if (isset($order['customer']['address']['countryIso']) && !empty($order['customer']['address']['countryIso'])) {
$paymentCountry = $this->getCountryByIsoCode($order['customer']['address']['countryIso']);
} else {
$paymentCountry = $this->getCountryByIsoCode($order['countryIso']);
}
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0;
$data['payment_zone_id'] = $payment_zone_id;
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0;
$data['shipping_zone_id'] = $shipping_zone_id;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : $ocOrder['payment_country_id'];
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : $ocOrder['payment_country'];
$data['payment_zone_id'] = $payment_zone_id ? $payment_zone_id : $ocOrder['payment_zone_id'];
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : $ocOrder['payment_zone'];
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : $ocOrder['shipping_country_id'];
$data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : $ocOrder['shipping_country'];
$data['shipping_zone_id'] = $shipping_zone_id ? $shipping_zone_id : $ocOrder['shipping_zone_id'];
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $ocOrder['shipping_zone'];
$data['shipping_address'] = '0';
$data['shipping_firstname'] = $order['firstName'];
$data['shipping_lastname'] = isset($order['lastName']) ? $order['lastName'] : $order['firstName'];
@ -260,19 +292,40 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['shipping_company_id'] = '';
$data['shipping_city'] = $order['delivery']['address']['city'];
$data['shipping_postcode'] = $order['delivery']['address']['index'];
$data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
if ($delivery !== null) {
if (isset($this->settings[$this->moduleTitle . '_delivery'][$ocOrder['shipping_code']])
&& isset($this->delivery[$delivery])
) {
$data['shipping'] = $this->delivery[$delivery];
$shipping = explode('.', $data['shipping']);
$shippingModule = $shipping[0];
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
} else {
$data['shipping_method'] =$this->ocDelivery[$shippingModule]['title'];
}
$data['shipping_code'] = $data['shipping'];
}
} else {
if (!isset($this->settings[$ocOrder['shipping_code']])
|| !isset($this->delivery[$delivery])
) {
$data['shipping_method'] = $ocOrder['shipping_method'];
$data['shipping_code'] = $ocOrder['shipping_code'];
}
}
if (isset($payment)) {
$data['payment'] = $this->payment[$payment['type']];
$data['payment_method'] = $this->ocPayment[$data['payment']];
$data['payment_code'] = $this->payment[$payment['type']];
$data['payment_method'] = isset($this->ocPayment[$data['payment']]) ? $this->ocPayment[$data['payment']] : $ocOrder['payment_method'];
$data['payment_code'] = isset($this->payment[$payment['type']]) ? $this->payment[$payment['type']] : $ocOrder['payment_code'];
} else {
$this->load->model('sale/order');
$order_data = $this->model_sale_order->getOrder($order['externalId']);
$data['payment_method'] = $order_data['payment_method'];
$data['payment_code'] = $order_data['payment_code'];
$data['payment_method'] = $ocOrder['payment_method'];
$data['payment_code'] = $ocOrder['payment_code'];
}
// this data will not retrive from crm for now
@ -295,6 +348,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if (mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
@ -311,14 +365,27 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
if($productOptionId == $productOption['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['option_value_id'] == $optionValueId) {
$options[$productOptionId] = $productOptionValue['product_option_value_id'];
$options[] = array(
'product_option_id' => $productOptionId,
'product_option_value_id' => $productOptionValue['product_option_value_id'],
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
'type' => $productOption['type'],
'name' => $productOption['name'],
);
}
}
}
}
}
}
$product = $this->model_catalog_product->getProduct($productId);
$data['order_product'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'price' => $item['initialPrice'],
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
@ -334,6 +401,8 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
}
$data['custom_field'] = isset($customFields) ? $customFields : '';
} else {
$data['custom_field'] = $ocOrder['custom_field'];
}
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
@ -347,6 +416,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
}
}
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
@ -359,7 +429,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
@ -383,10 +453,18 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['order_status_id'] = $tmpOrder['order_status_id'];
}
$this->opencartApiClient->editOrder($order['externalId'], $data);
$this->editOrder($order['externalId'], $data);
$this->opencartApiClient->addHistory($order['externalId'], $data['order_status_id']);
}
}
/**
* Create orders from history
*
* @param array $orders
*
* @return array
*/
protected function createOrders($orders)
{
$customersIdsFix = array();
@ -395,7 +473,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
foreach ($orders as $order) {
$store = $this->config->get('config_store_id');
if ($order['payments']) {
if (isset($order['payments']) && $order['payments']) {
$payment = end($order['payments']);
} elseif (isset($order['paymentType'])) {
$payment['type'] = $order['paymentType'];
@ -433,6 +511,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
'status' => 1,
'approved' => 1,
'safe' => 0,
'affiliate' => '',
'address' => array(
array(
'firstname' => isset($order['patronymic']) ? $order['firstName'] . ' ' . $order['patronymic'] : $order['firstName'],
@ -465,7 +544,12 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['telephone'] = $phone;
}
$data['currency_code'] = $this->config->get('config_currency');
$data['currency_value'] = $this->getCurrencyByCode($data['currency_code'], 'value');
$data['currency_id'] = $this->getCurrencyByCode($data['currency_code'], 'currency_id');
$data['language_id'] = $this->getLanguageByCode($this->config->get('config_language'), 'language_id');
$data['store_id'] = $store == null ? 0 : $store;
$data['store_name'] = $this->config->get('config_name');
$data['customer'] = $order['firstName'];
$data['customer_id'] = $customer_id;
$data['customer_group_id'] = 1;
@ -518,9 +602,13 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$delivery = isset($order['delivery']['code']) ? $order['delivery']['code'] : null;
$data['payment_country_id'] = $paymentCountry ? $paymentCountry['country_id'] : 0;
$data['payment_country'] = isset($paymentCountry) ? $paymentCountry['name'] : '';
$data['payment_zone_id'] = $payment_zone_id;
$data['payment_zone'] = isset($order['customer']['address']['region']) ? $order['customer']['address']['region'] : '';
$data['shipping_country_id'] = $shippingCountry ? $shippingCountry['country_id'] : 0;
$data['shipping_country'] = $shippingCountry ? $shippingCountry['name'] : '';
$data['shipping_zone_id'] = $shipping_zone_id;
$data['shipping_zone'] = $shippingZone ? $shippingZone['name'] : $data['payment_zone'];
$data['shipping_address'] = '0';
$data['shipping_firstname'] = $order['firstName'];
$data['shipping_lastname'] = (isset($order['lastName'])) ? $order['lastName'] : $order['firstName'];
@ -531,9 +619,17 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['shipping_city'] = $order['delivery']['address']['city'];
$data['shipping_postcode'] = $order['delivery']['address']['index'];
$data['shipping'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$data['shipping_method'] = $this->ocDelivery[$data['shipping']];
$data['shipping_code'] = $delivery != null ? $this->delivery[$delivery] : $this->delivery_default;
$shipping = explode('.', $data['shipping']);
$shippingModule = $shipping[0];
if (isset($this->ocDelivery[$shippingModule][$data['shipping']]['title'])) {
$data['shipping_method'] = $this->ocDelivery[$shippingModule][$data['shipping']]['title'];
} else {
$data['shipping_method'] = $this->ocDelivery[$shippingModule]['title'];
}
if (isset($payment)) {
$data['payment'] = $this->payment[$payment['type']];
$data['payment_method'] = $this->ocPayment[$data['payment']];
@ -551,7 +647,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['product_id'] = '';
$data['reward'] = '';
$data['affiliate'] = '';
$data['affiliate_id'] = '';
$data['affiliate_id'] = 0;
$data['payment_tax_id'] = '';
$data['order_product_id'] = '';
$data['payment_company'] = '';
@ -564,6 +660,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
foreach ($order['items'] as $item) {
$productId = $item['offer']['externalId'];
$options = array();
if(mb_strpos($item['offer']['externalId'], '#') > 1) {
$offer = explode('#', $item['offer']['externalId']);
$productId = $offer[0];
@ -580,14 +677,27 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
if($productOptionId == $productOption['product_option_id']) {
foreach($productOption['product_option_value'] as $productOptionValue) {
if($productOptionValue['option_value_id'] == $optionValueId) {
$options[$productOptionId] = $productOptionValue['product_option_value_id'];
$options[] = array(
'product_option_id' => $productOptionId,
'product_option_value_id' => $productOptionValue['product_option_value_id'],
'value' => $this->getOptionValue($productOptionValue['option_value_id'], 'name'),
'type' => $productOption['type'],
'name' => $productOption['name'],
);
}
}
}
}
}
}
$product = $this->model_catalog_product->getProduct($productId);
$data['order_product'][] = array(
'name' => $product['name'],
'model' => $product['model'],
'price' => $item['initialPrice'],
'total' => (float)($item['initialPrice'] * $item['quantity']),
'product_id' => $productId,
'quantity' => $item['quantity'],
'option' => $options
@ -607,6 +717,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$deliveryCost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : 0;
$data['total'] = $order['totalSumm'];
$data['order_total'] = array(
array(
'order_total_id' => '',
@ -619,7 +730,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
array(
'order_total_id' => '',
'code' => 'shipping',
'title' => $this->ocDelivery[$data['shipping_code']],
'title' => $data['shipping_method'],
'value' => $deliveryCost,
'text' => $deliveryCost,
'sort_order' => $this->shippingSettings[$this->totalTitle . 'shipping_sort_order']
@ -637,7 +748,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$data['fromApi'] = true;
$data['order_status_id'] = 1;
$order_id = $this->opencartApiClient->addOrder($data);
$order_id = $this->addOrder($data);
$ordersIdsFix[] = array('id' => $order['id'], 'externalId' => (int) $order_id);
}
@ -648,7 +759,6 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
protected function updateCustomers($customers)
{
foreach ($customers as $customer) {
$customer_id = $customer['externalId'];
$customerData = $this->model_customer_customer->getCustomer($customer_id);
@ -677,7 +787,7 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$customerAddress['country_id'] = $customerCountry['country_id'];
}
if (isset($customerZone)) {
if (isset($customerZone) && isset($customerZone['zone_id'])) {
$customerAddress['zone_id'] = $customerZone['zone_id'];
}
@ -697,40 +807,4 @@ class ModelExtensionRetailcrmHistoryV45 extends Model
$this->model_customer_customer->editCustomer($customer_id, $customerData);
}
}
private function getModuleTitle()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = 'retailcrm';
} else {
$title = 'module_retailcrm';
}
return $title;
}
private function totalTitles()
{
if (version_compare(VERSION, '3.0', '<')) {
$title = '';
} else {
$title = 'total_';
}
return $title;
}
public function getCountryByIsoCode($isoCode)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "country` WHERE iso_code_2 = '" . $isoCode . "'");
return $query->row;
}
public function getZoneByName($name)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE name = '" . $name . "'");
return $query->row;
}
}

View File

@ -13,6 +13,17 @@ class ModelExtensionRetailcrmIcml extends Model
private $options;
private $optionValues;
/**
* Constructor
*
* @param Registry $registry
*/
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
}
public function generateICML()
{
$this->load->language('extension/module/retailcrm');
@ -100,78 +111,16 @@ class ModelExtensionRetailcrmIcml extends Model
$products = $this->model_catalog_product->getProducts(array());
foreach ($products as $product) {
// Формируем офферы отнсительно доступных опций
$options = $this->model_catalog_product->getProductOptions($product['product_id']);
$offerOptions = array('select', 'radio');
$requiredOptions = array();
$notRequiredOptions = array();
// Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет
foreach($options as $option) {
if(in_array($option['type'], $offerOptions)) {
if($option['required']) {
$requiredOptions[] = $option;
} else {
$notRequiredOptions[] = $option;
}
}
}
$offers = array();
// Сначала совмещаем все обязательные опции
foreach($requiredOptions as $requiredOption) {
// Если первая итерация
if(empty($offers)) {
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
}
// Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть.
foreach($notRequiredOptions as $notRequiredOption) {
// Если обязательных опцией не оказалось и первая итерация
if(empty($offers)) {
$offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
}
if(empty($offers)) {
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
}
$offers = $this->retailcrm->getOffers($product);
foreach ($offers as $optionsString => $optionsValues) {
$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(
@ -181,19 +130,23 @@ class ModelExtensionRetailcrmIcml extends Model
);
}
}
ksort($options);
$offerId = array();
foreach($options as $optionKey => $optionData) {
$offerId[] = $optionKey.'-'.$optionData['value_id'];
}
$offerId = implode('_', $offerId);
$e = $this->eOffers->appendChild($this->dd->createElement('offer'));
if (!empty($offerId)) {
$e->setAttribute('id', $product['product_id'] . '#' . $offerId);
$e->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $optionsValues['qty']);
}
else {
} else {
$e->setAttribute('id', $product['product_id']);
$e->setAttribute('productId', $product['product_id']);
$e->setAttribute('quantity', $product['quantity']);
@ -324,13 +277,6 @@ class ModelExtensionRetailcrmIcml extends Model
$width,
$height
);
return $this->model_tool_image->resize(
$image,
$this->config->get('config_image_product_width'),
$this->config->get('config_image_product_height')
);
}
private function getOptionData($optionId, $optionValueId) {
@ -340,12 +286,14 @@ class ModelExtensionRetailcrmIcml extends Model
$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']

View File

@ -106,10 +106,15 @@ class ModelExtensionRetailcrmOrder extends Model {
$payment_code = '';
}
if (!empty($order_data['shipping_code']) && isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
if (!empty($order_data['shipping_code'])) {
$shippingCode = explode('.', $order_data['shipping_code']);
$shippingModule = $shippingCode[0];
if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} else {
$delivery_code = '';
} elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule];
}
}
$order['number'] = $order_data['order_id'];

View File

@ -0,0 +1,201 @@
<?php
class ModelExtensionRetailcrmPrices extends Model
{
protected $retailcrmApiClient;
protected $settings;
protected $moduleTitle;
private $options;
private $optionValues;
/**
* Constructor
*
* @param Registry $registry
*/
public function __construct($registry)
{
parent::__construct($registry);
$this->load->library('retailcrm/retailcrm');
$this->load->model('catalog/option');
$this->load->model('setting/setting');
$this->moduleTitle = $this->retailcrm->getModuleTitle();
$this->settings = $this->model_setting_setting->getSetting($this->moduleTitle);
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Upload prices to CRM
*
* @param array $products
*
* @return void
*/
public function uploadPrices($products)
{
$prices = $this->getPrices($products);
$pricesUpload = array_chunk($prices, 250);
foreach ($pricesUpload as $priceUpload) {
$this->retailcrmApiClient->storePricesUpload($priceUpload);
}
}
/**
* Get prices
*
* @param array $products
*
* @return array $prices
*/
protected function getPrices($products)
{
$prices = array();
$site = $this->getSite();
if (!isset($this->settings[$this->moduleTitle . '_special'])
|| $this->settings[$this->moduleTitle . '_apiversion'] == 'v3'
) {
return;
}
foreach ($products as $product) {
$specials = $this->model_catalog_product->getProductSpecials($product['product_id']);
if (!$specials) {
continue;
}
if (is_array($specials) && count($specials)) {
$productPrice = $this->getSpecialPrice($specials);
if (!$productPrice) {
continue;
}
}
$offers = $this->retailcrm->getOffers($product);
foreach ($offers as $optionsString => $optionsValues) {
$optionsString = explode('_', $optionsString);
$options = array();
foreach($optionsString as $optionString) {
$option = explode('-', $optionString);
$optionIds = explode(':', $option[0]);
if ($optionString != '0:0-0') {
$optionData = $this->getOptionData($optionIds[1], $option[1]);
$options[$optionIds[0]] = array(
'name' => $optionData['optionName'],
'value' => $optionData['optionValue'],
'value_id' => $option[1]
);
}
}
ksort($options);
$offerId = array();
foreach($options as $optionKey => $optionData) {
$offerId[] = $optionKey.'-'.$optionData['value_id'];
}
$offerId = implode('_', $offerId);
$prices[] = array(
'externalId' => $offerId ? $product['product_id'] . '#' . $offerId : $product['product_id'],
'site' => $site,
'prices' => array(
array(
'code' => $this->settings[$this->moduleTitle . '_special'],
'price' => $productPrice + $optionsValues['price']
)
)
);
}
}
return $prices;
}
/**
* Get actual special
*
* @param array $specials
*
* @return float $productPrice
*/
private function getSpecialPrice($specials)
{
$date = date('Y-m-d');
$always = '0000-00-00';
$productPrice = 0;
foreach ($specials as $special) {
if (($special['date_start'] == $always && $special['date_end'] == $always)
|| ($special['date_start'] <= $date && $special['date_end'] >= $date)
) {
if ((isset($priority) && $priority > $special['priority'])
|| !isset($priority)
) {
$productPrice = $special['price'];
$priority = $special['priority'];
}
}
}
return $productPrice;
}
/**
* Get data option
*
* @param int $optionId
* @param int $optionValueId
*
* @return array
*/
private function getOptionData($optionId, $optionValueId) {
if (!empty($this->options[$optionId])) {
$option = $this->options[$optionId];
} else {
$option = $this->model_catalog_option->getOption($optionId);
$this->options[$optionId] = $option;
}
if (!empty($this->optionValues[$optionValueId])) {
$optionValue = $this->optionValues[$optionValueId];
} else {
$optionValue = $this->model_catalog_option->getOptionValue($optionValueId);
$this->optionValues[$optionValueId] = $optionValue;
}
return array(
'optionName' => $option['name'],
'optionValue' => $optionValue['name']
);
}
/**
* Get site
*
* @return mixed boolean | string
*/
private function getSite()
{
$response = $this->retailcrmApiClient->sitesList();
if ($response && $response->isSuccessful()) {
$sites = $response->sites;
$site = end($sites);
return $site['code'];
}
return false;
}
}

View File

@ -1,9 +1,11 @@
<?php
class ModelExtensionRetailcrmReferences extends Model {
class ModelExtensionRetailcrmReferences extends Model
{
protected $settings;
protected $moduleTitle;
protected $retailcrmApiClient;
private $opencartApiClient;
public function __construct($registry)
@ -17,14 +19,23 @@ class ModelExtensionRetailcrmReferences extends Model {
$this->retailcrmApiClient = $this->retailcrm->getApiClient();
}
/**
* Get opencart delivery methods
*
* @return array
*/
public function getOpercartDeliveryTypes()
{
$this->opencartApiClient = $this->retailcrm->getOcApiClient($this->registry);
return $this->opencartApiClient->request('retailcrm/getDeliveryTypes', array(), array());
return $this->opencartApiClient->getDeliveryTypes();
}
/**
* Get all delivery types
*
* @return array
*/
public function getDeliveryTypes()
{
$this->load->model('setting/store');
@ -35,6 +46,11 @@ class ModelExtensionRetailcrmReferences extends Model {
);
}
/**
* Get all statuses
*
* @return array
*/
public function getOrderStatuses()
{
return array(
@ -43,6 +59,11 @@ class ModelExtensionRetailcrmReferences extends Model {
);
}
/**
* Get all payment types
*
* @return array
*/
public function getPaymentTypes()
{
return array(
@ -51,6 +72,11 @@ class ModelExtensionRetailcrmReferences extends Model {
);
}
/**
* Get all custom fields
*
* @return array
*/
public function getCustomFields()
{
return array(
@ -59,6 +85,11 @@ class ModelExtensionRetailcrmReferences extends Model {
);
}
/**
* Get opencart order statuses
*
* @return array
*/
public function getOpercartOrderStatuses()
{
$this->load->model('localisation/order_status');
@ -67,6 +98,11 @@ class ModelExtensionRetailcrmReferences extends Model {
->getOrderStatuses(array());
}
/**
* Get opencart payment types
*
* @return array
*/
public function getOpercartPaymentTypes()
{
$paymentTypes = array();
@ -95,6 +131,11 @@ class ModelExtensionRetailcrmReferences extends Model {
return $paymentTypes;
}
/**
* Get opencart custom fields
*
* @return array
*/
public function getOpencartCustomFields()
{
$this->load->model('customer/custom_field');
@ -102,6 +143,11 @@ class ModelExtensionRetailcrmReferences extends Model {
return $this->model_customer_custom_field->getCustomFields();
}
/**
* Get RetailCRM delivery types
*
* @return array
*/
public function getApiDeliveryTypes()
{
$response = $this->retailcrmApiClient->deliveryTypesList();
@ -109,6 +155,11 @@ class ModelExtensionRetailcrmReferences extends Model {
return (!$response->isSuccessful()) ? array() : $response->deliveryTypes;
}
/**
* Get RetailCRM order statuses
*
* @return array
*/
public function getApiOrderStatuses()
{
$response = $this->retailcrmApiClient->statusesList();
@ -116,6 +167,11 @@ class ModelExtensionRetailcrmReferences extends Model {
return (!$response->isSuccessful()) ? array() : $response->statuses;
}
/**
* Get RetailCRM payment types
*
* @return array
*/
public function getApiPaymentTypes()
{
$response = $this->retailcrmApiClient->paymentTypesList();
@ -123,6 +179,11 @@ class ModelExtensionRetailcrmReferences extends Model {
return (!$response->isSuccessful()) ? array() : $response->paymentTypes;
}
/**
* Get RetailCRM custom fields
*
* @return array
*/
public function getApiCustomFields()
{
$customers = $this->retailcrmApiClient->customFieldsList(array('entity' => 'customer'));
@ -137,4 +198,16 @@ class ModelExtensionRetailcrmReferences extends Model {
return array('customers' => $customFieldsCustomers, 'orders' => $customFieldsOrders);
}
/**
* Get RetailCRM price types
*
* @return array
*/
public function getPriceTypes()
{
$response = $this->retailcrmApiClient->priceTypesList();
return (!$response->isSuccessful()) ? array() : $response->priceTypes;
}
}

View File

@ -2,3 +2,4 @@
.retailcrm_unit input {width: 30%;}
.checkbox input{width: auto;}
.retailcrm_unit input[type=checkbox] {width: 13px;}
.retailcrm_unit select {max-width: 500px;}

View File

@ -98,6 +98,21 @@
<label><?php echo $text_button_export_order; ?> № </label><input type="text" name="order_id">
<button type="button" id="export_order" data-toggle="tooltip" title="<?php echo $text_button_export_order; ?>" class="btn btn-success"><i class="fa fa-download"></i></button>
</div>
<?php if (isset($saved_settings['retailcrm_apiversion']) && $saved_settings['retailcrm_apiversion'] != 'v3') : ?>
<h3><?php echo $special_price_settings; ?></h3>
<div class="retailcrm_unit">
<label><?php echo $special_price_settings; ?></label>
<select id="retailcrm_special" name="retailcrm_special">
<?php foreach ($priceTypes as $priceType) :?>
<?php if ($priceType['active'] == true) :?>
<option value="<?php echo $priceType['code']; ?>" <?php if(isset($saved_settings['retailcrm_special']) && $saved_settings['retailcrm_special'] == $priceType['code']):?>selected="selected"<?php endif;?>>
<?php echo $priceType['name']; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
</div>
<div class="tab-pane" id="tab-references">

View File

@ -97,6 +97,21 @@
<label>{{ text_button_export_order }} № </label><input type="text" name="order_id">
<button type="button" id="export_order" data-toggle="tooltip" title="{{ text_button_export_order }}" class="btn btn-success"><i class="fa fa-download"></i></button>
</div>
{% if saved_settings.retailcrm_apiversion is defined and saved_settings.retailcrm_apiversion != 'v3' %}
<h3>{{ special_price_settings }}</h3>
<div class="retailcrm_unit">
<label>{{ special_price_settings }}</label>
<select id="module_retailcrm_special" name="module_retailcrm_special">
{% for priceType in priceTypes %}
{% if priceType.active == true %}
<option value="{{priceType.code }}" {% if saved_settings.retailcrm_special is defined and saved_settings.retailcrm_special == priceType.code %} selected="selected" {% endif %}>
{{ priceType.name }}
</option>
{% endif %}
{% endfor %}
</select>
</div>
{% endif %}
</div>
<div class="tab-pane" id="tab-references">

View File

@ -1,17 +1,24 @@
<?php
class ControllerApiRetailcrm extends Controller
{
public function getDeliveryTypes()
{
$api = $this->auth();
if (isset($api['error'])) {
$response = $api;
} else {
$this->load->model('localisation/country');
$this->load->model('setting/setting');
$this->load->library('retailcrm/retailcrm');
$moduleTitle = $this->retailcrm->getModuleTitle();
$countries = $this->model_setting_setting->getSetting($moduleTitle)[$moduleTitle . '_country'];
$deliveryTypes = array();
$response = array();
foreach ($countries as $country) {
$deliveryTypes = array_merge($deliveryTypes, $this->getDeliveryTypesByZones($country));
$response = array_merge($response, $this->getDeliveryTypesByZones($country));
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
@ -22,7 +29,32 @@ class ControllerApiRetailcrm extends Controller
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($deliveryTypes));
$this->response->setOutput(json_encode($response));
}
public function addOrderHistory()
{
$api = $this->auth();
if (isset($api['error'])) {
$response = $api;
} elseif (!isset($this->request->post['order_id']) || !isset($this->request->post['order_status_id'])) {
$response = array('error' => 'Not found data');
} else {
$this->load->model('checkout/order');
$this->model_checkout_order->addOrderHistory($this->request->post['order_id'], $this->request->post['order_status_id']);
$response = array('success' => true);
}
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($response));
}
protected function getDeliveryTypesByZones($country_id)
@ -49,6 +81,7 @@ class ControllerApiRetailcrm extends Controller
foreach ($shippingModules as $shippingModule) {
$this->load->model('extension/shipping/' . $shippingModule['code']);
if (version_compare(VERSION, '3.0', '<')) {
$shippingCode = $shippingModule['code'];
} else {
@ -66,6 +99,19 @@ class ControllerApiRetailcrm extends Controller
if ($this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address)) {
$quote_data[] = $this->{'model_extension_shipping_' . $shippingModule['code']}->getQuote($address);
} else {
$this->load->language('extension/shipping/' . $shippingModule['code']);
$quote_data[] = array(
'code' => $shippingModule['code'],
'title' => $this->language->get('text_title'),
'quote' => array(
array(
'code' => $shippingModule['code'],
'title' => $this->language->get('text_title')
)
)
);
}
}
}
@ -74,17 +120,47 @@ class ControllerApiRetailcrm extends Controller
$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;
}
private function auth()
{
if (!isset($this->request->get['key'])
|| !$this->request->get['key']
) {
return array('error' => 'Not found api key');
}
if (isset($this->request->get['key'])
&& !empty($this->request->get['key'])
) {
$this->load->model('account/api');
if ( version_compare(VERSION, '3.0', '<')) {
$api = $this->model_account_api->getApiByKey($this->request->get['key']);
} else {
$api = $this->model_account_api->login($this->request->get['username'], $this->request->get['key']);
if (empty($api)) {
$this->load->model('extension/retailcrm/api');
$api = $this->model_extension_retailcrm_api->login($this->request->get['username'], $this->request->get['key']);
}
}
if (!empty($api)) {
return $api;
}
return array('error' => 'Invalid api key');
}
}
private function loadModels()
{
if (version_compare(VERSION, '3.0', '<')) {

View File

@ -0,0 +1,11 @@
<?php
class ModelExtensionRetailcrmApi extends Model
{
public function login($username, $key)
{
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "api` WHERE `username` = '" . $this->db->escape($username) . "' AND `key` = '" . $this->db->escape($key) . "' AND status = '1'");
return $query->row;
}
}

View File

@ -135,10 +135,15 @@ class ModelExtensionRetailcrmOrder extends Model {
$payment_code = '';
}
if (!empty($order_data['shipping_code']) && isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
if (!empty($order_data['shipping_code'])) {
$shippingCode = explode('.', $order_data['shipping_code']);
$shippingModule = $shippingCode[0];
if (isset($this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$order_data['shipping_code']];
} else {
$delivery_code = '';
} elseif (isset($this->settings[$this->moduleTitle . '_delivery'][$shippingModule])) {
$delivery_code = $this->settings[$this->moduleTitle . '_delivery'][$shippingModule];
}
}
$order['number'] = $order_data['order_id'];
@ -169,9 +174,13 @@ class ModelExtensionRetailcrmOrder extends Model {
if ($this->settings[$this->moduleTitle . '_apiversion'] != 'v5') {
$order['paymentType'] = $payment_code;
if (isset($couponTotal)) $order['discount'] = $couponTotal;
if (isset($couponTotal)) {
$order['discount'] = $couponTotal;
}
} else {
if (isset($couponTotal)) $order['discountManualAmount'] = $couponTotal;
if (isset($couponTotal)) {
$order['discountManualAmount'] = $couponTotal;
}
}
$country = (isset($order_data['shipping_country'])) ? $order_data['shipping_country'] : '' ;

View File

@ -11,12 +11,14 @@ if (!isset($cli_action)) {
}
// Version
$version = '1.5.6';
$version = '2.3.0';
$indexFile = file_get_contents(realpath(dirname(__FILE__)) . '/../../index.php');
preg_match("/define\([\s]*['\"]VERSION['\"][\s]*,[\s]*['\"](.*)['\"][\s]*\)[\s]*;/mi", $indexFile, $versionMatches);
if (isset($versionMatches[1])) {
$version = $versionMatches[1];
}
define('VERSION', $version);
// Configuration (note we're using the admin config)
@ -118,6 +120,7 @@ function error_handler($errno, $errstr, $errfile, $errline) {
return true;
}
set_error_handler('error_handler');
$request = new Request();
$registry->set('request', $request);
@ -145,7 +148,13 @@ foreach ($query->rows as $result) {
$adminLanguageCode = $config->get('config_admin_language');
$config->set('config_language_id', $languages[$adminLanguageCode]['language_id']);
if (version_compare(VERSION, '2.3', '<')) {
$language = new Language($languages[$adminLanguageCode]['directory']);
} else {
$language = new Language($adminLanguageCode);
}
if(isset($languages[$adminLanguageCode]['filename'])) {
$language->load($languages[$adminLanguageCode]['filename']);
} else {

View File

@ -1,2 +0,0 @@
<?php
echo $_SERVER['REMOTE_ADDR'];

4
system/cron/prices.php Normal file
View File

@ -0,0 +1,4 @@
<?php
$cli_action = 'extension/module/retailcrm/prices';
require_once('dispatch.php');

View File

@ -31,29 +31,39 @@ class OpencartApiClient {
$cookies = array();
foreach($cookieFile as $line) {
if(empty($line) OR $line{0} == '#')
if(empty($line) OR $line{0} == '#') {
continue;
}
$params = explode("\t", $line);
$cookies[$params[5]] = $params[6];
}
if(isset($cookies[$cookieName]))
if (isset($cookies[$cookieName])) {
return $cookies[$cookieName];
}
return false;
}
public function request($method, $getParams, $postParams) {
private function request($method, $getParams, $postParams) {
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
if(!empty($this->apiToken)) {
if ($this->apiToken !== false) {
if (version_compare(VERSION, '3.0', '<')) {
$getParams['token'] = $this->apiToken;
$getParams['key'] = $this->apiToken['key'];
} else {
$getParams['api_token'] = $this->apiToken;
}
$getParams['key'] = $this->apiToken['key'];
$getParams['username'] = $this->apiToken['username'];
if (isset($this->session->data['user_token'])) {
$getParams['api_token'] = $this->session->data['user_token'];
} else {
$session = $this->registry->get('session');
$session->start();
$getParams['api_token'] = $session->getId();
}
}
}
$postParams['fromApi'] = true;
@ -112,6 +122,7 @@ class OpencartApiClient {
$apiUsers = $this->model_user_api->getApis();
$api = array();
foreach ($apiUsers as $apiUser) {
if($apiUser['status'] == 1) {
$api = $apiUser;
@ -119,257 +130,38 @@ class OpencartApiClient {
}
}
if(!isset($api['api_id']))
if (!isset($api['api_id'])) {
return 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);
}
if (version_compare(VERSION, '3.0', '<')){
$apiAnswer = $this->request('login', array(), $api);
$this->apiToken = $apiAnswer['token'];
if (isset($api) && !empty($api)) {
$this->apiToken = $api;
} else {
$this->apiToken = $this->apiLogin();
$this->apiToken = false;
}
if (isset($apiAnswer))
return $apiAnswer;
}
public function editOrder($order_id, $data) {
$data['telephone'] = trim($data['telephone']);
$customer = array(
'currency' => isset($data['currency']) ? $data['currency'] : '',
'customer' => $data['customer'],
'customer_id' => $data['customer_id'],
'customer_group_id' => $data['customer_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'telephone' => !empty($data['telephone']) ? $data['telephone'] : '0000',
'fax' => $data['fax']
);
if (isset($data['custom_field'])) {
$customer['custom_field'] = $data['custom_field'];
}
$this->request('customer', array(), $customer);
$products = array();
foreach ($data['order_product'] as $order_product) {
$products[] = array(
'product_id' => $order_product['product_id'],
'quantity' => $order_product['quantity'],
'option' => $order_product['option']
);
}
$this->request('cart/add', array(), array('product' => $products));
$payment_address = array(
'payment_address' => $data['payment_address'],
'firstname' => $data['payment_firstname'],
'lastname' => $data['payment_lastname'],
'company' => $data['payment_company'],
'address_1'=> $data['payment_address_1'],
'address_2' => $data['payment_address_2'],
'city' => !empty($data['payment_city']) ? $data['payment_city'] : 'none',
'postcode' => $data['payment_postcode'],
'country_id' => $data['payment_country_id'],
'zone_id' => !empty($data['payment_zone_id']) ? $data['payment_zone_id'] : 0,
);
$this->request('payment/address', array(), $payment_address);
$this->request('payment/methods', array(), array());
$payment_method = array(
'payment_method' => $data['payment_code']
);
$this->request('payment/method', array(), $payment_method);
$shipping_address = array(
'shipping_address' => $data['shipping_address'],
'firstname' => $data['shipping_firstname'],
'lastname' => $data['shipping_lastname'],
'company' => $data['shipping_company'],
'address_1' => $data['shipping_address_1'],
'address_2' => $data['shipping_address_2'],
'city' => !empty($data['shipping_city']) ? $data['shipping_city'] : 'none',
'postcode' => $data['shipping_postcode'],
'country_id' => $data['shipping_country_id'],
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
);
$this->request('shipping/address', array(), $shipping_address);
$this->request('shipping/methods', array(), array());
$shipping_method = array(
'shipping_method' => $data['shipping_code']
);
$this->request('shipping/method', array(), $shipping_method);
$order = array(
'shipping_method' => $data['shipping_code'],
'payment_method' => $data['payment_code'],
'order_status_id' => $data['order_status_id'],
'comment' => $data['comment'],
'affiliate_id' => $data['affiliate_id'],
);
$this->request('order/edit', array('order_id' => $order_id), $order);
}
public function addOrder($data) {
$currency = $this->getCookieValue('currency');
if($currency) {
$a = $this->request('currency', array(), array('currency' => $currency));
}
$customer = array(
'store_id' => $data['store_id'],
'currency' => $currency != false ? $currency : '',
'customer' => $data['customer'],
'customer_id' => $data['customer_id'],
'customer_group_id' => $data['customer_group_id'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'fax' => $data['fax'],
);
$this->request('customer', array(), $customer);
$products = array();
foreach ($data['order_product'] as $order_product) {
$products[] = array(
'product_id' => $order_product['product_id'],
'quantity' => $order_product['quantity'],
'option' => $order_product['option']
);
}
$this->request('cart/add', array(), array('product' => $products));
$payment_address = array(
'payment_address' => $data['payment_address'],
'firstname' => $data['payment_firstname'],
'lastname' => $data['payment_lastname'],
'company' => $data['payment_company'],
'address_1' => $data['payment_address_1'],
'address_2' => $data['payment_address_2'],
'city' => $data['payment_city'],
'postcode' => $data['payment_postcode'],
'country_id' => $data['payment_country_id'],
'zone_id' => $data['payment_zone_id'],
);
$this->request('payment/address', array(), $payment_address);
$shipping_address = array(
'shipping_address' => $data['shipping_address'],
'firstname' => $data['shipping_firstname'],
'lastname' => $data['shipping_lastname'],
'company' => $data['shipping_company'],
'address_1' => $data['shipping_address_1'],
'address_2' => $data['shipping_address_2'],
'city' => $data['shipping_city'],
'postcode' => $data['shipping_postcode'],
'country_id' => $data['shipping_country_id'],
'zone_id' => !empty($data['shipping_zone_id']) ? $data['shipping_zone_id'] : 0,
);
$this->request('shipping/address', array(), $shipping_address);
$this->request('shipping/methods', array(), array());
$shipping_method = array(
'shipping_method' => $data['shipping_code']
);
$this->request('shipping/method', array(), $shipping_method);
$this->request('payment/methods', array(), array());
$payment_method = array(
'payment_method' => $data['payment_code']
);
$this->request('payment/method', array(), $payment_method);
$order = array(
'shipping_method' => $data['shipping_code'],
'payment_method' => $data['payment_code'],
'order_status_id' => $data['order_status_id'],
'comment' => $data['comment'],
'affiliate_id' => $data['affiliate_id'],
);
$response = $this->request('order/add', array(), $order);
if (isset($response['order_id'])) {
return $response['order_id'];
}
}
private function getInnerIpAddr() {
$opencartStoreInfo = $this->model_setting_store->getStore($this->opencartStoreId);
if ($opencartStoreInfo) {
$url = $opencartStoreInfo['ssl'];
} else {
$url = HTTPS_CATALOG;
}
$curl = curl_init();
// Set SSL if required
if (substr($url, 0, 5) == 'https') {
curl_setopt($curl, CURLOPT_PORT, 443);
}
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url . 'system/cron/getmyip.php');
return curl_exec($curl);
}
/**
* Login api user for opencart version > 3.0
* Get delivery types
*
* @return string
* @return array
*/
private function apiLogin() {
$this->load->model('user/api');
$api_info = $this->model_user_api->getApi($this->config->get('config_api_id'));
if ($this->session->data) {
$this->session->data['api_id'] = $api_info['api_id'];
$api_token = $this->session->getId();
} else {
$session = new Session($this->config->get('session_engine'), $this->registry);
$session_id = $this->getCookieValue('OCSESSID');
if ($session_id) {
$session->start($session_id);
} else {
$session->start();
public function getDeliveryTypes()
{
return $this->request('retailcrm/getDeliveryTypes', array(), array());
}
$this->model_user_api->deleteApiSessionBySessonId($session->getId());
$this->model_user_api->addApiSession($api_info['api_id'], $session->getId(), $this->getInnerIpAddr());
$session->data['api_id'] = $api_info['api_id'];
$api_token = $session->getId();
$this->registry->set('session', $session);
}
return $api_token;
/**
* Add history order
*
* @param int $order_id
* @param int $order_status_id
*
* @return void
*/
public function addHistory($order_id, $order_status_id)
{
$this->request('retailcrm/addOrderHistory', array(), array('order_id' => $order_id, 'order_status_id' => $order_status_id));
}
/**

View File

@ -862,6 +862,26 @@ class RetailcrmApiClient4
);
}
/**
* Upload prices
*
* @param array $prices (default: array())
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function storePricesUpload(array $prices = array())
{
return $this->client->makeRequest(
'/store/prices/upload',
RetailcrmHttpClient::METHOD_POST,
array('prices' => json_encode($prices))
);
}
/**
* Get delivery settings
*
@ -1412,6 +1432,23 @@ class RetailcrmApiClient4
);
}
/**
* Returns price types list
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function priceTypesList()
{
return $this->client->makeRequest(
'/reference/price-types',
RetailcrmHttpClient::METHOD_GET
);
}
/**
* Get telephony settings
*

View File

@ -1504,6 +1504,26 @@ class RetailcrmApiClient5
);
}
/**
* Upload prices
*
* @param array $prices (default: array())
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function storePricesUpload(array $prices = array())
{
return $this->client->makeRequest(
'/store/prices/upload',
RetailcrmHttpClient::METHOD_POST,
array('prices' => json_encode($prices))
);
}
/**
* Get delivery settings
*
@ -2054,6 +2074,23 @@ class RetailcrmApiClient5
);
}
/**
* Returns price types list
*
* @throws \InvalidArgumentException
* @throws \RetailCrm\Exception\CurlException
* @throws \RetailCrm\Exception\InvalidJsonException
*
* @return ApiResponse
*/
public function priceTypesList()
{
return $this->client->makeRequest(
'/reference/price-types',
RetailcrmHttpClient::METHOD_GET
);
}
/**
* Get telephony settings
*

View File

@ -55,7 +55,10 @@ class RetailcrmHistoryHelper {
$orders[$change['order']['id']]['items'][$change['item']['id']]['delete'] = true;
}
if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create']) && $fields['item'][$change['field']]) {
if (!isset($orders[$change['order']['id']]['items'][$change['item']['id']]['create'])
&& isset($fields['item'][$change['field']])
&& $fields['item'][$change['field']]
) {
$orders[$change['order']['id']]['items'][$change['item']['id']][$fields['item'][$change['field']]] = $change['newValue'];
}
} else {

View File

@ -89,4 +89,78 @@ class Retailcrm {
return $token;
}
public function getOffers($product)
{
// Формируем офферы отнсительно доступных опций
$options = $this->model_catalog_product->getProductOptions($product['product_id']);
$offerOptions = array('select', 'radio');
$requiredOptions = array();
$notRequiredOptions = array();
// Оставляем опции связанные с вариациями товаров, сортируем по параметру обязательный или нет
foreach($options as $option) {
if(in_array($option['type'], $offerOptions)) {
if($option['required']) {
$requiredOptions[] = $option;
} else {
$notRequiredOptions[] = $option;
}
}
}
$offers = array();
// Сначала совмещаем все обязательные опции
foreach($requiredOptions as $requiredOption) {
// Если первая итерация
if(empty($offers)) {
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
unset($offers[$optionKey]); // Работая в контексте обязательных опций не забываем удалять прошлые обязательные опции, т.к. они должны быть скомбинированы с другими обязательными опциями
foreach($requiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$requiredOption['product_option_id'].':'.$requiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
}
// Совмещаем или добавляем необязательные опции, учитывая тот факт что обязательных опций может и не быть.
foreach($notRequiredOptions as $notRequiredOption) {
// Если обязательных опцией не оказалось и первая итерация
if(empty($offers)) {
$offers['0:0-0'] = 0; // В случае работы с необязательными опциями мы должны учитывать товарное предложение без опций, поэтому создадим "пустую" опцию
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => (float)$optionValue['price'],
'qty' => $optionValue['quantity']
);
}
} else {
foreach($offers as $optionKey => $optionAttr) {
foreach($notRequiredOption['product_option_value'] as $optionValue) {
$offers[$optionKey.'_'.$notRequiredOption['product_option_id'].':'.$notRequiredOption['option_id'].'-'.$optionValue['option_value_id']] = array(
'price' => $optionAttr['price'] + (float)$optionValue['price'],
'qty' => ($optionAttr['qty'] > $optionValue['quantity']) ?
$optionValue['quantity'] : $optionAttr['qty']
);
}
}
}
}
if(empty($offers)) {
$offers = array('0:0-0' => array('price' => '0', 'qty' => '0'));
}
return $offers;
}
}