Fix mixed payments

This commit is contained in:
max-baranikov 2021-10-12 14:35:29 +03:00 committed by GitHub
parent 273efdaab0
commit 35bccc98b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 187 additions and 159 deletions

View File

@ -182,13 +182,8 @@ class RetailcrmHistory
*/ */
public static function ordersHistory() public static function ordersHistory()
{ {
$default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
$lastSync = Configuration::get('RETAILCRM_LAST_ORDERS_SYNC'); $lastSync = Configuration::get('RETAILCRM_LAST_ORDERS_SYNC');
$lastDate = Configuration::get('RETAILCRM_LAST_SYNC'); $lastDate = Configuration::get('RETAILCRM_LAST_SYNC');
$references = new RetailcrmReferences(self::$api);
$receiveOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING));
$sendOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING));
if ($lastSync === false && $lastDate === false) { if ($lastSync === false && $lastDate === false) {
$filter = array( $filter = array(
@ -228,6 +223,10 @@ class RetailcrmHistory
} }
if (count($historyChanges)) { if (count($historyChanges)) {
$default_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
$references = new RetailcrmReferences(self::$api);
$receiveOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_RECEIVING));
$sendOrderNumber = (bool)(Configuration::get(RetailCRM::ENABLE_ORDER_NUMBER_SENDING));
$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)));
$cartStatus = (string)(Configuration::get('RETAILCRM_API_SYNCHRONIZED_CART_STATUS')); $cartStatus = (string)(Configuration::get('RETAILCRM_API_SYNCHRONIZED_CART_STATUS'));
$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)));
@ -235,6 +234,11 @@ class RetailcrmHistory
$deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true); $deliveryDefault = json_decode(Configuration::get('RETAILCRM_API_DELIVERY_DEFAULT'), true);
$paymentDefault = json_decode(Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT'), true); $paymentDefault = json_decode(Configuration::get('RETAILCRM_API_PAYMENT_DEFAULT'), true);
$paymentsCMS = [];
foreach ($references->getSystemPaymentModules() as $paymentCMS) {
$paymentsCMS[$paymentCMS['code']] = $paymentCMS['name'];
}
$orders = RetailcrmHistoryHelper::assemblyOrder($historyChanges); $orders = RetailcrmHistoryHelper::assemblyOrder($historyChanges);
RetailcrmLogger::writeDebugArray(__METHOD__, array('Assembled history:', $orders)); RetailcrmLogger::writeDebugArray(__METHOD__, array('Assembled history:', $orders));
@ -271,54 +275,58 @@ class RetailcrmHistory
} }
// payment // payment
$paymentTypeCRM = null;
$paymentId = null;
$paymentType = null;
if (isset($order['payments'])) { if (isset($order['payments'])) {
if (count($order['payments']) == 1) { if (count($order['payments']) === 1) {
$paymentCRM = end($order['payments']); $paymentCRM = end($order['payments']);
$payment = $paymentCRM['type']; $paymentTypeCRM = $paymentCRM['type'];
} elseif (count($order['payments']) > 1) { } elseif (count($order['payments']) > 1) {
foreach ($order['payments'] as $paymentCRM) { foreach ($order['payments'] as $paymentCRM) {
if (isset($paymentCRM['status']) && $paymentCRM['status'] != 'paid') { if (isset($paymentCRM['status']) && $paymentCRM['status'] !== 'paid') {
$payment = $paymentCRM['type']; $paymentTypeCRM = $paymentCRM['type'];
break; break;
} }
} }
} }
} }
unset($paymentCRM);
$crmPaymentType = isset($payment) ? $payment : null; // todo move to separate function
if (!is_null($crmPaymentType) && if ($paymentTypeCRM) {
array_key_exists($crmPaymentType, $payments) && !empty($payments[$crmPaymentType])) { if (array_key_exists($paymentTypeCRM, $payments) && !empty($payments[$paymentTypeCRM])) {
if (Module::getInstanceByName($payments[$crmPaymentType])) { $paymentId = $payments[$paymentTypeCRM];
$paymentType = Module::getModuleName($payments[$crmPaymentType]);
} else {
$paymentType = $payments[$crmPaymentType];
}
$paymentId = $payments[$crmPaymentType];
}
if ($paymentDefault && (!isset($paymentId) || !$paymentId)) {
$paymentId = $paymentDefault;
}
if (!isset($paymentType) || !$paymentType) {
if ($paymentDefault) {
if (Module::getInstanceByName($paymentDefault)) {
$paymentType = Module::getModuleName($paymentDefault);
} else {
$paymentType = $paymentDefault;
}
} else { } else {
RetailcrmLogger::writeCaller( RetailcrmLogger::writeCaller(
'orderHistory', __METHOD__,
sprintf( sprintf(
'set default payment(error in order where id = %d)', 'unmapped payment type %s (error in order where id = %d)',
$paymentTypeCRM,
$order['id'] $order['id']
) )
); );
continue; continue;
} }
} elseif ($paymentDefault) {
$paymentId = $paymentDefault;
} else {
RetailcrmLogger::writeCaller(
__METHOD__,
sprintf(
'set default payment (error in order where id = %d)',
$order['id']
)
);
continue;
}
if ($paymentId && isset($paymentsCMS[$paymentId])) {
$paymentType = $paymentsCMS[$paymentId];
} else {
$paymentType = $paymentId;
} }
// delivery // delivery
@ -332,7 +340,7 @@ class RetailcrmHistory
$deliveryType = $deliveryDefault; $deliveryType = $deliveryDefault;
} else { } else {
RetailcrmLogger::writeCaller( RetailcrmLogger::writeCaller(
'orderHistory', __METHOD__,
sprintf( sprintf(
'set default delivery(error in order where id = %d)', 'set default delivery(error in order where id = %d)',
$order['id'] $order['id']
@ -346,7 +354,7 @@ class RetailcrmHistory
$customer = null; $customer = null;
$customerId = null; $customerId = null;
if ($order['customer']['type'] == 'customer_corporate' if ($order['customer']['type'] === 'customer_corporate'
&& RetailcrmTools::isCorporateEnabled() && RetailcrmTools::isCorporateEnabled()
&& !empty($order['contact']) && !empty($order['contact'])
&& array_key_exists('externalId', $order['contact']) && array_key_exists('externalId', $order['contact'])
@ -594,37 +602,44 @@ class RetailcrmHistory
foreach ($order['payments'] as $payment) { foreach ($order['payments'] as $payment) {
if (!isset($payment['externalId']) if (!isset($payment['externalId'])
&& isset($payment['status']) && isset($payment['status'])
&& $payment['status'] == 'paid' && $payment['status'] === 'paid'
) { ) {
$ptype = $payment['type']; $paymentTypeCRM = isset($payment['type']) ? $payment['type'] : null;
$ptypes = $references->getSystemPaymentModules(); $paymentType = null;
$paymentId = null;
if ($payments[$ptype] != null) { if ($paymentTypeCRM) {
foreach ($ptypes as $pay) { if (array_key_exists($paymentTypeCRM, $payments) && !empty($payments[$paymentTypeCRM])) {
if ($pay['code'] == $payments[$ptype]) { $paymentId = $payments[$paymentTypeCRM];
$payType = $pay['name']; } else {
} continue;
} }
} elseif ($paymentDefault) {
$orderPayment = new OrderPayment(); $paymentId = $paymentDefault;
$orderPayment->payment_method = $payType; } else {
$orderPayment->order_reference = $newOrder->reference; continue;
$orderPayment->id_currency = $default_currency;
$orderPayment->amount = $payment['amount'];
$orderPayment->date_add = $payment['paidAt'];
RetailcrmLogger::writeDebug(
__METHOD__,
sprintf(
'<Order Reference: %s> %s::%s',
$newOrder->reference,
get_class($orderPayment),
'save'
)
);
$orderPayment->save();
} }
$paymentType = isset($paymentsCMS[$paymentId]) ? $paymentsCMS[$paymentId] : $paymentId;
$orderPayment = new OrderPayment();
$orderPayment->payment_method = $paymentType;
$orderPayment->order_reference = $newOrder->reference;
$orderPayment->id_currency = $default_currency;
$orderPayment->amount = $payment['amount'];
$orderPayment->date_add = $payment['paidAt'];
RetailcrmLogger::writeDebug(
__METHOD__,
sprintf(
'<Order Reference: %s> %s::%s',
$newOrder->reference,
get_class($orderPayment),
'save'
)
);
$orderPayment->save();
} }
} }
} }
@ -709,17 +724,17 @@ class RetailcrmHistory
} }
// collect order ids for single fix request // collect order ids for single fix request
array_push($orderFix, array('id' => $order['id'], 'externalId' => $newOrder->id)); $orderFix[] = array('id' => $order['id'], 'externalId' => $newOrder->id);
// update order items ids in crm // update order items ids in crm
$newItemsIdsByOrderId[$newOrder->id] = $newItemsIds; $newItemsIdsByOrderId[$newOrder->id] = $newItemsIds;
// collect orders id and reference if option sendOrderNumber enabled // collect orders id and reference if option sendOrderNumber enabled
if ($sendOrderNumber) { if ($sendOrderNumber) {
array_push($updateOrderIds, array( $updateOrderIds[] = array(
'externalId' => $newOrder->id, 'externalId' => $newOrder->id,
'number' => $newOrder->reference, 'number' => $newOrder->reference,
)); );
} }
} else { } else {
$order = $order_history; $order = $order_history;
@ -839,12 +854,14 @@ class RetailcrmHistory
$dtype = !empty($order['delivery']['code']) ? $order['delivery']['code'] : null; $dtype = !empty($order['delivery']['code']) ? $order['delivery']['code'] : null;
$dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null; $dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null;
if ($dtype != null && ( if (
(
$dtype !== null &&
isset($deliveries[$dtype]) isset($deliveries[$dtype])
&& $deliveries[$dtype] != null && $deliveries[$dtype] !== null
&& $deliveries[$dtype] != $orderToUpdate->id_carrier && $deliveries[$dtype] !== $orderToUpdate->id_carrier
) )
|| $dcost != null || $dcost !== null
) { ) {
if (property_exists($orderToUpdate, 'id_order_carrier')) { if (property_exists($orderToUpdate, 'id_order_carrier')) {
$idOrderCarrier = $orderToUpdate->id_order_carrier; $idOrderCarrier = $orderToUpdate->id_order_carrier;
@ -878,46 +895,52 @@ class RetailcrmHistory
foreach ($order['payments'] as $payment) { foreach ($order['payments'] as $payment) {
if (!isset($payment['externalId']) if (!isset($payment['externalId'])
&& isset($payment['status']) && isset($payment['status'])
&& $payment['status'] == 'paid' && $payment['status'] === 'paid'
) { ) {
$ptype = $payment['type']; $paymentTypeCRM = isset($payment['type']) ? $payment['type'] : null;
$ptypes = $references->getSystemPaymentModules(); $paymentType = null;
$paymentId = null;
if ($payments[$ptype] != null) { if ($paymentTypeCRM) {
foreach ($ptypes as $pay) { if (array_key_exists($paymentTypeCRM, $payments) && !empty($payments[$paymentTypeCRM])) {
if ($pay['code'] == $payments[$ptype]) { $paymentId = $payments[$paymentTypeCRM];
$payType = $pay['name'];
}
}
$paymentType = Module::getModuleName($payments[$ptype]);
$orderToUpdate->payment = $paymentType != null ? $paymentType : $payments[$ptype];
$orderPayment = new OrderPayment();
$orderPayment->payment_method = $payType;
$orderPayment->order_reference = $orderToUpdate->reference;
if (isset($payment['amount'])) {
$orderPayment->amount = $payment['amount'];
} else { } else {
$orderPayment->amount = $orderToUpdate->total_paid; continue;
} }
} elseif ($paymentDefault) {
$orderPayment->id_currency = $default_currency; $paymentId = $paymentDefault;
$orderPayment->date_add = } else {
isset($payment['paidAt']) ? $payment['paidAt'] : date('Y-m-d H:i:s'); continue;
RetailcrmLogger::writeDebug(
__METHOD__,
sprintf(
'<Order Reference: %s> %s::%s',
$orderToUpdate->reference,
get_class($orderPayment),
'save'
)
);
$orderPayment->save();
} }
$paymentType = isset($paymentsCMS[$paymentId]) ? $paymentsCMS[$paymentId] : $paymentId;
$orderToUpdate->payment = $paymentType;
$orderPayment = new OrderPayment();
$orderPayment->payment_method = $paymentType;
$orderPayment->order_reference = $orderToUpdate->reference;
if (isset($payment['amount'])) {
$orderPayment->amount = $payment['amount'];
} else {
$orderPayment->amount = $orderToUpdate->total_paid;
}
$orderPayment->id_currency = $default_currency;
$orderPayment->date_add =
isset($payment['paidAt']) ? $payment['paidAt'] : date('Y-m-d H:i:s');
RetailcrmLogger::writeDebug(
__METHOD__,
sprintf(
'<Order Reference: %s> %s::%s',
$orderToUpdate->reference,
get_class($orderPayment),
'save'
)
);
$orderPayment->save();
} }
} }
} }
@ -1139,10 +1162,10 @@ class RetailcrmHistory
// collect orders id and reference if option sendOrderNumber enabled // collect orders id and reference if option sendOrderNumber enabled
if ($sendOrderNumber) { if ($sendOrderNumber) {
array_push($updateOrderIds, array( $updateOrderIds[] = array(
'externalId' => $orderToUpdate->id, 'externalId' => $orderToUpdate->id,
'number' => $orderToUpdate->reference, 'number' => $orderToUpdate->reference,
)); );
} }
} }
} }
@ -1357,13 +1380,15 @@ class RetailcrmHistory
WHERE id_order = ' . pSQL((int)$order_id) . ' WHERE id_order = ' . pSQL((int)$order_id) . '
AND product_id = ' . pSQL((int)$product_id) . ' AND product_id = ' . pSQL((int)$product_id) . '
AND product_attribute_id = ' . pSQL((int)$product_attribute_id) . ' AND product_attribute_id = ' . pSQL((int)$product_attribute_id) . '
AND id_order_detail = ' . pSQL((int)$id_order_detail)); AND id_order_detail = ' . pSQL((int)$id_order_detail)
);
} }
private static function getNewOrderDetailId() private static function getNewOrderDetailId()
{ {
return Db::getInstance()->getRow(' return Db::getInstance()->getRow('
SELECT MAX(id_order_detail) FROM ' . _DB_PREFIX_ . 'order_detail'); SELECT MAX(id_order_detail) FROM ' . _DB_PREFIX_ . 'order_detail'
);
} }
/** /**

View File

@ -753,7 +753,7 @@ class RetailcrmTools
foreach ($checkMapping as $field) { foreach ($checkMapping as $field) {
if ($first->$field != $second->$field) { if ($first->$field != $second->$field) {
RetailcrmLogger::writeDebug(__METHOD__, print_r(array( RetailcrmLogger::writeDebug(__METHOD__, json_encode(array(
'first' => array( 'first' => array(
'id' => $first->id, 'id' => $first->id,
$field => $first->$field $field => $first->$field
@ -762,7 +762,7 @@ class RetailcrmTools
'id' => $second->id, 'id' => $second->id,
$field => $second->$field $field => $second->$field
), ),
), true)); )));
return false; return false;
} }

View File

@ -386,7 +386,7 @@ class RetailCRM extends Module
if (empty($existingOrder)) { if (empty($existingOrder)) {
$response = $this->api->ordersCreate($crmOrder); $response = $this->api->ordersCreate($crmOrder);
if ($response->isSuccessful() && $receiveOrderNumber) { if ($response instanceof RetailcrmApiResponse && $response->isSuccessful() && $receiveOrderNumber) {
$crmOrder = $response->order; $crmOrder = $response->order;
$object->reference = $crmOrder['number']; $object->reference = $crmOrder['number'];
$object->update(); $object->update();
@ -862,7 +862,7 @@ class RetailCRM extends Module
} else { } else {
$response = $this->api->ordersCreate($order); $response = $this->api->ordersCreate($order);
if ($response->isSuccessful() && $receiveOrderNumber) { if ($response instanceof RetailcrmApiResponse && $response->isSuccessful() && $receiveOrderNumber) {
$crmOrder = $response->order; $crmOrder = $response->order;
$cmsOrder->reference = $crmOrder['number']; $cmsOrder->reference = $crmOrder['number'];
$cmsOrder->update(); $cmsOrder->update();
@ -894,28 +894,22 @@ class RetailCRM extends Module
public function hookActionPaymentCCAdd($params) public function hookActionPaymentCCAdd($params)
{ {
$payments = $this->reference->getSystemPaymentModules(); $payments = array_filter(json_decode(Configuration::get(static::PAYMENT), true));
$paymentCRM = json_decode(Configuration::get(static::PAYMENT), true); $paymentType = false;
$payment = ""; $externalId = false;
$payCode = "";
foreach ($payments as $valPay) { foreach ($this->reference->getSystemPaymentModules() as $paymentCMS) {
if ($valPay['name'] == $params['paymentCC']->payment_method) { if (
$payCode = $valPay['code']; $paymentCMS['name'] === $params['paymentCC']->payment_method
&& array_key_exists($paymentCMS['code'], $payments)
&& !empty($payments[$paymentCMS['code']])
) {
$paymentType = $payments[$paymentCMS['code']];
break;
} }
} }
if (!empty($payCode) && array_key_exists($payCode, $paymentCRM) && !empty($paymentCRM[$payCode])) { if (!$paymentType || empty($params['cart']) || empty((int) $params['cart']->id)) {
$payment = $paymentCRM[$payCode];
}
if (empty($payment)) {
return false;
}
$externalId = false;
if (empty($params['cart']) || empty((int) $params['cart']->id)) {
return false; return false;
} }
@ -925,12 +919,20 @@ class RetailCRM extends Module
$externalId = RetailcrmTools::getCartOrderExternalId($params['cart']); $externalId = RetailcrmTools::getCartOrderExternalId($params['cart']);
} else { } else {
if (version_compare(_PS_VERSION_, '1.7.1.0', '>=')) { if (version_compare(_PS_VERSION_, '1.7.1.0', '>=')) {
$id_order = (int)Order::getIdByCartId((int)$params['cart']->id); $id_order = (int) Order::getIdByCartId((int) $params['cart']->id);
} else { } else {
$id_order = (int)Order::getOrderByCartId((int)$params['cart']->id); $id_order = (int) Order::getOrderByCartId((int) $params['cart']->id);
} }
if ($id_order > 0) { if ($id_order > 0) {
// do not update payment if the order in Cart and OrderPayment aren't the same
if ($params['paymentCC']->order_reference) {
$order = Order::getByReference($params['paymentCC']->order_reference)->getFirst();
if (!$order || $order->id !== $id_order) {
return false;
}
}
$response = $this->api->ordersGet($id_order); $response = $this->api->ordersGet($id_order);
if ($response !== false && isset($response['order'])) { if ($response !== false && isset($response['order'])) {
$externalId = $id_order; $externalId = $id_order;
@ -938,38 +940,39 @@ class RetailCRM extends Module
} }
} }
if ($externalId === false) {
return false;
}
$status = (round($params['paymentCC']->amount, 2) > 0 ? 'paid' : null); $status = (round($params['paymentCC']->amount, 2) > 0 ? 'paid' : null);
$orderCRM = $response['order'];
if ($externalId !== false) { if ($orderCRM && $orderCRM['payments']) {
$orderCRM = $response['order']; foreach ($orderCRM['payments'] as $orderPayment) {
if ($orderPayment['type'] === $paymentType) {
if ($orderCRM && $orderCRM['payments']) { $updatePayment = $orderPayment;
foreach ($orderCRM['payments'] as $orderPayment) { $updatePayment['amount'] = $params['paymentCC']->amount;
if ($orderPayment['type'] == $payment) { $updatePayment['paidAt'] = $params['paymentCC']->date_add;
$updatePayment = $orderPayment; $updatePayment['status'] = $status;
$updatePayment['amount'] = $params['paymentCC']->amount;
$updatePayment['paidAt'] = $params['paymentCC']->date_add;
$updatePayment['status'] = $status;
}
} }
} }
}
if (isset($updatePayment)) { if (isset($updatePayment)) {
$this->api->ordersPaymentEdit($updatePayment, 'id'); $this->api->ordersPaymentEdit($updatePayment, 'id');
} else { } else {
$createPayment = array( $createPayment = array(
'externalId' => $params['paymentCC']->id, 'externalId' => $params['paymentCC']->id,
'amount' => $params['paymentCC']->amount, 'amount' => $params['paymentCC']->amount,
'paidAt' => $params['paymentCC']->date_add, 'paidAt' => $params['paymentCC']->date_add,
'type' => $payment, 'type' => $paymentType,
'status' => $status, 'status' => $status,
'order' => array( 'order' => array(
'externalId' => $externalId, 'externalId' => $externalId,
), ),
); );
$this->api->ordersPaymentCreate($createPayment); $this->api->ordersPaymentCreate($createPayment);
}
} }
return true; return true;