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)));
$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);
@ -46,6 +48,56 @@ if ($history->isSuccessful() && count($history->history) > 0) {
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] != '') {
$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();
if(!empty($order['customer']['email']))
$customer->getByEmail($order['customer']['email']);
@ -82,35 +134,13 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$address->phone = $order['phone'];
$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->id_currency = $default_currency;
$cart->id_lang = $default_lang;
$cart->id_customer = $customer->id;
$cart->id_address_delivery = (int) $address->id;
$cart->id_address_invoice = (int) $address->id;
$cart->id_carrier = (int) $deliveries[$delivery];
$cart->id_carrier = (int) $deliveryType;
$cart->add();
@ -137,8 +167,8 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/
$newOrder = new Order();
$shops = Shop::getShops();
$newOrder->id_shop = Shop::getCurrentShop();
$newOrder->id_shop_group = (int)$shops[Shop::getCurrentShop()]['id_shop_group'];
$newOrder->id_shop = Context::getContext()->shop->id;
$newOrder->id_shop_group = (int)$shops[Context::getContext()->shop->id]['id_shop_group'];
$newOrder->id_address_delivery = (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($paymentType)) {
$newOrder->payment = $paymentType;
$newOrder->module = $payments[$payment];
$newOrder->module = $paymentId;
}
$newOrder->total_paid = $order['summ'] + $order['delivery']['cost'];
$newOrder->total_paid_tax_incl = $order['summ'] + $order['delivery']['cost'];
@ -272,7 +302,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
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`)
INSERT INTO `' . _DB_PREFIX_ . 'order_history` (`id_employee`, `id_order`, `id_order_state`, `date_add`)
VALUES (
0,
' . $orderToUpdate->id . ',
@ -319,7 +349,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
$updateCarrierFields = implode(', ', $updateCarrierFields);
Db::getInstance()->execute('
UPDATE `' . _DB_PREFIX_ . 'order_carrier` SET
UPDATE `' . _DB_PREFIX_ . 'order_carrier` SET
'.$updateCarrierFields.'
WHERE `id_order` = \'' . $orderToUpdate->id . '\''
);
@ -354,13 +384,13 @@ if ($history->isSuccessful() && count($history->history) > 0) {
* Clean deleted items
*/
foreach ($order['items'] as $key => $item) {
if (isset($item['deleted']) && $item['deleted'] == true) {
if(strpos($item['id'], '#') !== false) {
$itemId = explode('#', $item['id']);
if (isset($item['delete']) && $item['delete'] == true) {
if(strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0];
$product_attribute_id = $itemId[1];
} else {
$product_id = $item['id'];
$product_id = $item['offer']['externalId'];
$product_attribute_id = 0;
}
@ -372,6 +402,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
);
unset($order['items'][$key]);
$ItemDiscount = true
}
}
@ -380,6 +411,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
*/
foreach ($orderToUpdate->getProductsDetail() as $orderItem) {
foreach ($order['items'] as $key => $item) {
if (isset($item['discount']) || isset($item['discountPercent'])) $ItemDiscount = true;
if(strpos($item['offer']['externalId'], '#') !== false) {
$itemId = explode('#', $item['offer']['externalId']);
$product_id = $itemId[0];
@ -419,6 +451,7 @@ if ($history->isSuccessful() && count($history->history) > 0) {
VALUES';
foreach ($order['items'] as $key => $newItem) {
if ($newItem['discount'] || $newItem['discountPercent']) $ItemDiscount = true;
$product_id = $newItem['offer']['externalId'];
$product_attribute_id = 0;
if(strpos($product_id, '#') !== false) {
@ -468,39 +501,26 @@ if ($history->isSuccessful() && count($history->history) > 0) {
* Fix prices & discounts
* Discounts only for whole order
*/
$orderDiscout = null;
$orderTotalProducts = 0;
foreach($orderToUpdate->getProductsDetail() as $orderItem) {
$orderTotalProducts += $orderItem['total_price_tax_incl'];
}
$orderTotalProducts = round($orderTotalProducts, 2);
if (isset($order['discount']) ||
isset($order['discountPercent']) ||
isset($order['delivery']['cost']) ||
$ItemDiscount) {
if (isset($order['discount']) && $order['discount'] > 0) {
if ($order['discount'] != $orderToUpdate->total_discounts) {
$orderDiscout = ($orderDiscout == null) ? $order['discount'] : $order['discount'] + $orderDiscout;
$infoOrd = $api->ordersGet($order['externalId']);
$infoOrder = $infoOrd->order;
$orderTotalProducts = $infoOrder['summ'];
$totalPaid = $infoOrder['totalSumm'];
$deliveryCost = $infoOrder['delivery']['cost'];
$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();
if (isset($order['discountPercent']) && $order['discountPercent'] > 0) {
$percent = ($order['summ'] * $order['discountPercent'])/100;
if ($percent != $orderToUpdate->total_discounts) {
$orderDiscout = ($orderDiscout == null) ? $percent : $percent + $orderDiscout;
}
}
$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('
UPDATE `'._DB_PREFIX_.'orders`
SET `total_discounts` = '.$totalDiscount.',
@ -515,10 +535,11 @@ if ($history->isSuccessful() && count($history->history) > 0) {
`total_products_wt` = '.$orderTotalProducts.'
WHERE `id_order` = '.(int) $order['externalId']
);
unset($ItemDiscount);
}
}
}
/*
* Update last sync timestamp
*/

View File

@ -15,6 +15,7 @@ class RetailcrmCatalog
$id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
$shop_url = (Configuration::get('PS_SSL_ENABLED') ? _PS_BASE_URL_SSL_ : _PS_BASE_URL_);
$protocol = (Configuration::get('PS_SSL_ENABLED')) ? "https://" : "http://";
$items = array();
$categories = array();
@ -128,7 +129,7 @@ class RetailcrmCatalog
$pictures = array();
$covers = Image::getImages($id_lang, $product['id_product'], $offer['id_product_attribute']);
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;
}
@ -171,7 +172,7 @@ class RetailcrmCatalog
$pictures = array();
$covers = Image::getImages($id_lang, $product['id_product'], null);
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;
}

View File

@ -7,13 +7,7 @@ class RetailcrmReferences
{
$this->api = $client;
$this->default_lang = (int) Configuration::get('PS_LANG_DEFAULT');
}
public function getDeliveryTypes()
{
$deliveryTypes = array();
$carriers = Carrier::getCarriers(
$this->carriers = Carrier::getCarriers(
$this->default_lang,
true,
false,
@ -21,9 +15,14 @@ class RetailcrmReferences
null,
PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
);
}
if (!empty($carriers)) {
foreach ($carriers as $carrier) {
public function getDeliveryTypes()
{
$deliveryTypes = array();
if (!empty($this->carriers)) {
foreach ($this->carriers as $carrier) {
$deliveryTypes[] = array(
'type' => 'select',
'label' => $carrier['name'],
@ -105,6 +104,69 @@ class RetailcrmReferences
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()
{
$shop_id = Context::getContext()->shop->id;

View File

@ -80,6 +80,8 @@ class RetailCRM extends Module
$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'));
if (!$this->validateCrmAddress($address) || !Validate::isGenericName($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_STATUS', $status);
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'));
$this->apiUrl = $address;
@ -177,6 +182,14 @@ class RetailCRM extends Module
'legend' => array('title' => $this->l('Payment types')),
'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);
}
@ -363,12 +394,11 @@ class RetailCRM extends Module
}
}
$order['items'][] = array(
'initialPrice' => !empty($item['rate'])
? $item['price'] + ($item['price'] * $item['rate'] / 100)
: $item['price']
,
: $item['price'],
'quantity' => $item['quantity'],
'offer' => array('externalId' => $productId),
'productName' => $item['name'],
@ -413,6 +443,24 @@ class RetailCRM extends Module
$order['customer']['externalId'] = $customer['externalId'];
$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
)
);
}
}
}