diff --git a/src/include/api/class-wc-retailcrm-client-v5.php b/src/include/api/class-wc-retailcrm-client-v5.php index 273cb36..593a043 100644 --- a/src/include/api/class-wc-retailcrm-client-v5.php +++ b/src/include/api/class-wc-retailcrm-client-v5.php @@ -161,28 +161,25 @@ class WC_Retailcrm_Client_V5 /** * Get corporate customers history + * * @param array $filter - * @param null $page - * @param null $limit + * @param int $page + * @param int $limit * * @return WC_Retailcrm_Response */ - public function customersCorporateHistory(array $filter= array(), $page = null, $limit = null) + public function customersCorporateHistory(array $filter = [], int $page = 1, int $limit = 100) { - $parameters= array(); - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } + $parameters = [ + 'page' => $page, + 'limit' => $limit, + 'filter' => $filter, + ]; + /* @noinspection PhpUndefinedMethodInspection */ return $this->client->makeRequest( '/customers-corporate/history', - "GET", + WC_Retailcrm_Request::METHOD_GET, $parameters ); } @@ -1218,25 +1215,20 @@ class WC_Retailcrm_Client_V5 /** * Get orders history + * * @param array $filter - * @param null $page - * @param null $limit + * @param int $page + * @param int $limit * * @return WC_Retailcrm_Response */ - public function ordersHistory(array $filter = array(), $page = null, $limit = null) + public function ordersHistory(array $filter = [], int $page = 1, int $limit = 100) { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } + $parameters = [ + 'page' => $page, + 'limit' => $limit, + 'filter' => $filter, + ]; return $this->client->makeRequest( '/orders/history', @@ -1542,25 +1534,20 @@ class WC_Retailcrm_Client_V5 /** * Get customers history + * * @param array $filter - * @param null $page - * @param null $limit + * @param int $page + * @param int $limit * * @return WC_Retailcrm_Response */ - public function customersHistory(array $filter = array(), $page = null, $limit = null) + public function customersHistory(array $filter = [], int $page = 1, int $limit = 100) { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } + $parameters = [ + 'page' => $page, + 'limit' => $limit, + 'filter' => $filter, + ]; return $this->client->makeRequest( '/customers/history', @@ -1743,28 +1730,22 @@ class WC_Retailcrm_Client_V5 * Get orders assembly history * * @param array $filter (default: array()) - * @param int $page (default: null) - * @param int $limit (default: null) + * @param int $page (default: int) + * @param int $limit (default: null) * - * @throws InvalidArgumentException + * @return WC_Retailcrm_Response * @throws WC_Retailcrm_Exception_Curl * @throws WC_Retailcrm_Exception_Json * - * @return WC_Retailcrm_Response + * @throws InvalidArgumentException */ - public function ordersPacksHistory(array $filter = array(), $page = null, $limit = null) + public function ordersPacksHistory(array $filter = [], int $page = 1, int $limit = 100) { - $parameters = array(); - - if (count($filter)) { - $parameters['filter'] = $filter; - } - if (null !== $page) { - $parameters['page'] = (int) $page; - } - if (null !== $limit) { - $parameters['limit'] = (int) $limit; - } + $parameters = [ + 'page' => $page, + 'limit' => $limit, + 'filter' => $filter, + ]; return $this->client->makeRequest( '/orders/packs/history', diff --git a/src/include/class-wc-retailcrm-history.php b/src/include/class-wc-retailcrm-history.php index 349999e..3cd9812 100644 --- a/src/include/class-wc-retailcrm-history.php +++ b/src/include/class-wc-retailcrm-history.php @@ -1,4 +1,5 @@ retailcrmSettings['order_methods'])) { $this->orderMethods = $this->retailcrmSettings['order_methods']; + unset($this->retailcrmSettings['order_methods']); } $this->retailcrm = $retailcrm; - - $this->startDate = new DateTime(date('Y-m-d H:i:s', strtotime('-1 days', strtotime(date('Y-m-d H:i:s'))))); - $this->startDateOrders = $this->startDate; - $this->startDateCustomers = $this->startDate; + $this->startDate = new DateTime('-1 days'); } /** * Get history method. * * @return void - * @throws \Exception */ public function getHistory() { - $ordersSinceId = get_option('retailcrm_orders_history_since_id'); - $customersSinceId = get_option('retailcrm_customers_history_since_id'); - - // @codeCoverageIgnoreStart - // TODO: There is a task to analyze the work of getting history by date - if (!$ordersSinceId && isset($this->retailcrmSettings['history_orders'])) { - $this->startDateOrders = new DateTime($this->retailcrmSettings['history_orders']); - } - - - if (!$customersSinceId && isset($this->retailcrmSettings['history_customers'])) { - $this->startDateCustomers = new DateTime($this->retailcrmSettings['history_customers']); - } - // @codeCoverageIgnoreEnd - try { - $this->customersHistory($this->startDateCustomers->format('Y-m-d H:i:s'), $customersSinceId); - $this->ordersHistory($this->startDateOrders->format('Y-m-d H:i:s'), $ordersSinceId); + $this->customersHistory(); + $this->ordersHistory(); // @codeCoverageIgnoreStart } catch (\Exception $exception) { WC_Retailcrm_Logger::add( - sprintf("[%s] - %s", $exception->getMessage(), - 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()) + sprintf( + "[%s] - %s", + $exception->getMessage(), + 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() + ) ); } // @codeCoverageIgnoreEnd @@ -104,164 +86,192 @@ if (!class_exists('WC_Retailcrm_History')) : /** * History customers * - * @param string $date - * @param int $sinceId - * * @return void * @throws \Exception */ - protected function customersHistory($date, $sinceId) + protected function customersHistory() { - $filter = array('startDate' => $date); + $sinceId = get_option('retailcrm_customers_history_since_id'); + $request = new WC_Retailcrm_Paginated_Request(); + $pagination = 1; - if ($sinceId) { - $filter = array('sinceId' => $sinceId); - } + $filter = !empty($sinceId) + ? ['sinceId' => $sinceId] + : ['startDate' => $this->startDate->format('Y-m-d H:i:s')]; - $request = new WC_Retailcrm_Paginated_Request(); - $history = $request - ->setApi($this->retailcrm) - ->setMethod('customersHistory') - ->setParams(array($filter, '{{page}}')) - ->setDataKey('history') - ->setLimit(100) - ->execute() - ->getData(); + do { + $history = $request + ->reset() + ->setApi($this->retailcrm) + ->setMethod('customersHistory') + ->setParams([$filter]) + ->execute() + ->getData(); - if (!empty($history)) { - $builder = new WC_Retailcrm_WC_Customer_Builder(); - $lastChange = end($history); - $customers = WC_Retailcrm_History_Assembler::assemblyCustomer($history); - WC_Retailcrm_Plugin::$history_run = true; - WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled customers history:', $customers)); + if (!empty($history)) { + $builder = new WC_Retailcrm_WC_Customer_Builder(); + $lastChange = end($history); + $customers = WC_Retailcrm_History_Assembler::assemblyCustomer($history); - foreach ($customers as $crmCustomer) { - // Only update customers, if customer not exist in WP - skip this customer ! - if (!isset($crmCustomer['externalId'])) { - continue; - } + WC_Retailcrm_Plugin::$history_run = true; + WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled customers history:', $customers)); - try { - $builder->reset(); + foreach ($customers as $crmCustomer) { + /* + * Only update customers, if customer not exist in WP - skip this customer ! + * Update sinceId, because we must process history data. + */ + if (!isset($crmCustomer['externalId'])) { + $filter['sinceId'] = $lastChange['id']; - // @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'] - )); continue; } + + try { + $builder->reset(); + + // @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'] + )); + + // If customer not found in the DB, update sinceId + $filter['sinceId'] = $lastChange['id']; + + continue; + } + // @codeCoverageIgnoreEnd + + $wcCustomer = $builder + ->setData($crmCustomer) + ->build() + ->getResult(); + + if ($wcCustomer instanceof WC_Customer) { + $wcCustomer->save(); + + $customerCustomFields = $this->getCustomData('customer'); + + $this->updateMetaData($customerCustomFields, $crmCustomer, $wcCustomer->get_id()); + } + + WC_Retailcrm_Logger::debug(__METHOD__, array('Updated WC_Customer:', $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()); + } // @codeCoverageIgnoreEnd - $wcCustomer = $builder - ->setData($crmCustomer) - ->build() - ->getResult(); + update_option('retailcrm_customers_history_since_id', $lastChange['id']); - if ($wcCustomer instanceof WC_Customer) { - $wcCustomer->save(); - - $customerCustomFields = $this->getCustomData('customer'); - - $this->updateMetaData($customerCustomFields, $crmCustomer, $wcCustomer->get_id()); - } - - WC_Retailcrm_Logger::debug(__METHOD__, array('Updated WC_Customer:', $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()); + $filter['sinceId'] = $lastChange['id']; } - // @codeCoverageIgnoreEnd + } else { + break; } - update_option('retailcrm_customers_history_since_id', $lastChange['id']); - WC_Retailcrm_Plugin::$history_run = false; - } + $pagination++; + } while ($pagination !== self::PAGE_LIMIT); } /** * History orders * - * @param string $date - * @param int $sinceId - * - * @return boolean + * @return bool */ - protected function ordersHistory($date, $sinceId) + protected function ordersHistory() { - $filter = array('startDate' => $date); - $options = array_flip(array_filter($this->retailcrmSettings)); + $options = array_flip(array_filter($this->retailcrmSettings)); + $sinceId = get_option('retailcrm_orders_history_since_id'); + $request = new WC_Retailcrm_Paginated_Request(); + $pagination = 1; - if ($sinceId) { - $filter = array('sinceId' => $sinceId); - } + $filter = !empty($sinceId) + ? ['sinceId' => $sinceId] + : ['startDate' => $this->startDate->format('Y-m-d H:i:s')]; - $request = new WC_Retailcrm_Paginated_Request(); - $history = $request - ->setApi($this->retailcrm) - ->setMethod('ordersHistory') - ->setParams(array($filter, '{{page}}')) - ->setDataKey('history') - ->setLimit(100) - ->execute() - ->getData(); + do { + $history = $request + ->reset() + ->setApi($this->retailcrm) + ->setMethod('ordersHistory') + ->setParams([$filter]) + ->execute() + ->getData(); - if (!empty($history)) { - $lastChange = end($history); - $historyAssembly = WC_Retailcrm_History_Assembler::assemblyOrder($history); + if (!empty($history)) { + $lastChange = end($history); + $historyAssembly = WC_Retailcrm_History_Assembler::assemblyOrder($history); - WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled orders history:', $historyAssembly)); - WC_Retailcrm_Plugin::$history_run = true; + WC_Retailcrm_Logger::debug(__METHOD__, array('Assembled orders history:', $historyAssembly)); + WC_Retailcrm_Plugin::$history_run = true; - foreach ($historyAssembly as $orderHistory) { - $order = WC_Retailcrm_Plugin::clearArray(apply_filters('retailcrm_history_before_save', $orderHistory)); - - if (isset($order['deleted']) && $order['deleted'] == true) { - continue; - } - - try { - if (isset($order['externalId'])) { - $wcOrderId = $this->orderUpdate($order, $options); - } else { - $wcOrderId = $this->orderCreate($order, $options); - } - - $wcOrder = wc_get_order($wcOrderId); - $orderCustomFields = $this->getCustomData('order'); - - $this->updateMetaData($orderCustomFields, $order, $wcOrderId, 'order'); - - if ($wcOrder instanceof WC_Order) { - $wcOrder->calculate_totals(); - } - - // @codeCoverageIgnoreStart - } catch (Exception $exception) { - WC_Retailcrm_Logger::add( - sprintf("[%s] - %s", $exception->getMessage(), - 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine()) + foreach ($historyAssembly as $orderHistory) { + $order = WC_Retailcrm_Plugin::clearArray( + apply_filters( + 'retailcrm_history_before_save', + $orderHistory + ) ); - continue; + if (isset($order['deleted']) && $order['deleted'] == true) { + continue; + } + + try { + if (isset($order['externalId'])) { + $wcOrderId = $this->orderUpdate($order, $options); + } else { + $wcOrderId = $this->orderCreate($order, $options); + } + + $wcOrder = wc_get_order($wcOrderId); + $orderCustomFields = $this->getCustomData('order'); + + $this->updateMetaData($orderCustomFields, $order, $wcOrderId, 'order'); + + if ($wcOrder instanceof WC_Order) { + $wcOrder->calculate_totals(); + } + + // @codeCoverageIgnoreStart + } catch (Exception $exception) { + WC_Retailcrm_Logger::add( + sprintf( + "[%s] - %s", + $exception->getMessage(), + 'Exception in file - ' . $exception->getFile() . ' on line ' . $exception->getLine() + ) + ); + + continue; + } + // @codeCoverageIgnoreEnd } - // @codeCoverageIgnoreEnd + + update_option('retailcrm_orders_history_since_id', $lastChange['id']); + + $filter['sinceId'] = $lastChange['id']; + } else { + break; } - update_option('retailcrm_orders_history_since_id', $lastChange['id']); - WC_Retailcrm_Plugin::$history_run = false; - } + $pagination++; + } while ($pagination !== self::PAGE_LIMIT); + + WC_Retailcrm_Plugin::$history_run = false; return true; } @@ -493,7 +503,8 @@ if (!class_exists('WC_Retailcrm_History')) : if (count($order['payments']) == 1) { $paymentType = reset($order['payments']); - if (isset($paymentType['type']) + if ( + isset($paymentType['type']) && isset($options[$paymentType['type']]) && isset($paymentTypes[$options[$paymentType['type']]]) ) { @@ -530,7 +541,7 @@ if (!class_exists('WC_Retailcrm_History')) : } if ($checkNewItem == true) { - $this->editOrder($order,'update'); + $this->editOrder($order, 'update'); } } @@ -842,9 +853,9 @@ if (!class_exists('WC_Retailcrm_History')) : */ protected function editOrder($order, $event = 'create') { - $data= array(); - $crmOrder= array(); - $orderItems= array(); + $data = []; + $crmOrder = []; + $orderItems = []; if ($event == 'update') { $result = $this->retailcrm->ordersGet($order['externalId']); @@ -965,10 +976,10 @@ if (!class_exists('WC_Retailcrm_History')) : WC_Retailcrm_Logger::debug( __METHOD__, - array( + [ 'processing order', $order - ) + ] ); if (isset($order['customer'])) { @@ -1121,14 +1132,15 @@ if (!class_exists('WC_Retailcrm_History')) : { $crmOrderResponse = $this->retailcrm->ordersGet($id, $by); - if (!empty($crmOrderResponse) + if ( + !empty($crmOrderResponse) && $crmOrderResponse->isSuccessful() && $crmOrderResponse->offsetExists('order') ) { return (array) $crmOrderResponse['order']; } - return array(); + return []; } /** @@ -1142,12 +1154,12 @@ if (!class_exists('WC_Retailcrm_History')) : { WC_Retailcrm_Logger::debug( __METHOD__, - array( + [ 'Using this individual person data in order to set it into order,', $data->getWcOrder()->get_id(), ': ', $crmCustomer - ) + ] ); if ($isContact) { diff --git a/src/include/components/class-wc-retailcrm-paginated-request.php b/src/include/components/class-wc-retailcrm-paginated-request.php index eb62ae3..df532f4 100644 --- a/src/include/components/class-wc-retailcrm-paginated-request.php +++ b/src/include/components/class-wc-retailcrm-paginated-request.php @@ -28,29 +28,11 @@ class WC_Retailcrm_Paginated_Request */ private $params; - /** - * @var string - */ - private $dataKey; - - /** - * @var int - */ - private $limit; - /** * @var array */ private $data; - /** - * WC_Retailcrm_Paginated_Request constructor. - */ - public function __construct() - { - $this->reset(); - } - /** * Sets retailCRM api client to request * @@ -61,6 +43,7 @@ class WC_Retailcrm_Paginated_Request public function setApi($api) { $this->api = $api; + return $this; } @@ -74,11 +57,12 @@ class WC_Retailcrm_Paginated_Request public function setMethod($method) { $this->method = $method; + return $this; } /** - * Sets method params for API client (leave `{{page}}` instead of page and `{{limit}}` instead of limit) + * Sets method params for API client. * * @param array $params * @@ -87,32 +71,7 @@ class WC_Retailcrm_Paginated_Request public function setParams($params) { $this->params = $params; - return $this; - } - /** - * Sets dataKey (key with data in response) - * - * @param string $dataKey - * - * @return self - */ - public function setDataKey($dataKey) - { - $this->dataKey = $dataKey; - return $this; - } - - /** - * Sets record limit per request - * - * @param int $limit - * - * @return self - */ - public function setLimit($limit) - { - $this->limit = $limit; return $this; } @@ -123,24 +82,16 @@ class WC_Retailcrm_Paginated_Request */ public function execute() { - $this->data = array(); - $response = true; - $page = 1; + $response = call_user_func_array( + [$this->api, $this->method], + $this->params + ); - do { - $response = call_user_func_array( - array($this->api, $this->method), - $this->buildParams($this->params, $page) - ); + if ($response->isSuccessful() && !empty($response['history'])) { + $this->data = array_merge($this->data, $response['history']); + } - if ($response instanceof WC_Retailcrm_Response && $response->offsetExists($this->dataKey)) { - $this->data = array_merge($this->data, $response[$this->dataKey]); - $page = $response['pagination']['currentPage'] + 1; - } - - time_nanosleep(0, 300000000); - } while ($response && (isset($response['pagination']) - && $response['pagination']['currentPage'] < $response['pagination']['totalPageCount'])); + time_nanosleep(0, 300000000); return $this; } @@ -162,33 +113,9 @@ class WC_Retailcrm_Paginated_Request */ public function reset() { + $this->data = []; $this->method = ''; - $this->limit = 100; - $this->data = array(); return $this; } - - /** - * buildParams - * - * @param array $placeholderParams - * @param int $currentPage - * - * @return mixed - */ - private function buildParams($placeholderParams, $currentPage) - { - foreach ($placeholderParams as $key => $param) { - if ($param == '{{page}}') { - $placeholderParams[$key] = $currentPage; - } - - if ($param == '{{limit}}') { - $placeholderParams[$key] = $this->limit; - } - } - - return $placeholderParams; - } } diff --git a/tests/test-wc-retailcrm-history.php b/tests/test-wc-retailcrm-history.php index 8d555d6..d9b46fd 100644 --- a/tests/test-wc-retailcrm-history.php +++ b/tests/test-wc-retailcrm-history.php @@ -100,7 +100,7 @@ class WC_Retailcrm_History_Test extends WC_Retailcrm_Test_Case_Helper $retailcrm_history->getHistory(); $orders = wc_get_orders(array( 'numberposts' => - 1 )); - $wcOrder = end($orders); + $wcOrder = end($orders); $options = get_option(\WC_Retailcrm_Base::$option_key); $this->assertEquals('status1', $options[$wcOrder->get_status()]); @@ -181,14 +181,19 @@ class WC_Retailcrm_History_Test extends WC_Retailcrm_Test_Case_Helper DataHistoryRetailCrm::get_history_data_product_add($product->get_id(), $order->get_id()) ); + $oldSinceId = get_option('retailcrm_orders_history_since_id'); $retailcrm_history = new \WC_Retailcrm_History($this->apiMock); $retailcrm_history->getHistory(); - $wcOrder = wc_get_order($order->get_id()); + $sinceId = get_option('retailcrm_orders_history_since_id'); + $wcOrder = wc_get_order($order->get_id()); $wcOrderItems = $wcOrder->get_items(); - $wcOrderItem = end($wcOrderItems); + $wcOrderItem = end($wcOrderItems); - $this->assertEquals(2, count($wcOrderItems)); + $this->assertNotEquals($sinceId, $oldSinceId); + $this->assertEquals(0, get_option('retailcrm_customers_history_since_id')); + + // Check added products $this->assertEquals(2, $wcOrderItem->get_quantity()); $this->assertEquals($product->get_id(), $wcOrderItem->get_product()->get_id()); } @@ -246,7 +251,6 @@ class WC_Retailcrm_History_Test extends WC_Retailcrm_Test_Case_Helper $this->assertNotEquals('status4', $order_updated->get_status()); } - public function test_history_customer_create() { $this->mockHistory( @@ -258,9 +262,7 @@ class WC_Retailcrm_History_Test extends WC_Retailcrm_Test_Case_Helper $retailcrm_history = new WC_Retailcrm_History($this->apiMock); $retailcrm_history->getHistory(); - $sinceId = get_option('retailcrm_orders_history_since_id'); - - $this->assertEquals(0, $sinceId); + $this->assertEquals(0, get_option('retailcrm_orders_history_since_id')); } public function test_history_customer_update()