Skip to content

Commit

Permalink
Added support WooCommerce 8.2 (HPOS) (#319)
Browse files Browse the repository at this point in the history
  • Loading branch information
uryvskiy-dima authored Dec 7, 2023
1 parent f49cc38 commit a0d6815
Show file tree
Hide file tree
Showing 16 changed files with 219 additions and 301 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 2023-12-07 4.7.0
* Added support WooCommerce 8.2 (HPOS)

## 2023-11-20 4.6.14
* Fix module activation/deactivation

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4.6.14
4.7.0
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,10 @@ public function init_form_fields()
),
];

foreach (get_post_statuses() as $status_key => $status_value) {
$this->form_fields['p_' . $status_key] = [
'title' => $status_value,
foreach (get_post_statuses() as $statusKey => $statusValue) {
$this->form_fields['p_' . $statusKey] = [
'title' => $statusValue,
'label' => ' ',
'description' => '',
'class' => 'checkbox',
'type' => 'checkbox',
'desc_tip' => true,
Expand Down
50 changes: 26 additions & 24 deletions src/include/api/class-wc-retailcrm-response.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,30 +170,32 @@ public function offsetGet($offset)
return $this->response[$offset];
}

/**
* Returns error string. If there's multiple errors present - they will be squashed into single string.
*
* @return string
*/
public function getErrorString()
{
if ($this->offsetExists('error')) {
return (string) $this->response['error'];
} elseif ($this->offsetExists('errors') && is_array($this->response['errors'])) {
$errorMessage = '';

foreach ($this->response['errors'] as $error) {
$errorMessage .= $error . ' >';
}

if (strlen($errorMessage) > 2) {
return (string) substr($errorMessage, 0, strlen($errorMessage) - 2);
}

return $errorMessage;
}

return '';
/**
* Returns error string. If there's multiple errors present - they will be squashed into single string.
*
* @return string
*/
public function getErrorString()
{
if ($this->offsetExists('errorMsg')) {
return (string) $this->response['errorMsg'];
}

if (is_array($this->response['errors']) && $this->offsetExists('errors')) {
$errorMessage = '';

foreach ($this->response['errors'] as $error) {
$errorMessage .= $error . ' >';
}

if (strlen($errorMessage) > 2) {
return (string) substr($errorMessage, 0, strlen($errorMessage) - 2);
}

return $errorMessage;
}

return '';
}

/**
Expand Down
6 changes: 5 additions & 1 deletion src/include/class-wc-retailcrm-base.php
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,11 @@ private function getMetaData($entity)
{
global $wpdb;

$table = $entity === 'order' ? $wpdb->postmeta : $wpdb->usermeta;
if ('user' === $entity) {
$table = $wpdb->usermeta;
} else {
$table = useHpos() ? $wpdb->prefix . 'wc_orders_meta' : $wpdb->postmeta;
}

$metaData = ['default_retailcrm' => __('Select value', 'retailcrm')];
$sqlQuery = "SELECT DISTINCT `meta_key` FROM $table ORDER BY `meta_key`";
Expand Down
3 changes: 2 additions & 1 deletion src/include/class-wc-retailcrm-history.php
Original file line number Diff line number Diff line change
Expand Up @@ -1354,7 +1354,8 @@ private function updateMetaData($customFields, $crmData, $wcObject)
}

if ($wcObject instanceof WC_Order) {
update_post_meta($wcObject->get_id(), $metaKey, $crmData['customFields'][$customKey]);
$wcObject->update_meta_data($metaKey, $crmData['customFields'][$customKey]);
$wcObject->save_meta_data();
} else {
update_user_meta($wcObject->get_id(), $metaKey, $crmData['customFields'][$customKey]);
}
Expand Down
65 changes: 42 additions & 23 deletions src/include/class-wc-retailcrm-orders.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,34 +72,40 @@ public function __construct(
/**
* Create order. Returns wc_get_order data or error string.
*
* @param $order_id
* @param $orderId
*
* @return bool|WC_Order|WC_Order_Refund|string
* @return bool|WC_Order|string
* @throws \Exception
*/
public function orderCreate($order_id)
public function orderCreate($orderId)
{
if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null;
}

$this->order_payment->resetData();
try {
$this->order_payment->resetData();

$wcOrder = wc_get_order($order_id);
$this->processOrder($wcOrder);
$wcOrder = wc_get_order($orderId);

try {
$response = $this->retailcrm->ordersCreate($this->order);
$this->processOrder($wcOrder);

if ($response instanceof WC_Retailcrm_Proxy) {
if ($response->isSuccessful()) {
return $wcOrder;
}
$response = $this->retailcrm->ordersCreate($this->order);

if (!$response instanceof WC_Retailcrm_Response || !$response->isSuccessful()) {
return $response->getErrorString();
}
} catch (InvalidArgumentException $exception) {
return $exception->getMessage();
} catch (Throwable $exception) {
writeBaseLogs(
sprintf(
'Error message: %s, file: %s on line: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
)
);

return null;
}

return $wcOrder;
Expand Down Expand Up @@ -252,25 +258,38 @@ protected function fillOrderCreate($wcCustomerId, $wcCustomerEmail, $wcOrder)
/**
* Edit order in CRM
*
* @param int $order_id
* @param int $orderId
*
* @return WC_Order $order | null
* @throws \Exception
*/
public function updateOrder($order_id)
public function updateOrder($orderId)
{
if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null;
}

$wcOrder = wc_get_order($order_id);
try {
$wcOrder = wc_get_order($orderId);

$this->processOrder($wcOrder, true);
$this->processOrder($wcOrder, true);

$response = $this->retailcrm->ordersEdit($this->order);
$response = $this->retailcrm->ordersEdit($this->order);

if (!empty($response) && $response->isSuccessful()) {
$this->payment = $this->orderUpdatePaymentType($wcOrder);
if ($response instanceof WC_Retailcrm_Response && $response->isSuccessful()) {
$this->payment = $this->orderUpdatePaymentType($wcOrder);
}
} catch (Throwable $exception) {
writeBaseLogs(
sprintf(
'Error message: %s, file: %s on line: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
)
);

return null;
}

return $wcOrder;
Expand Down Expand Up @@ -337,11 +356,11 @@ protected function processOrder($order, $update = false)
return;
}

if ($order->get_status() == 'auto-draft') {
if ('auto-draft' === $order->get_status()) {
return;
}

if ($update === true) {
if ($update) {
$this->orders->is_new = false;
}

Expand Down
77 changes: 41 additions & 36 deletions src/include/class-wc-retailcrm-uploader.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,41 +59,45 @@ public function __construct($retailcrm, $orders, $customers)
*/
public function uploadSelectedOrders()
{
if (!empty($_GET['order_ids_retailcrm'])) {
$ids = array_unique(explode(',', $_GET['order_ids_retailcrm']));

if (!empty($ids)) {
$this->uploadArchiveOrders(0, $ids);
$ids = $_GET['order_ids_retailcrm'];

if (!empty($ids)) {
preg_match_all('/\d+/', $ids, $matches);

if (!empty($matches[0])) {
$this->uploadArchiveOrders(null, $matches[0]);
}
}
}

/**
* Uploads archive order in CRM
*
* @param int $page Number page uploads.
* @param array $ids Ids orders upload.
* @param null|int $page Number page uploads.
* @param array $ids Ids orders upload.
*
* @return void|null
* @throws Exception Invalid argument exception.
*/
public function uploadArchiveOrders($page, $ids = array())
public function uploadArchiveOrders($page, $ids = [])
{
if (!$this->retailcrm instanceof WC_Retailcrm_Proxy) {
return null;
}

$uploadErrors = array();
$ordersCms = $this->getCmsOrders($page, $ids);
$orderIds = [];
$uploadErrors = [];

foreach ($ordersCms as $dataOrder) {
$orderId = $dataOrder->ID;
if (null !== $page) {
$orderIds = $this->getCmsOrders($page);
} elseif ([] !== $ids) {
$orderIds = $ids;
}

foreach ($orderIds as $orderId) {
$errorMessage = $this->orders->orderCreate($orderId);

if (true === is_string($errorMessage)) {
$errorMessage = empty($errorMessage) === true
? 'Order exist. External id: ' . $orderId
: $errorMessage;
if (is_string($errorMessage)) {
$uploadErrors[$orderId] = $errorMessage;
}
}
Expand All @@ -118,7 +122,7 @@ public function uploadArchiveCustomers($page)
$users = $this->getCmsUsers($page);

if (false === empty($users)) {
$dataCustomers = array();
$dataCustomers = [];

foreach ($users as $user) {
if ($this->customers->isCustomer($user) === false) {
Expand All @@ -140,20 +144,19 @@ public function uploadArchiveCustomers($page)
* Return orders ids
*
* @param integer $page Number page uploads.
* @param array $ids Ids orders upload.
*
* @return mixed
*/
private function getCmsOrders($page, $ids = array())
private function getCmsOrders($page)
{
return get_posts(
array(
'numberposts' => self::RETAILCRM_COUNT_OBJECT_UPLOAD,
'offset' => self::RETAILCRM_COUNT_OBJECT_UPLOAD * $page,
'post_type' => wc_get_order_types('view-orders'),
'post_status' => array_keys(wc_get_order_statuses()),
'include' => $ids,
)
return wc_get_orders(
[
'type' => wc_get_order_types('view-orders'),
'limit' => self::RETAILCRM_COUNT_OBJECT_UPLOAD,
'status' => array_keys(wc_get_order_statuses()),
'offset' => self::RETAILCRM_COUNT_OBJECT_UPLOAD * $page,
'return' => 'ids',
]
);
}

Expand All @@ -166,30 +169,33 @@ public function getCountOrders()
{
global $wpdb;

$result = $wpdb->get_results("SELECT COUNT(ID) as `count` FROM $wpdb->posts WHERE post_type = 'shop_order'");
if (useHpos()) {
// Use {$wpdb->prefix}, because wp_wc_orders not standard WP table
$result = $wpdb->get_results("SELECT COUNT(ID) as `count` FROM {$wpdb->prefix}wc_orders");
} else {
$result = $wpdb->get_results("SELECT COUNT(ID) as `count` FROM $wpdb->posts WHERE post_type = 'shop_order'");
}

return empty($result[0]->count) === false ? (int) $result[0]->count : 0;
return $result[0]->count ? (int) $result[0]->count : 0;
}


/**
* Return users ids
*
* @param integer $page Number page uploads.
*
* @return mixed
*/
private function getCmsUsers($page)
private function getCmsUsers(int $page)
{
return get_users(
array(
[
'number' => self::RETAILCRM_COUNT_OBJECT_UPLOAD,
'offset' => self::RETAILCRM_COUNT_OBJECT_UPLOAD * $page,
)
]
);
}


/**
* Return count users
*
Expand All @@ -199,10 +205,9 @@ public function getCountUsers()
{
$userCount = count_users();

return empty($userCount['total_users']) === false ? $userCount['total_users'] : 0;
return $userCount['total_users'] ? (int) $userCount['total_users'] : 0;
}


/**
* Array keys must be orders ID's in WooCommerce, values must be strings (error messages).
*
Expand Down
11 changes: 11 additions & 0 deletions src/include/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,14 @@ function writeBaseLogs($message)
{
WC_Retailcrm_Logger::addCaller(__METHOD__, $message);
}

/**
* Checking the use of HPOS.
*
* @codeCoverageIgnore
*/
function useHpos()
{
return class_exists(Automattic\WooCommerce\Utilities\OrderUtil::class)
&& Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
}
Loading

0 comments on commit a0d6815

Please sign in to comment.