diff --git a/src/include/api/class-wc-retailcrm-proxy.php b/src/include/api/class-wc-retailcrm-proxy.php index f44f69c..027f11f 100644 --- a/src/include/api/class-wc-retailcrm-proxy.php +++ b/src/include/api/class-wc-retailcrm-proxy.php @@ -38,25 +38,20 @@ if (!class_exists('WC_Retailcrm_Proxy')) : 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 * * @return string[] */ - private function methodsWithoutDebugResponse() + private function methodsWithoutFullResponse() { - $methodsList = array('statusesList', 'paymentTypesList', 'deliveryTypesList', 'orderMethodsList'); + $methodsList = array( + 'statusesList', + 'paymentTypesList', + 'deliveryTypesList', + 'orderMethodsList', + 'storesList' + ); foreach ($methodsList as $key => $method) { $method = get_class($this->retailcrm) . '::' . $method; @@ -68,71 +63,67 @@ 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)) + WC_Retailcrm_Logger::info( + $method, + empty($arguments) ? '[no params]' : json_encode($arguments), WC_Retailcrm_Logger::TYPE[0] ); /** @var \WC_Retailcrm_Response $response */ $response = call_user_func_array(array($this->retailcrm, $method), $arguments); if (is_string($response)) { - WC_Retailcrm_Logger::debug($called, array($response)); + WC_Retailcrm_Logger::info($method, $response, WC_Retailcrm_Logger::TYPE[1]); return $response; } if (empty($response)) { - WC_Retailcrm_Logger::add(sprintf("[%s] null (no response whatsoever)", $called)); + WC_Retailcrm_Logger::error( + $method, + sprintf("[%s] null (no response whatsoever)", $called), + WC_Retailcrm_Logger::TYPE[1] + ); + 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())); - } + if (in_array( + $called, + $this->methodsWithoutFullResponse() + )) { + WC_Retailcrm_Logger::info( + $method, + 'Ok [request was successful, but response is omitted]', + WC_Retailcrm_Logger::TYPE[1] + ); + } else { + WC_Retailcrm_Logger::info( + $method, + 'Ok ' . $response->getRawResponse(), + WC_Retailcrm_Logger::TYPE[1] + ); } - $result = ' Ok'; } else { - $result = sprintf( - $called ." : Error: [HTTP-code %s] %s", + WC_Retailcrm_Logger::error($method, sprintf( + "Error: [HTTP-code %s] %s %s", $response->getStatusCode(), - $response->getErrorString() + $response->getErrorString(), + $response->getRawResponse()), + WC_Retailcrm_Logger::TYPE[1] ); - - 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)); + WC_Retailcrm_Logger::error($method, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } 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)); + WC_Retailcrm_Logger::error($method, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } 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)); + WC_Retailcrm_Logger::error($method, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } return !empty($response) ? $response : new WC_Retailcrm_Response(900, '{}'); diff --git a/src/include/class-wc-retailcrm-base.php b/src/include/class-wc-retailcrm-base.php index 9f8b65b..e7bde3f 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::setEntry(__FUNCTION__); $this->init_form_fields(); $this->init_settings(); } @@ -193,6 +194,8 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function api_sanitized($settings) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + WC_Retailcrm_Logger::info(__METHOD__, 'Module settings: ' . json_encode($settings)); $isLoyaltyUploadPrice = false; if ( @@ -285,6 +288,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function clear_cron_tasks() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); wp_clear_scheduled_hook('retailcrm_icml'); wp_clear_scheduled_hook('retailcrm_history'); wp_clear_scheduled_hook('retailcrm_inventories'); @@ -301,6 +305,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function generate_icml() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); /* * A temporary solution. * We have rebranded the module and changed the name of the ICML file. @@ -360,9 +365,11 @@ 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 +379,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, task automatically upload 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 +409,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function retailcrm_history_get() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $retailcrm_history = new WC_Retailcrm_History($this->apiClient); $retailcrm_history->getHistory(); } @@ -410,6 +421,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function retailcrm_process_order($order_id) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $order_id); $this->orders->orderCreate($order_id); } @@ -420,6 +432,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function load_stocks() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $inventories = new WC_Retailcrm_Inventories($this->apiClient); $inventories->updateQuantity(); @@ -434,6 +447,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function upload_selected_orders() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $this->uploader->uploadSelectedOrders(); } @@ -444,6 +458,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function upload_to_crm() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $page = filter_input(INPUT_POST, 'Step'); $entity = filter_input(INPUT_POST, 'Entity'); @@ -466,12 +481,13 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function create_customer($customerId) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $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 +510,16 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function update_customer($customerId) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $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; } @@ -517,6 +537,7 @@ if (!class_exists('WC_Retailcrm_Base')) { public function create_order($order_id) { if (is_admin()) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $order_id); $this->retailcrm_process_order($order_id); } } @@ -532,27 +553,41 @@ if (!class_exists('WC_Retailcrm_Base')) { { global $woocommerce; + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + 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::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } @@ -571,31 +606,49 @@ if (!class_exists('WC_Retailcrm_Base')) { { global $woocommerce; + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + 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::info( + __METHOD__, + $exception->getMessage() + ); } } public function update_order($orderId) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $orderId); if (WC_Retailcrm_Plugin::history_running() === true) { return; } @@ -614,6 +667,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function take_update_order($order_id) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $order_id); if ( WC_Retailcrm_Plugin::history_running() === true || did_action('woocommerce_checkout_order_processed') @@ -627,6 +681,7 @@ if (!class_exists('WC_Retailcrm_Base')) { public function update_order_loyalty() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); if ($this->updatedOrderId !== []) { foreach ($this->updatedOrderId as $orderId) { $this->orders->updateOrder($orderId); @@ -636,12 +691,14 @@ if (!class_exists('WC_Retailcrm_Base')) { public function update_order_items($orderId) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $orderId); $this->orders->updateOrder($orderId); } public function trash_order_action($id) { if ('shop_order' == get_post_type($id)) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__, $id); $this->orders->updateOrder($id, true); } } @@ -740,7 +797,9 @@ if (!class_exists('WC_Retailcrm_Base')) { } if (!$isSuccessful) { - writeBaseLogs('Errors when registering a loyalty program. Passed parameters: ' . + WC_Retailcrm_Logger::error( + __METHOD__, + 'Errors when registering a loyalty program. Passed parameters: ' . json_encode(['site' => $site, 'userId' => $userId, 'phone' => $phone]) ); echo json_encode(['error' => __('Error while registering in the loyalty program. Try again later', 'retailcrm')]); @@ -761,7 +820,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 +834,8 @@ if (!class_exists('WC_Retailcrm_Base')) { public function coupon_info() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + try { $result = $this->loyalty->createLoyaltyCoupon(); @@ -786,52 +850,59 @@ 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::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } public function refresh_loyalty_coupon() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + try { $this->loyalty->createLoyaltyCoupon(true); } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } public function clear_loyalty_coupon() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); + try { $this->loyalty->clearLoyaltyCoupon(); } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } public function remove_coupon($couponCode) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); try { if (!$this->loyalty->deleteLoyaltyCoupon($couponCode)) { $this->loyalty->createLoyaltyCoupon(true); } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } public function apply_coupon($couponCode) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); try { if (!$this->loyalty->isLoyaltyCoupon($couponCode)) { $this->loyalty->createLoyaltyCoupon(true); } } catch (Throwable $exception) { - writeBaseLogs($exception->getMessage()); + WC_Retailcrm_Logger::error(__METHOD__, $exception->getMessage(), WC_Retailcrm_Logger::TYPE[2]); } } public function reviewCreditBonus() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $resultHtml = $this->loyalty->getCreditBonuses(); if ($resultHtml) { @@ -1009,6 +1080,7 @@ if (!class_exists('WC_Retailcrm_Base')) { if (!$this->apiClient instanceof WC_Retailcrm_Proxy) { return null; } + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $orderMetaData = $this->getMetaData('order'); $customerMetaData = $this->getMetaData('user'); @@ -1046,6 +1118,7 @@ if (!class_exists('WC_Retailcrm_Base')) { public function add_loyalty_item($items) { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $items['loyalty'] = __('Loyalty program', 'retailcrm'); return $items; @@ -1063,6 +1136,7 @@ if (!class_exists('WC_Retailcrm_Base')) { if (!isset($userId)) { return; } + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $jsScript = 'retailcrm-loyalty-actions'; $loyaltyUrl = ['url' => get_admin_url()]; @@ -1168,6 +1242,7 @@ if (!class_exists('WC_Retailcrm_Base')) { */ public function deactivate() { + WC_Retailcrm_Logger::setEntry(__FUNCTION__); $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..d0b610a 100644 --- a/src/include/class-wc-retailcrm-cart.php +++ b/src/include/class-wc-retailcrm-cart.php @@ -80,7 +80,11 @@ 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::error( + __METHOD__, + 'Error process cart: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2] + ); } return $isSuccessful; @@ -97,7 +101,11 @@ if (!class_exists('WC_Retailcrm_Carts')) : $isSuccessful = $clearResponse->isSuccessful() && !empty($clearResponse['success']); } } catch (Throwable $exception) { - writeBaseLogs('Error clear cart: ' . $exception->getMessage()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Error clear cart: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2]) + ; } return $isSuccessful; diff --git a/src/include/class-wc-retailcrm-customers.php b/src/include/class-wc-retailcrm-customers.php index 0c0f87f..0c22bf2 100644 --- a/src/include/class-wc-retailcrm-customers.php +++ b/src/include/class-wc-retailcrm-customers.php @@ -98,6 +98,7 @@ if (!class_exists('WC_Retailcrm_Customers')) : if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) { return null; } + WC_Retailcrm_Logger::info(__METHOD__, 'WC_Customer: ' . $customerId); $wcCustomer = new WC_Customer($customerId); $email = $wcCustomer->get_billing_email(); @@ -107,7 +108,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 +137,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 +146,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 +174,15 @@ 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__, 'WC_Customer: ' . WC_Retailcrm_Logger::formatWCObject($customer) + ); $this->processCustomer($customer, $order); $response = $this->retailcrm->customersCreate($this->customer); @@ -200,6 +211,9 @@ if (!class_exists('WC_Retailcrm_Customers')) : $customer = $this->wcCustomerGet($customerId); if ($this->isCustomer($customer)) { + WC_Retailcrm_Logger::info( + __METHOD__, 'WC_Customer: ' . WC_Retailcrm_Logger::formatWCObject($customer) + ); $this->processCustomer($customer); $this->retailcrm->customersEdit($this->customer); } @@ -225,6 +239,11 @@ if (!class_exists('WC_Retailcrm_Customers')) : $customer = $this->wcCustomerGet($customerId); if ($this->isCustomer($customer)) { + WC_Retailcrm_Logger::info(__METHOD__, sprintf( + 'WC_Customer: %s. CRM_Customer ID: %s', + WC_Retailcrm_Logger::formatWCObject($customer), + $crmCustomerId) + ); $this->processCustomer($customer); $this->customer['id'] = $crmCustomerId; $this->retailcrm->customersEdit($this->customer, 'id'); @@ -368,6 +387,9 @@ if (!class_exists('WC_Retailcrm_Customers')) : */ public function processCustomerForUpload($customer) { + WC_Retailcrm_Logger::info( + __METHOD__, 'WC_Customer: ' . WC_Retailcrm_Logger::formatWCObject($customer) + ); $this->processCustomer($customer); } @@ -675,6 +697,15 @@ 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__,'New customer: ', json_encode( + [ + 'firstName' => $new_customer->get_first_name(), + 'lastName' => $new_customer->get_last_name(), + 'email' => $new_customer->get_email(), + 'created' => $new_customer->get_date_created() + ] + )); + return $new_customer; } diff --git a/src/include/class-wc-retailcrm-history.php b/src/include/class-wc-retailcrm-history.php index f665ed6..243f38c 100644 --- a/src/include/class-wc-retailcrm-history.php +++ b/src/include/class-wc-retailcrm-history.php @@ -83,12 +83,14 @@ if (!class_exists('WC_Retailcrm_History')) : $this->ordersHistory(); // @codeCoverageIgnoreStart } catch (\Exception $exception) { - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( '[%s] - %s', $exception->getMessage(), 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() - ) + ), + WC_Retailcrm_Logger::TYPE[2] ); } // @codeCoverageIgnoreEnd @@ -118,15 +120,10 @@ 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'] - ]); - $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: ' . json_encode($customers)); WC_Retailcrm_Plugin::$history_run = true; foreach ($customers as $crmCustomer) { @@ -145,7 +142,7 @@ if (!class_exists('WC_Retailcrm_History')) : // @codeCoverageIgnoreStart if (!$builder->loadExternalId($crmCustomer['externalId'])) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( + WC_Retailcrm_Logger::info(__METHOD__, sprintf( 'Customer with id=%s is not found in the DB, skipping...', $crmCustomer['externalId'] )); @@ -175,20 +172,23 @@ 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__, sprintf( + 'Updated WC_Customer %s: %s', + $crmCustomer['externalId'], + 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::error( + __METHOD__, + sprintf( + 'Error: %s - %s', + $exception->getMessage(), + 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() + ), + WC_Retailcrm_Logger::TYPE[2] + ); } // @codeCoverageIgnoreEnd } @@ -229,14 +229,14 @@ if (!class_exists('WC_Retailcrm_History')) : update_option('retailcrm_orders_history_since_id', $lastChange['id']); - WC_Retailcrm_Logger::debug(__METHOD__, [ - 'Processing orders history, ID:', + 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: ' . json_encode($historyAssembly)); WC_Retailcrm_Plugin::$history_run = true; foreach ($historyAssembly as $orderHistory) { @@ -297,14 +297,21 @@ if (!class_exists('WC_Retailcrm_History')) : $this->retailcrm->ordersEdit($orderEditData, 'id'); } + + WC_Retailcrm_Logger::info( + __METHOD__, + 'Result WC_Order: ' . WC_Retailcrm_Logger::formatWCObject($wcOrder) + ); } } catch (Exception $exception) { - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( - '[%s] - %s', + 'Error: %s - %s', $exception->getMessage(), 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() - ) + ), + WC_Retailcrm_Logger::TYPE[2] ); continue; @@ -406,6 +413,7 @@ if (!class_exists('WC_Retailcrm_History')) : if (!$wcOrder instanceof WC_Order) { return false; } + WC_Retailcrm_Logger::info(__METHOD__, 'Updating WC_Order: ' . WC_Retailcrm_Logger::formatWCObject($wcOrder)); if (isset($order['status']) && isset($options[$order['status']])) { $wcOrder->update_status($options[$order['status']]); @@ -485,7 +493,7 @@ if (!class_exists('WC_Retailcrm_History')) : ); if (!$wcProduct) { - WC_Retailcrm_Logger::add('Product not found by ' . $this->bindField); + WC_Retailcrm_Logger::error(__METHOD__, 'Product not found by ' . $this->bindField); continue; } @@ -647,6 +655,7 @@ if (!class_exists('WC_Retailcrm_History')) : if (!isset($order['create'])) { return false; } + WC_Retailcrm_Logger::info(__METHOD__, 'Creating WC_Order from CRM_Order: ' . json_encode($order)); if ( is_array($this->orderMethods) @@ -700,7 +709,8 @@ if (!class_exists('WC_Retailcrm_History')) : if (!empty($order['contact']['address'])) { $billingAddress = $order['contact']['address']; } else { - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( '[%d] => %s', $order['id'], @@ -723,7 +733,9 @@ 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,10 +749,10 @@ if (!class_exists('WC_Retailcrm_History')) : } if ($wcOrder instanceof WP_Error) { - WC_Retailcrm_Logger::add(sprintf( + WC_Retailcrm_Logger::error(__METHOD__, sprintf( '[%d] error while creating order: %s', $order['id'], - print_r($wcOrder->get_error_messages(), true) + json_encode($wcOrder->get_error_messages()) )); return false; @@ -830,7 +842,7 @@ if (!class_exists('WC_Retailcrm_History')) : ); if (!$wcProduct) { - WC_Retailcrm_Logger::add('Product not found by ' . $this->bindField); + WC_Retailcrm_Logger::error(__METHOD__, 'Product not found by ' . $this->bindField); continue; } @@ -951,9 +963,10 @@ 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'] ) @@ -966,9 +979,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 +1128,12 @@ if (!class_exists('WC_Retailcrm_History')) : */ private function addProductInWcOrder($wcOrder, $wcProduct, $crmProduct) { + WC_Retailcrm_Logger::info(__METHOD__, sprintf( + 'WC_Order: %s, WC_Product: %s, CRM_Product: %s', + WC_Retailcrm_Logger::formatWCObject($wcOrder), + WC_Retailcrm_Logger::formatWCObject($wcProduct), + json_encode($crmProduct) + )); $discountTotal = $crmProduct['discountTotal']; $productQuantity = $crmProduct['quantity']; @@ -1164,6 +1184,15 @@ if (!class_exists('WC_Retailcrm_History')) : $wcOrderItem->save(); } + + WC_Retailcrm_Logger::info( + __METHOD__, + sprintf( + 'WC_Order_Item: %s, CRM_Product: %s', + WC_Retailcrm_Logger::formatWCObject($wcOrderItem), + json_encode($crmProduct) + ) + ); } private function getProductSubTotalPrice($wcProduct, $quantity) @@ -1200,15 +1229,15 @@ 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 ' . json_encode($order)); if (isset($order['customer'])) { $crmOrder = $this->getCRMOrder($order['id'], 'id'); if (empty($crmOrder)) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( + WC_Retailcrm_Logger::info(__METHOD__, sprintf( 'Cannot get order data from retailCRM. Skipping customer change. History data: %s', - print_r($order, true) + json_encode($order) )); return false; @@ -1239,9 +1268,9 @@ if (!class_exists('WC_Retailcrm_History')) : } if (empty($crmOrder)) { - WC_Retailcrm_Logger::addCaller(__METHOD__, sprintf( + WC_Retailcrm_Logger::info(__METHOD__, sprintf( 'Cannot get order data from retailCRM. Skipping customer change. History data: %s', - print_r($order, true) + json_encode($order) )); return false; @@ -1284,13 +1313,13 @@ if (!class_exists('WC_Retailcrm_History')) : isset($order['company']) ? $order['company']['name'] : '', $exception->getMessage() ); - WC_Retailcrm_Logger::addCaller(__METHOD__, $errorMessage); - WC_Retailcrm_Logger::debug(__METHOD__, sprintf( - '%s%s%s', + + WC_Retailcrm_Logger::error(__METHOD__, sprintf( + '%s - %s', $errorMessage, - PHP_EOL, - $exception->getTraceAsString() - )); + 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()), + WC_Retailcrm_Logger::TYPE[2] + ); $handled = false; } // @codeCoverageIgnoreEnd @@ -1396,14 +1425,12 @@ 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() . + ': ' . + json_encode($crmCustomer) ); if ($isContact) { diff --git a/src/include/class-wc-retailcrm-icml.php b/src/include/class-wc-retailcrm-icml.php index 80d1116..42dc1b8 100644 --- a/src/include/class-wc-retailcrm-icml.php +++ b/src/include/class-wc-retailcrm-icml.php @@ -76,7 +76,7 @@ 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 +85,7 @@ 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 +95,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 +128,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..59c6bb6 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::error( + __METHOD__, + 'Exception get loyalty accounts: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2] + ); return $result; } @@ -83,12 +87,19 @@ 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->getRawResponse() + ); } return $response->isSuccessful(); } catch (Throwable $exception) { - writeBaseLogs('Exception while registering in the loyalty program: ' . $exception->getMessage()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Exception while registering in the loyalty program: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2] + ); return false; } @@ -100,12 +111,19 @@ 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->getRawResponse() + ); } return $response->isSuccessful(); } catch (Throwable $exception) { - writeBaseLogs('Exception while activate loyalty account: ' . $exception->getMessage()); + WC_Retailcrm_Logger::error( + __METHOD__, + 'Exception while activate loyalty account: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2] + ); return false; } @@ -341,7 +359,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::error( + __METHOD__, + 'Exception get loyalty accounts: ' . $exception->getMessage(), + WC_Retailcrm_Logger::TYPE[2] + ); return false; } @@ -414,7 +436,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..0fc0faf 100644 --- a/src/include/class-wc-retailcrm-orders.php +++ b/src/include/class-wc-retailcrm-orders.php @@ -95,6 +95,7 @@ if (!class_exists('WC_Retailcrm_Orders')) : if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) { return null; } + WC_Retailcrm_Logger::info(__METHOD__, 'Start order creating ' . $orderId); try { $this->order_payment->resetData(); @@ -113,7 +114,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 +127,9 @@ if (!class_exists('WC_Retailcrm_Orders')) : } } + WC_Retailcrm_Logger::info( + __METHOD__, 'WC_Order: ' . WC_RETAILCRM_LOGGER::formatWCObject($wcOrder) + ); $this->processOrder($wcOrder); if (isset($privilegeType)) { @@ -142,13 +149,15 @@ if (!class_exists('WC_Retailcrm_Orders')) : $this->loyalty->applyLoyaltyDiscount($wcOrder, $response['order'], $discountLp); } } catch (Throwable $exception) { - writeBaseLogs( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( 'Error message: %s, file: %s on line: %s', $exception->getMessage(), $exception->getFile(), $exception->getLine() - ) + ), + WC_Retailcrm_Logger::TYPE[2] ); return null; @@ -211,6 +220,9 @@ if (!class_exists('WC_Retailcrm_Orders')) : */ protected function fillOrderCreate($wcCustomerId, $wcCustomerEmail, $wcOrder) { + WC_Retailcrm_Logger::info(__METHOD__, sprintf( + '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,7 +276,8 @@ if (!class_exists('WC_Retailcrm_Orders')) : // If address not found create new address. if (!$addressFound) { - WC_Retailcrm_Logger::add( + WC_Retailcrm_Logger::info( + __METHOD__, sprintf( '[%d] => %s', $this->order['customer']['id'], @@ -317,6 +330,9 @@ if (!class_exists('WC_Retailcrm_Orders')) : try { $wcOrder = wc_get_order($orderId); + WC_Retailcrm_Logger::info( + __METHOD__, 'WC_Order: ' . WC_Retailcrm_Logger::formatWCObject($wcOrder) + ); $needRecalculate = false; $this->processOrder($wcOrder, true, $statusTrash); @@ -334,7 +350,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,13 +368,15 @@ if (!class_exists('WC_Retailcrm_Orders')) : } } } catch (Throwable $exception) { - writeBaseLogs( + WC_Retailcrm_Logger::error( + __METHOD__, sprintf( 'Error message: %s, file: %s on line: %s', $exception->getMessage(), $exception->getFile(), $exception->getLine() - ) + ), + WC_Retailcrm_Logger::TYPE[2] ); return null; @@ -429,6 +447,7 @@ if (!class_exists('WC_Retailcrm_Orders')) : } if ('auto-draft' === $order->get_status()) { + WC_Retailcrm_Logger::info(__METHOD__, 'Skip, order in auto-draft status'); return; } @@ -519,6 +538,9 @@ if (!class_exists('WC_Retailcrm_Orders')) : $orderItems[] = $this->order_item->build($item, $crmItem)->getData(); $this->order_item->resetData($this->cancelLoyalty); + WC_Retailcrm_Logger::info( + __METHOD__, 'WC_Order_Item_Product: ' . WC_RETAILCRM_LOGGER::formatWCObject($item) + ); } unset($crmItems, $crmItem); diff --git a/src/include/class-wc-retailcrm-uploader.php b/src/include/class-wc-retailcrm-uploader.php index 2c9241a..9e96a27 100644 --- a/src/include/class-wc-retailcrm-uploader.php +++ b/src/include/class-wc-retailcrm-uploader.php @@ -60,6 +60,7 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { public function uploadSelectedOrders() { $ids = $_GET['order_ids_retailcrm']; + WC_Retailcrm_Logger::info(__METHOD__, 'IDs: ' . json_encode($ids)); if (!empty($ids)) { preg_match_all('/\d+/', $ids, $matches); @@ -81,6 +82,7 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { */ public function uploadArchiveOrders($page, $ids = []) { + WC_Retailcrm_Logger::info(__METHOD__, 'IDs: ' . implode(', ', $ids)); if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) { return null; } @@ -223,13 +225,11 @@ if (class_exists('WC_Retailcrm_Uploader') === false) { return; } - WC_Retailcrm_Logger::add('Errors while uploading these orders'); + WC_Retailcrm_Logger::error(__METHOD__, '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("[%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..7d650c8 100644 --- a/src/include/components/class-wc-retailcrm-customer-switcher.php +++ b/src/include/components/class-wc-retailcrm-customer-switcher.php @@ -43,7 +43,7 @@ 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__, 'State: ' . json_encode($this->data)); $newCustomer = $this->data->getNewCustomer(); $newContact = $this->data->getNewContact(); @@ -51,36 +51,32 @@ 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 +102,9 @@ 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 - ) + sprintf('Switching in order %s to %s', $wcOrder->get_id(), json_encode($newCustomer)) ); if (isset($newCustomer['externalId'])) { @@ -121,24 +112,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..3a2ebcb 100644 --- a/src/include/components/class-wc-retailcrm-logger.php +++ b/src/include/components/class-wc-retailcrm-logger.php @@ -19,6 +19,12 @@ if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')) : /** @var string */ const HANDLE = 'retailcrm'; + const TYPE = array( + 0 => 'REQUEST', + 1 => 'RESPONSE', + 2 => 'EXCEPTION' + ); + /** * @var \WC_Logger_Interface $instance */ @@ -29,6 +35,25 @@ if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')) : */ private static $additionalHandlers; + /** + * @var string $logIdentifier + */ + private static $logIdentifier; + + /** + * First called action name + * + * @var string $entrypoint + */ + private static $entrypoint; + + /** + * First called action time + * + * @var float $startTime + */ + private static $startTime; + /** * WC_Retailcrm_Logger constructor. */ @@ -57,72 +82,136 @@ if (!class_exists('WC_Retailcrm_Logger') && class_exists('WC_Log_Levels')) : } /** - * Regular logging + * Called in base class for action hooks * - * @param string $message - * @param string $level + * @param string $action + * @param $id + * @return void */ - public static function add($message, $level = WC_Log_Levels::NOTICE) + public static function setEntry(string $action, $id = null) { - self::getInstance()->add(self::HANDLE, $message, $level); - } - - /** - * 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) - { - 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 (empty(static::$entrypoint)) { + static::$entrypoint = $id === null ? $action : sprintf('%s-%s', $action, $id); } } + + private static function getIdentifier() + { + if (empty(static::$logIdentifier)) { + static::$logIdentifier = substr(uniqid('', false), -8); + } + + return static::$logIdentifier; + } + + private static function getStartTime() + { + if (empty(static::$startTime)) { + static::$startTime = microtime(true); + } + + return static::$startTime; + } + + /** + * Error logging + * + * @param string $method + * @param string $message + * @param null|string $type + */ + public static function error(string $method, string $message, $type = null) + { + self::log($method, $message, $type, WC_Log_Levels::ERROR); + } + + /** + * Info logging + * + * @param string $method + * @param string $message + * @param null|string $type + */ + public static function info(string $method, string $message, $type = null) + { + self::log($method, $message, $type, WC_Log_Levels::INFO); + } + + /** + * Regular logging function. + * + * @param string $method + * @param string $message + * @param string|null $type + * @param string|null $level + */ + private static function log(string $method, string $message, $type = null, $level = null) + { + $time = self::getStartTime(); + $context = ['time' => round((microtime(true) - $time), 3), 'source' => self::HANDLE]; + + $message = sprintf( + '%s [%s] <%s> %s=> %s', + self::getIdentifier(), + self::$entrypoint, + $method, + $type ? $type . ' ' : '', + $message + ); + + self::getInstance()->log($level ?? 'info', $message, $context); + } + + public static function formatWCObject($object): string + { + if ($object instanceof WC_Order) { + return json_encode([ + 'id' => $object->get_id(), + 'status' => $object->get_status(), + 'date_modified' => $object->get_date_modified(), + 'total' => $object->get_total(), + 'shipping' => [ + "first_name" => $object->get_shipping_first_name(), + "last_name" => $object->get_shipping_last_name(), + "company" => $object->get_shipping_company(), + "address_1" => $object->get_shipping_address_1(), + "address_2" => $object->get_shipping_address_2(), + "city" => $object->get_shipping_city(), + "state" => $object->get_shipping_state(), + "postcode" => $object->get_shipping_postcode(), + "country" => $object->get_shipping_country(), + "phone" => $object->get_shipping_phone() + ], + 'email' => $object->get_billing_email(), + 'payment_method_title' => $object->get_payment_method_title(), + ]); + } + + if ($object instanceof WC_Customer) { + return json_encode([ + 'id' => $object->get_id(), + 'date_modified' => $object->get_date_modified(), + 'email' => $object->get_email(), + 'display_name' => $object->get_display_name(), + 'role' => $object->get_role(), + 'username' => $object->get_username(), + 'shipping' => [ + "first_name" => $object->get_shipping_first_name(), + "last_name" => $object->get_shipping_last_name(), + "company" => $object->get_shipping_company(), + "address_1" => $object->get_shipping_address_1(), + "address_2" => $object->get_shipping_address_2(), + "city" => $object->get_shipping_city(), + "state" => $object->get_shipping_state(), + "postcode" => $object->get_shipping_postcode(), + "country" => $object->get_shipping_country(), + "phone" => $object->get_shipping_phone() + ], + ]); + } + + return method_exists($object, 'get_data') ? + json_encode(array_filter($object->get_data())) : json_encode($object); + } } 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..319e857 100644 --- a/src/include/customer/class-wc-retailcrm-customer-address.php +++ b/src/include/customer/class-wc-retailcrm-customer-address.php @@ -33,7 +33,10 @@ 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. 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..49f4b98 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,10 @@ 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. 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..781340b 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,10 @@ 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: ' . json_encode($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..e7de3ca 100644 --- a/src/include/functions.php +++ b/src/include/functions.php @@ -189,7 +189,7 @@ function calculatePriceExcludingTax($priceIncludingTax, $rate) */ function writeBaseLogs($message) { - WC_Retailcrm_Logger::addCaller(__METHOD__, $message); + WC_Retailcrm_Logger::info(__METHOD__, $message); } /** 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..04b2aaf 100644 --- a/src/include/models/class-wc-retailcrm-customer-switcher-result.php +++ b/src/include/models/class-wc-retailcrm-customer-switcher-result.php @@ -63,12 +63,12 @@ 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 + sprintf( + 'Saving customer: %s and order: %s', + WC_Retailcrm_Logger::formatWCObject($this->wcCustomer), + WC_Retailcrm_Logger::formatWCObject($this->wcOrder) ) ); 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..e589be0 100644 --- a/src/include/models/class-wc-retailcrm-customer-switcher-state.php +++ b/src/include/models/class-wc-retailcrm-customer-switcher-state.php @@ -170,12 +170,12 @@ 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() + sprintf( + 'State data - customer: %s and contact: %s', + json_encode($this->getNewCustomer()), + json_encode($this->getNewContact()) ) ); throw new \InvalidArgumentException( 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..122251a 100644 --- a/src/include/order/class-wc-retailcrm-order-payment.php +++ b/src/include/order/class-wc-retailcrm-order-payment.php @@ -62,15 +62,11 @@ 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__, + '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.' ); } else { $paymentData['status'] = 'paid';