bug fixes and other changes (#8)

* [productId] replace to [offer][externalId]

* properties for items in order and in icml

* fix

* correct order creation

* correct url images

* skip orders with incorrect data

* create order with default payment and delivery, transfer order status from cms

* correct transfer discount

* correct delete items and discount
This commit is contained in:
DmitryZagorulko 2017-04-05 17:56:26 +03:00 committed by Alex Lushpai
parent 6eed3ad0e7
commit 1ca1f31abc
4 changed files with 209 additions and 77 deletions

View File

@ -39,6 +39,8 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true))); $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))); $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))); $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); $orders = RetailcrmHistoryHelper::assemblyOrder($history->history);
@ -46,6 +48,56 @@ if ($history->isSuccessful() && count($history->history) > 0) {
if (isset($order['deleted']) && $order['deleted'] == true) continue; if (isset($order['deleted']) && $order['deleted'] == true) continue;
if (!array_key_exists('externalId', $order)) { if (!array_key_exists('externalId', $order)) {
$delivery = $order['delivery']['code'];
if (array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') {
$deliveryType = $deliveries[$delivery];
}
$payment = $order['paymentType'];
if (array_key_exists($payment, $payments) && $payments[$payment] != '') {
if(Module::getInstanceByName($payments[$payment])) {
$paymentType = Module::getModuleName($payments[$payment]);
} else {
$paymentType = $payments[$payment];
}
$paymentId = $payments[$payment];
}
$state = $order['status'];
if (array_key_exists($state, $statuses) && $statuses[$state] != '') {
$orderStatus = $statuses[$state];
}
if (!$paymentType){
if ($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');
continue;
}
}
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');
continue;
}
}
$customer = new Customer(); $customer = new Customer();
if(!empty($order['customer']['email'])) if(!empty($order['customer']['email']))
$customer->getByEmail($order['customer']['email']); $customer->getByEmail($order['customer']['email']);
@ -82,35 +134,13 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$address->phone = $order['phone']; $address->phone = $order['phone'];
$address->add(); $address->add();
$delivery = $order['delivery']['code'];
if (array_key_exists($delivery, $deliveries) && $deliveries[$delivery] != '') {
$deliveryType = $deliveries[$delivery];
}
$payment = $order['paymentType'];
if (array_key_exists($payment, $payments) && $payments[$payment] != '') {
if(Module::getInstanceByName($payments[$payment])) {
$paymentType = Module::getModuleName($payments[$payment]);
} else {
$paymentType = $payments[$payment];
}
}
$state = $order['status'];
if (array_key_exists($state, $statuses) && $statuses[$state] != '') {
$orderStatus = $statuses[$state];
}
$cart = new Cart(); $cart = new Cart();
$cart->id_currency = $default_currency; $cart->id_currency = $default_currency;
$cart->id_lang = $default_lang; $cart->id_lang = $default_lang;
$cart->id_customer = $customer->id; $cart->id_customer = $customer->id;
$cart->id_address_delivery = (int) $address->id; $cart->id_address_delivery = (int) $address->id;
$cart->id_address_invoice = (int) $address->id; $cart->id_address_invoice = (int) $address->id;
$cart->id_carrier = (int) $deliveries[$delivery]; $cart->id_carrier = (int) $deliveryType;
$cart->add(); $cart->add();
@ -137,8 +167,8 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/ */
$newOrder = new Order(); $newOrder = new Order();
$shops = Shop::getShops(); $shops = Shop::getShops();
$newOrder->id_shop = Shop::getCurrentShop(); $newOrder->id_shop = Context::getContext()->shop->id;
$newOrder->id_shop_group = (int)$shops[Shop::getCurrentShop()]['id_shop_group']; $newOrder->id_shop_group = (int)$shops[Context::getContext()->shop->id]['id_shop_group'];
$newOrder->id_address_delivery = (int) $address->id; $newOrder->id_address_delivery = (int) $address->id;
$newOrder->id_address_invoice = (int) $address->id; $newOrder->id_address_invoice = (int) $address->id;
@ -149,7 +179,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
if (isset($deliveryType)) $newOrder->id_carrier = (int) $deliveryType; if (isset($deliveryType)) $newOrder->id_carrier = (int) $deliveryType;
if (isset($paymentType)) { if (isset($paymentType)) {
$newOrder->payment = $paymentType; $newOrder->payment = $paymentType;
$newOrder->module = $payments[$payment]; $newOrder->module = $paymentId;
} }
$newOrder->total_paid = $order['summ'] + $order['delivery']['cost']; $newOrder->total_paid = $order['summ'] + $order['delivery']['cost'];
$newOrder->total_paid_tax_incl = $order['summ'] + $order['delivery']['cost']; $newOrder->total_paid_tax_incl = $order['summ'] + $order['delivery']['cost'];
@ -354,13 +384,13 @@ if ($history->isSuccessful() && count($history->history) > 0) {
* Clean deleted items * Clean deleted items
*/ */
foreach ($order['items'] as $key => $item) { foreach ($order['items'] as $key => $item) {
if (isset($item['deleted']) && $item['deleted'] == true) { if (isset($item['delete']) && $item['delete'] == true) {
if(strpos($item['id'], '#') !== false) { if(strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['id']); $itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0]; $product_id = $itemId[0];
$product_attribute_id = $itemId[1]; $product_attribute_id = $itemId[1];
} else { } else {
$product_id = $item['id']; $product_id = $item['offer']['externalId'];
$product_attribute_id = 0; $product_attribute_id = 0;
} }
@ -372,6 +402,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
); );
unset($order['items'][$key]); unset($order['items'][$key]);
$ItemDiscount = true
} }
} }
@ -380,6 +411,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/ */
foreach ($orderToUpdate->getProductsDetail() as $orderItem) { foreach ($orderToUpdate->getProductsDetail() as $orderItem) {
foreach ($order['items'] as $key => $item) { foreach ($order['items'] as $key => $item) {
if (isset($item['discount']) || isset($item['discountPercent'])) $ItemDiscount = true;
if(strpos($item['offer']['externalId'], '#') !== false) { if(strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['offer']['externalId']); $itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0]; $product_id = $itemId[0];
@ -419,6 +451,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
VALUES'; VALUES';
foreach ($order['items'] as $key => $newItem) { foreach ($order['items'] as $key => $newItem) {
if ($newItem['discount'] || $newItem['discountPercent']) $ItemDiscount = true;
$product_id = $newItem['offer']['externalId']; $product_id = $newItem['offer']['externalId'];
$product_attribute_id = 0; $product_attribute_id = 0;
if(strpos($product_id, '#') !== false) { if(strpos($product_id, '#') !== false) {
@ -468,39 +501,26 @@ if ($history->isSuccessful() && count($history->history) > 0) {
* Fix prices & discounts * Fix prices & discounts
* Discounts only for whole order * Discounts only for whole order
*/ */
$orderDiscout = null; if (isset($order['discount']) ||
$orderTotalProducts = 0; isset($order['discountPercent']) ||
foreach($orderToUpdate->getProductsDetail() as $orderItem) { isset($order['delivery']['cost']) ||
$orderTotalProducts += $orderItem['total_price_tax_incl']; $ItemDiscount) {
}
$orderTotalProducts = round($orderTotalProducts, 2);
if (isset($order['discount']) && $order['discount'] > 0) { $infoOrd = $api->ordersGet($order['externalId']);
if ($order['discount'] != $orderToUpdate->total_discounts) { $infoOrder = $infoOrd->order;
$orderDiscout = ($orderDiscout == null) ? $order['discount'] : $order['discount'] + $orderDiscout;
}
}
if (isset($order['discountPercent']) && $order['discountPercent'] > 0) { $orderTotalProducts = $infoOrder['summ'];
$percent = ($order['summ'] * $order['discountPercent'])/100; $totalPaid = $infoOrder['totalSumm'];
if ($percent != $orderToUpdate->total_discounts) { $deliveryCost = $infoOrder['delivery']['cost'];
$orderDiscout = ($orderDiscout == null) ? $percent : $percent + $orderDiscout; $totalDiscount = $deliveryCost + $orderTotalProducts - $totalPaid;
}
$orderCartRules = $orderToUpdate->getCartRules();
foreach ($orderCartRules as $valCartRules) {
$order_cart_rule = new OrderCartRule($valCartRules['id_order_cart_rule']);
$order_cart_rule->delete();
} }
$orderToUpdate->update();
$totalDiscount = ($orderDiscout == null) ? $orderToUpdate->total_discounts : $orderDiscout;
$deliveryCost = $orderToUpdate->total_shipping;
if(!empty($order['delivery']['cost'])) {
$deliveryCost = $order['delivery']['cost'];
}
$totalPaid = $deliveryCost + $orderTotalProducts;
if ($totalDiscount != $orderToUpdate->total_discounts ||
$orderTotalProducts != $orderToUpdate->total_products_wt ||
$deliveryCost != $orderToUpdate->total_shipping
) {
Db::getInstance()->execute(' Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'orders` UPDATE `'._DB_PREFIX_.'orders`
SET `total_discounts` = '.$totalDiscount.', SET `total_discounts` = '.$totalDiscount.',
@ -515,10 +535,11 @@ if ($history->isSuccessful() && count($history->history) > 0) {
`total_products_wt` = '.$orderTotalProducts.' `total_products_wt` = '.$orderTotalProducts.'
WHERE `id_order` = '.(int) $order['externalId'] WHERE `id_order` = '.(int) $order['externalId']
); );
}
}
}
unset($ItemDiscount);
}
}
}
/* /*
* Update last sync timestamp * Update last sync timestamp
*/ */

View File

@ -15,6 +15,7 @@ class RetailcrmCatalog
$id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
$shop_url = (Configuration::get('PS_SSL_ENABLED') ? _PS_BASE_URL_SSL_ : _PS_BASE_URL_); $shop_url = (Configuration::get('PS_SSL_ENABLED') ? _PS_BASE_URL_SSL_ : _PS_BASE_URL_);
$protocol = (Configuration::get('PS_SSL_ENABLED')) ? "https://" : "http://";
$items = array(); $items = array();
$categories = array(); $categories = array();
@ -128,7 +129,7 @@ class RetailcrmCatalog
$pictures = array(); $pictures = array();
$covers = Image::getImages($id_lang, $product['id_product'], $offer['id_product_attribute']); $covers = Image::getImages($id_lang, $product['id_product'], $offer['id_product_attribute']);
foreach($covers as $cover) { foreach($covers as $cover) {
$picture = 'http://' . $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $cover['id_image'], 'large_default'); $picture = $protocol . $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $cover['id_image'], 'large_default');
$pictures[] = $picture; $pictures[] = $picture;
} }
@ -171,7 +172,7 @@ class RetailcrmCatalog
$pictures = array(); $pictures = array();
$covers = Image::getImages($id_lang, $product['id_product'], null); $covers = Image::getImages($id_lang, $product['id_product'], null);
foreach($covers as $cover) { foreach($covers as $cover) {
$picture = 'http://' . $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $cover['id_image'], 'large_default'); $picture = $protocol . $link->getImageLink($product['link_rewrite'], $product['id_product'] . '-' . $cover['id_image'], 'large_default');
$pictures[] = $picture; $pictures[] = $picture;
} }

View File

@ -7,13 +7,7 @@ class RetailcrmReferences
{ {
$this->api = $client; $this->api = $client;
$this->default_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $this->default_lang = (int) Configuration::get('PS_LANG_DEFAULT');
} $this->carriers = Carrier::getCarriers(
public function getDeliveryTypes()
{
$deliveryTypes = array();
$carriers = Carrier::getCarriers(
$this->default_lang, $this->default_lang,
true, true,
false, false,
@ -21,9 +15,14 @@ class RetailcrmReferences
null, null,
PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
); );
}
if (!empty($carriers)) { public function getDeliveryTypes()
foreach ($carriers as $carrier) { {
$deliveryTypes = array();
if (!empty($this->carriers)) {
foreach ($this->carriers as $carrier) {
$deliveryTypes[] = array( $deliveryTypes[] = array(
'type' => 'select', 'type' => 'select',
'label' => $carrier['name'], 'label' => $carrier['name'],
@ -105,6 +104,69 @@ class RetailcrmReferences
return $paymentTypes; return $paymentTypes;
} }
public function getPaymentAndDeliveryForDefault()
{
$paymentTypes = array();
$deliveryTypes = array();
$paymentDeliveryTypes = array();
if (!empty($this->carriers)) {
$deliveryTypes[] = array(
'id_option' => '',
'name' => '',
);
foreach ($this->carriers as $valCarrier) {
$deliveryTypes[] = array(
'id_option' => $valCarrier['id_carrier'],
'name' => $valCarrier['name'],
);
}
$paymentDeliveryTypes[] = array(
'type' => 'select',
'label' => "Доставка",
'name' => 'RETAILCRM_API_DELIVERY_DEFAULT',
'required' => false,
'options' => array(
'query' => $deliveryTypes,
'id' => 'id_option',
'name' => 'name'
)
);
}
if (!empty($this->getSystemPaymentModules())) {
$paymentTypes[] = array(
'id_option' => '',
'name' => '',
);
foreach ($this->getSystemPaymentModules() as $valPayment) {
$paymentTypes[$valPayment['id']] = array(
'id_option' => $valPayment['code'],
'name' => $valPayment['name'],
);
}
$paymentDeliveryTypes[] = array(
'type' => 'select',
'label' => "Система оплаты",
'name' => 'RETAILCRM_API_PAYMENT_DEFAULT',
'required' => false,
'options' => array(
'query' => $paymentTypes,
'id' => 'id_option',
'name' => 'name'
)
);
}
return $paymentDeliveryTypes;
}
protected function getSystemPaymentModules() protected function getSystemPaymentModules()
{ {
$shop_id = Context::getContext()->shop->id; $shop_id = Context::getContext()->shop->id;

View File

@ -80,6 +80,8 @@ class RetailCRM extends Module
$delivery = json_encode(Tools::getValue('RETAILCRM_API_DELIVERY')); $delivery = json_encode(Tools::getValue('RETAILCRM_API_DELIVERY'));
$status = json_encode(Tools::getValue('RETAILCRM_API_STATUS')); $status = json_encode(Tools::getValue('RETAILCRM_API_STATUS'));
$payment = json_encode(Tools::getValue('RETAILCRM_API_PAYMENT')); $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'));
if (!$this->validateCrmAddress($address) || !Validate::isGenericName($address)) { if (!$this->validateCrmAddress($address) || !Validate::isGenericName($address)) {
$output .= $this->displayError($this->l('Invalid crm address')); $output .= $this->displayError($this->l('Invalid crm address'));
@ -91,6 +93,9 @@ class RetailCRM extends Module
Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery); Configuration::updateValue('RETAILCRM_API_DELIVERY', $delivery);
Configuration::updateValue('RETAILCRM_API_STATUS', $status); Configuration::updateValue('RETAILCRM_API_STATUS', $status);
Configuration::updateValue('RETAILCRM_API_PAYMENT', $payment); Configuration::updateValue('RETAILCRM_API_PAYMENT', $payment);
Configuration::updateValue('RETAILCRM_API_DELIVERY_DEFAULT', $deliveryDefault);
Configuration::updateValue('RETAILCRM_API_PAYMENT_DEFAULT', $paymentDefault);
$output .= $this->displayConfirmation($this->l('Settings updated')); $output .= $this->displayConfirmation($this->l('Settings updated'));
$this->apiUrl = $address; $this->apiUrl = $address;
@ -177,6 +182,14 @@ class RetailCRM extends Module
'legend' => array('title' => $this->l('Payment types')), 'legend' => array('title' => $this->l('Payment types')),
'input' => $this->reference->getPaymentTypes(), 'input' => $this->reference->getPaymentTypes(),
); );
/*
* Default
*/
$fields_form[4]['form'] = array(
'legend' => array('title' => 'По умолчанию'),
'input' => $this->reference->getPaymentAndDeliveryForDefault(),
);
} }
/* /*
@ -251,6 +264,24 @@ class RetailCRM extends Module
} }
} }
$paymentSettingsDefault = Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT');
if (isset($paymentSettingsDefault) && $paymentSettingsDefault != '') {
$paymentTypesDefault = json_decode($paymentSettingsDefault);
if ($paymentTypesDefault) {
$name = 'RETAILCRM_API_PAYMENT_DEFAULT';
$helper->fields_value[$name] = $paymentTypesDefault;
}
}
$deliverySettingsDefault = Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT');
if (isset($deliverySettingsDefault) && $deliverySettingsDefault != '') {
$deliveryTypesDefault = json_decode($deliverySettingsDefault);
if ($deliveryTypesDefault) {
$name = 'RETAILCRM_API_DELIVERY_DEFAULT';
$helper->fields_value[$name] = $deliveryTypesDefault;
}
}
return $helper->generateForm($fields_form); return $helper->generateForm($fields_form);
} }
@ -367,8 +398,7 @@ class RetailCRM extends Module
$order['items'][] = array( $order['items'][] = array(
'initialPrice' => !empty($item['rate']) 'initialPrice' => !empty($item['rate'])
? $item['price'] + ($item['price'] * $item['rate'] / 100) ? $item['price'] + ($item['price'] * $item['rate'] / 100)
: $item['price'] : $item['price'],
,
'quantity' => $item['quantity'], 'quantity' => $item['quantity'],
'offer' => array('externalId' => $productId), 'offer' => array('externalId' => $productId),
'productName' => $item['name'], 'productName' => $item['name'],
@ -413,6 +443,24 @@ class RetailCRM extends Module
$order['customer']['externalId'] = $customer['externalId']; $order['customer']['externalId'] = $customer['externalId'];
$this->api->ordersCreate($order); $this->api->ordersCreate($order);
} elseif (isset($params['newOrderStatus'])){
$statusCode = $params['newOrderStatus']->id;
if (array_key_exists($statusCode, $status) && !empty($status[$statusCode])) {
$orderStatus = $status[$statusCode];
}
if (isset($orderStatus)) {
$this->api->ordersEdit(
array(
'externalId' => $params['id_order'],
'status' => $orderStatus
)
);
}
} }
} }