Bug fix empty payment in history (#19)

This commit is contained in:
Akolzin Dmitry 2017-09-01 10:14:13 +02:00 committed by Alex Lushpai
parent 77298a48a2
commit f0582b9938
12 changed files with 266 additions and 234 deletions

View File

@ -1,6 +1,10 @@
<?php
/*
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
* The MIT License (MIT)
*
* Copyright (c) 2014 Rob Dunham
@ -33,8 +37,7 @@
*
* @package Autoloader
* @license http://opensource.org/licenses/MIT MIT License
* @author Rob Dunham <contact@robunham.info>
* @author Alex Lushpai <lushpai@gmail.com>
*
*/
class RetailcrmAutoloader
{
@ -64,11 +67,10 @@ class RetailcrmAutoloader
$filename = $className . self::$fileExt;
foreach ($fileIterator as $file) {
if (strtolower($file->getFilename()) === strtolower($filename) && $file->isReadable()) {
if (Tools::strtolower($file->getFilename()) === Tools::strtolower($filename) && $file->isReadable()) {
include_once $file->getPathname();
}
}
}
/**
@ -91,7 +93,6 @@ class RetailcrmAutoloader
{
self::$pathTop = $path;
}
}
RetailcrmAutoloader::setPath(realpath(dirname(__FILE__)));

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>retailcrm</name>
<displayName><![CDATA[RetailCRM]]></displayName>
<version><![CDATA[2.0.1]]></version>
<description><![CDATA[Integration module for RetailCRM]]></description>
<author><![CDATA[Retail Driver LCC]]></author>
<tab><![CDATA[export]]></tab>
<confirmUninstall><![CDATA[Are you sure you want to uninstall?]]></confirmUninstall>
<is_configurable>1</is_configurable>
<need_instance>1</need_instance>
<limited_countries></limited_countries>
</module>

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>retailcrm</name>
<displayName><![CDATA[RetailCRM]]></displayName>
<version><![CDATA[1.6]]></version>
<description><![CDATA[Модуль интеграции с RetailCRM]]></description>
<author><![CDATA[Retail Driver LCC]]></author>
<tab><![CDATA[export]]></tab>
<confirmUninstall><![CDATA[Вы уверены, что хотите удалить модуль?]]></confirmUninstall>
<is_configurable>1</is_configurable>
<need_instance>1</need_instance>
<limited_countries></limited_countries>
</module>

1
retailcrm/index.php Normal file
View File

@ -0,0 +1 @@
<?php // Silence is golden

View File

@ -1,4 +1,13 @@
<?php
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
*
*/
$_SERVER['HTTPS'] = 1;
require(dirname(__FILE__) . '/../../../config/config.inc.php');
@ -41,7 +50,6 @@ foreach ($customerRecords as $record) {
unset($customerRecords);
foreach ($orderRecords as $record) {
$object = new Order($record['id_order']);
if (Module::getInstanceByName('advancedcheckout') === false) {
@ -122,8 +130,8 @@ foreach ($orderRecords as $record) {
$products = $object->getProducts();
foreach($products as $product) {
if(isset($product['product_attribute_id']) && $product['product_attribute_id'] > 0) {
foreach ($products as $product) {
if (isset($product['product_attribute_id']) && $product['product_attribute_id'] > 0) {
$productId = $product['product_id'] . '#' . $product['product_attribute_id'];
} else {
$productId = $product['product_id'];

View File

@ -1,4 +1,13 @@
<?php
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
*
*/
$_SERVER['HTTPS'] = 1;
require(dirname(__FILE__) . '/../../../config/config.inc.php');

1
retailcrm/job/index.php Normal file
View File

@ -0,0 +1 @@
<?php // Silence is golden

View File

@ -1,4 +1,13 @@
<?php
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
*
*/
$_SERVER['HTTPS'] = 1;
$shortopts = 'o:';
@ -142,7 +151,7 @@ if (isset($orderInstance->total_shipping_tax_incl) && (int) $orderInstance->tota
$products = $orderInstance->getProducts();
foreach($products as $product) {
foreach ($products as $product) {
$item = array(
//'productId' => $product['product_id'],
'offer' => array('externalId' => $product['product_id']),

View File

@ -1,4 +1,13 @@
<?php
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
*
*/
$_SERVER['HTTPS'] = 1;
require(dirname(__FILE__) . '/../../../config/config.inc.php');
@ -29,27 +38,25 @@ $startFrom = ($lastSync === false)
$customerFix = array();
$orderFix = array();
$startDate = new DateTime($startFrom);
$history = $api->ordersHistory(array(
'startDate' => $startDate->format('Y-m-d H:i:s')
));
if ($history->isSuccessful() && count($history->history) > 0) {
$statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true)));
$deliveries = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true)));
$payments = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true)));
$deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true);
$paymentDefault = json_decode(Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT'), true);
$orders = RetailcrmHistoryHelper::assemblyOrder($history->history);
foreach ($orders as $order) {
if (isset($order['deleted']) && $order['deleted'] == true) continue;
if (isset($order['deleted']) && $order['deleted'] == true) {
continue;
}
if (!array_key_exists('externalId', $order)) {
$delivery = $order['delivery']['code'];
if (array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') {
@ -72,7 +79,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
}
if (array_key_exists($payment, $payments) && $payments[$payment] != '') {
if(Module::getInstanceByName($payments[$payment])) {
if (Module::getInstanceByName($payments[$payment])) {
$paymentType = Module::getModuleName($payments[$payment]);
} else {
$paymentType = $payments[$payment];
@ -85,44 +92,52 @@ if ($history->isSuccessful() && count($history->history) > 0) {
if (array_key_exists($state, $statuses) && $statuses[$state] != '') {
$orderStatus = $statuses[$state];
}
if (!$paymentType){
if (!isset($paymentId) || !$paymentId) {
$paymentId = $paymentDefault;
}
if (!$paymentType) {
if ($paymentDefault) {
if(Module::getInstanceByName($paymentDefault)) {
if (Module::getInstanceByName($paymentDefault)) {
$paymentType = Module::getModuleName($paymentDefault);
} else {
$paymentType = $paymentDefault;
}
$paymentId = $paymentDefault;
} else{
error_log('orderHistory: set default payment(error in order where id = '.$order['id'].')', 3, _PS_ROOT_DIR_ . '/retailcrm.log');
} else {
error_log(
'orderHistory: set default payment(error in order where id = '.$order['id'].')',
3,
_PS_ROOT_DIR_ . '/retailcrm.log'
);
continue;
}
}
if (!$deliveryType){
if (!$deliveryType) {
if ($deliveryDefault) {
$deliveryType = $deliveryDefault;
} else{
error_log('orderHistory: set default delivery(error in order where id = '.$order['id'].')', 3, _PS_ROOT_DIR_ . '/retailcrm.log');
} else {
error_log(
'orderHistory: set default delivery(error in order where id = '.$order['id'].')',
3,
_PS_ROOT_DIR_ . '/retailcrm.log'
);
continue;
}
}
$customer = new Customer();
if(!empty($order['customer']['email']))
if (!empty($order['customer']['email'])) {
$customer->getByEmail($order['customer']['email']);
}
if (!array_key_exists('externalId', $order['customer'])) {
if (!$customer->id)
{
if (!$customer->id) {
$customer->firstname = $order['customer']['firstName'];
$customer->lastname = !empty($order['customer']['lastName']) ? $order['customer']['lastName'] : '-';
$customer->email = Validate::isEmail($order['customer']['email']) ? $order['customer']['email'] : md5($order['customer']['firstName']) . '@retailcrm.ru';
$customer->passwd = substr(str_shuffle(strtolower(sha1(rand() . time()))),0, 5);
$customer->email = Validate::isEmail($order['customer']['email']) ?
$order['customer']['email'] :
md5($order['customer']['firstName']) . '@retailcrm.ru';
$customer->passwd = Tools::substr(str_shuffle(Tools::strtolower(sha1(rand() . time()))), 0, 5);
$customer->add();
}
@ -143,8 +158,10 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$address->firstname = $customer->firstname;
$address->alias = 'default';
$address->postcode = $order['delivery']['address']['index'];
$address->city = !empty($order['delivery']['address']['city']) ? $order['delivery']['address']['city'] : '-';
$address->address1 = !empty($order['delivery']['address']['text']) ? $order['delivery']['address']['text'] : '-';
$address->city = !empty($order['delivery']['address']['city']) ?
$order['delivery']['address']['city'] : '-';
$address->address1 = !empty($order['delivery']['address']['text']) ?
$order['delivery']['address']['text'] : '-';
$address->phone = $order['phone'];
$address->add();
@ -160,7 +177,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$products = array();
if(!empty($order['items'])) {
if (!empty($order['items'])) {
foreach ($order['items'] as $item) {
$productId = explode('#', $item['offer']['externalId']);
@ -190,7 +207,9 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$newOrder->id_currency = $default_currency;
$newOrder->id_lang = $default_lang;
$newOrder->id_customer = (int) $customer->id;
if (isset($deliveryType)) $newOrder->id_carrier = (int) $deliveryType;
if (isset($deliveryType)) {
$newOrder->id_carrier = (int) $deliveryType;
}
if (isset($paymentType)) {
$newOrder->payment = $paymentType;
$newOrder->module = $paymentId;
@ -205,16 +224,19 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$newOrder->total_shipping_tax_incl = $order['delivery']['cost'];
$newOrder->total_shipping_tax_excl = $order['delivery']['cost'];
$newOrder->conversion_rate = 1.000000;
if (isset($orderStatus)) $newOrder->current_state = (int) $orderStatus;
if (!empty($order['delivery']['date'])) $newOrder->delivery_date = $order['delivery']['date'];
if (isset($orderStatus)) {
$newOrder->current_state = (int) $orderStatus;
}
if (!empty($order['delivery']['date'])) {
$newOrder->delivery_date = $order['delivery']['date'];
}
$newOrder->date_add = $order['createdAt'];
$newOrder->date_upd = $order['createdAt'];
$newOrder->invoice_date = $order['createdAt'];
$newOrder->valid = 1;
$newOrder->secure_key = md5(time());
if (isset($order['discount']))
{
if (isset($order['discount'])) {
$newOrder->total_discounts = $order['discount'];
}
@ -224,15 +246,16 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$product = new Product((int) $item['offer']['externalId'], false, $default_lang);
$product_id = $item['offer']['externalId'];
$product_attribute_id = 0;
if(strpos($item['offer']['externalId'], '#') !== false) {
if (strpos($item['offer']['externalId'], '#') !== false) {
$product_id = explode('#', $item['offer']['externalId']);
$product_attribute_id = $product_id[1];
$product_id = $product_id[0];
}
if($product_attribute_id != 0) {
$productName = htmlspecialchars(strip_tags(Product::getProductName($product_id, $product_attribute_id)));
if ($product_attribute_id != 0) {
$productName = htmlspecialchars(
strip_tags(Product::getProductName($product_id, $product_attribute_id))
);
$productPrice = Combination::getPrice($product_attribute_id);
$productPrice = $productPrice > 0 ? $productPrice : $product->price;
} else {
@ -266,18 +289,15 @@ if ($history->isSuccessful() && count($history->history) > 0) {
}
}
$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'] . '\'
)'
);
Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment`
(`payment_method`, `order_reference` , `amount`, `date_add`)
VALUES
(\'' . $payType . '\',
\'' . $newOrder->reference . '\',
\'' . $payment['amount'] . '\',
\'' . $payment['paidAt'] . '\')');
}
}
}
}
$carrier = new OrderCarrierCore();
@ -329,46 +349,47 @@ if ($history->isSuccessful() && count($history->history) > 0) {
Db::getInstance()->execute(rtrim($query, ','));
if(!empty($customerFix))
if (!empty($customerFix)) {
$api->customersFixExternalIds($customerFix);
if(!empty($orderFix))
}
if (!empty($orderFix)) {
$api->ordersFixExternalIds($orderFix);
}
} else {
$orderToUpdate = new Order((int) $order['externalId']);
/*
* check delivery type
*/
if(!empty($order['delivery']['code'])) {
if (!empty($order['delivery']['code'])) {
$dtype = $order['delivery']['code'];
$dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null;
if ($deliveries[$dtype] != null) {
if ($deliveries[$dtype] != $orderToUpdate->id_carrier OR $dcost != null) {
if($dtype != null) {
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'orders`
SET `id_carrier` = \'' . $deliveries[$dtype] . '\'
WHERE `id_order` = ' . (int)$order['externalId']
);
if ($deliveries[$dtype] != $orderToUpdate->id_carrier or $dcost != null) {
if ($dtype != null) {
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders`
SET
`id_carrier` = \'' . $deliveries[$dtype] . '\'
WHERE
`id_order` = ' . (int)$order['externalId']);
}
$updateCarrierFields = array();
if($dtype != null) {
if ($dtype != null) {
$updateCarrierFields[] = '`id_carrier` = \'' . $deliveries[$dtype] . '\' ';
}
if($dcost != null) {
if ($dcost != null) {
$updateCarrierFields[] = '`shipping_cost_tax_incl` = \'' . $dcost . '\' ';
$updateCarrierFields[] = '`shipping_cost_tax_excl` = \'' . $dcost . '\' ';
}
$updateCarrierFields = implode(', ', $updateCarrierFields);
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'order_carrier` SET
'.$updateCarrierFields.'
WHERE `id_order` = \'' . $orderToUpdate->id . '\''
);
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_carrier`
SET
'.$updateCarrierFields.'
WHERE
`id_order` = \'' . $orderToUpdate->id . '\'');
}
}
}
@ -376,54 +397,50 @@ if ($history->isSuccessful() && count($history->history) > 0) {
/*
* check payment type
*/
if(!empty($order['paymentType']) && $apiVersion != 5) {
if (!empty($order['paymentType']) && $apiVersion != 5) {
$ptype = $order['paymentType'];
if ($payments[$ptype] != null) {
$paymentType = Module::getModuleName($payments[$ptype]);
if ($payments[$ptype] != $orderToUpdate->payment) {
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'orders`
SET `payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\'
WHERE `id_order` = ' . (int)$order['externalId']
);
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'order_payment`
SET `payment_method` = \'' . $payments[$ptype] . '\'
WHERE `order_reference` = \'' . $orderToUpdate->reference . '\''
);
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders`
SET
`payment` = \'' . ($paymentType != null ? $paymentType : $payments[$ptype]). '\'
WHERE
`id_order` = ' . (int)$order['externalId']);
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'order_payment`
SET
`payment_method` = \'' . $payments[$ptype] . '\'
WHERE
`order_reference` = \'' . $orderToUpdate->reference . '\'');
}
}
} elseif (!empty($order['payments']) && $apiVersion == 5) {
if ($order['payments']) {
foreach ($order['payments'] as $payment) {
if (!isset($payment['externalId']) && $payment['status'] == 'paid') {
$ptype = $payment['type'];
$ptypes = $references->getSystemPaymentModules();
if ($payments[$ptype] != null) {
$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('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'] . '\'
)'
);
Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_payment`
(`payment_method`, `order_reference` , `amount`, `date_add`)
VALUES
(\'' . $payType . '\',
\'' . $orderToUpdate->reference . '\',
\'' . $payment['amount'] . '\',
\'' . $payment['paidAt'] . '\')');
}
}
}
@ -435,7 +452,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/
foreach ($order['items'] as $key => $item) {
if (isset($item['delete']) && $item['delete'] == true) {
if(strpos($item['offer']['externalId'], '#') !== false) {
if (strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0];
$product_attribute_id = $itemId[1];
@ -444,12 +461,11 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$product_attribute_id = 0;
}
Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'order_detail`
WHERE `id_order` = '. $orderToUpdate->id .'
AND `product_id` = '.$product_id. '
AND `product_attribute_id` = '.$product_attribute_id
);
Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'order_detail`
WHERE
`id_order` = '. $orderToUpdate->id .'
AND
`product_id` = '.$product_id. ' AND `product_attribute_id` = '.$product_attribute_id);
unset($order['items'][$key]);
$ItemDiscount = true;
@ -461,7 +477,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/
foreach ($orderToUpdate->getProductsDetail() as $orderItem) {
foreach ($order['items'] as $key => $item) {
if(strpos($item['offer']['externalId'], '#') !== false) {
if (strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0];
$product_attribute_id = $itemId[1];
@ -470,14 +486,16 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$product_attribute_id = 0;
}
if ($product_id == $orderItem['product_id'] && $product_attribute_id == $orderItem['product_attribute_id']) {
if ($product_id == $orderItem['product_id'] &&
$product_attribute_id == $orderItem['product_attribute_id']) {
// discount
if (isset($item['discount']) || isset($item['discountPercent']) || isset($item['discountTotal'])) {
if (isset($item['discount']) ||
isset($item['discountPercent']) ||
isset($item['discountTotal'])) {
$product = new Product((int) $product_id, false, $default_lang);
$tax = new TaxCore($product->id_tax_rules_group);
if($product_attribute_id != 0) {
if ($product_attribute_id != 0) {
$prodPrice = Combination::getPrice($product_attribute_id);
$prodPrice = $prodPrice > 0 ? $prodPrice : $product->price;
} else {
@ -490,23 +508,23 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$productPrice = $productPrice - ($prodPrice / 100 * $item['discountPercent']);
$productPrice = $prodPrice - $item['discountTotal'];
$productPrice = round($productPrice , 2);
$productPrice = round($productPrice, 2);
Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'order_detail`
SET `unit_price_tax_incl` = '.$productPrice.'
WHERE `id_order_detail` = '.$orderItem['id_order_detail']
);
Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail`
SET
`unit_price_tax_incl` = '.$productPrice.'
WHERE
`id_order_detail` = '.$orderItem['id_order_detail']);
}
// quantity
if (isset($item['quantity']) && $item['quantity'] != $orderItem['product_quantity']) {
Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'order_detail`
SET `product_quantity` = '.$item['quantity'].',
`product_quantity_in_stock` = '.$item['quantity'].'
WHERE `id_order_detail` = '.$orderItem['id_order_detail']
);
Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'order_detail`
SET
`product_quantity` = '.$item['quantity'].',
`product_quantity_in_stock` = '.$item['quantity'].'
WHERE
`id_order_detail` = '.$orderItem['id_order_detail']);
}
$ItemDiscount = true;
@ -532,7 +550,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
foreach ($order['items'] as $key => $newItem) {
$product_id = $newItem['offer']['externalId'];
$product_attribute_id = 0;
if(strpos($product_id, '#') !== false) {
if (strpos($product_id, '#') !== false) {
$product_id = explode('#', $product_id);
$product_attribute_id = $product_id[1];
@ -542,9 +560,10 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$product = new Product((int) $product_id, false, $default_lang);
$tax = new TaxCore($product->id_tax_rules_group);
if($product_attribute_id != 0) {
$productName = htmlspecialchars(strip_tags(Product::getProductName($product_id, $product_attribute_id)));
if ($product_attribute_id != 0) {
$productName = htmlspecialchars(
strip_tags(Product::getProductName($product_id, $product_attribute_id))
);
$productPrice = Combination::getPrice($product_attribute_id);
$productPrice = $productPrice > 0 ? $productPrice : $product->price;
} else {
@ -593,10 +612,8 @@ if ($history->isSuccessful() && count($history->history) > 0) {
isset($order['delivery']['cost']) ||
isset($order['discountTotal']) ||
$ItemDiscount) {
$infoOrd = $api->ordersGet($order['externalId']);
$infoOrder = $infoOrd->order;
$orderTotalProducts = $infoOrder['summ'];
$totalPaid = $infoOrder['totalSumm'];
$deliveryCost = $infoOrder['delivery']['cost'];
@ -609,20 +626,19 @@ if ($history->isSuccessful() && count($history->history) > 0) {
}
$orderToUpdate->update();
Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'orders`
SET `total_discounts` = '.$totalDiscount.',
`total_discounts_tax_incl` = '.$totalDiscount.',
`total_discounts_tax_excl` = '.$totalDiscount.',
`total_shipping` = '.$deliveryCost.',
`total_shipping_tax_incl` = '.$deliveryCost.',
`total_shipping_tax_excl` = '.$deliveryCost.',
`total_paid` = '.$totalPaid.',
`total_paid_tax_incl` = '.$totalPaid.',
`total_paid_tax_excl` = '.$totalPaid.',
`total_products_wt` = '.$orderTotalProducts.'
WHERE `id_order` = '.(int) $order['externalId']
);
Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'orders`
SET
`total_discounts` = '.$totalDiscount.',
`total_discounts_tax_incl` = '.$totalDiscount.',
`total_discounts_tax_excl` = '.$totalDiscount.',
`total_shipping` = '.$deliveryCost.',
`total_shipping_tax_incl` = '.$deliveryCost.',
`total_shipping_tax_excl` = '.$deliveryCost.',
`total_paid` = '.$totalPaid.',
`total_paid_tax_incl` = '.$totalPaid.',
`total_paid_tax_excl` = '.$totalPaid.',
`total_products_wt` = '.$orderTotalProducts.'
WHERE `id_order` = '.(int) $order['externalId']);
unset($ItemDiscount);
}
@ -630,30 +646,26 @@ if ($history->isSuccessful() && count($history->history) > 0) {
/*
* check status
*/
if(!empty($order['status'])) {
if (!empty($order['status'])) {
$stype = $order['status'];
if ($statuses[$stype] != null) {
if ($statuses[$stype] != $orderToUpdate->current_state) {
Db::getInstance()->execute('
INSERT INTO `' . _DB_PREFIX_ . 'order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)
VALUES (
0,
' . $orderToUpdate->id . ',
' . $statuses[$stype] . ',
"' . date('Y-m-d H:i:s') . '"
)
');
Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'order_history`
(`id_employee`, `id_order`, `id_order_state`, `date_add`)
VALUES
(0, ' . $orderToUpdate->id . ',
' . $statuses[$stype] . ',
"' . date('Y-m-d H:i:s') . '")');
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'orders`
SET `current_state` = \'' . $statuses[$stype] . '\'
WHERE `id_order` = ' . (int)$order['externalId']
);
Db::getInstance()->execute('UPDATE `' . _DB_PREFIX_ . 'orders`
SET
`current_state` = \'' . $statuses[$stype] . '\'
WHERE
`id_order` = ' . (int)$order['externalId']);
}
}
}
}
}
/*

1
retailcrm/lib/index.php Normal file
View File

@ -0,0 +1 @@
<?php // Silence is golden

View File

@ -1,9 +1,14 @@
<?php
/**
* @author Retail Driver LCC
* @copyright RetailCRM
* @license GPL
* @version 2.1.1
* @link https://retailcrm.ru
*
*/
if (
function_exists('date_default_timezone_set') &&
function_exists('date_default_timezone_get')
) {
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
date_default_timezone_set(@date_default_timezone_get());
}
@ -16,12 +21,11 @@ require_once(dirname(__FILE__) . '/bootstrap.php');
class RetailCRM extends Module
{
function __construct()
public function __construct()
{
$this->name = 'retailcrm';
$this->tab = 'export';
$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');
@ -33,10 +37,11 @@ class RetailCRM extends Module
$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->psVersion = Tools::substr(_PS_VERSION_, 0, 3);
$this->log = _PS_ROOT_DIR_ . '/retailcrm.log';
if ($this->version == '1.6') {
$this->module_key = '149c765c6cddcf35e1f13ea6c71e9fa5';
if ($this->psVersion == '1.6') {
$this->bootstrap = true;
$this->use_new_hooks = false;
}
@ -49,7 +54,7 @@ class RetailCRM extends Module
parent::__construct();
}
function install()
public function install()
{
return (
parent::install() &&
@ -62,7 +67,7 @@ class RetailCRM extends Module
);
}
function uninstall()
public function uninstall()
{
return parent::uninstall() &&
Configuration::deleteByName('RETAILCRM_ADDRESS') &&
@ -74,25 +79,24 @@ class RetailCRM extends Module
}
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'));
$address = (string)(Tools::getValue('RETAILCRM_ADDRESS'));
$token = (string)(Tools::getValue('RETAILCRM_API_TOKEN'));
$version = (string)(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,
'address' => $address,
'token' => $token,
'version' => $version
);
@ -150,6 +154,7 @@ class RetailCRM extends Module
'name' => 'v5'
)
);
$fields_form = array();
/*
* Network connection form
*/
@ -164,7 +169,7 @@ class RetailCRM extends Module
'label' => $this->l('API version'),
'options' => array(
'query' => $apiVersions,
'id' => 'option_id',
'id' => 'option_id',
'name' => 'name'
)
),
@ -220,7 +225,9 @@ class RetailCRM extends Module
*/
$fields_form[4]['form'] = array(
'legend' => array('title' => $this->l('Default')),
'input' => $this->reference->getPaymentAndDeliveryForDefault(array($this->l('Delivery method'), $this->l('Payment type'))),
'input' => $this->reference->getPaymentAndDeliveryForDefault(
array($this->l('Delivery method'), $this->l('Payment type'))
),
);
}
@ -363,7 +370,7 @@ class RetailCRM extends Module
}
public function hookActionOrderEdited($params)
{
{
$apiVersion = Configuration::get('RETAILCRM_API_VERSION');
$order = array(
'externalId' => $params['order']->id,
@ -382,7 +389,7 @@ class RetailCRM extends Module
$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'];
@ -401,7 +408,7 @@ class RetailCRM extends Module
}
public function hookActionOrderStatusPostUpdate($params)
{
{
$delivery = json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true);
$payment = json_decode(Configuration::get('RETAILCRM_API_PAYMENT'), true);
$status = json_decode(Configuration::get('RETAILCRM_API_STATUS'), true);
@ -466,7 +473,7 @@ class RetailCRM extends Module
}
foreach ($cart->getProducts() as $item) {
if(isset($item['id_product_attribute']) && $item['id_product_attribute'] > 0) {
if (isset($item['id_product_attribute']) && $item['id_product_attribute'] > 0) {
$productId = $item['id_product'] . '#' . $item['id_product_attribute'];
} else {
$productId = $item['id_product'];
@ -476,12 +483,11 @@ class RetailCRM extends Module
$arProp = array();
$count = 0;
$arAttr = explode(",", $item['attributes']);
foreach ($arAttr as $valAttr) {
foreach ($arAttr as $valAttr) {
$arItem = explode(":", $valAttr);
$arProp[$count]['name'] = trim($arItem[0]);
$arProp[$count]['value'] = trim($arItem[1]);
$count++;
}
}
@ -507,10 +513,10 @@ class RetailCRM extends Module
}
if (Module::getInstanceByName('advancedcheckout') === false) {
$paymentCode = $params['order']->module;
} else {
$paymentCode = $params['order']->payment;
}
$paymentCode = $params['order']->module;
} else {
$paymentCode = $params['order']->payment;
}
if ($apiVersion != 5) {
if (array_key_exists($paymentCode, $payment) && !empty($payment[$paymentCode])) {
@ -524,7 +530,9 @@ class RetailCRM extends Module
);
}
if (isset($payment)) $order['payments'][] = $payment;
if (isset($payment)) {
$order['payments'][] = $payment;
}
$statusCode = $params['orderStatus']->id;
@ -543,9 +551,7 @@ class RetailCRM extends Module
$order['customer']['externalId'] = $customer['externalId'];
$this->api->ordersCreate($order);
} elseif (isset($params['newOrderStatus'])){
} elseif (isset($params['newOrderStatus'])) {
$statusCode = $params['newOrderStatus']->id;
if (array_key_exists($statusCode, $status) && !empty($status[$statusCode])) {
@ -553,14 +559,12 @@ class RetailCRM extends Module
}
if (isset($orderStatus)) {
$this->api->ordersEdit(
array(
'externalId' => $params['id_order'],
'status' => $orderStatus
)
);
}
}
}
@ -618,23 +622,34 @@ class RetailCRM extends Module
return true;
}
private function validateCrmAddress($address) {
if(preg_match("/https:\/\/(.*).retailcrm.ru/", $address) === 1)
private function validateCrmAddress($address)
{
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();
private function validateApiVersion($settings)
{
$api = new RetailcrmProxy(
$settings['address'],
$settings['token'],
_PS_ROOT_DIR_ . '/retailcrm.log',
$settings['version']
);
$response = $api->deliveryTypesList();
if ($response['errorMsg'] != 'API method not found') return true;
if ($response->isSuccessful()) {
return true;
}
return false;
}
private function validateForm($settings, $output) {
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'] == '') {

View File

@ -0,0 +1 @@
<?php // Silence is golden