From d91ba6d4c22b6c9c9316885a8e0b18f9d386e6bc Mon Sep 17 00:00:00 2001 From: max-baranikov Date: Fri, 17 Sep 2021 14:05:42 +0300 Subject: [PATCH] Improved work with order addresses in history methods --- retailcrm/lib/RetailcrmAddressBuilder.php | 16 +++ .../lib/RetailcrmCustomerAddressBuilder.php | 61 +++++---- retailcrm/lib/RetailcrmHistory.php | 128 +++++++++++------- retailcrm/lib/RetailcrmHistoryHelper.php | 6 + retailcrm/lib/RetailcrmTools.php | 14 +- retailcrm/objects.xml | 2 +- retailcrm/retailcrm.php | 7 +- retailcrm/views/templates/admin/settings.tpl | 6 +- 8 files changed, 154 insertions(+), 86 deletions(-) diff --git a/retailcrm/lib/RetailcrmAddressBuilder.php b/retailcrm/lib/RetailcrmAddressBuilder.php index 5308e24..0b401ba 100644 --- a/retailcrm/lib/RetailcrmAddressBuilder.php +++ b/retailcrm/lib/RetailcrmAddressBuilder.php @@ -185,6 +185,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder case static::MODE_ORDER_DELIVERY: $this->buildOrderAddress(); $this->buildOrderPhones(); + $this->buildOrderNames(); break; default: throw new \InvalidArgumentException("Incorrect builder mode"); @@ -254,6 +255,7 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder $this->address->address1, $this->address->address2, ])), + 'notes' => $this->address->other, 'region' => $state )); } @@ -290,6 +292,20 @@ class RetailcrmAddressBuilder extends RetailcrmAbstractDataBuilder } } + /** + * Extract order first and last names from address + */ + private function buildOrderNames() + { + if (!empty($this->address->firstname)) { + $this->data['order']['firstName'] = $this->address->firstname; + } + + if (!empty($this->address->lastname)) { + $this->data['order']['lastName'] = $this->address->lastname; + } + } + /** * Build regular customer address */ diff --git a/retailcrm/lib/RetailcrmCustomerAddressBuilder.php b/retailcrm/lib/RetailcrmCustomerAddressBuilder.php index b1b2503..2455013 100644 --- a/retailcrm/lib/RetailcrmCustomerAddressBuilder.php +++ b/retailcrm/lib/RetailcrmCustomerAddressBuilder.php @@ -88,12 +88,14 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setCustomerAddress($customerAddress) { $this->customerAddress = $customerAddress; + return $this; } public function setDataCrm($dataCrm) { $this->dataCrm = $dataCrm; + return $this; } @@ -104,6 +106,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setIdCustomer($idCustomer) { $this->idCustomer = $idCustomer; + return $this; } @@ -114,6 +117,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setAlias($alias) { $this->alias = $alias; + return $this; } @@ -124,6 +128,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setFirstName($firstName) { $this->firstName = $firstName; + return $this; } @@ -134,6 +139,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setLastName($lastName) { $this->lastName = $lastName; + return $this; } @@ -144,6 +150,7 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement public function setPhone($phone) { $this->phone = $phone; + return $this; } @@ -174,13 +181,22 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement $this->setAddressField('alias', $this->alias, 'default'); $this->setAddressField('lastname', $this->lastName, ''); $this->setAddressField('firstname', $this->firstName, ''); + $this->setAddressField('phone', $this->phone, ''); - $addressLine = $this->buildAddressLine(); - $this->setAddressField('address1', $addressLine[0], '--'); - $this->setAddressField('address2', $addressLine[1], ''); + $this->buildAddressLine(); - $countryIso = isset($this->dataCrm['countryIso']) ? Country::getByIso($this->dataCrm['countryIso']) : null; - $this->setAddressField('id_country', $countryIso, Configuration::get('PS_COUNTRY_DEFAULT')); + if (isset($this->dataCrm['notes'])) { + $this->setAddressField('other', $this->dataCrm['notes'], ''); + } + + if (isset($this->dataCrm['countryIso'])) { + $countryIso = null; + if (Validate::isLanguageIsoCode($this->dataCrm['countryIso'])) { + $countryIso = Country::getByIso($this->dataCrm['countryIso']); + } + + $this->setAddressField('id_country', $countryIso, Configuration::get('PS_COUNTRY_DEFAULT')); + } if (isset($this->dataCrm['city'])) { $this->setAddressField('city', $this->dataCrm['city'], '--'); @@ -188,23 +204,17 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement if (isset($this->dataCrm['index'])) { $this->setAddressField('postcode', $this->dataCrm['index'], ''); } - if (isset($this->dataCrm['region'])) { - $state = State::getIdByName($this->dataCrm['region']); - - if (!empty($state)) { - $this->customerAddress->id_state = $state; - } + $this->setAddressField('id_state', (int) State::getIdByName($this->dataCrm['region'])); } - $this->setAddressField('phone', $this->phone, ''); - $this->customerAddress = RetailcrmTools::filter( 'RetailcrmFilterSaveCustomerAddress', $this->customerAddress, array( 'dataCrm' => $this->dataCrm - )); + ) + ); return $this; } @@ -217,26 +227,27 @@ class RetailcrmCustomerAddressBuilder extends RetailcrmAbstractBuilder implement if ($value !== null) { $this->customerAddress->$field = $value; - } elseif (empty($this->customerAddress->$field)) { + } else { $this->customerAddress->$field = $default; } } private function buildAddressLine() { - $addressLine = [ - null, - null - ]; - if (isset($this->dataCrm['text'])) { - $addressLine = explode(RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER, $this->dataCrm['text'], 2); + $text = $this->dataCrm['text']; + if (isset($this->dataCrm['notes'])) { + $text = str_replace($this->dataCrm['notes'], '', $text); + } + + $addressLine = explode(RetailcrmAddressBuilder::ADDRESS_LINE_DIVIDER, $text, 2); + + $this->setAddressField('address1', $addressLine[0], '--'); if (count($addressLine) == 1) { - $addressLine[] = null; + $this->setAddressField('address2', ''); + } else { + $this->setAddressField('address2', $addressLine[1], ''); } } - - return $addressLine; } } - diff --git a/retailcrm/lib/RetailcrmHistory.php b/retailcrm/lib/RetailcrmHistory.php index a45b027..ce5bfe4 100644 --- a/retailcrm/lib/RetailcrmHistory.php +++ b/retailcrm/lib/RetailcrmHistory.php @@ -83,7 +83,7 @@ class RetailcrmHistory $customerHistory = RetailcrmTools::filter( 'RetailcrmFilterCustomersHistory', $customerHistory - ); + ); if (isset($customerHistory['deleted']) && $customerHistory['deleted']) { continue; @@ -228,7 +228,6 @@ class RetailcrmHistory } if (count($historyChanges)) { - $statuses = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_STATUS'), true))); $cartStatus = (string)(Configuration::get('RETAILCRM_API_SYNCHRONIZED_CART_STATUS')); $deliveries = array_flip(array_filter(json_decode(Configuration::get('RETAILCRM_API_DELIVERY'), true))); @@ -251,7 +250,6 @@ class RetailcrmHistory $infoOrder = null; if (!array_key_exists('externalId', $order_history)) { - // get full order $order = self::getCRMOrder($order_history['id'], 'id'); if (!$order) { @@ -288,7 +286,8 @@ class RetailcrmHistory } $crmPaymentType = isset($payment) ? $payment : null; - if (!is_null($crmPaymentType) && array_key_exists($crmPaymentType, $payments) && !empty($payments[$crmPaymentType])) { + if (!is_null($crmPaymentType) && + array_key_exists($crmPaymentType, $payments) && !empty($payments[$crmPaymentType])) { if (Module::getInstanceByName($payments[$crmPaymentType])) { $paymentType = Module::getModuleName($payments[$crmPaymentType]); } else { @@ -384,7 +383,6 @@ class RetailcrmHistory $customer = $corporateCustomerBuilder->getData()->getCustomer(); $addressInvoice = $corporateCustomerBuilder->getData()->getCustomerAddress(); - } else { $customerBuilder = new RetailcrmCustomerBuilder(); if ($customerId) { @@ -418,7 +416,10 @@ class RetailcrmHistory self::$api->customersCorporateAddressesEdit( $order['customer']['id'], $order['company']['address']['id'], - array_merge($order['company']['address'], array('externalId' => $addressInvoice->id)), + array_merge( + $order['company']['address'], + array('externalId' => $addressInvoice->id) + ), 'id', 'id' ); @@ -467,7 +468,6 @@ class RetailcrmHistory $products = array(); if (!empty($order['items'])) { foreach ($order['items'] as $item) { - if (RetailcrmOrderBuilder::isGiftItem($item)) { continue; } @@ -572,7 +572,6 @@ class RetailcrmHistory // set status for the order if (isset($newOrderHistoryRecord)) { - $newOrderHistoryRecord->id_order = $newOrder->id; $newOrderHistoryRecord->id_order_state = $newOrder->current_state; $newOrderHistoryRecord->id_employee = static::getFirstEmployeeId(); @@ -656,7 +655,6 @@ class RetailcrmHistory $newItemsIds = array(); if (!empty($order['items'])) { foreach ($order['items'] as $item) { - $product = new Product((int)$item['offer']['externalId'], false, self::$default_lang); $product_id = $item['offer']['externalId']; $product_attribute_id = 0; @@ -719,13 +717,11 @@ class RetailcrmHistory // collect orders id and reference if option sendOrderNumber enabled if ($sendOrderNumber) { array_push($updateOrderIds, array( - 'externalId' => $newOrder->id, + 'externalId' => $newOrder->id, 'number' => $newOrder->reference, )); } - } else { - $order = $order_history; if (stripos($order['externalId'], 'pscart_') !== false) { @@ -750,19 +746,22 @@ class RetailcrmHistory /* * check delivery changes */ - if (isset($order['delivery']) - || isset($order['firstName']) - || isset($order['lastName']) - || isset($order['phone']) + if (isset($order['delivery']['address']) + || array_key_exists('firstName', $order) + || array_key_exists('lastName', $order) + || array_key_exists('phone', $order) ) { $addressBuilder = new RetailcrmCustomerAddressBuilder(); - $orderAddressCrm = []; - if (isset($order['delivery']['address'])) { - $orderAddressCrm = $order['delivery']['address']; - } + $orderAddress = new Address($orderToUpdate->id_address_delivery); + $orderAddressCrm = isset($order['delivery']['address']) ? $order['delivery']['address'] : []; + $orderFirstName = $orderAddress->firstname; + $orderLastName = $orderAddress->lastname; + $orderPhone = $orderAddress->phone; - if (RetailcrmHistoryHelper::isAddressLineChanged($orderAddressCrm)) { + if (RetailcrmHistoryHelper::isAddressLineChanged($orderAddressCrm) + || !Validate::isLoadedObject($orderAddress) + ) { $infoOrder = self::getCRMOrder($order['externalId']); if (isset($infoOrder['delivery']['address'])) { // array_replace used to save changes, made by custom filters @@ -771,30 +770,64 @@ class RetailcrmHistory $orderAddressCrm ); } + + if (isset($infoOrder['firstName'])) { + $orderFirstName = $infoOrder['firstName']; + } + if (isset($infoOrder['lastName'])) { + $orderLastName = $infoOrder['lastName']; + } + if (isset($infoOrder['phone'])) { + $orderPhone = $infoOrder['phone']; + } + } + + // may override actual order data, but used to save changes, made by custom filters + if (array_key_exists('firstName', $order)) { + $orderFirstName = $order['firstName']; + } + if (array_key_exists('lastName', $order)) { + $orderLastName = $order['lastName']; + } + if (array_key_exists('phone', $order)) { + $orderPhone = $order['phone']; } $address = $addressBuilder - ->setCustomerAddress(new Address($orderToUpdate->id_address_delivery)) + ->setCustomerAddress($orderAddress) ->setIdCustomer($orderToUpdate->id_customer) ->setDataCrm($orderAddressCrm) - ->setFirstName(isset($order['firstName']) ? $order['firstName'] : null) - ->setLastName(isset($order['lastName']) ? $order['lastName'] : null) - ->setPhone(isset($order['phone']) ? $order['phone'] : null) + ->setFirstName($orderFirstName) + ->setLastName($orderLastName) + ->setPhone($orderPhone) + ->setAlias($orderAddress->alias) ->build() ->getData(); if (RetailcrmTools::validateEntity($address, $orderToUpdate)) { - // Modifying an address in order creates another address - // instead of changing the original one. This issue has been fixed in PS 1.7.7 - if (version_compare(_PS_VERSION_, '1.7.7', '<')) { - $address->id = null; - self::loadInCMS($address, 'add'); + $address->id = null; + RetailcrmTools::assignAddressIdsByFields(new Customer($orderToUpdate->id_customer), $address); + + if ($address->id === null) { + // Modifying an address in order creates another address + // instead of changing the original one. This issue has been fixed in PS 1.7.7 + if (version_compare(_PS_VERSION_, '1.7.7', '<')) { + self::loadInCMS($address, 'add'); + + $orderToUpdate->id_address_delivery = $address->id; + self::loadInCMS($orderToUpdate, 'update'); + } else { + $address->id = $orderToUpdate->id_address_delivery; + self::loadInCMS($address, 'update'); + } + } elseif ($address->id !== $orderToUpdate->id_address_delivery) { + RetailcrmLogger::writeDebug(__METHOD__, sprintf( + 'Binding to existing address [%d]', + $address->id + )); $orderToUpdate->id_address_delivery = $address->id; self::loadInCMS($orderToUpdate, 'update'); - } else { - $address->id = $orderToUpdate->id_address_delivery; - self::loadInCMS($address, 'update'); } } } @@ -803,12 +836,10 @@ class RetailcrmHistory * check delivery type and cost */ if (!empty($order['delivery']['code']) || !empty($order['delivery']['cost'])) { - $dtype = !empty($order['delivery']['code']) ? $order['delivery']['code'] : null; $dcost = !empty($order['delivery']['cost']) ? $order['delivery']['cost'] : null; - if ( - $dtype != null && ( + if ($dtype != null && ( isset($deliveries[$dtype]) && $deliveries[$dtype] != null && $deliveries[$dtype] != $orderToUpdate->id_carrier @@ -893,7 +924,6 @@ class RetailcrmHistory // change order totals if (isset($order['items']) || isset($order['delivery']['cost'])) { - // get full order if (empty($infoOrder)) { $infoOrder = self::getCRMOrder($order['externalId']); @@ -901,14 +931,12 @@ class RetailcrmHistory // items if (isset($order['items']) && is_array($order['items'])) { - /* * Clean deleted items */ $id_order_detail = null; foreach ($order['items'] as $key => $item) { if (isset($item['delete']) && $item['delete'] == true) { - if (RetailcrmOrderBuilder::isGiftItem($item)) { $orderToUpdate->gift = false; } @@ -929,7 +957,6 @@ class RetailcrmHistory */ foreach ($orderToUpdate->getProductsDetail() as $orderItem) { foreach ($order['items'] as $key => $item) { - if (RetailcrmOrderBuilder::isGiftItem($item)) { continue; } @@ -1055,7 +1082,6 @@ class RetailcrmHistory // delete all cart discount $orderCartRules = $orderToUpdate->getCartRules(); foreach ($orderCartRules as $valCartRules) { - $order_cart_rule = new OrderCartRule($valCartRules['id_order_cart_rule']); $order_cart_rule->delete(); } @@ -1082,7 +1108,6 @@ class RetailcrmHistory if (isset($statuses[$stype]) && !empty($statuses[$stype])) { if ($statuses[$stype] != $orderToUpdate->current_state) { - $orderHistory = new OrderHistory(); $orderHistory->id_employee = 0; $orderHistory->id_order = $orderToUpdate->id; @@ -1115,7 +1140,7 @@ class RetailcrmHistory // collect orders id and reference if option sendOrderNumber enabled if ($sendOrderNumber) { array_push($updateOrderIds, array( - 'externalId' => $orderToUpdate->id, + 'externalId' => $orderToUpdate->id, 'number' => $orderToUpdate->reference, )); } @@ -1126,7 +1151,7 @@ class RetailcrmHistory if (!empty($orderFix)) { self::$api->ordersFixExternalIds($orderFix); } - + // update orders number in CRM if (!empty($updateOrderIds)) { foreach ($updateOrderIds as $upOrder) { @@ -1332,15 +1357,13 @@ class RetailcrmHistory WHERE id_order = ' . pSQL((int)$order_id) . ' AND product_id = ' . pSQL((int)$product_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() { return Db::getInstance()->getRow(' - SELECT MAX(id_order_detail) FROM ' . _DB_PREFIX_ . 'order_detail' - ); + SELECT MAX(id_order_detail) FROM ' . _DB_PREFIX_ . 'order_detail'); } /** @@ -1442,7 +1465,7 @@ class RetailcrmHistory && isset($entry['apiKey']['current']) && $entry['apiKey']['current'] == true ) { - if (isset($notOurChanges[$externalId][$field]) || $entry['field'] == 'externalId') { + if (isset($notOurChanges[$externalId][$field]) || $field == 'externalId' || $field == 'status') { $organizedHistory[$externalId][] = $entry; } else { continue; @@ -1604,7 +1627,6 @@ class RetailcrmHistory $orderdb = new Order($orderId); foreach ($orderdb->getProducts() as $item) { - if (isset($item['product_attribute_id']) && $item['product_attribute_id'] > 0) { $productId = $item['product_id'] . '#' . $item['product_attribute_id']; } else { @@ -1676,7 +1698,10 @@ class RetailcrmHistory ); } - if ($historyResponse instanceof RetailcrmApiResponse && $historyResponse->offsetExists('history') && !empty($historyResponse['history'])) { + if ($historyResponse instanceof RetailcrmApiResponse + && $historyResponse->offsetExists('history') + && !empty($historyResponse['history']) + ) { $history = $historyResponse['history']; $lastSinceId = end($history)['id']; @@ -1690,4 +1715,3 @@ class RetailcrmHistory return true; } } - diff --git a/retailcrm/lib/RetailcrmHistoryHelper.php b/retailcrm/lib/RetailcrmHistoryHelper.php index cc36fd6..4272b85 100644 --- a/retailcrm/lib/RetailcrmHistoryHelper.php +++ b/retailcrm/lib/RetailcrmHistoryHelper.php @@ -316,7 +316,13 @@ class RetailcrmHistoryHelper { */ public static function isAddressLineChanged($address) { + // TODO countryIso, city, index and region added because module can't get changes of [text] field with api. + // Should be removed when the api logic is updated $keys = [ + 'countryIso', + 'city', + 'index', + 'region', 'street', 'building', 'flat', diff --git a/retailcrm/lib/RetailcrmTools.php b/retailcrm/lib/RetailcrmTools.php index 13c572a..94c2204 100644 --- a/retailcrm/lib/RetailcrmTools.php +++ b/retailcrm/lib/RetailcrmTools.php @@ -678,14 +678,18 @@ class RetailcrmTools /** * Assign address ID and customer ID from customer addresses. - * Customer ID in the address isn't checked (it will be set to id from provided customer, even if it doesn't have ID yet). + * Customer ID in the address isn't checked + * (it will be set to id from provided customer, even if it doesn't have ID yet). * * @param Customer|CustomerCore $customer * @param Address|\AddressCore $address */ public static function assignAddressIdsByFields($customer, $address) { - RetailcrmLogger::writeDebugArray(__METHOD__, array('Called with customer', $customer->id, 'and address', self::dumpEntity($address))); + RetailcrmLogger::writeDebugArray( + __METHOD__, + array('Called with customer', $customer->id, 'and address', self::dumpEntity($address)) + ); foreach ($customer->getAddresses(self::defaultLang()) as $customerInnerAddress) { $customerAddress = new Address($customerInnerAddress['id_address']); @@ -738,7 +742,10 @@ class RetailcrmTools 'firstname', 'postcode', 'city', + 'id_state', 'address1', + 'address2', + 'other', 'phone', 'company', 'vat_number' @@ -779,7 +786,8 @@ class RetailcrmTools return $object; } if (!in_array(RetailcrmFilterInterface::class, class_implements($filter))) { - RetailcrmLogger::writeDebug(__METHOD__, sprintf('Filter class %s must implements %s interface', + RetailcrmLogger::writeDebug(__METHOD__, sprintf( + 'Filter class %s must implements %s interface', $filter, RetailcrmFilterInterface::class )); diff --git a/retailcrm/objects.xml b/retailcrm/objects.xml index 950b07b..78d1cde 100644 --- a/retailcrm/objects.xml +++ b/retailcrm/objects.xml @@ -102,7 +102,7 @@ cost netCost - country + countryIso index region city diff --git a/retailcrm/retailcrm.php b/retailcrm/retailcrm.php index c6c946b..a59b0d8 100644 --- a/retailcrm/retailcrm.php +++ b/retailcrm/retailcrm.php @@ -1004,7 +1004,7 @@ class RetailCRM extends Module 'enableOrderNumberSending' => (Tools::getValue(static::ENABLE_ORDER_NUMBER_SENDING) !== false), 'enableOrderNumberReceiving' => (Tools::getValue(static::ENABLE_ORDER_NUMBER_RECEIVING) !== false), 'debugMode' => (Tools::getValue(static::ENABLE_DEBUG_MODE) !== false), - 'webJobs' => (Tools::getValue(static::ENABLE_WEB_JOBS) !== false ? '1' : '0'), + 'webJobs' => (Tools::getValue(static::ENABLE_WEB_JOBS, true) !== false ? '1' : '0'), 'collectorActive' => (Tools::getValue(static::COLLECTOR_ACTIVE) !== false), 'collectorKey' => (string) (Tools::getValue(static::COLLECTOR_KEY)), 'clientId' => Configuration::get(static::CLIENT_ID), @@ -1028,7 +1028,10 @@ class RetailCRM extends Module Configuration::updateValue(static::ENABLE_HISTORY_UPLOADS, $settings['enableHistoryUploads']); Configuration::updateValue(static::ENABLE_BALANCES_RECEIVING, $settings['enableBalancesReceiving']); Configuration::updateValue(static::ENABLE_ORDER_NUMBER_SENDING, $settings['enableOrderNumberSending']); - Configuration::updateValue(static::ENABLE_ORDER_NUMBER_RECEIVING, $settings['enableOrderNumberReceiving']); + Configuration::updateValue( + static::ENABLE_ORDER_NUMBER_RECEIVING, + $settings['enableOrderNumberReceiving'] + ); Configuration::updateValue(static::COLLECTOR_ACTIVE, $settings['collectorActive']); Configuration::updateValue(static::COLLECTOR_KEY, $settings['collectorKey']); Configuration::updateValue(static::SYNC_CARTS_ACTIVE, $settings['synchronizeCartsActive']); diff --git a/retailcrm/views/templates/admin/settings.tpl b/retailcrm/views/templates/admin/settings.tpl index f3886ca..792148a 100644 --- a/retailcrm/views/templates/admin/settings.tpl +++ b/retailcrm/views/templates/admin/settings.tpl @@ -169,7 +169,7 @@
{$catalogTitleName|escape:'htmlall':'UTF-8'} {l s='is outdated' mod='retailcrm'}
- {elseif !$catalogInfo.isUrlActual} + {elseif !isset($catalogInfo.isUrlActual) or !$catalogInfo.isUrlActual} {assign var="showUpdateButton" value=true}
@@ -519,8 +519,8 @@ - -