Multi module (#17)

* multi module for api v4, v5
* bug fix install module
This commit is contained in:
Akolzin Dmitry 2017-08-14 12:06:10 +02:00 committed by Alex Lushpai
parent ee33a5fb40
commit b9f557277c
14 changed files with 2806 additions and 205 deletions

View File

@ -2,7 +2,7 @@
<module>
<name>retailcrm</name>
<displayName><![CDATA[RetailCRM]]></displayName>
<version><![CDATA[2.0.1]]></version>
<version><![CDATA[1.6]]></version>
<description><![CDATA[Модуль интеграции с RetailCRM]]></description>
<author><![CDATA[Retail Driver LCC]]></author>
<tab><![CDATA[export]]></tab>
@ -10,4 +10,4 @@
<is_configurable>1</is_configurable>
<need_instance>1</need_instance>
<limited_countries></limited_countries>
</module>
</module>

View File

@ -7,9 +7,10 @@ require(dirname(__FILE__) . '/../bootstrap.php');
$apiUrl = Configuration::get('RETAILCRM_ADDRESS');
$apiKey = Configuration::get('RETAILCRM_API_TOKEN');
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
if (!empty($apiUrl) && !empty($apiKey)) {
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log');
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log', $apiVersion);
} else {
error_log('orderHistory: set api key & url first', 3, _PS_ROOT_DIR_ . '/retailcrm.log');
exit();
@ -32,7 +33,7 @@ foreach ($customerRecords as $record) {
$customers[$record['id_customer']] = array(
'externalId' => $record['id_customer'],
'firstName' => $record['firstname'],
'lastName' => $record['lastname'],
'lastname' => $record['lastname'],
'email' => $record['email']
);
}
@ -98,8 +99,17 @@ foreach ($orderRecords as $record) {
$order['phone'] = $phone;
}
if (array_key_exists($paymentType, $payment)) {
$order['paymentType'] = $payment[$paymentType];
if ($apiVersion != 5) {
if (array_key_exists($paymentType, $payment)) {
$order['paymentType'] = $payment[$paymentType];
}
} else {
$order_payment = array(
'externalId' => $record['id_order'] .'#'. $record['reference'],
'amount' => $record['total_paid'],
'type' => $payment[$paymentType] ? $payment[$paymentType] : ''
);
$order['payments'][] = $order_payment;
}
if (array_key_exists($record['id_carrier'], $delivery)) {

View File

@ -15,9 +15,10 @@ require(dirname(__FILE__) . '/../bootstrap.php');
$apiUrl = Configuration::get('RETAILCRM_ADDRESS');
$apiKey = Configuration::get('RETAILCRM_API_TOKEN');
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
if (!empty($apiUrl) && !empty($apiKey)) {
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log');
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log', $apiVersion);
} else {
echo('Set api key & url first');
exit();

View File

@ -11,16 +11,17 @@ $default_country = (int) Configuration::get('PS_COUNTRY_DEFAULT');
$apiUrl = Configuration::get('RETAILCRM_ADDRESS');
$apiKey = Configuration::get('RETAILCRM_API_TOKEN');
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
if (!empty($apiUrl) && !empty($apiKey)) {
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log');
$api = new RetailcrmProxy($apiUrl, $apiKey, _PS_ROOT_DIR_ . '/retailcrm.log', $apiVersion);
} else {
error_log('orderHistory: set api key & url first', 3, _PS_ROOT_DIR_ . '/retailcrm.log');
exit();
}
$lastSync = Configuration::get('RETAILCRM_LAST_SYNC');
$references = new RetailcrmReferences($api);
$startFrom = ($lastSync === false)
? date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))
: $lastSync
@ -55,7 +56,20 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$deliveryType = $deliveries[$delivery];
}
$payment = $order['paymentType'];
if ($apiVersion != 5) {
$payment = $order['paymentType'];
} else {
if (isset($order['payments']) && count($order['payments']) == 1) {
$paymentCRM = end($order['payments']);
$payment = $paymentCRM['type'];
} elseif (isset($order['payments']) && count($order['payments']) > 1) {
foreach ($order['payments'] as $paymentCRM) {
if ($payment['status'] != 'paid') {
$payment = $paymentCRM['type'];
}
}
}
}
if (array_key_exists($payment, $payments) && $payments[$payment] != '') {
if(Module::getInstanceByName($payments[$payment])) {
@ -169,7 +183,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$shops = Shop::getShops();
$newOrder->id_shop = Context::getContext()->shop->id;
$newOrder->id_shop_group = (int)$shops[Context::getContext()->shop->id]['id_shop_group'];
$newOrder->reference = $newOrder->generateReference();
$newOrder->id_address_delivery = (int) $address->id;
$newOrder->id_address_invoice = (int) $address->id;
$newOrder->id_cart = (int) $cart->id;
@ -204,24 +218,6 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$newOrder->total_discounts = $order['discount'];
}
$newOrder->add(false, false);
$carrier = new OrderCarrierCore();
$carrier->id_order = $newOrder->id;
$carrier->id_carrier = $deliveryType;
$carrier->shipping_cost_tax_excl = $order['delivery']['cost'];
$carrier->shipping_cost_tax_incl = $order['delivery']['cost'];
$carrier->date_add = $order['delivery']['date'];
$carrier->add(false, false);
/*
* collect order ids for single fix request
*/
array_push($orderFix, array('id' => $order['id'], 'externalId' => $newOrder->id));
/*
* Create order details
*/
$product_list = array();
foreach ($order['items'] as $item) {
@ -251,8 +247,55 @@ if ($history->isSuccessful() && count($history->history) > 0) {
'product_name' => $productName,
'quantity' => $item['quantity']
);
if (isset($item['discountTotal']) && $apiVersion == 5) {
$newOrder->total_discounts += $item['discountTotal'] * $item['quantity'];
}
}
$newOrder->add(false, false);
foreach ($order['payments'] as $pay) {
if (!isset($pay['externalId']) && $pay['status'] == 'paid') {
$ptype = $payment['type'];
$ptypes = $references->getSystemPaymentModules();
if ($payments[$ptype] != null) {
foreach ($ptypes as $pay) {
if ($pay['code'] == $payments[$ptype]) {
$payType = $pay['name'];
}
}
$paymentType = Module::getModuleName($payments[$ptype]);
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'order_payment`
(`payment_method`, `order_reference` , `amount`, `date_add`)
VALUES (
\'' . $payType . '\',
\'' . $orderToUpdate->reference . '\',
\'' . $payment['amount'] . '\',
\'' . $payment['paidAt'] . '\'
)'
);
}
}
}
$carrier = new OrderCarrierCore();
$carrier->id_order = $newOrder->id;
$carrier->id_carrier = $deliveryType;
$carrier->shipping_cost_tax_excl = $order['delivery']['cost'];
$carrier->shipping_cost_tax_incl = $order['delivery']['cost'];
$carrier->date_add = $order['delivery']['date'];
$carrier->add(false, false);
/*
* collect order ids for single fix request
*/
array_push($orderFix, array('id' => $order['id'], 'externalId' => $newOrder->id));
/*
* Create order details
*/
$query = 'INSERT `'._DB_PREFIX_.'order_detail`
(
`id_order`, `id_order_invoice`, `id_shop`, `product_id`, `product_attribute_id`,
@ -333,7 +376,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
/*
* check payment type
*/
if(!empty($order['paymentType'])) {
if(!empty($order['paymentType']) && $apiVersion != 5) {
$ptype = $order['paymentType'];
if ($payments[$ptype] != null) {
@ -352,6 +395,39 @@ if ($history->isSuccessful() && count($history->history) > 0) {
}
}
} elseif (!empty($order['payments']) && $apiVersion == 5) {
if ($order['payments']) {
foreach ($order['payments'] as $payment) {
if (!isset($payment['externalId']) && $payment['status'] == 'paid') {
$ptype = $payment['type'];
$ptypes = $references->getSystemPaymentModules();
if ($payments[$ptype] != null) {
foreach ($ptypes as $pay) {
if ($pay['code'] == $payments[$ptype]) {
$payType = $pay['name'];
}
}
$paymentType = Module::getModuleName($payments[$ptype]);
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'orders`
SET `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\'
WHERE `id_order` = ' . (int)$order['externalId']
);
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'order_payment`
(`payment_method`, `order_reference` , `amount`, `date_add`)
VALUES (
\'' . $payType . '\',
\'' . $orderToUpdate->reference . '\',
\'' . $payment['amount'] . '\',
\'' . $payment['paidAt'] . '\'
)'
);
}
}
}
}
}
/*
@ -397,7 +473,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
if ($product_id == $orderItem['product_id'] && $product_attribute_id == $orderItem['product_attribute_id']) {
// discount
if (isset($item['discount']) || isset($item['discountPercent'])) {
if (isset($item['discount']) || isset($item['discountPercent']) || isset($item['discountTotal'])) {
$product = new Product((int) $product_id, false, $default_lang);
$tax = new TaxCore($product->id_tax_rules_group);
@ -412,6 +488,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$productPrice = $prodPrice - $item['discount'];
$productPrice = $productPrice - ($prodPrice / 100 * $item['discountPercent']);
$productPrice = $prodPrice - $item['discountTotal'];
$productPrice = round($productPrice , 2);
@ -476,8 +553,9 @@ if ($history->isSuccessful() && count($history->history) > 0) {
}
// discount
if ($newItem['discount'] || $newItem['discountPercent']) {
if ($newItem['discount'] || $newItem['discountPercent']|| $newItem['discountTotal']) {
$productPrice = $productPrice - $newItem['discount'];
$productPrice = $productPrice - $newItem['discountTotal'];
$productPrice = $productPrice - ($prodPrice / 100 * $newItem['discountPercent']);
$ItemDiscount = true;
}
@ -513,6 +591,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
if (isset($order['discount']) ||
isset($order['discountPercent']) ||
isset($order['delivery']['cost']) ||
isset($order['discountTotal']) ||
$ItemDiscount) {
$infoOrd = $api->ordersGet($order['externalId']);

View File

@ -10,9 +10,8 @@
* @license https://opensource.org/licenses/MIT MIT License
* @link http://www.retailcrm.ru/docs/Developers/ApiVersion4
*/
class RetailcrmApiClient
class RetailcrmApiClientV4
{
const VERSION = 'v4';
protected $client;

File diff suppressed because it is too large Load Diff

View File

@ -26,7 +26,7 @@ class RetailcrmCatalog
$currencies = Currency::getCurrencies();
$types = Category::getCategories($id_lang, false, false);
$types = Category::getCategories($id_lang, true, false);
foreach ($types AS $category) {
$categories[] = array(
'id' => $category['id_category'],
@ -106,9 +106,9 @@ class RetailcrmCatalog
} else {
$size = null;
}
$productForCombination = new Product($product['id_product']);
$productForCombination = new Product($product['id_product']);
$offers = Product::getProductAttributesIds($product['id_product']);
if(!empty($offers)) {
@ -116,7 +116,7 @@ class RetailcrmCatalog
$combinations = $productForCombination->getAttributeCombinationsById($offer['id_product_attribute' ], $id_lang);
if (!empty($combinations)) {
foreach ($combinations as $combination) {
$arSet = array(
'group_name' => $combination['group_name'],
@ -126,11 +126,6 @@ class RetailcrmCatalog
}
}
if (!empty($combinations[0]['reference'])) {
$articleCombination = $combinations[0]['reference'];
} else {
$articleCombination = null;
}
$pictures = array();
$covers = Image::getImages($id_lang, $product['id_product'], $offer['id_product_attribute']);
foreach($covers as $cover) {
@ -145,8 +140,7 @@ class RetailcrmCatalog
}
$offerPrice = Combination::getPrice($offer['id_product_attribute']);
//$offerPrice = $offerPrice > 0 ? $offerPrice : $price;
$offerPrice = $offerPrice != 0 ? $offerPrice + $price : $price;
$offerPrice = $offerPrice > 0 ? $offerPrice : $price;
$item = array(
'id' => $product['id_product'] . '#' . $offer['id_product_attribute'],
@ -161,12 +155,9 @@ class RetailcrmCatalog
'purchasePrice' => $purchasePrice,
'price' => round($offerPrice, 2),
'vendor' => $vendor,
'article' => ($articleCombination) ? $articleCombination : $article,
'article' => $article,
'weight' => $weight,
'size' => $size,
'width' => $width,
'height' => $height,
'depth' => $depth
'size' => $size
);
if (!empty($combinations)) {
@ -174,7 +165,7 @@ class RetailcrmCatalog
$item[mb_strtolower($itemComb['group_name'])] = htmlspecialchars($itemComb['attribute']);
}
}
$items[] = $item;
}
} else {
@ -206,10 +197,7 @@ class RetailcrmCatalog
'vendor' => $vendor,
'article' => $article,
'weight' => $weight,
'size' => $size,
'width' => $width,
'height' => $height,
'depth' => $depth
'size' => $size
);
$items[] = $item;

View File

@ -33,7 +33,24 @@ class RetailcrmHistoryHelper {
} else {
$orders[$change['order']['id']] = $change['order'];
}
if($change['payment']) {
if($orders[$change['order']['id']]['payments'][$change['payment']['id']]) {
$orders[$change['order']['id']]['payments'][$change['payment']['id']] = array_merge($orders[$change['order']['id']]['payments'][$change['payment']['id']], $change['payment']);
} else {
$orders[$change['order']['id']]['payments'][$change['payment']['id']] = $change['payment'];
}
if($change['oldValue'] == null && $change['field'] == 'payments') {
$orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] = true;
}
if($change['newValue'] == null && $change['field'] == 'payments') {
$orders[$change['order']['id']]['payments'][$change['payment']['id']]['delete'] = true;
}
if(!$orders[$change['order']['id']]['payments'][$change['payment']['id']]['create'] && $fields['payment'][$change['field']]) {
$orders[$change['order']['id']]['payments'][$change['payment']['id']][$fields['payment'][$change['field']]] = $change['newValue'];
}
}
if($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']);
@ -65,6 +82,8 @@ class RetailcrmHistoryHelper {
$orders[$change['order']['id']]['customFields'][str_replace('custom_', '', $change['field'])] = self::newValue($change['newValue']);
} elseif($fields['order'][$change['field']]) {
$orders[$change['order']['id']][$fields['order'][$change['field']]] = self::newValue($change['newValue']);
} elseif($fields['payment'][$change['field']]) {
$orders[$change['order']['id']]['payments'][$change['payment']['id']][$fields['payment'][$change['field']]] = self::newValue($change['newValue']);
}
if(isset($change['created'])) {

View File

@ -33,10 +33,7 @@ class RetailcrmIcml
'color' => 'Цвет',
'weight' => 'Вес',
'size' => 'Размер',
'tax' => 'Наценка',
'width' => 'Ширина',
'height' => 'Высота',
'depth' => 'Глубина'
'tax' => 'Наценка'
);
}
@ -78,14 +75,14 @@ class RetailcrmIcml
foreach ($categories as $category) {
$e = $this->eCategories->appendChild(
$this->dd->createElement(
'category', htmlspecialchars($category['name'])
'category', $category['name']
)
);
$e->setAttribute('id', $category['id']);
if ($category['parentId'] > 0) {
$e->setAttribute('parentId', htmlspecialchars($category['parentId']));
$e->setAttribute('parentId', $category['parentId']);
}
}
}

View File

@ -6,23 +6,34 @@
*/
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 = '4')
{
switch ($version) {
case '5':
$this->api = new RetailcrmApiClientV5($url, $key);
break;
case '4':
$this->api = new RetailcrmApiClientV4($url, $key);
break;
case '3':
$this->api = new RetailcrmApiClientV3($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);
if (!$response->isSuccessful()) {
error_log("[$method] " . $response->getErrorMsg() . "\n", 3, $this->log);
error_log("[$date] @ [$method] " . $response->getErrorMsg() . "\n", 3, $this->log);
if (isset($response['errors'])) {
$error = implode("\n", $response['errors']);
error_log($error . "\n", 3, $this->log);
@ -32,10 +43,10 @@ class RetailcrmProxy
return $response;
} catch (CurlException $e) {
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log);
error_log("[$date] @ [$method] " . $e->getMessage() . "\n", 3, $this->log);
return false;
} catch (InvalidJsonException $e) {
error_log("[$method] " . $e->getMessage() . "\n", 3, $this->log);
error_log("[$date] @ [$method] " . $e->getMessage() . "\n", 3, $this->log);
return false;
}
}

View File

@ -94,7 +94,7 @@ class RetailcrmReferences
return $paymentTypes;
}
public function getPaymentAndDeliveryForDefault($arParams)
public function getPaymentAndDeliveryForDefault($arParams)
{
$paymentTypes = array();
$deliveryTypes = array();
@ -158,7 +158,7 @@ public function getPaymentAndDeliveryForDefault($arParams)
return $paymentDeliveryTypes;
}
protected function getSystemPaymentModules()
public function getSystemPaymentModules()
{
$shop_id = Context::getContext()->shop->id;

View File

@ -63,7 +63,10 @@
<field id="shipment_date" group="order">shipmentDate</field>
<field id="shipped" group="order">shipped</field>
<!--<field id="order_product" group="order">item</field>-->
<field id="payment" group="order">payments</field>
<field id="payments.amount" group="payment">amount</field>
<field id="payments.status" group="payment">status</field>
<field id="order_product.id" group="item">id</field>
<field id="order_product.initial_price" group="item">initialPrice</field>
<field id="order_product.discount" group="item">discount</field>

View File

@ -20,7 +20,8 @@ class RetailCRM extends Module
{
$this->name = 'retailcrm';
$this->tab = 'export';
$this->version = '2.2';
$this->version = '2.1.1';
$this->version = '2.1';
$this->author = 'Retail Driver LCC';
$this->displayName = $this->l('RetailCRM');
$this->description = $this->l('Integration module for RetailCRM');
@ -30,16 +31,18 @@ class RetailCRM extends Module
$this->default_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
$this->apiUrl = Configuration::get('RETAILCRM_ADDRESS');
$this->apiKey = Configuration::get('RETAILCRM_API_TOKEN');
$this->apiVersion = Configuration::get('RETAILCRM_API_VERSION');
$this->ps_versions_compliancy = array('min' => '1.5', 'max' => _PS_VERSION_);
$this->version = substr(_PS_VERSION_, 0, 3);
$this->log = _PS_ROOT_DIR_ . '/retailcrm.log';
if ($this->version == '1.6') {
$this->bootstrap = true;
$this->use_new_hooks = false;
}
if ($this->validateCrmAddress($this->apiUrl) && !empty($this->apiKey)) {
$this->api = new RetailcrmProxy($this->apiUrl, $this->apiKey, _PS_ROOT_DIR_ . '/retailcrm.log');
if ($this->apiUrl && $this->apiKey) {
$this->api = new RetailcrmProxy($this->apiUrl, $this->apiKey, $this->log, $this->apiVersion);
$this->reference = new RetailcrmReferences($this->api);
}
@ -66,32 +69,39 @@ class RetailCRM extends Module
Configuration::deleteByName('RETAILCRM_API_TOKEN') &&
Configuration::deleteByName('RETAILCRM_API_STATUS') &&
Configuration::deleteByName('RETAILCRM_API_DELIVERY') &&
Configuration::deleteByName('RETAILCRM_LAST_SYNC');
Configuration::deleteByName('RETAILCRM_LAST_SYNC') &&
Configuration::deleteByName('RETAILCRM_API_VERSION');
}
public function getContent()
{
{
$output = null;
$address = Configuration::get('RETAILCRM_ADDRESS');
$token = Configuration::get('RETAILCRM_API_TOKEN');
$version = Configuration::get('RETAILCRM_API_VERSION');
if (Tools::isSubmit('submit' . $this->name)) {
$address = strval(Tools::getValue('RETAILCRM_ADDRESS'));
$token = strval(Tools::getValue('RETAILCRM_API_TOKEN'));
$version = strval(Tools::getValue('RETAILCRM_API_VERSION'));
$delivery = json_encode(Tools::getValue('RETAILCRM_API_DELIVERY'));
$status = json_encode(Tools::getValue('RETAILCRM_API_STATUS'));
$payment = json_encode(Tools::getValue('RETAILCRM_API_PAYMENT'));
$deliveryDefault = json_encode(Tools::getValue('RETAILCRM_API_DELIVERY_DEFAULT'));
$paymentDefault = json_encode(Tools::getValue('RETAILCRM_API_PAYMENT_DEFAULT'));
$settings = array(
'address' => $address,
'token' => $token,
'version' => $version
);
if (!$this->validateCrmAddress($address) || !Validate::isGenericName($address)) {
$output .= $this->displayError($this->l('Invalid crm address'));
} elseif (!$token || empty($token) || !Validate::isGenericName($token)) {
$output .= $this->displayError($this->l('Invalid crm api token'));
} else {
$output .= $this->validateForm($settings, $output);
if ($output === '') {
Configuration::updateValue('RETAILCRM_ADDRESS', $address);
Configuration::updateValue('RETAILCRM_API_TOKEN', $token);
Configuration::updateValue('RETAILCRM_API_VERSION', $version);
Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery);
Configuration::updateValue('RETAILCRM_API_STATUS', $status);
Configuration::updateValue('RETAILCRM_API_PAYMENT', $payment);
@ -99,25 +109,26 @@ class RetailCRM extends Module
Configuration::updateValue('RETAILCRM_API_PAYMENT_DEFAULT', $paymentDefault);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
$this->apiUrl = $address;
$this->apiKey = $token;
$this->api = new RetailcrmProxy($this->apiUrl, $this->apiKey, _PS_ROOT_DIR_ . '/retailcrm.log');
$this->reference = new RetailcrmReferences($this->api);
if ($version == 5 && $this->isRegisteredInHook('actionPaymentCCAdd') == 0) {
$this->registerHook('actionPaymentCCAdd');
} elseif ($version == 4 && $this->isRegisteredInHook('actionPaymentCCAdd') == 1) {
$hook_id = Hook::getIdByName('actionPaymentCCAdd');
$this->unregisterHook($hook_id);
}
}
if (!$this->validateCrmAddress($this->apiUrl)) {
$output .= $this->displayError($this->l('Invalid or empty crm address'));
} elseif (!$token || $token == '') {
$output .= $this->displayError($this->l('Invalid or empty crm api token'));
} else {
$output .= $this->displayConfirmation(
$this->l('Timezone settings must be identical to both of your crm and shop') .
" <a target=\"_blank\" href=\"$address/admin/settings#t-main\">$address/admin/settings#t-main</a>"
);
if ($address && $token) {
$this->api = new RetailcrmProxy($address, $token, $this->log, $version);
$this->reference = new RetailcrmReferences($this->api);
}
$output .= $this->displayConfirmation(
$this->l('Timezone settings must be identical to both of your crm and shop') .
" <a target=\"_blank\" href=\"$address/admin/settings#t-main\">$address/admin/settings#t-main</a>"
);
$this->display(__FILE__, 'retailcrm.tpl');
return $output . $this->displayForm();
@ -129,7 +140,16 @@ class RetailCRM extends Module
$this->displayConfirmation($this->l('Settings updated'));
$default_lang = $this->default_lang;
$apiVersions = array(
array(
'option_id' => '4',
'name' => 'v4'
),
array(
'option_id' => '5',
'name' => 'v5'
)
);
/*
* Network connection form
*/
@ -138,6 +158,16 @@ class RetailCRM extends Module
'title' => $this->l('Network connection'),
),
'input' => array(
array(
'type' => 'select',
'name' => 'RETAILCRM_API_VERSION',
'label' => $this->l('API version'),
'options' => array(
'query' => $apiVersions,
'id' => 'option_id',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('CRM address'),
@ -232,6 +262,7 @@ class RetailCRM extends Module
$helper->fields_value['RETAILCRM_ADDRESS'] = Configuration::get('RETAILCRM_ADDRESS');
$helper->fields_value['RETAILCRM_API_TOKEN'] = Configuration::get('RETAILCRM_API_TOKEN');
$helper->fields_value['RETAILCRM_API_VERSION'] = Configuration::get('RETAILCRM_API_VERSION');
$deliverySettings = Configuration::get('RETAILCRM_API_DELIVERY');
if (isset($deliverySettings) && $deliverySettings != '') {
@ -332,20 +363,26 @@ class RetailCRM extends Module
}
public function hookActionOrderEdited($params)
{
{
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
$order = array(
'externalId' => $params['order']->id,
'firstName' => $params['customer']->firstname,
'lastName' => $params['customer']->lastname,
'email' => $params['customer']->email,
'discount' => $params['order']->total_discounts,
'createdAt' => $params['order']->date_add,
'delivery' => array('cost' => $params['order']->total_shipping)
);
if ($apiVersion != 5) {
$order['discount'] = $params['order']->total_discounts;
} else {
$order['discountManualAmount'] = $params['order']->total_discounts;
}
$orderdb = new Order($params['order']->id);
foreach ($orderdb->getProducts() as $item) {
if (isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) {
if(isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) {
$productId = $item['product_id'] . '#' . $item['product_attribute_id'];
} else {
$productId = $item['product_id'];
@ -364,132 +401,150 @@ class RetailCRM extends Module
}
public function hookActionOrderStatusPostUpdate($params)
{
{
$delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true);
$payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true);
$status = json_decode(Configuration::get('RETAILCRM_API_STATUS'), true);
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
if (isset($params['orderStatus'])) {
$customer = array(
'externalId' => $params['customer']->id,
'lastName' => $params['customer']->lastname,
'firstName' => $params['customer']->firstname,
'email' => $params['customer']->email,
'createdAt' => $params['customer']->date_add
);
$customer = array(
'externalId' => $params['customer']->id,
'lastName' => $params['customer']->lastname,
'firstName' => $params['customer']->firstname,
'email' => $params['customer']->email,
'createdAt' => $params['customer']->date_add
$order = array(
'externalId' => $params['order']->id,
'firstName' => $params['customer']->firstname,
'lastName' => $params['customer']->lastname,
'email' => $params['customer']->email,
'createdAt' => $params['order']->date_add,
'delivery' => array('cost' => $params['order']->total_shipping)
);
if ($apiVersion != 5) {
$order['discount'] = $params['order']->total_discounts;
} else {
$order['discountManualAmount'] = $params['order']->total_discounts;
}
$cart = new Cart($params['cart']->id);
$addressCollection = $cart->getAddressCollection();
$address = array_shift($addressCollection);
if ($address instanceof Address) {
$phone = empty($address->phone)
? empty($address->phone_mobile) ? '' : $address->phone_mobile
: $address->phone;
$postcode = $address->postcode;
$city = $address->city;
$addres_line = sprintf("%s %s", $address->address1, $address->address2);
}
if (!empty($postcode)) {
$customer['address']['index'] = $postcode;
$order['delivery']['address']['index'] = $postcode;
}
if (!empty($city)) {
$customer['address']['city'] = $city;
$order['delivery']['address']['city'] = $city;
}
if (!empty($addres_line)) {
$customer['address']['text'] = $addres_line;
$order['delivery']['address']['text'] = $addres_line;
}
if (!empty($phone)) {
$customer['phones'][] = array('number' => $phone);
$order['phone'] = $phone;
}
foreach ($cart->getProducts() as $item) {
if(isset($item['id_product_attribute']) && $item['id_product_attribute'] > 0) {
$productId = $item['id_product'] . '#' . $item['id_product_attribute'];
} else {
$productId = $item['id_product'];
}
if ($item['attributes']) {
$arProp = array();
$count = 0;
$arAttr = explode(",", $item['attributes']);
foreach ($arAttr as $valAttr) {
$arItem = explode(":", $valAttr);
$arProp[$count]['name'] = trim($arItem[0]);
$arProp[$count]['value'] = trim($arItem[1]);
$count++;
}
}
$order['items'][] = array(
'initialPrice' => !empty($item['rate'])
? $item['price'] + ($item['price'] * $item['rate'] / 100)
: $item['price'],
'quantity' => $item['quantity'],
'offer' => array('externalId' => $productId),
'productName' => $item['name'],
'properties' => $arProp
);
$order = array(
'externalId' => $params['order']->id,
'firstName' => $params['customer']->firstname,
'lastName' => $params['customer']->lastname,
'email' => $params['customer']->email,
'discount' => $params['order']->total_discounts,
'createdAt' => $params['order']->date_add,
'delivery' => array('cost' => $params['order']->total_shipping)
);
unset($arAttr);
unset($count);
unset($arProp);
}
$cart = new Cart($params['cart']->id);
$addressCollection = $cart->getAddressCollection();
$address = array_shift($addressCollection);
$deliveryCode = $params['order']->id_carrier;
if ($address instanceof Address) {
$phone = empty($address->phone)
? empty($address->phone_mobile) ? '' : $address->phone_mobile
: $address->phone;
if (array_key_exists($deliveryCode, $delivery) && !empty($delivery[$deliveryCode])) {
$order['delivery']['code'] = $delivery[$deliveryCode];
}
$postcode = $address->postcode;
$city = $address->city;
$addres_line = sprintf("%s %s", $address->address1, $address->address2);
}
if (!empty($postcode)) {
$customer['address']['index'] = $postcode;
$order['delivery']['address']['index'] = $postcode;
}
if (!empty($city)) {
$customer['address']['city'] = $city;
$order['delivery']['address']['city'] = $city;
}
if (!empty($addres_line)) {
$customer['address']['text'] = $addres_line;
$order['delivery']['address']['text'] = $addres_line;
}
if (!empty($phone)) {
$customer['phones'][] = array('number' => $phone);
$order['phone'] = $phone;
}
foreach ($cart->getProducts() as $item) {
if (isset($item['id_product_attribute']) && $item['id_product_attribute'] > 0) {
$productId = $item['id_product'] . '#' . $item['id_product_attribute'];
} else {
$productId = $item['id_product'];
}
if ($item['attributes']) {
$arProp = array();
$count = 0;
$arAttr = explode(",", $item['attributes']);
foreach ($arAttr as $valAttr) {
$arItem = explode(":", $valAttr);
$arProp[$count]['name'] = trim($arItem[0]);
$arProp[$count]['value'] = trim($arItem[1]);
$count++;
}
}
$order['items'][] = array(
'initialPrice' => !empty($item['rate'])
? $item['price'] + ($item['price'] * $item['rate'] / 100)
: $item['price'],
'quantity' => $item['quantity'],
'offer' => array('externalId' => $productId),
'productName' => $item['name'],
'properties' => $arProp
);
unset($arAttr, $count, $arProp);
}
$deliveryCode = $params['order']->id_carrier;
if (array_key_exists($deliveryCode, $delivery) && !empty($delivery[$deliveryCode])) {
$order['delivery']['code'] = $delivery[$deliveryCode];
}
if (Module::getInstanceByName('advancedcheckout') === false) {
if (Module::getInstanceByName('advancedcheckout') === false) {
$paymentCode = $params['order']->module;
} else {
$paymentCode = $params['order']->payment;
}
if ($apiVersion != 5) {
if (array_key_exists($paymentCode, $payment) && !empty($payment[$paymentCode])) {
$order['paymentType'] = $payment[$paymentCode];
}
} else {
$payment = array(
'externalId' => $params['order']->id .'#'. $params['order']->reference,
'amount' => $params['order']->total_paid,
'type' => $payment[$paymentCode] ? $payment[$paymentCode] : ''
);
}
$statusCode = $params['orderStatus']->id;
if (isset($payment)) $order['payments'][] = $payment;
if (array_key_exists($statusCode, $status) && !empty($status[$statusCode])) {
$order['status'] = $status[$statusCode];
} else {
$order['status'] = 'new';
}
$statusCode = $params['orderStatus']->id;
$customerCheck = $this->api->customersGet($customer['externalId']);
if (array_key_exists($statusCode, $status) && !empty($status[$statusCode])) {
$order['status'] = $status[$statusCode];
} else {
$order['status'] = 'new';
}
if ($customerCheck === false) {
$this->api->customersCreate($customer);
}
$customerCheck = $this->api->customersGet($customer['externalId']);
$order['customer']['externalId'] = $customer['externalId'];
$this->api->ordersCreate($order);
if ($customerCheck === false) {
$this->api->customersCreate($customer);
}
} elseif (isset($params['newOrderStatus'])) {
$order['customer']['externalId'] = $customer['externalId'];
$this->api->ordersCreate($order);
} elseif (isset($params['newOrderStatus'])){
$statusCode = $params['newOrderStatus']->id;
@ -510,10 +565,84 @@ class RetailCRM extends Module
}
}
public function hookActionPaymentCCAdd($params)
{
$order_id = Order::getOrderByCartId($params['cart']->id);
$payments = $this->reference->getSystemPaymentModules();
$paymentCRM = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true);
foreach ($payments as $valPay) {
if ($valPay['name'] == $params['paymentCC']->payment_method) {
$payCode = $valPay['code'];
}
}
if (array_key_exists($payCode, $paymentCRM) && !empty($paymentCRM[$payCode])) {
$payment = $paymentCRM[$payCode];
}
$response = $this->api->ordersGet($order_id);
if ($response->isSuccessful()) {
$orderCRM = $response['order'];
if ($orderCRM && $orderCRM['payments']) {
foreach ($orderCRM['payments'] as $orderPayment) {
if ($orderPayment['type'] == $payment) {
$updatePayment = $orderPayment;
$updatePayment['amount'] = $params['paymentCC']->amount;
$updatePayment['paidAt'] = $params['paymentCC']->date_add;
if ($params['paymentCC']->amount == $orderCRM['totalSumm']) {
$updatePayment['status'] = 'paid';
}
}
}
}
}
if (isset($updatePayment)) {
$this->api->ordersPaymentEdit($updatePayment);
} else {
$this->api->ordersPaymentCreate(
array(
'externalId' => $params['paymentCC']->id,
'amount' => $params['paymentCC']->amount,
'paidAt' => $params['paymentCC']->date_add,
'type' => $payment,
'status' => 'paid',
'order' => array(
'externalId' => $order_id,
),
)
);
}
return true;
}
private function validateCrmAddress($address) {
if (preg_match("/https:\/\/(.*).retailcrm.ru/", $address) === 1)
if(preg_match("/https:\/\/(.*).retailcrm.ru/", $address) === 1)
return true;
return false;
}
private function validateApiVersion($settings) {
$api = new RetailcrmProxy($settings['address'], $settings['token'], _PS_ROOT_DIR_ . '/retailcrm.log', $settings['version']);
$response = $api->statisticUpdate();
if ($response->isSuccessful()) return true;
return false;
}
private function validateForm($settings, $output) {
if (!$this->validateCrmAddress($settings['address']) || !Validate::isGenericName($settings['address'])) {
$output .= $this->displayError($this->l('Invalid or empty crm address'));
} elseif (!$settings['token'] || $settings['token'] == '') {
$output .= $this->displayError($this->l('Invalid or empty crm api token'));
} elseif (!$this->validateApiVersion($settings)) {
$output .= $this->displayError($this->l('The selected version of the API is unavailable'));
}
return $output;
}
}

View File

@ -2,6 +2,7 @@
global $_MODULE;
$_MODULE = array();
$_MODULE['<{retailcrm}prestashop>retailcrm_7d1d9327371097419bdf83ffa671d2f2'] = 'Версия API';
$_MODULE['<{retailcrm}prestashop>retailcrm_463dc31aa1a0b6e871b1a9fed8e9860a'] = 'RetailCRM';
$_MODULE['<{retailcrm}prestashop>retailcrm_30de6237576b9a24f6fc599c22a35a4b'] = 'Модуль интеграции с RetailCRM';
$_MODULE['<{retailcrm}prestashop>retailcrm_876f23178c29dc2552c0b48bf23cd9bd'] = 'Вы уверены, что хотите удалить модуль?';
@ -49,4 +50,4 @@ $_MODULE['<{retailcrm}prestashop>retailcrm_69aede266809f89b89fe70681f6a129f'] =
$_MODULE['<{retailcrm}prestashop>retailcrm_57d056ed0984166336b7879c2af3657f'] = 'Город';
$_MODULE['<{retailcrm}prestashop>retailcrm_bcc254b55c4a1babdf1dcb82c207506b'] = 'Телефон';
$_MODULE['<{retailcrm}prestashop>retailcrm_f0e1fc6f97d36cb80f29196e2662ffde'] = 'Мобильный телефон';
$_MODULE['<{retailcrm}prestashop>retailcrm_7a1920d61156abc05a60135aefe8bc67'] = 'По умолчанию';
$_MODULE['<{retailcrm}prestashop>retailcrm_7a1920d61156abc05a60135aefe8bc67'] = 'По умолчанию';