From ec0b66c194d06bba15c9b2d110b1a00f31d6e738 Mon Sep 17 00:00:00 2001 From: Chupocabra <71826921+Chupocabra@users.noreply.github.com> Date: Mon, 30 Sep 2024 09:29:21 +0300 Subject: [PATCH] Logs refactoring (#344) --- CHANGELOG.md | 3 + VERSION | 2 +- resources/pot/retailcrm-es_ES.pot | 9 - resources/pot/retailcrm-ru_RU.pot | 9 - .../class-wc-retailcrm-abstracts-settings.php | 8 - src/include/api/class-wc-retailcrm-proxy.php | 145 ++++++----- src/include/class-wc-retailcrm-base.php | 148 +++++++++-- src/include/class-wc-retailcrm-cart.php | 4 +- src/include/class-wc-retailcrm-customers.php | 43 +++- src/include/class-wc-retailcrm-history.php | 217 +++++++++------- src/include/class-wc-retailcrm-icml.php | 10 +- src/include/class-wc-retailcrm-loyalty.php | 37 ++- src/include/class-wc-retailcrm-orders.php | 66 +++-- src/include/class-wc-retailcrm-plugin.php | 4 + ...ass-wc-retailcrm-upload-discount-price.php | 6 +- src/include/class-wc-retailcrm-uploader.php | 13 +- .../class-wc-retailcrm-customer-switcher.php | 52 ++-- .../components/class-wc-retailcrm-logger.php | 232 ++++++++++++------ .../class-wc-retailcrm-customer-address.php | 6 +- ...c-retailcrm-customer-corporate-address.php | 6 +- ...class-wc-retailcrm-wc-customer-builder.php | 6 +- src/include/functions.php | 10 - ...-wc-retailcrm-customer-switcher-result.php | 12 +- ...s-wc-retailcrm-customer-switcher-state.php | 13 +- .../class-wc-retailcrm-order-address.php | 2 +- .../class-wc-retailcrm-order-payment.php | 14 +- src/languages/retailcrm-es_ES.l10n.php | 5 - src/languages/retailcrm-ru_RU.l10n.php | 4 - src/readme.txt | 5 +- src/retailcrm.php | 2 +- src/uninstall.php | 2 +- tests/test-wc-retailcrm-base.php | 2 - 32 files changed, 680 insertions(+), 417 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe23a7c..569847c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## 2024-09-26 4.8.7 +* Logs refactoring + ## 2024-09-26 4.8.6 * Optimized url-validator diff --git a/VERSION b/VERSION index 7ea5948..5fb8716 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -4.8.6 +4.8.7 diff --git a/resources/pot/retailcrm-es_ES.pot b/resources/pot/retailcrm-es_ES.pot index 13c0093..8945537 100644 --- a/resources/pot/retailcrm-es_ES.pot +++ b/resources/pot/retailcrm-es_ES.pot @@ -274,15 +274,6 @@ msgstr "Presionando el botón «Exportar» puedes descargar a todos los pedidos msgid "Debug information" msgstr "Información Debug" -msgid "Debug mode" -msgstr "Modo de depuración" - -msgid "Enable debug mode in module" -msgstr "Activar el modo de depuración en el módulo" - -msgid "Is required to enable debug mode for advanced logs" -msgstr "Se requiere el modo de depuración para habilitar el registro avanzado de logs" - msgid "Custom fields" msgstr "Campos personalizados" diff --git a/resources/pot/retailcrm-ru_RU.pot b/resources/pot/retailcrm-ru_RU.pot index 53fdc24..8bed135 100644 --- a/resources/pot/retailcrm-ru_RU.pot +++ b/resources/pot/retailcrm-ru_RU.pot @@ -283,15 +283,6 @@ msgstr "Вы можете экспортировать все заказы и к msgid "Debug information" msgstr "Отладочная информация" -msgid "Debug mode" -msgstr "Режим отладки" - -msgid "Enable debug mode in module" -msgstr "Активировать режим отладки в модуле" - -msgid "Is required to enable debug mode for advanced logs" -msgstr "Требуется включить режим отладки для расширенного логирования" - msgid "Custom fields" msgstr "Пользовательские поля" diff --git a/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php b/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php index 8f7cb1a..735d608 100644 --- a/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php +++ b/src/include/abstracts/class-wc-retailcrm-abstracts-settings.php @@ -738,14 +738,6 @@ abstract class WC_Retailcrm_Abstracts_Settings extends WC_Integration 'type' => 'checkbox' ]; - $this->form_fields['debug_mode'] = [ - 'label' => __('Enable debug mode in module', 'retailcrm'), - 'title' => __('Debug mode', 'retailcrm'), - 'description' => __('Is required to enable debug mode for advanced logs', 'retailcrm'), - 'class' => 'checkbox', - 'type' => 'checkbox' - ]; - /** * Debug information */ diff --git a/src/include/api/class-wc-retailcrm-proxy.php b/src/include/api/class-wc-retailcrm-proxy.php index f44f69c..4a8dab9 100644 --- a/src/include/api/class-wc-retailcrm-proxy.php +++ b/src/include/api/class-wc-retailcrm-proxy.php @@ -21,42 +21,32 @@ if (!class_exists('WC_Retailcrm_Proxy')) : { $this->corporateEnabled = $corporateEnabled; - if ( ! class_exists( 'WC_Retailcrm_Client_V5' ) ) { + if (!class_exists('WC_Retailcrm_Client_V5')) { include_once(WC_Integration_Retailcrm::checkCustomFile('include/api/class-wc-retailcrm-client-v5.php')); } $this->retailcrm = new WC_Retailcrm_Client_V5($api_url, $api_key); } - /** - * getCorporateEnabled - * - * @return bool - */ - public function getCorporateEnabled() + public function getCorporateEnabled(): ?bool { return $this->corporateEnabled; } - private static function reduceErrors($errors) - { - $result = ''; - - foreach ($errors as $key => $error) { - $result .= " [$key] => $error"; - } - - return $result; - } - /** - * Response will be omitted in debug logs for those methods + * Response will be omitted in logs for those methods * * @return string[] */ - private function methodsWithoutDebugResponse() + private function methodsWithoutFullLog(): array { - $methodsList = array('statusesList', 'paymentTypesList', 'deliveryTypesList', 'orderMethodsList'); + $methodsList = [ + 'statusesList', + 'paymentTypesList', + 'deliveryTypesList', + 'orderMethodsList', + 'storesList', + ]; foreach ($methodsList as $key => $method) { $method = get_class($this->retailcrm) . '::' . $method; @@ -68,74 +58,79 @@ if (!class_exists('WC_Retailcrm_Proxy')) : public function __call($method, $arguments) { - $result = ''; $response = null; $called = sprintf('%s::%s', get_class($this->retailcrm), $method); try { - WC_Retailcrm_Logger::debug( - $called, - array(empty($arguments) ? '[no params]' : print_r($arguments, true)) - ); - /** @var \WC_Retailcrm_Response $response */ - $response = call_user_func_array(array($this->retailcrm, $method), $arguments); + $response = $this->getResponse($method, $arguments); if (is_string($response)) { - WC_Retailcrm_Logger::debug($called, array($response)); + WC_Retailcrm_Logger::info($method, $response, [], WC_Retailcrm_Logger::RESPONSE); + return $response; } - if (empty($response)) { - WC_Retailcrm_Logger::add(sprintf("[%s] null (no response whatsoever)", $called)); + if (!$response instanceof WC_Retailcrm_Response) { + WC_Retailcrm_Logger::error( + $method, + sprintf("[%s] null (no response whatsoever)", $called), + [], + WC_Retailcrm_Logger::RESPONSE + ); + return null; } - if ($response->isSuccessful()) { - // Don't print long lists in debug logs (errors while calling this will be easy to detect anyway) - // Also don't call useless array_map at all while debug mode is off. - if (retailcrm_is_debug()) { - if (in_array( - $called, - $this->methodsWithoutDebugResponse() - )) { - WC_Retailcrm_Logger::debug($called, array('[request was successful, but response is omitted]')); - } else { - WC_Retailcrm_Logger::debug($called, array($response->getRawResponse())); - } - } - - $result = ' Ok'; - } else { - $result = sprintf( - $called ." : Error: [HTTP-code %s] %s", - $response->getStatusCode(), - $response->getErrorString() - ); - - if (isset($response['errors'])) { - $result .= self::reduceErrors($response['errors']); - } - - WC_Retailcrm_Logger::debug($called, array($response->getErrorString())); - WC_Retailcrm_Logger::debug($called, array($response->getRawResponse())); - } - - WC_Retailcrm_Logger::add(sprintf("[%s] %s", $called, $result)); - } catch (WC_Retailcrm_Exception_Curl $exception) { - WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage())); - WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString())); - WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result)); - } catch (WC_Retailcrm_Exception_Json $exception) { - WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage())); - WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString())); - WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result)); - } catch (InvalidArgumentException $exception) { - WC_Retailcrm_Logger::debug(get_class($this->retailcrm).'::'.$called, array($exception->getMessage())); - WC_Retailcrm_Logger::debug('', array($exception->getTraceAsString())); - WC_Retailcrm_Logger::add(sprintf("[%s] %s - %s", $called, $exception->getMessage(), $result)); + $this->logResponse($response, $method, $called); + } catch (WC_Retailcrm_Exception_Curl|WC_Retailcrm_Exception_Json|InvalidArgumentException $exception) { + WC_Retailcrm_Logger::exception($method, $exception); } - return !empty($response) ? $response : new WC_Retailcrm_Response(900, '{}'); + return $response instanceof WC_Retailcrm_Response ? $response : new WC_Retailcrm_Response(900, '{}'); + } + + private function getResponse($method, $arguments) + { + WC_Retailcrm_Logger::info( + $method, + $arguments === [] ? '[no params]' : '[with params]', + ['params' => $arguments], + WC_Retailcrm_Logger::REQUEST + ); + + return call_user_func_array(array($this->retailcrm, $method), $arguments); + } + + private function logResponse(WC_Retailcrm_Response $response, $method, $called): void + { + if ($response->isSuccessful()) { + if (in_array($called, $this->methodsWithoutFullLog())) { + WC_Retailcrm_Logger::info( + $method, + 'Ok', + ['body' => 'request was successful, but response is omitted'], + WC_Retailcrm_Logger::RESPONSE + ); + } else { + WC_Retailcrm_Logger::info( + $method, + 'Ok', + ['body' => json_decode($response->getRawResponse(), true)], + WC_Retailcrm_Logger::RESPONSE + ); + } + } else { + WC_Retailcrm_Logger::error( + $method, + sprintf( + "Error: [HTTP-code %s] %s", + $response->getStatusCode(), + $response->getErrorString() + ), + ['response' => json_decode($response->getRawResponse(), true)], + WC_Retailcrm_Logger::RESPONSE + ); + } } } endif; diff --git a/src/include/class-wc-retailcrm-base.php b/src/include/class-wc-retailcrm-base.php index 9f8b65b..5d05161 100644 --- a/src/include/class-wc-retailcrm-base.php +++ b/src/include/class-wc-retailcrm-base.php @@ -182,6 +182,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function init_settings_fields() { + WC_Retailcrm_Logger::setHook(current_action()); $this->init_form_fields(); $this->init_settings(); } @@ -193,6 +194,12 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function api_sanitized($settings) { + WC_Retailcrm_Logger::setHook(current_action()); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Module settings', + ['settings' => $settings] + ); $isLoyaltyUploadPrice = false; if ( @@ -285,6 +292,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function clear_cron_tasks() { + WC_Retailcrm_Logger::setHook(current_action()); wp_clear_scheduled_hook('retailcrm_icml'); wp_clear_scheduled_hook('retailcrm_history'); wp_clear_scheduled_hook('retailcrm_inventories'); @@ -301,6 +309,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function generate_icml() { + WC_Retailcrm_Logger::setHook(current_action()); /* * A temporary solution. * We have rebranded the module and changed the name of the ICML file. @@ -360,9 +369,12 @@ if (!class_exists('WC_Retailcrm_Base')) { */ private function uploadCatalog($infoApiKey) { + WC_Retailcrm_Logger::info(__METHOD__, 'Add task for automatically upload catalog in CRM'); + if ($infoApiKey->isSuccessful() && !empty($infoApiKey['scopes'])) { if (!in_array('analytics_write', $infoApiKey['scopes'])) { - writeBaseLogs( + WC_Retailcrm_Logger::error( + __METHOD__, 'To automatically load the catalog in CRM, you need to enable analytics_write for the API key' ); @@ -372,11 +384,14 @@ if (!class_exists('WC_Retailcrm_Base')) { $statisticUpdate = $this->apiClient->statisticUpdate(); if ($statisticUpdate->isSuccessful()) { - writeBaseLogs('Catalog generated, task automatically upload added to CRM'); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Catalog generated, upload task added to CRM' + ); } else { - writeBaseLogs( - $statisticUpdate['errorMsg'] - ?? 'Unrecognized error when adding catalog upload task to CRM' + WC_Retailcrm_Logger::error( + __METHOD__, + $statisticUpdate['errorMsg'] ?? 'Unrecognized error when adding catalog upload task to CRM' ); } } @@ -399,6 +414,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function retailcrm_history_get() { + WC_Retailcrm_Logger::setHook(current_action()); $retailcrm_history = new WC_Retailcrm_History($this->apiClient); $retailcrm_history->getHistory(); } @@ -410,6 +426,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function retailcrm_process_order($order_id) { + WC_Retailcrm_Logger::setHook(current_action(), $order_id); $this->orders->orderCreate($order_id); } @@ -420,6 +437,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function load_stocks() { + WC_Retailcrm_Logger::setHook(current_action()); $inventories = new WC_Retailcrm_Inventories($this->apiClient); $inventories->updateQuantity(); @@ -434,6 +452,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function upload_selected_orders() { + WC_Retailcrm_Logger::setHook(current_action()); $this->uploader->uploadSelectedOrders(); } @@ -444,6 +463,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function upload_to_crm() { + WC_Retailcrm_Logger::setHook(current_action()); $page = filter_input(INPUT_POST, 'Step'); $entity = filter_input(INPUT_POST, 'Entity'); @@ -466,12 +486,14 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function create_customer($customerId) { + WC_Retailcrm_Logger::setHook(current_action(), $customerId); + if (WC_Retailcrm_Plugin::history_running() === true) { return; } if (empty($customerId)) { - WC_Retailcrm_Logger::add('Error: Customer externalId is empty'); + WC_Retailcrm_Logger::error(__METHOD__, 'Error: Customer externalId is empty'); return; } @@ -494,12 +516,16 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function update_customer($customerId) { + WC_Retailcrm_Logger::setHook(current_action(), $customerId); + if (WC_Retailcrm_Plugin::history_running() === true) { + WC_Retailcrm_Logger::info(__METHOD__, 'History in progress, skip'); + return; } if (empty($customerId)) { - WC_Retailcrm_Logger::add('Error: Customer externalId is empty'); + WC_Retailcrm_Logger::error(__METHOD__, 'Error: Customer externalId is empty'); return; } @@ -516,8 +542,13 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function create_order($order_id) { + WC_Retailcrm_Logger::setHook(current_action(), $order_id); + if (is_admin()) { + WC_Retailcrm_Logger::info(__METHOD__, 'Creation is from admin panel'); $this->retailcrm_process_order($order_id); + } else { + WC_Retailcrm_Logger::info(__METHOD__, 'Creation is not from admin panel, skip'); } } @@ -532,27 +563,41 @@ if (!class_exists('WC_Retailcrm_Base')) { { global $woocommerce; + WC_Retailcrm_Logger::setHook(current_action()); + try { $site = $this->apiClient->getSingleSiteForKey(); $cartItems = $woocommerce->cart->get_cart(); $customerId = $woocommerce->customer->get_id(); if (empty($site)) { - writeBaseLogs('Error with CRM credentials: need an valid apiKey assigned to one certain site'); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error with CRM credentials: need an valid apiKey assigned to one certain site' + ); } elseif (empty($customerId)) { - writeBaseLogs('Abandoned carts work only for registered customers'); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Abandoned carts work only for registered customers' + ); } else { $isCartExist = $this->cart->isCartExist($customerId, $site); $isSuccessful = $this->cart->processCart($customerId, $cartItems, $site, $isCartExist); if ($isSuccessful) { - writeBaseLogs('Cart for customer ID: ' . $customerId . ' processed. Hook: ' . current_filter()); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Cart for customer ID: ' . $customerId . ' processed. Hook: ' . current_filter() + ); } else { - writeBaseLogs('Cart for customer ID: ' . $customerId . ' not processed. Hook: ' . current_filter()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Cart for customer ID: ' . $customerId . ' not processed. Hook: ' . current_filter() + ); } } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } @@ -571,32 +616,50 @@ if (!class_exists('WC_Retailcrm_Base')) { { global $woocommerce; + WC_Retailcrm_Logger::setHook(current_action()); + try { $site = $this->apiClient->getSingleSiteForKey(); $customerId = $woocommerce->customer->get_id(); if (empty($site)) { - writeBaseLogs('Error with CRM credentials: need an valid apiKey assigned to one certain site'); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Error with CRM credentials: need an valid apiKey assigned to one certain site' + ); } elseif (empty($customerId)) { - writeBaseLogs('Abandoned carts work only for registered customers'); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Abandoned carts work only for registered customers' + ); } else { $isCartExist = $this->cart->isCartExist($customerId, $site); $isSuccessful = $this->cart->clearCart($customerId, $site, $isCartExist); if ($isSuccessful) { - writeBaseLogs('Cart for customer ID: ' . $customerId . ' cleared. Hook: ' . current_filter()); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Cart for customer ID: ' . $customerId . ' cleared. Hook: ' . current_filter() + ); } elseif ($isCartExist) { - writeBaseLogs('Cart for customer ID: ' . $customerId . ' not cleared. Hook: ' . current_filter()); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Cart for customer ID: ' . $customerId . ' not cleared. Hook: ' . current_filter() + ); } } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function update_order($orderId) { + WC_Retailcrm_Logger::setHook(current_action(), $orderId); + if (WC_Retailcrm_Plugin::history_running() === true) { + WC_Retailcrm_Logger::info(__METHOD__, 'History in progress, skip'); + return; } @@ -614,11 +677,18 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function take_update_order($order_id) { + WC_Retailcrm_Logger::setHook(current_action(), $order_id); + if ( WC_Retailcrm_Plugin::history_running() === true || did_action('woocommerce_checkout_order_processed') || did_action('woocommerce_new_order') ) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'History in progress or already did actions (woocommerce_checkout_order_processed;woocommerce_new_order), skip' + ); + return; } @@ -627,6 +697,8 @@ if (!class_exists('WC_Retailcrm_Base')) { public function update_order_loyalty() { + WC_Retailcrm_Logger::setHook(current_action()); + if ($this->updatedOrderId !== []) { foreach ($this->updatedOrderId as $orderId) { $this->orders->updateOrder($orderId); @@ -636,12 +708,14 @@ if (!class_exists('WC_Retailcrm_Base')) { public function update_order_items($orderId) { + WC_Retailcrm_Logger::setHook(current_action(), $orderId); $this->orders->updateOrder($orderId); } public function trash_order_action($id) { if ('shop_order' == get_post_type($id)) { + WC_Retailcrm_Logger::setHook(current_action(), $id); $this->orders->updateOrder($id, true); } } @@ -740,8 +814,12 @@ if (!class_exists('WC_Retailcrm_Base')) { } if (!$isSuccessful) { - writeBaseLogs('Errors when registering a loyalty program. Passed parameters: ' . - json_encode(['site' => $site, 'userId' => $userId, 'phone' => $phone]) + WC_Retailcrm_Logger::error( + __METHOD__, + sprintf( + 'Errors when registering a loyalty program. Passed parameters: %s', + json_encode(['site' => $site, 'userId' => $userId, 'phone' => $phone]) + ) ); echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later', 'retailcrm')]); } else { @@ -761,7 +839,10 @@ if (!class_exists('WC_Retailcrm_Base')) { } if (!$isSuccessful) { - writeBaseLogs('Errors when activate loyalty program. Passed parameters: ' . json_encode(['loyaltyId' => $loyaltyId])); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Errors when activate loyalty program. Passed parameters: ' . json_encode(['loyaltyId' => $loyaltyId]) + ); echo json_encode(['error' => __('Error when activating the loyalty program. Try again later', 'retailcrm')]); } else { echo json_encode(['isSuccessful' => true]); @@ -772,6 +853,8 @@ if (!class_exists('WC_Retailcrm_Base')) { public function coupon_info() { + WC_Retailcrm_Logger::setHook(current_action()); + try { $result = $this->loyalty->createLoyaltyCoupon(); @@ -786,52 +869,61 @@ if (!class_exists('WC_Retailcrm_Base')) { wp_enqueue_script('retailcrm-loyalty-cart', $jsScriptPath, '', '', true); wp_localize_script('retailcrm-loyalty-cart', 'AdminUrl', $wpAdminUrl); } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function refresh_loyalty_coupon() { + WC_Retailcrm_Logger::setHook(current_action()); + try { $this->loyalty->createLoyaltyCoupon(true); } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function clear_loyalty_coupon() { + WC_Retailcrm_Logger::setHook(current_action()); + try { $this->loyalty->clearLoyaltyCoupon(); } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function remove_coupon($couponCode) { + WC_Retailcrm_Logger::setHook(current_action()); + try { if (!$this->loyalty->deleteLoyaltyCoupon($couponCode)) { $this->loyalty->createLoyaltyCoupon(true); } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function apply_coupon($couponCode) { + WC_Retailcrm_Logger::setHook(current_action()); + try { if (!$this->loyalty->isLoyaltyCoupon($couponCode)) { $this->loyalty->createLoyaltyCoupon(true); } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } } public function reviewCreditBonus() { + WC_Retailcrm_Logger::setHook(current_action()); $resultHtml = $this->loyalty->getCreditBonuses(); if ($resultHtml) { @@ -1010,6 +1102,8 @@ if (!class_exists('WC_Retailcrm_Base')) { return null; } + WC_Retailcrm_Logger::setHook(current_action()); + $orderMetaData = $this->getMetaData('order'); $customerMetaData = $this->getMetaData('user'); $orderCustomFields = $this->getCustomFields('order'); @@ -1046,6 +1140,7 @@ if (!class_exists('WC_Retailcrm_Base')) { public function add_loyalty_item($items) { + WC_Retailcrm_Logger::setHook(current_action()); $items['loyalty'] = __('Loyalty program', 'retailcrm'); return $items; @@ -1064,6 +1159,8 @@ if (!class_exists('WC_Retailcrm_Base')) { return; } + WC_Retailcrm_Logger::setHook(current_action()); + $jsScript = 'retailcrm-loyalty-actions'; $loyaltyUrl = ['url' => get_admin_url()]; $jsScriptsPath = plugins_url() . self::ASSETS_DIR . '/js/'; @@ -1168,6 +1265,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function deactivate() { + WC_Retailcrm_Logger::setHook(current_action()); $api_client = $this->getApiClient(); $clientId = get_option('retailcrm_client_id'); diff --git a/src/include/class-wc-retailcrm-cart.php b/src/include/class-wc-retailcrm-cart.php index 41595ee..c4ce064 100644 --- a/src/include/class-wc-retailcrm-cart.php +++ b/src/include/class-wc-retailcrm-cart.php @@ -80,7 +80,7 @@ if (!class_exists('WC_Retailcrm_Carts')) : $setResponse = $this->apiClient->cartSet($crmCart, $site); $isSuccessful = $setResponse->isSuccessful() && !empty($setResponse['success']); } catch (Throwable $exception) { - writeBaseLogs('Error process cart: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } return $isSuccessful; @@ -97,7 +97,7 @@ if (!class_exists('WC_Retailcrm_Carts')) : $isSuccessful = $clearResponse->isSuccessful() && !empty($clearResponse['success']); } } catch (Throwable $exception) { - writeBaseLogs('Error clear cart: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } return $isSuccessful; diff --git a/src/include/class-wc-retailcrm-customers.php b/src/include/class-wc-retailcrm-customers.php index 0c0f87f..eef158a 100644 --- a/src/include/class-wc-retailcrm-customers.php +++ b/src/include/class-wc-retailcrm-customers.php @@ -99,6 +99,8 @@ if (!class_exists('WC_Retailcrm_Customers')) : return null; } + WC_Retailcrm_Logger::info(__METHOD__, 'Register WC_Customer ID: ' . $customerId); + $wcCustomer = new WC_Customer($customerId); $email = $wcCustomer->get_billing_email(); @@ -107,7 +109,10 @@ if (!class_exists('WC_Retailcrm_Customers')) : } if (empty($email)) { - WC_Retailcrm_Logger::add('Error: Customer email is empty, externalId: ' . $wcCustomer->get_id()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error: Customer email is empty, externalId: ' . $wcCustomer->get_id() + ); return null; } else { @@ -133,7 +138,7 @@ if (!class_exists('WC_Retailcrm_Customers')) : ->getResult() ->save(); - WC_Retailcrm_Logger::add('Customer was edited, externalId: ' . $wcCustomer->get_id()); + WC_Retailcrm_Logger::info(__METHOD__, 'Customer was edited, externalId: ' . $wcCustomer->get_id()); } } else { $this->createCustomer($customerId); @@ -142,8 +147,10 @@ if (!class_exists('WC_Retailcrm_Customers')) : ? 'The client has agreed to receive promotional newsletter, email: ' : 'The client refused to receive promotional newsletters, email: '; - WC_Retailcrm_Logger::addCaller('subscribe', $message . $email); - WC_Retailcrm_Logger::add('Customer was created, externalId: ' . $wcCustomer->get_id()); + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf('Customer was created, externalId: %s. %s', $wcCustomer->get_id(), $message . $email) + ); } } @@ -168,10 +175,17 @@ if (!class_exists('WC_Retailcrm_Customers')) : } if (!$customer instanceof WC_Customer) { + WC_Retailcrm_Logger::error(__METHOD__, 'Customer not found'); + return null; } if ($this->isCustomer($customer)) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'Process WC_Customer ' . $customer->get_id(), + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); $this->processCustomer($customer, $order); $response = $this->retailcrm->customersCreate($this->customer); @@ -200,6 +214,11 @@ if (!class_exists('WC_Retailcrm_Customers')) : $customer = $this->wcCustomerGet($customerId); if ($this->isCustomer($customer)) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'Update WC_Customer ' . $customer->get_id(), + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); $this->processCustomer($customer); $this->retailcrm->customersEdit($this->customer); } @@ -225,6 +244,11 @@ if (!class_exists('WC_Retailcrm_Customers')) : $customer = $this->wcCustomerGet($customerId); if ($this->isCustomer($customer)) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'Update WC_Customer by CRM_Customer ID: ' . $crmCustomerId, + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); $this->processCustomer($customer); $this->customer['id'] = $crmCustomerId; $this->retailcrm->customersEdit($this->customer, 'id'); @@ -368,6 +392,11 @@ if (!class_exists('WC_Retailcrm_Customers')) : */ public function processCustomerForUpload($customer) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'Processing for upload WC_Customer ' . $customer->get_id(), + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); $this->processCustomer($customer); } @@ -675,6 +704,12 @@ if (!class_exists('WC_Retailcrm_Customers')) : $new_customer->set_email($order->get_billing_email()); $new_customer->set_date_created($order->get_date_created()); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Build new customer from order data', + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($new_customer)] + ); + return $new_customer; } diff --git a/src/include/class-wc-retailcrm-history.php b/src/include/class-wc-retailcrm-history.php index f665ed6..841088f 100644 --- a/src/include/class-wc-retailcrm-history.php +++ b/src/include/class-wc-retailcrm-history.php @@ -83,13 +83,7 @@ if (!class_exists('WC_Retailcrm_History')) : $this->ordersHistory(); // @codeCoverageIgnoreStart } catch (\Exception $exception) { - WC_Retailcrm_Logger::add( - sprintf( - '[%s] - %s', - $exception->getMessage(), - 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() - ) - ); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } // @codeCoverageIgnoreEnd } @@ -118,15 +112,16 @@ if (!class_exists('WC_Retailcrm_History')) : update_option('retailcrm_customers_history_since_id', $lastChange['id']); - WC_Retailcrm_Logger::debug(__METHOD__, [ - 'Processing customers history, ID:', - $filter['sinceId'] - ]); + WC_Retailcrm_Logger::info(__METHOD__, 'Processing customers history, ID: ' . $filter['sinceId']); $builder = new WC_Retailcrm_WC_Customer_Builder(); $customers = WC_Retailcrm_History_Assembler::assemblyCustomer($history); - WC_Retailcrm_Logger::debug(__METHOD__, ['Assembled customers history:', $customers]); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Assembled customers history', + ['customers_history' => $customers] + ); WC_Retailcrm_Plugin::$history_run = true; foreach ($customers as $crmCustomer) { @@ -145,10 +140,13 @@ if (!class_exists('WC_Retailcrm_History')) : // @codeCoverageIgnoreStart if (!$builder->loadExternalId($crmCustomer['externalId'])) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( - 'Customer with id=%s is not found in the DB, skipping...', - $crmCustomer['externalId'] - )); + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf( + 'Customer with id=%s is not found in the DB, skipping...', + $crmCustomer['externalId'] + ) + ); // If customer not found in the DB, update sinceId $filter['sinceId'] = $lastChange['id']; @@ -175,20 +173,15 @@ if (!class_exists('WC_Retailcrm_History')) : $this->updateMetaData($customFields, $crmCustomer, $wcCustomer); } - WC_Retailcrm_Logger::debug(__METHOD__, ['Updated WC_Customer:', $wcCustomer]); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Updated WC_Customer ' . $crmCustomer['externalId'], + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($wcCustomer)] + ); // @codeCoverageIgnoreStart } catch (Exception $exception) { - WC_Retailcrm_Logger::error(sprintf( - 'Error while trying to process history: %s', - $exception->getMessage() - )); - WC_Retailcrm_Logger::error(sprintf( - '%s:%d', - $exception->getFile(), - $exception->getLine() - )); - WC_Retailcrm_Logger::error($exception->getTraceAsString()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); } // @codeCoverageIgnoreEnd } @@ -229,14 +222,15 @@ if (!class_exists('WC_Retailcrm_History')) : update_option('retailcrm_orders_history_since_id', $lastChange['id']); - WC_Retailcrm_Logger::debug(__METHOD__, [ - 'Processing orders history, ID:', - $filter['sinceId'] - ]); + WC_Retailcrm_Logger::info(__METHOD__, 'Processing orders history, ID: ' . $filter['sinceId']); $historyAssembly = WC_Retailcrm_History_Assembler::assemblyOrder($history); - WC_Retailcrm_Logger::debug(__METHOD__, ['Assembled orders history:', $historyAssembly]); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Assembled orders history', + ['orders_history' => $historyAssembly] + ); WC_Retailcrm_Plugin::$history_run = true; foreach ($historyAssembly as $orderHistory) { @@ -297,15 +291,15 @@ if (!class_exists('WC_Retailcrm_History')) : $this->retailcrm->ordersEdit($orderEditData, 'id'); } + + WC_Retailcrm_Logger::info( + __METHOD__, + 'Result WC_Order ' . $wcOrder->get_id(), + ['wc_order' => WC_Retailcrm_Logger::formatWcObject($wcOrder)] + ); } } catch (Exception $exception) { - WC_Retailcrm_Logger::add( - sprintf( - '[%s] - %s', - $exception->getMessage(), - 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() - ) - ); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); continue; } @@ -407,6 +401,12 @@ if (!class_exists('WC_Retailcrm_History')) : return false; } + WC_Retailcrm_Logger::info( + __METHOD__, + 'Updating WC_Order ' . $wcOrder->get_id(), + ['wc_order' => WC_Retailcrm_Logger::formatWcObject($wcOrder)] + ); + if (isset($order['status']) && isset($options[$order['status']])) { $wcOrder->update_status($options[$order['status']]); } @@ -485,7 +485,12 @@ if (!class_exists('WC_Retailcrm_History')) : ); if (!$wcProduct) { - WC_Retailcrm_Logger::add('Product not found by ' . $this->bindField); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Crm Product not found by ' . $this->bindField, + ['crm_product' => $crmProduct['offer']] + ); + continue; } @@ -648,6 +653,12 @@ if (!class_exists('WC_Retailcrm_History')) : return false; } + WC_Retailcrm_Logger::info( + __METHOD__, + 'Creating WC_Order from CRM_Order: ' . $order['id'] ?? 'id empty', + ['crm_order' => $order] + ); + if ( is_array($this->orderMethods) && $this->orderMethods @@ -700,12 +711,9 @@ if (!class_exists('WC_Retailcrm_History')) : if (!empty($order['contact']['address'])) { $billingAddress = $order['contact']['address']; } else { - WC_Retailcrm_Logger::add( - sprintf( - '[%d] => %s', - $order['id'], - 'Error: Contact address is empty' - ) + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error: Contact address is empty. Order ID: ' . $order['id'] ); } @@ -723,7 +731,10 @@ if (!class_exists('WC_Retailcrm_History')) : if (!empty($customer['address'])) { $billingAddress = $customer['address']; } else { - WC_Retailcrm_Logger::add(sprintf('[%d] => %s', $order['id'], 'Error: Customer address is empty')); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error: Customer address is empty. Order ID: ' . $order['id'] + ); } @@ -737,11 +748,14 @@ if (!class_exists('WC_Retailcrm_History')) : } if ($wcOrder instanceof WP_Error) { - WC_Retailcrm_Logger::add(sprintf( - '[%d] error while creating order: %s', - $order['id'], - print_r($wcOrder->get_error_messages(), true) - )); + WC_Retailcrm_Logger::error( + __METHOD__, + sprintf( + 'Error while creating order [%d]: %s', + $order['id'], + json_encode($wcOrder->get_error_messages()) + ) + ); return false; } @@ -830,7 +844,12 @@ if (!class_exists('WC_Retailcrm_History')) : ); if (!$wcProduct) { - WC_Retailcrm_Logger::add('Product not found by ' . $this->bindField); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Crm_Product not found by ' . $this->bindField, + ['crm_product' => $crmProduct['offer']] + ); + continue; } @@ -951,13 +970,15 @@ if (!class_exists('WC_Retailcrm_History')) : $woocommerceId = self::getItemWoocommerceId($crmOrder['items'][$item['id']]); } else { // @codeCoverageIgnoreStart - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( - "Order externalId=`%s`: item doesn't have woocomerceId, skipping... (item id=`%s`)", + "Order externalId=`%s`: item doesn't have woocommerceId, skipping... (item id=`%s`)", $order['externalId'], $item['id'] ) ); + continue; // @codeCoverageIgnoreEnd } @@ -966,9 +987,10 @@ if (!class_exists('WC_Retailcrm_History')) : } if (empty($woocommerceId)) { - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( - "Order externalId=`%s`: item doesn't have woocomerceId after all assertions, which" . + "Order externalId=`%s`: item doesn't have woocommerceId after all assertions, which" . " is unexpected, skipping... (item id=`%s`)", $order['externalId'], $item['id'] @@ -1114,6 +1136,20 @@ if (!class_exists('WC_Retailcrm_History')) : */ private function addProductInWcOrder($wcOrder, $wcProduct, $crmProduct) { + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf( + 'Add in order WC_Order: %s, product WC_Product: %s, CRM_Product: %s', + $wcOrder->get_id(), + $wcProduct->get_id(), + $crmProduct['id'] ?? 'id empty' + ), + [ + 'wc_order' => WC_Retailcrm_Logger::formatWcObject($wcOrder), + 'wc_product' => WC_Retailcrm_Logger::formatWcObject($wcProduct), + 'crm_product' => $crmProduct, + ] + ); $discountTotal = $crmProduct['discountTotal']; $productQuantity = $crmProduct['quantity']; @@ -1164,6 +1200,15 @@ if (!class_exists('WC_Retailcrm_History')) : $wcOrderItem->save(); } + + WC_Retailcrm_Logger::info( + __METHOD__, + 'Updating order product WC_Order_Item, CRM_Product', + [ + 'wc_order_item' => WC_Retailcrm_Logger::formatWcObject($wcOrderItem), + 'crm_product' => $crmProduct, + ] + ); } private function getProductSubTotalPrice($wcProduct, $quantity) @@ -1200,16 +1245,21 @@ if (!class_exists('WC_Retailcrm_History')) : $data->setWcOrder($wcOrder); - WC_Retailcrm_Logger::debug(__METHOD__, ['processing order', $order]); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Processing CRM_Order ' . $order['id'] ?? 'id empty', + ['crm_order' => $order] + ); if (isset($order['customer'])) { $crmOrder = $this->getCRMOrder($order['id'], 'id'); if (empty($crmOrder)) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( - 'Cannot get order data from retailCRM. Skipping customer change. History data: %s', - print_r($order, true) - )); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Cannot get order data from retailCRM. Skipping customer change.', + ['history_data' => $order] + ); return false; } @@ -1239,10 +1289,11 @@ if (!class_exists('WC_Retailcrm_History')) : } if (empty($crmOrder)) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( - 'Cannot get order data from retailCRM. Skipping customer change. History data: %s', - print_r($order, true) - )); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Cannot get order data from retailCRM. Skipping customer change.', + ['history_data' => $order] + ); return false; } @@ -1276,21 +1327,17 @@ if (!class_exists('WC_Retailcrm_History')) : $handled = true; // @codeCoverageIgnoreStart } catch (\Exception $exception) { - $errorMessage = sprintf( - 'Error switching order externalId=%s to customer id=%s (new company: id=%s %s). Reason: %s', - $order['externalId'], - $newCustomerId, - isset($order['company']) ? $order['company']['id'] : '', - isset($order['company']) ? $order['company']['name'] : '', - $exception->getMessage() + WC_Retailcrm_Logger::exception( + __METHOD__, + $exception, + sprintf( + 'Error switching order externalId=%s to customer id=%s (new company: id=%s %s). Reason: ', + $order['externalId'], + $newCustomerId, + isset($order['company']) ? $order['company']['id'] : '', + isset($order['company']) ? $order['company']['name'] : '' + ) ); - WC_Retailcrm_Logger::addCaller(__METHOD__, $errorMessage); - WC_Retailcrm_Logger::debug(__METHOD__, sprintf( - '%s%s%s', - $errorMessage, - PHP_EOL, - $exception->getTraceAsString() - )); $handled = false; } // @codeCoverageIgnoreEnd @@ -1396,14 +1443,10 @@ if (!class_exists('WC_Retailcrm_History')) : */ protected function prepareChangeToIndividual($crmCustomer, $data, $isContact = false) { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - [ - 'Using this individual person data in order to set it into order,', - $data->getWcOrder()->get_id(), - ': ', - $crmCustomer - ] + 'Using this individual person data in order to set it into order ' . $data->getWcOrder()->get_id(), + ['crm_customer' => $crmCustomer] ); if ($isContact) { diff --git a/src/include/class-wc-retailcrm-icml.php b/src/include/class-wc-retailcrm-icml.php index 80d1116..682dbc0 100644 --- a/src/include/class-wc-retailcrm-icml.php +++ b/src/include/class-wc-retailcrm-icml.php @@ -76,7 +76,8 @@ if (!class_exists('WC_Retailcrm_Icml')) : $categories = $this->prepareCategories(); if (empty($categories)) { - writeBaseLogs('Can`t get categories!'); + WC_Retailcrm_Logger::error(__METHOD__, 'Can`t get categories!'); + return; } @@ -85,7 +86,8 @@ if (!class_exists('WC_Retailcrm_Icml')) : $offers = $this->prepareOffers(); if (empty($offers)) { - writeBaseLogs('Can`t get offers!'); + WC_Retailcrm_Logger::error(__METHOD__, 'Can`t get offers!'); + return; } @@ -95,6 +97,7 @@ if (!class_exists('WC_Retailcrm_Icml')) : $this->icmlWriter->formatXml($this->tmpFile); rename($this->tmpFile, $this->file); + WC_Retailcrm_Logger::info(__METHOD__, 'Catalog generated'); } /** @@ -127,7 +130,8 @@ if (!class_exists('WC_Retailcrm_Icml')) : wp_cache_flush(); if (empty($products)) { - writeBaseLogs('Can`t get products!'); + WC_Retailcrm_Logger::error(__METHOD__, 'Can`t get products!'); + return; } diff --git a/src/include/class-wc-retailcrm-loyalty.php b/src/include/class-wc-retailcrm-loyalty.php index 282cfce..ca4ee50 100644 --- a/src/include/class-wc-retailcrm-loyalty.php +++ b/src/include/class-wc-retailcrm-loyalty.php @@ -48,7 +48,11 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : try { $response = $this->getLoyaltyAccounts($userId); } catch (Throwable $exception) { - writeBaseLogs('Exception get loyalty accounts: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception( + __METHOD__, + $exception, + 'Exception get loyalty accounts: ' + ); return $result; } @@ -83,12 +87,20 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : $response = $this->apiClient->createLoyaltyAccount($parameters, $site); if (!$response->isSuccessful()) { - writeBaseLogs('Error while registering in the loyalty program: ' . $response->getRawResponse()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error while registering in the loyalty program', + ['response' => json_decode($response->getRawResponse(), true)] + ); } return $response->isSuccessful(); } catch (Throwable $exception) { - writeBaseLogs('Exception while registering in the loyalty program: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception( + __METHOD__, + $exception, + 'Exception while registering in the loyalty program: ' + ); return false; } @@ -100,12 +112,16 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : $response = $this->apiClient->activateLoyaltyAccount($loyaltyId); if (!$response->isSuccessful()) { - writeBaseLogs('Error while registering in the loyalty program: ' . $response->getRawResponse()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error while registering in the loyalty program', + ['response' => json_decode($response->getRawResponse(), true)] + ); } return $response->isSuccessful(); } catch (Throwable $exception) { - writeBaseLogs('Exception while activate loyalty account: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); return false; } @@ -341,7 +357,11 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : try { $response = $this->getLoyaltyAccounts($wcCustomer->get_id()); } catch (Throwable $exception) { - writeBaseLogs('Exception get loyalty accounts: ' . $exception->getMessage()); + WC_Retailcrm_Logger::exception( + __METHOD__, + $exception, + 'Exception get loyalty accounts: ' + ); return false; } @@ -414,7 +434,10 @@ if (!class_exists('WC_Retailcrm_Loyalty')) : $response = $this->apiClient->ordersGet($orderExternalId); if (!$response instanceof WC_Retailcrm_Response || !$response->isSuccessful() || !isset($response['order'])) { - writeBaseLogs('Process order: Error when receiving an order from the CRM. Order Id: ' . $orderExternalId); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Process order: Error when receiving an order from the CRM. Order Id: ' . $orderExternalId + ); return []; } diff --git a/src/include/class-wc-retailcrm-orders.php b/src/include/class-wc-retailcrm-orders.php index 9c423f7..dc38f09 100644 --- a/src/include/class-wc-retailcrm-orders.php +++ b/src/include/class-wc-retailcrm-orders.php @@ -96,6 +96,12 @@ if (!class_exists('WC_Retailcrm_Orders')) : return null; } + WC_Retailcrm_Logger::info( + __METHOD__, + 'Start order creating ' . (is_int($orderId) ? $orderId : ''), + ['wc_order' => WC_Retailcrm_Logger::formatWcObject($orderId)] + ); + try { $this->order_payment->resetData(); @@ -113,7 +119,10 @@ if (!class_exists('WC_Retailcrm_Orders')) : if (!$this->loyalty->isValidOrder($wcCustomer, $wcOrder)) { if ($discountLp > 0) { - writeBaseLogs('The user does not meet the requirements for working with the loyalty program. Order Id: ' . $orderId); + WC_Retailcrm_Logger::info( + __METHOD__, + 'The user does not meet the requirements for working with the loyalty program. Order Id: ' . $orderId + ); } $discountLp = 0; @@ -123,6 +132,11 @@ if (!class_exists('WC_Retailcrm_Orders')) : } } + WC_Retailcrm_Logger::info( + __METHOD__, + 'Create WC_Order ' . $wcOrder->get_id(), + ['wc_order' => WC_Retailcrm_Logger::formatWcObject($wcOrder)] + ); $this->processOrder($wcOrder); if (isset($privilegeType)) { @@ -142,14 +156,7 @@ if (!class_exists('WC_Retailcrm_Orders')) : $this->loyalty->applyLoyaltyDiscount($wcOrder, $response['order'], $discountLp); } } catch (Throwable $exception) { - writeBaseLogs( - sprintf( - 'Error message: %s, file: %s on line: %s', - $exception->getMessage(), - $exception->getFile(), - $exception->getLine() - ) - ); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); return null; } @@ -211,6 +218,15 @@ if (!class_exists('WC_Retailcrm_Orders')) : */ protected function fillOrderCreate($wcCustomerId, $wcCustomerEmail, $wcOrder) { + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf( + 'Fill order data: WC_Customer ID: %s email: %s WC_Order ID: %s', + $wcCustomerId, + $wcCustomerEmail, + $wcOrder->get_id() + ) + ); $isContact = $this->retailcrm->getCorporateEnabled() && static::isCorporateOrder($wcOrder); $foundCustomer = $this->customers->findCustomerEmailOrId( @@ -264,12 +280,9 @@ if (!class_exists('WC_Retailcrm_Orders')) : // If address not found create new address. if (!$addressFound) { - WC_Retailcrm_Logger::add( - sprintf( - '[%d] => %s', - $this->order['customer']['id'], - 'Notification: Create new address for corporate customer' - ) + WC_Retailcrm_Logger::info( + __METHOD__, + 'Notification: Create new address for corporate customer ' . $this->order['customer']['id'] ); } @@ -317,6 +330,11 @@ if (!class_exists('WC_Retailcrm_Orders')) : try { $wcOrder = wc_get_order($orderId); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Update WC_Order ' . $wcOrder->get_id(), + ['wc_order' => WC_Retailcrm_Logger::formatWcObject($wcOrder)] + ); $needRecalculate = false; $this->processOrder($wcOrder, true, $statusTrash); @@ -334,7 +352,7 @@ if (!class_exists('WC_Retailcrm_Orders')) : $responseCancelBonus = $this->retailcrm->cancelBonusOrder(['externalId' => $this->order['externalId']]); if (!$responseCancelBonus instanceof WC_Retailcrm_Response || !$responseCancelBonus->isSuccessful()) { - writeBaseLogs('Error when canceling bonuses'); + WC_Retailcrm_Logger::error(__METHOD__, 'Error when canceling bonuses'); return null; } @@ -352,14 +370,7 @@ if (!class_exists('WC_Retailcrm_Orders')) : } } } catch (Throwable $exception) { - writeBaseLogs( - sprintf( - 'Error message: %s, file: %s on line: %s', - $exception->getMessage(), - $exception->getFile(), - $exception->getLine() - ) - ); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); return null; } @@ -429,6 +440,8 @@ if (!class_exists('WC_Retailcrm_Orders')) : } if ('auto-draft' === $order->get_status()) { + WC_Retailcrm_Logger::info(__METHOD__, 'Skip, order in auto-draft status'); + return; } @@ -515,6 +528,11 @@ if (!class_exists('WC_Retailcrm_Orders')) : /** @var WC_Order_Item_Product $item */ foreach ($wcItems as $id => $item) { + WC_Retailcrm_Logger::info( + __METHOD__, + 'Process WC_Order_Item_Product ' . $id, + ['wc_order_item_product' => WC_Retailcrm_Logger::formatWcObject($item)] + ); $crmItem = $crmItems[$id] ?? null; $orderItems[] = $this->order_item->build($item, $crmItem)->getData(); diff --git a/src/include/class-wc-retailcrm-plugin.php b/src/include/class-wc-retailcrm-plugin.php index 7a91dd3..5d9dc25 100644 --- a/src/include/class-wc-retailcrm-plugin.php +++ b/src/include/class-wc-retailcrm-plugin.php @@ -89,6 +89,10 @@ class WC_Retailcrm_Plugin return; } + if (!class_exists('WC_Retailcrm_Logger')) { + require_once(WC_Integration_Retailcrm::checkCustomFile('include/components/class-wc-retailcrm-logger.php')); + } + if (!class_exists('WC_Retailcrm_Icml')) { require_once(WC_Integration_Retailcrm::checkCustomFile('include/class-wc-retailcrm-icml.php')); } diff --git a/src/include/class-wc-retailcrm-upload-discount-price.php b/src/include/class-wc-retailcrm-upload-discount-price.php index c36101d..f7b6348 100644 --- a/src/include/class-wc-retailcrm-upload-discount-price.php +++ b/src/include/class-wc-retailcrm-upload-discount-price.php @@ -34,7 +34,7 @@ if (!class_exists('WC_Retailcrm_Upload_Discount_Price')): $error = $this->uploadSettings(); if ($error !== '') { - writeBaseLogs($error); + WC_Retailcrm_Logger::error(__METHOD__, $error); return; } @@ -66,7 +66,7 @@ if (!class_exists('WC_Retailcrm_Upload_Discount_Price')): } if (empty($products)) { - writeBaseLogs('Can`t get products!'); + WC_Retailcrm_Logger::error(__METHOD__, 'Can`t get products!'); return; } @@ -107,7 +107,7 @@ if (!class_exists('WC_Retailcrm_Upload_Discount_Price')): unset($chunks); } catch (\Throwable $exception) { - writeBaseLogs($exception->getMessage() . PHP_EOL . $exception->getTraceAsString()); + WC_Retailcrm_Logger::exception(__METHOD__, $exception); return; } diff --git a/src/include/class-wc-retailcrm-uploader.php b/src/include/class-wc-retailcrm-uploader.php index 2c9241a..f3119e1 100644 --- a/src/include/class-wc-retailcrm-uploader.php +++ b/src/include/class-wc-retailcrm-uploader.php @@ -61,6 +61,8 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { { $ids = $_GET['order_ids_retailcrm']; + WC_Retailcrm_Logger::info(__METHOD__, 'Selected order IDs: ' . json_encode($ids)); + if (!empty($ids)) { preg_match_all('/\d+/', $ids, $matches); @@ -81,6 +83,8 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { */ public function uploadArchiveOrders($page, $ids = []) { + WC_Retailcrm_Logger::info(__METHOD__, 'Archive order IDs: ' . implode(', ', $ids)); + if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) { return null; } @@ -223,13 +227,12 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { return; } - WC_Retailcrm_Logger::add('Errors while uploading these orders'); - foreach ($errors as $orderId => $error) { - WC_Retailcrm_Logger::add(sprintf("[%d] => %s", $orderId, $error)); + WC_Retailcrm_Logger::error( + __METHOD__, + sprintf("Error while uploading [%d] => %s", $orderId, $error) + ); } - - WC_Retailcrm_Logger::add('=================================='); } } }//end if diff --git a/src/include/components/class-wc-retailcrm-customer-switcher.php b/src/include/components/class-wc-retailcrm-customer-switcher.php index 6afd466..6e8bb0d 100644 --- a/src/include/components/class-wc-retailcrm-customer-switcher.php +++ b/src/include/components/class-wc-retailcrm-customer-switcher.php @@ -43,7 +43,11 @@ class WC_Retailcrm_Customer_Switcher implements WC_Retailcrm_Builder_Interface { $this->data->validate(); - WC_Retailcrm_Logger::debug(__METHOD__, array('state', $this->data)); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Build Customer state', + ['customer_state' => $this->data] + ); $newCustomer = $this->data->getNewCustomer(); $newContact = $this->data->getNewContact(); @@ -51,36 +55,30 @@ class WC_Retailcrm_Customer_Switcher implements WC_Retailcrm_Builder_Interface $companyAddress = $this->data->getCompanyAddress(); if (!empty($newCustomer)) { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Changing to individual customer for order', - $this->data->getWcOrder()->get_id() - ) + 'Changing to individual customer for order ' . $this->data->getWcOrder()->get_id() ); $this->processChangeToRegular($this->data->getWcOrder(), $newCustomer, false); $this->data->getWcOrder()->set_billing_company(''); } else { if (!empty($newContact)) { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Changing to contact person customer for order', - $this->data->getWcOrder()->get_id() - ) + 'Changing to contact person customer for order ' . $this->data->getWcOrder()->get_id() ); $this->processChangeToRegular($this->data->getWcOrder(), $newContact, true); } if (!empty($newCompany)) { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array(sprintf( + sprintf( 'Replacing old order id=`%d` company `%s` with new company `%s`', $this->data->getWcOrder()->get_id(), $this->data->getWcOrder()->get_billing_company(), $newCompany - )) + ) ); $this->processCompanyChange(); } @@ -106,14 +104,10 @@ class WC_Retailcrm_Customer_Switcher implements WC_Retailcrm_Builder_Interface { $wcCustomer = null; - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Switching in order', - $wcOrder->get_id(), - 'to', - $newCustomer - ) + 'Switching customer in order ' . $wcOrder->get_id(), + ['crm_customer' => $newCustomer] ); if (isset($newCustomer['externalId'])) { @@ -121,24 +115,16 @@ class WC_Retailcrm_Customer_Switcher implements WC_Retailcrm_Builder_Interface if (!empty($wcCustomer)) { $wcOrder->set_customer_id($wcCustomer->get_id()); - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Set customer to', - $wcCustomer->get_id(), - 'in order', - $wcOrder->get_id() - ) + sprintf('Set customer to %s in order %s', $wcCustomer->get_id(), $wcOrder->get_id()) ); } } else { $wcOrder->set_customer_id(0); - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Set customer to 0 (guest) in order', - $wcOrder->get_id() - ) + 'Set customer to 0 (guest) in order ' . $wcOrder->get_id() ); } diff --git a/src/include/components/class-wc-retailcrm-logger.php b/src/include/components/class-wc-retailcrm-logger.php index c7e85a4..cccba25 100644 --- a/src/include/components/class-wc-retailcrm-logger.php +++ b/src/include/components/class-wc-retailcrm-logger.php @@ -17,7 +17,10 @@ if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')) : class WC_Retailcrm_Logger { /** @var string */ - const HANDLE = 'retailcrm'; + private const HANDLE = 'retailcrm'; + public const REQUEST = 'REQUEST'; + public const RESPONSE = 'RESPONSE'; + public CONST EXCEPTION = 'EXCEPTION'; /** * @var \WC_Logger_Interface $instance @@ -30,99 +33,180 @@ if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')) : private static $additionalHandlers; /** - * WC_Retailcrm_Logger constructor. + * @var string $logIdentifier */ - private function __construct() {} + private static $logIdentifier; /** - * Instantiates logger with file handler. - * - * @return \WC_Logger_Interface + * @var string $currentHook */ - private static function getInstance() + private static $currentHook; + + /** + * @var float $startTime + */ + private static $startTime; + + private function __construct() {} + + private static function getInstance(): WC_Logger_Interface { - if (empty(static::$instance)) { + if (!static::$instance instanceof WC_Logger) { static::$instance = new WC_Logger(self::$additionalHandlers); } return static::$instance; } - /** - * @param array $additionalHandlers - */ - public static function setAdditionalHandlers($additionalHandlers) + public static function setAdditionalHandlers(array $additionalHandlers): void { self::$additionalHandlers = $additionalHandlers; } - /** - * Regular logging - * - * @param string $message - * @param string $level - */ - public static function add($message, $level = WC_Log_Levels::NOTICE) + public static function setHook(string $action, $id = null): void { - self::getInstance()->add(self::HANDLE, $message, $level); + static::$currentHook = $id === null ? $action : sprintf('%s-%d', $action, (int) $id); } - /** - * Regular logging with caller prefix - * - * @param string $caller - * @param string $message - * @param string $level - */ - public static function addCaller($caller, $message, $level = WC_Log_Levels::NOTICE) + private static function getIdentifier(): string { - self::add(sprintf('<%s> => %s', $caller, $message), $level); - } - - /** - * Log error - * - * @param string $message - */ - public static function error($message) - { - self::add($message, WC_Log_Levels::ERROR); - } - - /** - * Debug logging. Contains a lot of debug data like full requests & responses. - * This log will work only if debug mode is enabled (see retailcrm_is_debug() for details). - * Caller should be specified, or message will be ignored at all. - * - * @param string $method - * @param array|string $messages - */ - public static function debug($method, $messages) - { - if (retailcrm_is_debug()) { - if (!empty($method) && !empty($messages)) { - $result = is_array($messages) ? substr( - array_reduce( - $messages, - function ($carry, $item) { - $carry .= ' ' . print_r($item, true); - return $carry; - } - ), - 1 - ) : $messages; - - self::getInstance()->add( - self::HANDLE . '_debug', - sprintf( - '<%s> => %s', - $method, - $result - ), - WC_Log_Levels::DEBUG - ); - } + if (!is_string(static::$logIdentifier)) { + static::$logIdentifier = substr(wp_generate_uuid4(), 0, 8); } + + return static::$logIdentifier; + } + + private static function getStartTime(): float + { + if (!is_float(static::$startTime)) { + static::$startTime = microtime(true); + } + + return static::$startTime; + } + + public static function exception(string $method, Throwable $exception, string $additionalMessage = ''): void + { + self::error( + $method, + sprintf( + '%s%s - Exception in file %s on line %s', + $additionalMessage, + $exception->getMessage(), + $exception->getFile(), + $exception->getLine() + ), + ['trace' => $exception->getTraceAsString()], + self::EXCEPTION + ); + } + + public static function error(string $method, string $message, array $context = [], $type = null): void + { + self::log($method, $message, $context, $type, WC_Log_Levels::ERROR); + } + + public static function info(string $method, string $message, array $context = [], $type = null): void + { + self::log($method, $message, $context, $type, WC_Log_Levels::INFO); + } + + private static function log(string $method, string $message, array $context = [], $type = null, $level = 'info'): void + { + $time = self::getStartTime(); + $context['time'] = round((microtime(true) - $time), 3); + $context['source'] = self::HANDLE; + + $message = sprintf( + '%s [%s] <%s> %s=> %s', + self::getIdentifier(), + self::$currentHook, + $method, + $type ? $type . ' ' : '', + $message + ); + + self::getInstance()->log($level, $message, $context); + } + + /** + * Extracts information useful for logs from an object + * + * @param $object + * @return array + */ + public static function formatWcObject($object): array + { + if ($object instanceof WC_Order) { + return self::formatWcOrder($object); + } + + if ($object instanceof WC_Customer) { + return self::formatWcCustomer($object); + } + + if (is_object($object)) { + return method_exists($object, 'get_data') ? (array_filter($object->get_data())) : [$object]; + } + + return [$object]; + } + + public static function formatWcOrder(WC_Order $order) { + return [ + 'id' => $order->get_id(), + 'status' => $order->get_status(), + 'date_modified' => $order->get_date_modified(), + 'total' => $order->get_total(), + 'shipping' => [ + 'first_name' => $order->get_shipping_first_name(), + 'last_name' => $order->get_shipping_last_name(), + 'company' => $order->get_shipping_company(), + 'address_1' => $order->get_shipping_address_1(), + 'address_2' => $order->get_shipping_address_2(), + 'city' => $order->get_shipping_city(), + 'state' => $order->get_shipping_state(), + 'postcode' => $order->get_shipping_postcode(), + 'country' => $order->get_shipping_country(), + 'phone' => method_exists($order, 'get_shipping_phone') ? $order->get_shipping_phone() : '', + ], + 'billing' => [ + 'phone' => $order->get_billing_phone() + ], + 'email' => $order->get_billing_email(), + 'payment_method_title' => $order->get_payment_method_title(), + 'date_paid' => $order->get_date_paid(), + ]; + } + + public static function formatWcCustomer(WC_Customer $customer) + { + return [ + 'id' => $customer->get_id(), + 'date_modified' => $customer->get_date_modified(), + 'firstName' => $customer->get_first_name(), + 'lastName' => $customer->get_last_name(), + 'email' => $customer->get_email(), + 'display_name' => $customer->get_display_name(), + 'role' => $customer->get_role(), + 'username' => $customer->get_username(), + 'shipping' => [ + 'first_name' => $customer->get_shipping_first_name(), + 'last_name' => $customer->get_shipping_last_name(), + 'company' => $customer->get_shipping_company(), + 'address_1' => $customer->get_shipping_address_1(), + 'address_2' => $customer->get_shipping_address_2(), + 'city' => $customer->get_shipping_city(), + 'state' => $customer->get_shipping_state(), + 'postcode' => $customer->get_shipping_postcode(), + 'country' => $customer->get_shipping_country(), + 'phone' => method_exists($customer, 'get_shipping_phone') ? $customer->get_shipping_phone() : '', + ], + 'billing' => [ + 'phone' => $customer->get_billing_phone() + ], + ]; } } endif; diff --git a/src/include/customer/class-wc-retailcrm-customer-address.php b/src/include/customer/class-wc-retailcrm-customer-address.php index 2d191bb..1296cf2 100644 --- a/src/include/customer/class-wc-retailcrm-customer-address.php +++ b/src/include/customer/class-wc-retailcrm-customer-address.php @@ -33,7 +33,11 @@ class WC_Retailcrm_Customer_Address extends WC_Retailcrm_Abstracts_Address $this->setDataFields($customerAddress); } else { - WC_Retailcrm_Logger::add('Error Customer address is empty'); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error: Customer address is empty', + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); } return $this; diff --git a/src/include/customer/class-wc-retailcrm-customer-corporate-address.php b/src/include/customer/class-wc-retailcrm-customer-corporate-address.php index 8b2af5d..17087b2 100644 --- a/src/include/customer/class-wc-retailcrm-customer-corporate-address.php +++ b/src/include/customer/class-wc-retailcrm-customer-corporate-address.php @@ -51,7 +51,11 @@ class WC_Retailcrm_Customer_Corporate_Address extends WC_Retailcrm_Abstracts_Add $this->setDataFields($corporateCustomerAddress); } else { - WC_Retailcrm_Logger::add('Error Corporate Customer address is empty'); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error: Corporate Customer address is empty.', + ['wc_customer' => WC_Retailcrm_Logger::formatWcObject($customer)] + ); } return $this; diff --git a/src/include/customer/woocommerce/class-wc-retailcrm-wc-customer-builder.php b/src/include/customer/woocommerce/class-wc-retailcrm-wc-customer-builder.php index 6f8e824..0df0877 100644 --- a/src/include/customer/woocommerce/class-wc-retailcrm-wc-customer-builder.php +++ b/src/include/customer/woocommerce/class-wc-retailcrm-wc-customer-builder.php @@ -153,7 +153,11 @@ class WC_Retailcrm_WC_Customer_Builder extends WC_Retailcrm_Abstract_Builder { $this->checkBuilderValidity(); - WC_Retailcrm_Logger::debug(__METHOD__, ['Building WC_Customer from data:', $this->data]); + WC_Retailcrm_Logger::info( + __METHOD__, + 'Building WC_Customer from data', + ['customer_data' => $this->data] + ); $this->customer->set_first_name($this->dataValue('firstName', $this->customer->get_first_name())); $this->customer->set_last_name($this->dataValue('lastName', $this->customer->get_last_name())); diff --git a/src/include/functions.php b/src/include/functions.php index 2e099ea..cf2d196 100644 --- a/src/include/functions.php +++ b/src/include/functions.php @@ -182,16 +182,6 @@ function calculatePriceExcludingTax($priceIncludingTax, $rate) return round($priceIncludingTax / (1 + $rate / 100), wc_get_price_decimals()); } -/** - * Write base logs in retailcrm file. - * - * @codeCoverageIgnore - */ -function writeBaseLogs($message) -{ - WC_Retailcrm_Logger::addCaller(__METHOD__, $message); -} - /** * Checking the use of HPOS. * diff --git a/src/include/models/class-wc-retailcrm-customer-switcher-result.php b/src/include/models/class-wc-retailcrm-customer-switcher-result.php index 25e4070..040249b 100644 --- a/src/include/models/class-wc-retailcrm-customer-switcher-result.php +++ b/src/include/models/class-wc-retailcrm-customer-switcher-result.php @@ -63,13 +63,13 @@ class WC_Retailcrm_Customer_Switcher_Result */ public function save() { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'Saving customer and order:', - $this->wcCustomer, - $this->wcOrder - ) + 'Saving WC_Customer and WC_Order', + [ + 'wc_customer' => WC_Retailcrm_Logger::formatWcObject($this->wcCustomer), + 'wc_order' => WC_Retailcrm_Logger::formatWcObject($this->wcOrder), + ] ); if (!empty($this->wcCustomer) && $this->wcCustomer->get_id()) { diff --git a/src/include/models/class-wc-retailcrm-customer-switcher-state.php b/src/include/models/class-wc-retailcrm-customer-switcher-state.php index b323175..d3ec2f2 100644 --- a/src/include/models/class-wc-retailcrm-customer-switcher-state.php +++ b/src/include/models/class-wc-retailcrm-customer-switcher-state.php @@ -170,14 +170,15 @@ class WC_Retailcrm_Customer_Switcher_State } if (!empty($this->newCustomer) && !empty($this->newContact)) { - WC_Retailcrm_Logger::debug( + WC_Retailcrm_Logger::info( __METHOD__, - array( - 'State data (customer and contact):' . PHP_EOL, - $this->getNewCustomer(), - $this->getNewContact() - ) + 'State data - customer and contact', + [ + 'customer' => $this->getNewCustomer(), + 'contact' => $this->getNewContact(), + ] ); + throw new \InvalidArgumentException( 'Too much data in state - cannot determine which customer should be used.' ); diff --git a/src/include/order/class-wc-retailcrm-order-address.php b/src/include/order/class-wc-retailcrm-order-address.php index e59b796..efe959a 100644 --- a/src/include/order/class-wc-retailcrm-order-address.php +++ b/src/include/order/class-wc-retailcrm-order-address.php @@ -31,7 +31,7 @@ class WC_Retailcrm_Order_Address extends WC_Retailcrm_Abstracts_Address $this->setDataFields($orderAddress); } else { - WC_Retailcrm_Logger::add('Error: Order address is empty'); + WC_Retailcrm_Logger::error(__METHOD__, 'Error: Order address is empty'); } return $this; diff --git a/src/include/order/class-wc-retailcrm-order-payment.php b/src/include/order/class-wc-retailcrm-order-payment.php index 5f1dc38..358bee0 100644 --- a/src/include/order/class-wc-retailcrm-order-payment.php +++ b/src/include/order/class-wc-retailcrm-order-payment.php @@ -62,14 +62,12 @@ class WC_Retailcrm_Order_Payment extends WC_Retailcrm_Abstracts_Data if ($order->is_paid()) { if ($order->get_status() != 'completed' && $order->get_payment_method() == 'cod') { - writeBaseLogs( - implode( - ' ', - [ - 'Payment for order: ' . $order->get_id(), - 'Payment status cannot be changed as it is cash (or other payment method) on delivery.', - 'The status will be changed when the order is in status completed.', - ] + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf('Payment for order: %s. ' . + 'Payment status cannot be changed as it is cash (or other payment method) on delivery. ' . + 'The status will be changed when the order is in status completed.', + $order->get_id() ) ); } else { diff --git a/src/languages/retailcrm-es_ES.l10n.php b/src/languages/retailcrm-es_ES.l10n.php index 38195ad..af0db8a 100644 --- a/src/languages/retailcrm-es_ES.l10n.php +++ b/src/languages/retailcrm-es_ES.l10n.php @@ -124,11 +124,6 @@ return [ "You can export all orders and customers from CMS to Simla.com by clicking the «Upload» button. This process can take much time and before it is completed, you need to keep the tab open" => "Presionando el botón «Exportar» puedes descargar a todos los pedidos y clientes de CMS a Simla.com. Este proceso puede llevar mucho tiempo y es necesario mantener abierta la pestaña hasta que termine el proceso", "Debug information" => "Información Debug", - "Debug mode" => "Modo de depuración", - "Enable debug mode in module" => - "Activar el modo de depuración en el módulo", - "Is required to enable debug mode for advanced logs" => - "Se requiere el modo de depuración para habilitar el registro avanzado de logs", "Custom fields" => "Campos personalizados", "Select value" => "Selecciona un valor", "Custom fields for order" => "Campos de pedido personalizados", diff --git a/src/languages/retailcrm-ru_RU.l10n.php b/src/languages/retailcrm-ru_RU.l10n.php index 19a12cd..bb57e6a 100644 --- a/src/languages/retailcrm-ru_RU.l10n.php +++ b/src/languages/retailcrm-ru_RU.l10n.php @@ -127,10 +127,6 @@ return [ "You can export all orders and customers from CMS to Simla.com by clicking the «Upload» button. This process can take much time and before it is completed, you need to keep the tab open" => "Вы можете экспортировать все заказы и клиентов из CMS в Simla.com, нажав кнопку «Выгрузить». Этот процесс может занять много времени, и до его завершения необходимо держать вкладку открытой", "Debug information" => "Отладочная информация", - "Debug mode" => "Режим отладки", - "Enable debug mode in module" => "Активировать режим отладки в модуле", - "Is required to enable debug mode for advanced logs" => - "Требуется включить режим отладки для расширенного логирования", "Custom fields" => "Пользовательские поля", "Select value" => "Выберите значение", "Custom fields for order" => "Пользовательские поля для заказа", diff --git a/src/readme.txt b/src/readme.txt index 6db55e0..9664511 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -5,7 +5,7 @@ Tags: Интеграция, Simla.com, simla Requires PHP: 7.1 Requires at least: 5.3 Tested up to: 6.5 -Stable tag: 4.8.6 +Stable tag: 4.8.7 License: GPLv1 or later License URI: http://www.gnu.org/licenses/gpl-1.0.html @@ -82,6 +82,9 @@ Asegúrate de tener una clave API específica para cada tienda. Las siguientes i == Changelog == += 4.8.7 = +* Logs refactoring + = 4.8.6 = * Optimized url-validator diff --git a/src/retailcrm.php b/src/retailcrm.php index 24a7591..8f1d5aa 100644 --- a/src/retailcrm.php +++ b/src/retailcrm.php @@ -5,7 +5,7 @@ * Description: Integration plugin for WooCommerce & Simla.com * Author: RetailDriver LLC * Author URI: http://retailcrm.pro/ - * Version: 4.8.6 + * Version: 4.8.7 * Tested up to: 6.5 * Requires Plugins: woocommerce * WC requires at least: 5.4 diff --git a/src/uninstall.php b/src/uninstall.php index 2db9e4a..8a1f66c 100644 --- a/src/uninstall.php +++ b/src/uninstall.php @@ -16,7 +16,7 @@ * * @link https://wordpress.org/plugins/woo-retailcrm/ * - * @version 4.8.6 + * @version 4.8.7 * * @package RetailCRM */ diff --git a/tests/test-wc-retailcrm-base.php b/tests/test-wc-retailcrm-base.php index c24c3c9..77ad084 100644 --- a/tests/test-wc-retailcrm-base.php +++ b/tests/test-wc-retailcrm-base.php @@ -119,8 +119,6 @@ class WC_Retailcrm_Base_Test extends WC_Retailcrm_Test_Case_Helper $this->assertArrayHasKey('export_selected_orders_ids', $this->baseRetailcrm->form_fields); $this->assertArrayHasKey('export_selected_orders_btn', $this->baseRetailcrm->form_fields); - //Debug info settings - $this->assertArrayHasKey('debug_mode', $this->baseRetailcrm->form_fields); $this->assertArrayHasKey('debug-info', $this->baseRetailcrm->form_fields); //Other settings